text:
package edu.kit.dama.staging.util;

import edu.kit.dama.staging.entities.download.DownloadInformation;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.fzk.grid.util.MailNotifier;
import org.fzk.grid.util.MailNotifierListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Mail notification helper which is used to notify the user about available
 * downloads. The notification settings are obtained while scheduling a download
 * and they are written to a sub folder of the locally cached download. If the
 * download is prepared, the settings are read again and the notification is
 * send to the user.
 *
 * @author jejkal
 */
public final class MailNotificationHelper {

  private static final Logger LOGGER = LoggerFactory.getLogger(MailNotificationHelper.class);
  private static String mailServer = null;
  private static String sender = null;
  private final static String NOTIFICATION_PROPERTY_FILE = "notify.properties";
  private static boolean CONFIGURED = false;

  /**
   * Hidden constructor.
   */
  MailNotificationHelper() {
  }

  /**
   * Configure the helper with a mail server and the sender email.
   *
   * @param pServer The mail server.
   * @param pSender The sender of notification mails.
   */
  public static void configure(String pServer, String pSender) {
    mailServer = pServer;
    sender = pSender;

    if (mailServer != null && sender != null) {
      CONFIGURED = true;
    } else {
      LOGGER.warn("Either the configured mail server or sender is 'null'. Mail notification won't work.");
    }
  }

  /**
   * Store the mail notification properties in a file located in the provided
   * destination folder.
   *
   * @param pDestinationFolder The folder where the properties file is stored.
   * @param pReceiver The receiver of the mail notification.
   */
  public static void storeProperties(File pDestinationFolder, String pReceiver) {
    if (!CONFIGURED) {
      LOGGER.warn("Mail notifier is not configured properly");
      return;
    }
    Properties props = new Properties();
    props.put("receiver", pReceiver);
    FileOutputStream fout = null;
    try {
      fout = new FileOutputStream(new File(pDestinationFolder, NOTIFICATION_PROPERTY_FILE));
      props.store(fout, null);
    } catch (IOException ioe) {
      LOGGER.error("Failed to store mail notifier properies", ioe);
    } finally {
      if (fout != null) {
        try {
          fout.close();
        } catch (IOException ex) {
        }
      }
    }
  }

  /**
   * Restore all properties from a properties file located in the provided
   * folder.
   *
   * @param pSourceFolder The folder where the properties file is located.
   *
   * @return The restored properties object.
   */
  public static Properties restoreProperties(File pSourceFolder) {
    if (!CONFIGURED) {
      LOGGER.warn("Mail notifier is not configured properly");
      return new Properties();
    }
    File notifyProperties = new File(pSourceFolder, NOTIFICATION_PROPERTY_FILE);

    Properties result = new Properties();
    if (notifyProperties.exists()) {
      FileInputStream fin = null;
      try {
        LOGGER.debug("Loading notification properties");
        fin = new FileInputStream(notifyProperties);
        result.load(fin);
        LOGGER.debug("Removing notification properties file");
        if (notifyProperties.delete()) {
          LOGGER.debug("Notification properties file successfully deleted");
        } else {
          LOGGER.warn("Failed to delete notification properties file");
        }
      } catch (IOException ex) {
        LOGGER.error("Failed to load notification properties. Notification won't be sent.", ex);
      } finally {
        if (fin != null) {
          try {
            fin.close();
          } catch (IOException ex) {
          }
        }
      }
    } else {
      LOGGER.info("No mail notification properties found at {}", pSourceFolder.getPath());
    }
    return result;
  }

  /**
   * Send a download notification.
   *
   * @param pProperties Properties to use.
   * @param pInformation The download information about to notify.
   */
  public static void sendDownloadNotification(Properties pProperties, final DownloadInformation pInformation) {
    if (!CONFIGURED) {
      LOGGER.warn("Mail notifier is not configured properly");
      return;
    }

    final String receiver = pProperties.getProperty("receiver");
    LOGGER.debug("Try to send notification to {}", receiver);
    LOGGER.debug(" - Building message");
    StringBuilder builder = new StringBuilder();

    builder.append("Your download with the transfer ID ").append(pInformation.getTransferId()).append(" is now ready.\n");
    builder.append("You can access the data via:\n\n").append("  ").append(pInformation.getClientAccessUrl()).append("\n\n");
    builder.append("This mail is generated automatically. Please do not reply.");

    LOGGER.debug(" - Sending mail via mail server {} as {}", new Object[]{mailServer, sender});
    MailNotifier notifier = new MailNotifier(sender, new MailNotifierListener() {
      @Override
      public void fireMailSendEvent() {
        LOGGER.debug("Download notification for download {} successfully sent to {}", new Object[]{pInformation.getTransferId(), receiver});
      }

      @Override
      public void fireMailSendFailedEvent(String errorMessage) {
        LOGGER.error("Failed to send notification for download {} to {}. Message: {}", new Object[]{pInformation.getTransferId(), receiver, errorMessage});
      }
    }, mailServer);
    notifier.sendMail(receiver, "Download #" + pInformation.getTransferId() + " available", builder.toString());
    LOGGER.debug("Mail notification finished.");
  }

//  public static void main(String[] args) {
//    System.out.println("START");
//    new MailNotifier("noreply@dama.kit.edu", new MailNotifierListener() {
//      @Override
//      public void fireMailSendEvent() {
//        System.out.println("OK");
//      }
//
//      @Override
//      public void fireMailSendFailedEvent(String errorMessage) {
//
//      }
//    }, "smtp.kit.edu").sendMail("support@kitdatamanager.net", "Download  available", "Success!");
//    System.out.println("DONE");
//  }
}


text:
package routes

import "github.com/revel/revel"

type tGorpController struct {}
var GorpController tGorpController

func (_ tGorpController) Begin(
		) string {
	args := make(map[string]string)

	return revel.MainRouter.Reverse("GorpController.Begin", args).Url
}

func (_ tGorpController) Commit(
		) string {
	args := make(map[string]string)

	return revel.MainRouter.Reverse("GorpController.Commit", args).Url
}

func (_ tGorpController) Rollback(
		) string {
	args := make(map[string]string)

	return revel.MainRouter.Reverse("GorpController.Rollback", args).Url
}

type tJobs struct {}
var Jobs tJobs

func (_ tJobs) Status(
		) string {
	args := make(map[string]string)

	return revel.MainRouter.Reverse("Jobs.Status", args).Url
}

type tStatic struct {}
var Static tStatic

func (_ tStatic) Serve(
		prefix string,
		filepath string,
		) string {
	args := make(map[string]string)

	revel.Unbind(args, "prefix", prefix)
	revel.Unbind(args, "filepath", filepath)
	return revel.MainRouter.Reverse("Static.Serve", args).Url
}

func (_ tStatic) ServeModule(
		moduleName string,
		prefix string,
		filepath string,
		) string {
	args := make(map[string]string)

	revel.Unbind(args, "moduleName", moduleName)
	revel.Unbind(args, "prefix", prefix)
	revel.Unbind(args, "filepath", filepath)
	return revel.MainRouter.Reverse("Static.ServeModule", args).Url
}

type tApp struct {}
var App tApp

func (_ tApp) Index(
		) string {
	args := make(map[string]string)

	return revel.MainRouter.Reverse("App.Index", args).Url
}

type tStage struct {}
var Stage tStage

func (_ tStage) Now(
		id string,
		) string {
	args := make(map[string]string)

	revel.Unbind(args, "id", id)
	return revel.MainRouter.Reverse("Stage.Now", args).Url
}

func (_ tStage) CurrentLater(
		id string,
		) string {
	args := make(map[string]string)

	revel.Unbind(args, "id", id)
	return revel.MainRouter.Reverse("Stage.CurrentLater", args).Url
}

redpajama_set_name: RedPajamaGithub


text:
int catclose (nl_catd catd)
{
#ifdef __wasilibc_unmodified_upstream // wasi-libc doesn't support catgets yet
	char *map = (char *)catd;
	munmap(map, V(map+8)+20);
#endif
	return 0;
}


text:
import EmberObject from '@ember/object';

/**
 * A serializer that serializes values to JSON strings.
 *
 * @class JsonSerializer
 * @extends Ember.Object
 */
let JsonSerializer = EmberObject.extend({
  /**
   * Serialize a value
   *
   * @param value
   * @returns {String} JSON string
   */
  serialize(value) {
    if (value === null || value === undefined) {
      return null;
    }
    return JSON.stringify(value);
  },

  /**
   * Deserialize a value
   *
   * @param {String} JSON string
   * @returns {*} value
   */
  deserialize(value) {
    if (value === null || value === undefined) {
      return null;
    }
    return JSON.parse(value);
  },
});

JsonSerializer.reopenClass({
  toString() {
    return 'ember-local-settings/serializers/json';
  },
});

export default JsonSerializer;


text:
package com.navercorp.pinpoint.common.util;

import org.junit.Assert;
import org.junit.Test;

public class DefaultParsingResultTest {

    @Test
    public void testId() throws Exception {
        DefaultParsingResult result = new DefaultParsingResult();
        Assert.assertEquals(ParsingResult.ID_NOT_EXIST, result.getId());

        // update
        Assert.assertTrue(result.setId(1));

        // already updated
        Assert.assertFalse(result.setId(1));
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_background"
    android:orientation="vertical"
    android:divider="@drawable/list_divider"
    android:descendantFocusability="blocksDescendants"
    android:showDividers="middle"
    android:layout_width="150dp"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/tv_title"
        android:text="test"
        android:maxWidth="150dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/tv_ok"
        android:drawableLeft="@drawable/ic_location_small"
        android:layout_marginTop="@dimen/view_common_margin"
        android:clickable="true"
        android:text="@string/use_this_location"
        android:textColor="@color/dodgerblue"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


text:
// Copyright 2018, Bosch Software Innovations GmbH.
// Copyright 2021, Apex.AI Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RCLCPP__GENERIC_SUBSCRIPTION_HPP_
#define RCLCPP__GENERIC_SUBSCRIPTION_HPP_

#include <functional>
#include <memory>
#include <string>

#include "rcpputils/shared_library.hpp"

#include "rclcpp/callback_group.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/node_interfaces/node_base_interface.hpp"
#include "rclcpp/node_interfaces/node_topics_interface.hpp"
#include "rclcpp/qos.hpp"
#include "rclcpp/serialized_message.hpp"
#include "rclcpp/subscription_base.hpp"
#include "rclcpp/typesupport_helpers.hpp"
#include "rclcpp/visibility_control.hpp"

namespace rclcpp
{

/// %Subscription for serialized messages whose type is not known at compile time.
/**
 * Since the type is not known at compile time, this is not a template, and the dynamic library
 * containing type support information has to be identified and loaded based on the type name.
 *
 * It does not support intra-process handling.
 */
class GenericSubscription : public rclcpp::SubscriptionBase
{
public:
  // cppcheck-suppress unknownMacro
  RCLCPP_SMART_PTR_DEFINITIONS(GenericSubscription)

  /// Constructor.
  /**
   * In order to properly subscribe to a topic, this subscription needs to be added to
   * the node_topic_interface of the node passed into this constructor.
   *
   * \sa rclcpp::Node::create_generic_subscription() or rclcpp::create_generic_subscription() for
   * creating an instance of this class and adding it to the node_topic_interface.
   *
   * \param node_base Pointer to parent node's NodeBaseInterface
   * \param ts_lib Type support library, needs to correspond to topic_type
   * \param topic_name Topic name
   * \param topic_type Topic type
   * \param qos %QoS settings
   * \param callback Callback for new messages of serialized form
   * \param options %Subscription options.
   * Not all subscription options are currently respected, the only relevant options for this
   * subscription are `event_callbacks`, `use_default_callbacks`, `ignore_local_publications`, and
   * `%callback_group`.
   */
  template<typename AllocatorT = std::allocator<void>>
  GenericSubscription(
    rclcpp::node_interfaces::NodeBaseInterface * node_base,
    const std::shared_ptr<rcpputils::SharedLibrary> ts_lib,
    const std::string & topic_name,
    const std::string & topic_type,
    const rclcpp::QoS & qos,
    // TODO(nnmm): Add variant for callback with message info. See issue #1604.
    std::function<void(std::shared_ptr<rclcpp::SerializedMessage>)> callback,
    const rclcpp::SubscriptionOptionsWithAllocator<AllocatorT> & options)
  : SubscriptionBase(
      node_base,
      *rclcpp::get_typesupport_handle(topic_type, "rosidl_typesupport_cpp", *ts_lib),
      topic_name,
      options.template to_rcl_subscription_options<rclcpp::SerializedMessage>(qos),
      true),
    callback_(callback),
    ts_lib_(ts_lib)
  {
    // This is unfortunately duplicated with the code in subscription.hpp.
    // TODO(nnmm): Deduplicate by moving this into SubscriptionBase.
    if (options.event_callbacks.deadline_callback) {
      this->add_event_handler(
        options.event_callbacks.deadline_callback,
        RCL_SUBSCRIPTION_REQUESTED_DEADLINE_MISSED);
    }
    if (options.event_callbacks.liveliness_callback) {
      this->add_event_handler(
        options.event_callbacks.liveliness_callback,
        RCL_SUBSCRIPTION_LIVELINESS_CHANGED);
    }
    if (options.event_callbacks.incompatible_qos_callback) {
      this->add_event_handler(
        options.event_callbacks.incompatible_qos_callback,
        RCL_SUBSCRIPTION_REQUESTED_INCOMPATIBLE_QOS);
    } else if (options.use_default_callbacks) {
      // Register default callback when not specified
      try {
        this->add_event_handler(
          [this](QOSRequestedIncompatibleQoSInfo & info) {
            this->default_incompatible_qos_callback(info);
          },
          RCL_SUBSCRIPTION_REQUESTED_INCOMPATIBLE_QOS);
      } catch (UnsupportedEventTypeException & /*exc*/) {
        // pass
      }
    }
    if (options.event_callbacks.message_lost_callback) {
      this->add_event_handler(
        options.event_callbacks.message_lost_callback,
        RCL_SUBSCRIPTION_MESSAGE_LOST);
    }
  }

  RCLCPP_PUBLIC
  virtual ~GenericSubscription() = default;

  // Same as create_serialized_message() as the subscription is to serialized_messages only
  RCLCPP_PUBLIC
  std::shared_ptr<void> create_message() override;

  RCLCPP_PUBLIC
  std::shared_ptr<rclcpp::SerializedMessage> create_serialized_message() override;

  /// Cast the message to a rclcpp::SerializedMessage and call the callback.
  RCLCPP_PUBLIC
  void handle_message(
    std::shared_ptr<void> & message, const rclcpp::MessageInfo & message_info) override;

  /// Handle dispatching rclcpp::SerializedMessage to user callback.
  RCLCPP_PUBLIC
  void
  handle_serialized_message(
    const std::shared_ptr<rclcpp::SerializedMessage> & serialized_message,
    const rclcpp::MessageInfo & message_info) override;

  /// This function is currently not implemented.
  RCLCPP_PUBLIC
  void handle_loaned_message(
    void * loaned_message, const rclcpp::MessageInfo & message_info) override;

  // Same as return_serialized_message() as the subscription is to serialized_messages only
  RCLCPP_PUBLIC
  void return_message(std::shared_ptr<void> & message) override;

  RCLCPP_PUBLIC
  void return_serialized_message(std::shared_ptr<rclcpp::SerializedMessage> & message) override;

private:
  RCLCPP_DISABLE_COPY(GenericSubscription)

  std::function<void(std::shared_ptr<rclcpp::SerializedMessage>)> callback_;
  // The type support library should stay loaded, so it is stored in the GenericSubscription
  std::shared_ptr<rcpputils::SharedLibrary> ts_lib_;
};

}  // namespace rclcpp

#endif  // RCLCPP__GENERIC_SUBSCRIPTION_HPP_


text:
_clipboard(){
    local cur prev words cword

#    echo "comp_key" "$COMP_KEY"
#    echo "comp type" "$COMP_TYPE"
#    echo "cur" "$cur"
    # we want to tell the diff between a completion
    # invoke via "TAB" and the keybinding mapped
    # to clipboard completion (let's say, \C-h for
    # example. If we are the clipboard config, we
    # search the clipboard history, otherwise we
    # just pass to the default completion here
    if [ $COMP_KEY == 9 ] ; then
        if [ $COMP_TYPE == 37 ] ; then
            COMPREPLY=()
            #COMPREPLY=( abba babba cabba dabba easy foobar glippy )
            #COMPREPLY=( $( compgen -F _clips -- "$cur") )
            mapfile -t CLIPS < ~/.local/clipbored/clips
            IFS=$'\n';
            COMPREPLY=( $( compgen -W "${CLIPS[*]}" -- "$cur") )
            #unset IFS
            #COMPREPLY=( "$CLIPS[@]" )
        fi
    fi
}

# complete on empty so we can paste an
# entire command
#complete -E -F _clipboard ''
complete -E -F _clipboard
complete -D -F _clipboard
#complete -F -o default _clipboard


text:
import { MDCComponent } from '@material/base/component';
import { MDCRipple } from '@material/ripple/component';
import { MDCFormFieldFoundation } from './foundation';
export interface MDCFormFieldInput {
    readonly ripple: MDCRipple | undefined;
}
export declare class MDCFormField extends MDCComponent<MDCFormFieldFoundation> {
    static attachTo(root: HTMLElement): MDCFormField;
    private input_?;
    input: MDCFormFieldInput | undefined;
    private readonly label_;
    getDefaultFoundation(): MDCFormFieldFoundation;
}


text:
package com.itkweb.hday.config;

import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 * Spring configuration class to manage JPA transaction manager<br />
 * Enable also the entity manager factory
 *
 * @author Vincent DAVY
 *
 */
@Configuration
@PropertySource("classpath:/properties/MySQL-test.properties")
public class SpringDatabaseDtdTestConfiguration {

	@Value("${jdbc.driverclass}")
	private String driverClass;

	@Value("${db.schemaName}")
	private String schemaName;

	@Value("${db.login}")
	private String login;

	@Value("${db.password}")
	private String password;

	@Value("${db.address}")
	private String address;

	@Value("#{'${hibernate.properties}'.split(',')}")
	private List<String> propertiesList;

	/**
	 * Create the {@link DataSource}
	 *
	 * @return the {@link DataSource}
	 */
	@Bean
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(driverClass);
		dataSource.setUrl(address + schemaName);
		dataSource.setUsername(login);
		dataSource.setPassword(password);
		return dataSource;
	}

	/**
	 * This is needed to parse properties placeholders (${...}) and is must be in a static way
	 *
	 * @see http://www.java-allandsundry.com/2013/07/spring-bean-and-propertyplaceholderconf.html
	 * @see http
	 *      ://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html
	 *      "Working with externalized values" section
	 * @return the {@link PropertySourcesPlaceholderConfigurer}
	 */
	@Bean
	public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
		return new PropertySourcesPlaceholderConfigurer();
	}

	//	/**
	//	 * Create the {@link TransactionManager}
	//	 *
	//	 * @return the {@link TransactionManager}
	//	 */
	//	@Bean
	//	public PlatformTransactionManager transactionManager() {
	//		return new JpaTransactionManager(entityManagerFactory().getObject());
	//	}
	//
	//	/**
	//	 * Create the {@link EntityManagerFactory}
	//	 *
	//	 * @return the {@link LocalContainerEntityManagerFactoryBean}
	//	 */
	//	@Bean
	//	public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
	//		LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
	//		emf.setDataSource(dataSource());
	//		emf.setPackagesToScan("com.itkweb.hday");
	//		emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
	//
	//		Properties properties = new Properties();
	//		for (String property : propertiesList) {
	//			String[] propertyArray = property.split(":");
	//			if (propertyArray != null && propertyArray.length > 1) {
	//				properties.setProperty(propertyArray[0], propertyArray[1]);
	//			}
	//
	//		}
	//		emf.setJpaProperties(properties);
	//
	//		return emf;
	//	}
}


text:
const SPACE = /[^ ]+/g

// Field-length norm: the shorter the field, the higher the weight.
// Set to 3 decimals to reduce index size.
export default function norm(mantissa = 3) {
  const cache = new Map()

  return {
    get(value) {
      const numTokens = value.match(SPACE).length

      if (cache.has(numTokens)) {
        return cache.get(numTokens)
      }

      const n = parseFloat((1 / Math.sqrt(numTokens)).toFixed(mantissa))

      cache.set(numTokens, n)

      return n
    },
    clear() {
      cache.clear()
    }
  }
}


text: import 'rxjs-compat/add/operator/mergeAll';


text:
package org.smurn.jply;

import java.io.IOException;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

/**
 * Declaration of a list property of an element.
 *
A list property stores a list of values for an element. The length
 * of the list can be different for every element.

 *
Some property names have a pre-defined meaning in the specification
 * and should only be used accordingly. See {@link ElementType} for a list
 * and a description of those properties.

 *
All instances of this class are immutable.

 */
public class ListProperty extends Property {

    /** Type of the element count value. */
    private final DataType countType;

    /**
     * Creates an instance.
     * @param countType Data type of the value storing the number of
     * elements in the list.
     * @param name  Name of the property.
     * @param type Data type of this property.
     * @throws NullPointerException if {@code countType}, {@code name} or
     * {@code type} is {@code null}.
     */
    public ListProperty(final DataType countType, final String name,
            final DataType type) {
        super(name, type);
        if (countType == null) {
            throw new NullPointerException("countType must not be null.");
        }
        this.countType = countType;
    }

    /**
     * Gets the type of the value storing the number of elements in the list.
     * @return Data type. Is never {@code null}.
     */
    public DataType getCountType() {
        return countType;
    }

    /**
     * Parses a list-property header line.
     * @param line Header line.
     * @return Property described on the line.
     * @throws IOException if the header line as an invalid format.
     */
    static Property parse(final String line) throws IOException {
        if (!line.startsWith("property ")) {
            throw new IOException("not a property: '"
                    + line + "'");
        }
        String definition = line.substring("property ".length());
        definition = definition.trim();

        if (!definition.startsWith("list ")) {
            throw new IllegalArgumentException("not a list property: '"
                    + line + "'");
        }
        definition = definition.substring("list ".length());
        definition = definition.trim();

        String[] parts = definition.split(" +", 3);
        if (parts.length != 3) {
            throw new IOException("Expected three parts in list property "
                    + "definition: '" + line + "'");
        }
        String countType = parts[0];
        String type = parts[1];
        String name = parts[2];

        DataType dataType;
        DataType countDataType;
        try {
            dataType = DataType.parse(type);
            countDataType = DataType.parse(countType);
        }
        catch (IllegalArgumentException e) {
            throw new IOException(e.getMessage());
        }

        return new ListProperty(countDataType, name, dataType);
    }

    @Override
    public String toString() {
        return "property list " + countType + " " + getType() + " " + getName();
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }
        ListProperty rhs = (ListProperty) obj;
        EqualsBuilder builder = new EqualsBuilder();
        builder.appendSuper(super.equals(obj));
        builder.append(countType, rhs.countType);
        return builder.isEquals();
    }

    @Override
    public int hashCode() {
        HashCodeBuilder builder = new HashCodeBuilder();
        builder.appendSuper(super.hashCode());
        builder.append(countType);
        return builder.toHashCode();
    }
}


text:
"""
ruler() generates a string ruler with embedded text.
head() does the same thing but prints it.
"""
__all__ = ['ruler', 'head']

def ruler(arg=None, sep="_", print_=False, width=60):
    if arg:
        result = "[ {} ]".format(str(arg)).center(width, sep) + "\n"
    else:
        result = "".center(width, sep) + "\n"
    if print_:
        print(result.rstrip())
    else:
        return result

def head(arg=None, sep="_", width=60): ruler(arg, sep, True, width)


text:
import { Component, Input, OnInit } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { State, vmSnapshotsSelectors } from '../../../root-store';
import { EntityAction } from '../../../shared/interfaces';
import { VmSnapshotViewModel } from '../../models/vm-snapshot.view-model';

@Component({
  selector: 'cs-vm-snapshot-action-menu',
  templateUrl: './vm-snapshot-action-menu.component.html',
  styleUrls: ['./vm-snapshot-action-menu.component.scss'],
})
export class VmSnapshotActionMenuComponent implements OnInit {
  @Input()
  public snapshot: VmSnapshotViewModel;
  public actions$: Observable<EntityAction[]>;

  constructor(private store: Store<State>) {}

  public ngOnInit() {
    this.actions$ = this.store.pipe(
      select(vmSnapshotsSelectors.getVmSnapshotEntityActions(this.snapshot.id)),
    );
  }
}


text:
Browse the Reddit poems of /u/Poem_for_your_sprog from your phone!

Google Play and the Google Play logo are trademarks of Google Inc.


text:
/*
 * This file was semi-automatically converted from the public-domain USGS PROJ source.
 */
package org.osgeo.proj4j.proj;

public class Wagner5Projection extends MolleweideProjection {

	public Wagner5Projection() {
		super( MolleweideProjection.WAGNER5 );
	}

}


text:
package io.fabric8.kubernetes.client.utils;

import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.internal.SSLUtils;
import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import static okhttp3.ConnectionSpec.CLEARTEXT;

public class HttpClientUtils {

  private static Pattern VALID_IPV4_PATTERN = null;
  public static final String ipv4Pattern = "(http:\\/\\/|https:\\/\\/)?(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])(\\/[0-9]\\d|1[0-9]\\d|2[0-9]\\d|3[0-2]\\d)?";
  private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

  static {
    try {
      VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);
    } catch (PatternSyntaxException e) {
      throw KubernetesClientException.launderThrowable("Unable to compile ipv4address pattern.", e);
    }
  }

  public static OkHttpClient createHttpClient(final Config config) {
        try {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

            // Follow any redirects
            httpClientBuilder.followRedirects(true);
            httpClientBuilder.followSslRedirects(true);

            if (config.isTrustCerts() || config.isDisableHostnameVerification()) {
                httpClientBuilder.hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });
            }

            TrustManager[] trustManagers = SSLUtils.trustManagers(config);
            KeyManager[] keyManagers = SSLUtils.keyManagers(config);

            if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
                X509TrustManager trustManager = null;
                if (trustManagers != null && trustManagers.length == 1) {
                  trustManager = (X509TrustManager) trustManagers[0];
                }

                try {
                    SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                    httpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
                } catch (GeneralSecurityException e) {
                    throw new AssertionError(); // The system has no TLS. Just give up.
                }
            } else {
              SSLContext context = SSLContext.getInstance("TLSv1.2");
              context.init(keyManagers, trustManagers, null);
              httpClientBuilder.sslSocketFactory(context.getSocketFactory(), (X509TrustManager) trustManagers[0]);
            }

          httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
              Request request = chain.request();
              if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) {
                Request authReq = chain.request().newBuilder().addHeader("Authorization", Credentials.basic(config.getUsername(), config.getPassword())).build();
                return chain.proceed(authReq);
              } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
                Request authReq = chain.request().newBuilder().addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                return chain.proceed(authReq);
              }
              return chain.proceed(request);
            }
          }).addInterceptor(new ImpersonatorInterceptor(config))
            .addInterceptor(new BackwardsCompatibilityInterceptor());

            Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
            if (reqLogger.isTraceEnabled()) {
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                httpClientBuilder.addNetworkInterceptor(loggingInterceptor);
            }

            if (config.getConnectionTimeout() > 0) {
                httpClientBuilder.connectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
            }

            if (config.getRequestTimeout() > 0) {
                httpClientBuilder.readTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
            }

            if (config.getWebsocketPingInterval() > 0) {
              httpClientBuilder.pingInterval(config.getWebsocketPingInterval(), TimeUnit.MILLISECONDS);
            }

            if (config.getMaxConcurrentRequestsPerHost() > 0) {
              Dispatcher dispatcher = new Dispatcher();
              dispatcher.setMaxRequests(config.getMaxConcurrentRequests());
              dispatcher.setMaxRequestsPerHost(config.getMaxConcurrentRequestsPerHost());
              httpClientBuilder.dispatcher(dispatcher);
            }

            // Only check proxy if it's a full URL with protocol
            if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX) || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
                try {
                    URL proxyUrl = getProxyUrl(config);
                    if (proxyUrl != null) {
                        httpClientBuilder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));

                        if (config.getProxyUsername() != null) {
                          httpClientBuilder.proxyAuthenticator(new Authenticator() {
                            @Override
                            public Request authenticate(Route route, Response response) throws IOException {

                              String credential = Credentials.basic(config.getProxyUsername(), config.getProxyPassword());
                              return response.request().newBuilder().header("Proxy-Authorization", credential).build();
                            }
                          });
                        }
                    }

                } catch (MalformedURLException e) {
                    throw new KubernetesClientException("Invalid proxy server configuration", e);
                }
            }

            if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
                httpClientBuilder.addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent()).build();
                        return chain.proceed(agent);
                    }
                });
            }

            if (config.getTlsVersions() != null && config.getTlsVersions().length > 0) {
              ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(config.getTlsVersions())
                .build();
              httpClientBuilder.connectionSpecs(Arrays.asList(spec, CLEARTEXT));
            }

            return httpClientBuilder.build();
        } catch (Exception e) {
            throw KubernetesClientException.launderThrowable(e);
        }
    }

    private static URL getProxyUrl(Config config) throws MalformedURLException {
        URL master = new URL(config.getMasterUrl());
        String host = master.getHost();
        if (config.getNoProxy() != null) {
	        for (String noProxy : config.getNoProxy()) {
            if (isIpAddress(noProxy)) {
              if (new IpAddressMatcher(noProxy).matches(host)) {
                return null;
              }
            } else {
              if (host.contains(noProxy)) {
                return null;
              }
            }
	        }
        }
        String proxy = config.getHttpsProxy();
        if (master.getProtocol().equals("http")) {
            proxy = config.getHttpProxy();
        }
        if (proxy != null) {
            return new URL(proxy);
        }
        return null;
    }

    private static boolean isIpAddress(String ipAddress) {
        Matcher ipMatcher = VALID_IPV4_PATTERN.matcher(ipAddress);
        return ipMatcher.matches();
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jme3.ai.steering.behaviour;

import com.jme3.math.Vector3f;

/**
 * Seek (or pursuit of a static target) acts to steer the character
 * towards a specified position in global space. This behavior adjusts
 * the character so that its velocity is radially aligned towards the target.
 *
 * @author Brent Owens
 */
public class Seek implements Behaviour {

    public Vector3f calculateForce(Vector3f location, Vector3f velocity,
                                    float speed, Vector3f target) {

        Vector3f desierdVel = target.subtract(location).normalize().mult(speed);
        Vector3f steering = desierdVel.subtract(velocity);

        return steering;
    }
}


text:
from biopandas.pdb import PandasPdb
import os
import numpy as np
import pandas as pd
from nose.tools import raises

TESTDATA_FILENAME = os.path.join(
    os.path.dirname(__file__), "data", "3eiy_stripped_no_ele.pdb"
)

ppdb = PandasPdb()
ppdb.read_pdb(TESTDATA_FILENAME)

def test_impute_hetatm():
    new = ppdb.impute_element(records=["HETATM"])
    assert new["HETATM"]["element_symbol"][1] == "N"
    assert new["HETATM"]["element_symbol"][10] == "O"
    assert new["ATOM"]["element_symbol"][1] == ""
    assert new["ATOM"]["element_symbol"][10] == ""

def test_impute_atom():
    new = ppdb.impute_element(records=["ATOM"])
    assert new["ATOM"]["element_symbol"][1] == "C"
    assert new["ATOM"]["element_symbol"][10] == "C"
    assert new["HETATM"]["element_symbol"][1] == ""
    assert new["HETATM"]["element_symbol"][10] == ""

def test_impute_default():
    assert ppdb.df["ATOM"]["element_symbol"][1] == ""
    assert ppdb.df["HETATM"]["element_symbol"][1] == ""
    new = ppdb.impute_element()
    assert new["ATOM"]["element_symbol"][1] == "C"
    assert new["ATOM"]["element_symbol"][10] == "C"
    assert new["HETATM"]["element_symbol"][1] == "N"
    assert new["HETATM"]["element_symbol"][10] == "O"


text:
package org.apache.streams.jackson;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * Created by sblackmon on 3/27/14.
 */
public class StreamsJacksonMapper extends ObjectMapper {

    private static final StreamsJacksonMapper INSTANCE = new StreamsJacksonMapper();

    public static StreamsJacksonMapper getInstance(){
        return INSTANCE;
    }

    public StreamsJacksonMapper() {
        super();
        registerModule(new StreamsJacksonModule());
        disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
        configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.TRUE);
        configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
        configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
        configure(DeserializationFeature.WRAP_EXCEPTIONS, Boolean.FALSE);
        configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, Boolean.TRUE);
        // If a user has an 'object' that does not have an explicit mapping, don't cause the serialization to fail.
        configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, Boolean.FALSE);
        configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, Boolean.FALSE);
        configure(SerializationFeature.WRITE_NULL_MAP_VALUES, Boolean.FALSE);
        setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.DEFAULT);
    }

}


text:
import xml.etree.ElementTree as ET
from .. import Parser, parser, LegacyItemAccess

@parser('rhn-entitlement-cert.xml')
class RHNCertConf(LegacyItemAccess, Parser):
    """Class to parse the xml files ``rhn-entitlement-cert.xml*``

    Attributes:
        data (dict): A dict likes
        {
            'product': 'RHN-SATELLITE-001'
            'satellite-version': '5.2'
            'signature': '-----BEGIN PGP SIGNATURE-----....'
            'channel-families':
            {
                'rhel-cluster': {'quantity':'10'}
                'sam-rhel-server-6': {'quantity':'102', 'flex':'0'}
                ...
            }
            ...
        }
        ---
        And there may be patterns of "rhn_entitlement_cert.xml" files on the host,
        you can use the 'file_name' attribute to check where the settings are
        actually gotten from. E.g:
        ---
            rhn_certs = shared[rhn_cert]
            for cert in rhn_certs:
                if cert.file_name == 'rhn_entitlement_cert.xml':
                   cf = cert.get('channel_families')
                   ...

    ---Sample---
        <?xml version="1.0" encoding="UTF-8"?>
        <rhn-cert version="0.1">
          <rhn-cert-field name="product">RHN-SATELLITE-001</rhn-cert-field>
          <rhn-cert-field name="owner">Clay's Precious Satellite</rhn-cert-field>
          <rhn-cert-field name="issued">2005-01-11 00:00:00</rhn-cert-field>
          <rhn-cert-field name="expires">2005-03-11 00:00:00</rhn-cert-field>
          <rhn-cert-field name="slots">30</rhn-cert-field>
          <rhn-cert-field name="provisioning-slots">30</rhn-cert-field>
          <rhn-cert-field name="nonlinux-slots">30</rhn-cert-field>
          <rhn-cert-field name="channel-families" quantity="10" family="rhel-cluster"/>
          <rhn-cert-field name="channel-families" quantity="30" family="rhel-ws-extras"/>
          <rhn-cert-field name="channel-families" quantity="10" family="rhel-gfs"/>
          <rhn-cert-field name="channel-families" quantity="10" family="rhel-es-extras"/>
          <rhn-cert-field name="channel-families" quantity="40" family="rhel-as"/>
          <rhn-cert-field name="channel-families" quantity="30" family="rhn-tools"/>
          <rhn-cert-field name="channel-families" quantity="102" flex="0" family="sam-rhel-server-6"/>
          <rhn-cert-field name="channel-families" quantity="102" flex="51" family="cf-tools-5-beta"/>
          <rhn-cert-field name="satellite-version">5.2</rhn-cert-field>
          <rhn-cert-field name="generation">2</rhn-cert-field>
          <rhn-cert-signature>
        -----BEGIN PGP SIGNATURE-----
        Version: Crypt::OpenPGP 1.03

        iQBGBAARAwAGBQJCAG7yAAoJEJ5yna8GlHkysOkAn07qmlUrkGKs7/5yb8H/nboG
        mhHkAJ9wdmqOeKfcBa3IUDL53oNMEBP/dg==
        =0Kv7
        -----END PGP SIGNATURE-----
        </rhn-cert-signature>
        </rhn-cert>
    """

    def parse_content(self, content):

        rhn_cert = {}
        # ignore empty xml file
        if len(content) > 3:
            rhntree = ET.fromstring('\n'.join(content))
            channel_familes = {}
            for field in rhntree.findall(".//rhn-cert-field"):
                family = field.get('family')
                if family:
                    channel_familes[family] = {
                        k: v for k, v in field.items() if k not in ('name', 'family')}
                elif field.text:
                    rhn_cert[field.get('name')] = field.text
            # for all channel families
            rhn_cert['channel-families'] = channel_familes
            singature = rhntree.findall(".//rhn-cert-signature")
            rhn_cert['signature'] = singature[0].text

        self.data = rhn_cert


text:
from CIM15.IEC61968.Common.ActivityRecord import ActivityRecord

class FailureEvent(ActivityRecord):
    """An event where an asset has failed to perform its functions within specified parameters.An event where an asset has failed to perform its functions within specified parameters.
    """

    def __init__(self, failureIsolationMethod="fuse", corporateCode='', faultLocatingMethod='', location='', *args, **kw_args):
        """Initialises a new 'FailureEvent' instance.

        @param failureIsolationMethod: How the asset failure was isolated from the system. Values are: "fuse", "manuallyIsolated", "breakerOperation", "other", "burnedInTheClear"
        @param corporateCode: Code for asset failure.
        @param faultLocatingMethod: The method used for locating the faulted part of the asset. For example, cable options include: Cap Discharge-Thumping, Bridge Method, Visual Inspection, Other.
        @param location: Failure location on an object.
        """
        #: How the asset failure was isolated from the system. Values are: "fuse", "manuallyIsolated", "breakerOperation", "other", "burnedInTheClear"
        self.failureIsolationMethod = failureIsolationMethod

        #: Code for asset failure.
        self.corporateCode = corporateCode

        #: The method used for locating the faulted part of the asset. For example, cable options include: Cap Discharge-Thumping, Bridge Method, Visual Inspection, Other.
        self.faultLocatingMethod = faultLocatingMethod

        #: Failure location on an object.
        self.location = location

        super(FailureEvent, self).__init__(*args, **kw_args)

    _attrs = ["failureIsolationMethod", "corporateCode", "faultLocatingMethod", "location"]
    _attr_types = {"failureIsolationMethod": str, "corporateCode": str, "faultLocatingMethod": str, "location": str}
    _defaults = {"failureIsolationMethod": "fuse", "corporateCode": '', "faultLocatingMethod": '', "location": ''}
    _enums = {"failureIsolationMethod": "FailureIsolationMethodKind"}
    _refs = []
    _many_refs = []


text:
<?php

namespace PW\UserBundle\Command;

use PW\PostBundle\Document\Post,
    Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand,
    Symfony\Component\Console\Input\InputArgument,
    Symfony\Component\Console\Input\InputInterface,
    Symfony\Component\Console\Output\OutputInterface;

/**
 * Import a user generated from the export command on a different environment
 */
class UserImportCommand extends ContainerAwareCommand
{

    protected $references = array();

    /**
     * configure
     */
    protected function configure()
    {
        $this
            ->setName('user:import')
            ->setDescription('Import a user\'s data network: user, boards and posts')
            ->setDefinition(array(
                new InputArgument(
                    'userId',
                    InputArgument::REQUIRED,
                    'The user id , email, username or name'
                )
            ));
    }

    /**
     * execute
     *
     * Directly insert data into the db to avoid doctrine munging everything.
     * With the exception of posts, which need to be inserted via doctrine to trigger events
     * and be assigned a sequencial id
     *
     * @param InputInterface  $input  instance
     * @param OutputInterface $output instance
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->output = $output;

        $this->dm = $this->getContainer()->get('doctrine_mongodb.odm.document_manager');
        $this->repos['assets'] = $this->dm->getRepository('PWAssetBundle:Asset');
        $this->repos['boards'] = $this->dm->getRepository('PWBoardBundle:Board');
        $this->repos['categories'] = $this->dm->getRepository('PWCategoryBundle:Category');
        $this->repos['posts'] = $this->dm->getRepository('PWPostBundle:Post');
        $this->repos['users'] = $this->dm->getRepository('PWUserBundle:User');

        $host = $this->getContainer()->getParameter('mongodb.default.host');
        $port = $this->getContainer()->getParameter('mongodb.default.port');
        $db = $this->getContainer()->getParameter('mongodb.default.name');

        $m = new \Mongo("mongodb://$host:$port");
        $this->db = $m->selectDB($db);

        $userId = $input->getArgument('userId');

        if (file_exists($userId)) {
            $inputFile = $userId;
        } else {
            $userId = preg_replace("@\W+@", '', $userId);
            $inputFile = 'dump/' . $userId . '.json';
            if (!file_exists($inputFile)) {
                $output->writeln("<error>{$inputFile} doesn't exist</error>");
                return;
            }
        }

        $inputJson = file_get_contents($inputFile);
        if (!$inputJson) {
            $output->writeln("<error>{$inputFile} appears to be empty</error>");
            return;
        }

        $data = json_decode($inputJson, true);
        if (!$data) {
            $output->writeln("<error>{$inputFile} does not contain valid json</error>");
            return;
        }

        $this->convertObjectIds($data);
        $this->convertDates($data);

        $this->processReferences($data);
        $this->processUser($data);
        $this->processBoards($data);
        $this->processPosts($data);

        $output->writeln("\ndone");
    }

    /**
     * processReferences
     *
     * Run over the data array and change id values to point to equivalent data.
     *
     * @param array &$data the full export
     */
    protected function processReferences(&$data)
    {
        $this->references = $data['references'];

        $key = $data['user']['_id'];
        if (!is_string($key)) {
            $key = $key->__toString();
        }
        $this->references['users'][$key]['_id'] = $data['user']['_id'];
        unset($data['references']);
        $this->deReference($data);
    }

    /**
     * processUser
     *
     * Create or update the user record to match the data in the export file
     *
     * @param array &$data the full export
     */
    protected function processUser(&$data)
    {
        $userId = $this->references['users'][$data['user']['_id']->__toString()]['_id'];
        if ($userId) {
            $data['user']['_id'] = $userId;
        } else {
            $userId = $data['user']['_id'];
        }
        $id = $userId->__toString();

        $user = $this->db->users->findOne(array('_id' => $userId));
        if ($user) {
            $this->output->writeln("Updating user record for {$data['user']['username']} (id: $id)");
            unset($data['user']['_id']);
            $this->db->users->update(
                array('_id' => $userId),
                array('$set' => $data['user']),
                array('safe' => true)
            );
        } else {
            $this->output->writeln("Creating user record for {$data['user']['username']} (id: $id)");
            $this->db->users->insert($data['user']);
            $user = $this->db->users->findOne(array('_id' => $userId));
        }
        $data['user']['_id'] = $userId;
    }

    /**
     * processBoards
     *
     * Find or create each board in the export data
     *
     * @param array $data the full export
     */
    protected function processBoards($data)
    {
        foreach ($data['boards'] as $board) {
            $exists = $this->db->boards->findOne(array('_id' => $board['_id']));
            if ($exists) {
                $id = $exists['_id']->__toString();
                $this->output->writeln("Found board {$board['name']} (id: $id)");
            } else {
                $id = $board['_id']->__toString();
                $this->output->writeln("Creating board {$board['name']} (id: $id)");
                $board['postCount'] = 0;
                $this->db->boards->insert($board);
            }
        }

        $this->db->boards->update(
            array('createdBy.$id' => $data['user']['_id']),
            array('$set' => array(
                'createdBy.type' => $data['user']['type']
            )),
            array('multiple' => true, 'safe' => true)
        );
    }

    /**
     * processPosts
     *
     * Find or create each post in the export data
     *
     * @param array $data the full export
     */
    protected function processPosts($data)
    {
        foreach ($data['posts'] as $post) {

            if (!empty($post['parent'])) {
                $this->output->writeln("<error>Ignoring import for repost {$post['description']} (id: {$post['_id']})");
                continue;
            }

            $this->convertReferencesToObjects($post);
            $exists = $this->repos['posts']->createQueryBuilder()
                ->field('board')->references($post['board'])
                ->field('createdBy')->references($post['createdBy'])
                ->field('target')->references($post['target'])
                ->getQuery()->execute()->getSingleResult();
            if ($exists) {
                $id = $exists->getId();
                $board = $exists->getBoard()->getName();
                $this->output->writeln("Found post {$post['description']} on board $board (id: $id)");
            } else {
                $board = $post['board']->getName();
                $this->output->writeln("Creating post {$post['description']} on board $board");
                unset($post['_id']);

                try {
                    $new = new Post($post);
                    $this->dm->persist($new);
                    $this->dm->flush();
                } catch (Exception $e) {
                    $this->output->writeln("<error>" . $e->getMessage() . "</error>");
                }
            }
        }

        $this->db->posts->update(
            array('createdBy.$id' => $data['user']['_id']),
            array('$set' => array(
                    'userType' => $data['user']['type'],
                    'createdBy.type' => $data['user']['type']
            )),
            array('multiple' => true, 'safe' => true)
        );
    }

    /**
     * convert string ids to object ids
     *
     * @param mixed &$input an array, probably
     */
    protected function convertObjectIds(&$input)
    {
        if (!is_array($input)) {
            return;
        }

        if (!empty($input['$id']) && is_string($input['$id'])) {
            if (strlen($input['$id']) === 24) {
                if (array_keys($input) === array('$id')) {
                    $input = new \MongoId($input['$id']);
                    return;
                }
                $input['$id'] = new \MongoId($input['$id']);
            }
            return;
        }

        foreach ($input as &$val) {
            $this->convertObjectIds($val);
        }
    }

    /**
     * convert Dates back to objects
     *
     * @param mixed &$input post array initially
     */
    protected function convertDates(&$input)
    {
        if (!is_array($input)) {
            return;
        }

        if (array_keys($input) === array('sec', 'usec')) {
            $input = new \MongoDate($input['sec']);
            return;
        }

        foreach ($input as &$val) {
            $this->convertDates($val);
        }
    }

    /**
     * convertReferencesToObjects
     *
     * To be able to pass the input array to a doctrine model constructor, convert any references
     * to doctrine objects. This is called as part of the post-creation step.
     *
     * @param mixed &$input post array initially
     */
    protected function convertReferencesToObjects(&$input)
    {
        if (!is_array($input)) {
            return;
        }

        if (empty($input['$id'])) {
            foreach ($input as &$val) {
                $this->convertReferencesToObjects($val);
            }
            return;
        }

        $input = $this->repos[$input['$ref']]->findOneBy(array('_id' => ($input['$id'])));
    }

    /**
     * deReference
     *
     * Take an array and for any record which is a reference to another collection look for and
     * replace the array data with the id of the equivalent object in the target database. This
     * accounts for two categories in different installs, with different ids but the same name;
     * and will replace the id in the input array with the id which exists or has just been created.
     *
     * @param mixed &$input probably an array
     */
    protected function deReference(&$input)
    {
        if (!is_array($input)) {
            return;
        }

        if (!empty($input['$id']) && !empty($input['$ref'])) {
            $id = $this->findReference($input['$ref'], $input['$id']);
            if ($input['$id'] != $id) {
                //$this->output->writeln("Swapping {$input['$ref']} reference from {$input['$id']} to $id");
                $input['$id'] = $id;
            }
            return;
        }

        foreach ($input as &$val) {
            $this->deReference($val);
        }
    }

    /**
     * findReference
     *
     * The export data contains a reference and id. If the id is a mongoid and it exists we can be
     * sure that the record is the same entity as the entity being referenced in the export file.
     * If a record with the same id does not exist, then we need to look for an equilvalent record
     * (to avoid creating duplicates) and if it doesn't exist - only then create it.
     *
     * @param string $collection name
     * @param mixed  $id         mongo id or string
     *
     * @return the id to use
     */
    protected function findReference($collection, $id)
    {
        $key = $id;
        if (!is_string($key)) {
            $key = $key->__toString();
        }
        if (empty($this->references[$collection][$key])) {
            return $id;
        }

        $reference = $this->references[$collection][$key];

        if ($reference['_id'] != $id) {
            return $reference['_id'];
        }

        if (is_object($id)) {
            //$this->output->write("\nlooking for $collection $key");
            $exists = $this->db->$collection->findOne(array('_id' => $id));
            if ($exists) {
                //$this->output->write(" found");
            } else {
                if (!empty($reference['hash'])) {
                    $exists = $this->db->$collection->findOne(array('hash' => $reference['hash']));
                } elseif (!empty($reference['username'])) {
                    $exists = $this->db->$collection->findOne(array('username' => $reference['username']));
                } else {
                    if (!empty($reference['name'])) {
                        if (!empty($reference['type'])) {
                            $exists = $this->db->$collection->findOne(array('name' => $reference['name'], 'type' => $reference['type']));
                        } else {
                            $exists = $this->db->$collection->findOne(array('name' => $reference['name']));
                        }
                    }
                }
                if ($exists) {
                    $id = $exists['_id'];
                    //$this->output->write(" found " . $id);
                    $this->references[$collection][$key]['_id'] = $id;;
                } else {
                    //$this->output->writeln(" creating it");
                    $this->db->$collection->insert($reference);
                }
            }
        } else {
            $this->output->writeln("<error> Cannot check for $collection $key automatically </error>");
            //d("shouldn't get here'");
            //die;
        }

        return $id;
    }
}


text:
""" Spectral analysis of MBSolve results. """

import numpy as np

def freq_list(mb_solve):
    """ Fourier transform of the tlist into the frequency domain for
        spectral analysis.

    Args:
        mb_solve: An MBSolve object.

        Returns:
            Array[num_time_points] of frequency values.

    """

    t_step = mb_solve.tlist[1] - mb_solve.tlist[0]
    f_list = np.fft.fftfreq(len(mb_solve.tlist), t_step)  # FFT Freq
    return np.fft.fftshift(f_list)

def rabi_freq(mb_solve, field_idx):
    """ Fourier transform of the field result of field index.

    Args:
        mb_solve: An MBSolve object.
        field_idx: Field to return FFT of.

    Returns:
        Array[num_z_steps, num_t_steps] Field result in frequency domain.

    """

    rabi_freq_zt = mb_solve.Omegas_zt[field_idx]

    rabi_freq_fft = np.zeros(rabi_freq_zt.shape, dtype=np.complex)

    # TODO: I should be able to do this without the loop by specifying
    # axis?
    for i, Omega_z_i in enumerate(rabi_freq_zt):

        rabi_freq_fft[i] = np.fft.fft(rabi_freq_zt[i])
        rabi_freq_fft[i] = np.fft.fftshift(rabi_freq_fft[i])

    return rabi_freq_fft

def absorption(mb_solve, field_idx, z_idx=-1):
    """ Field absorption in the frequency domain.

    Args:
        mb_solve: An MBSolve object.
        field_idx: Field to return spectrum of.
        z_idx: z step at which to return absorption.

    Returns:
        Array[num_freq_points] of absorption values.

    Note:
        In the linear regime this is the imaginary part of the linear
        susceptibility (with a factor k/2).
        See TP Ogden thesis Eqn (2.58)
    """

    rabi_freq_abs = np.abs(rabi_freq(mb_solve, field_idx))

    return -np.log(rabi_freq_abs[z_idx] / rabi_freq_abs[0])

def dispersion(mb_solve, field_idx, z_idx=-1):
    """ Field dispersion in the frequency domain.

    Args:
        mb_solve: An MBSolve object.
        field_idx: Field to return spectrum of.
        z_idx: z step at which to return absorption.

    Note:
        In the linear regime this is the real part of the linear
        susceptibility.

        See TP Ogden Thesis Eqn (2.59)
    """

    Omega_freq_angle = np.angle(rabi_freq(mb_solve, field_idx))

    return Omega_freq_angle[0] - Omega_freq_angle[z_idx]

def susceptibility_two_linear_known(freq_list, interaction_strength,
        decay_rate):
    """ In the linear regime for a two-level system, the suecpetibility is
        known analytically. This is here for useful comparison, as good
        agreement between a simulated weak field in a two-level system tells us
        that the model is accurate in the linear regime, which gives us
        confidence in the scheme for going beyond the weak field limit.

        Notes:
            See TP Ogden Thesis Eqn(2.61)
    """

    return 1j * interaction_strength / (decay_rate / 2 - 1j * freq_list)

def absorption_two_linear_known(freq_list, interaction_strength, decay_rate):
    """ The absorption is half the imaginary part of the susecptibility. """

    return susceptibility_two_linear_known(freq_list, interaction_strength,
        decay_rate).imag/2.0

def dispersion_two_linear_known(freq_list, interaction_strength, decay_rate):
    """ The dispersion is half the real part of the susecptibility. """

    return susceptibility_two_linear_known(freq_list, interaction_strength,
        decay_rate).real/2.0

def voigt_two_linear_known(freq_list, decay_rate, thermal_width):
    """ Returns the Voigt profile for a two-level system in the linear regime.

    The Voigt profile is the convolution of a Lorentzian with a Gaussian, and
    describes the absorption lineshape for a thermal two-level system.

    Args:
        freq_list: List of frequency detunings from resonance (in 2pi Gamma).
        decay_rate: Spontaneous decay rate of the transition (in 2pi Gamma).
        thermal_width: Width of the lineshape in the same units as decay rate
            (in 2pi Gamma).

    Notes:
        See my thesis section 2.5.6 for more information.
    """
    from scipy.special import wofz
    a = decay_rate/(2*np.pi*thermal_width)
    b = freq_list/(2*np.pi*thermal_width)
    s = 1.0j*(0.5*np.sqrt(np.pi)/(2*np.pi*thermal_width))*wofz(b + 0.5j*a)
    return s


text:
namespace AstonClub.ServiceDiscovery
{
    public class EndPoint
    {
        public string IpAddress { get; internal set; }
        public uint Port { get; internal set; }
    }
}


text:
var React = require('react');
var PropTypes = React.PropTypes;
var ReactRouterBootstrap = require('react-router-bootstrap');
var LinkContainer = ReactRouterBootstrap.LinkContainer;
var Bootstrap = require('react-bootstrap');
var Button = Bootstrap.Button;
var ButtonGroup = Bootstrap.ButtonGroup;

var EntityButtonGroup = React.createClass({
  propTypes: {
    environmentID: PropTypes.string.isRequired,
    services: PropTypes.bool,
    tasks: PropTypes.bool,
    loadBalancers: PropTypes.bool
  },
  getLink: function(entity) {
    return '#/dashboard/' + this.props.environmentID + '/' + entity
  },
  render: function() {
    return (
      <ButtonGroup justified>
        <Button href={this.getLink('services')} active={this.props.services}>Services</Button>
        <Button href={this.getLink('tasks')} active={this.props.tasks}>Tasks</Button>
        <Button href={this.getLink('loadBalancers')} active={this.props.loadBalancers}>Load Balancers</Button>
      </ButtonGroup>
    )
  },
});

module.exports = EntityButtonGroup;


text:
To compare two text files and check for differences, you can use the Unix `diff` command on Linux or Mac OS X:

    diff file1.txt file2.txt

or on Windows the `FC` command:

    FC file1.txt file2.txt

Any number of graphical diff tools are also available, for example FileMerge is part of Apple's free XCode tools.

Although OWL ontology files are text, it's possible to have two identical ontologies saved to two files with very different structure. ROBOT provides a `diff` command that compares two ontologies while ignoring these differences:

    robot diff --left edit.owl --right release.owl

If `--output` is provided then a report will be written with any differences between the two ontologies:

    robot diff --left edit.owl \
      --right release.owl \
      --output results/release-diff.txt

If your left and right ontologies have different catalog files (perhaps pointing to different import files), you can load them with their correct catalog files using `--left-catalog` and `--right-catalog`:

    robot diff --left imports.owl \
      --left-catalog catalog.xml \
      --right imports-right.owl \
      --right-catalog catalog-right.xml \
      --output results/catalog-diff.txt

See [release-diff.txt](/examples/release-diff.txt) for an example.

The default "plain" output is in OWL Functional syntax with IRIs. You can include entity labels with `--labels true`. In addition, Markdown and HTML diff formats (based on Manchester syntax) are available. You can select the desired format using the `--format` (or `-f`) option, with possible values `plain`, `pretty` (text with labels and CURIEs), `html`, or `markdown`.

You can also compare ontologies by IRI with `--left-iri` and `--right-iri`. You may want to compare a local file to a release, in which case:
<!-- DO NOT TEST -->
```
robot diff --left edit.owl \
  --right-iri http://purl.obolibrary.org/obo/release.owl
```

---

## Error Messages

### Double Input Error

You may specify the input with either `--left`/`--right` or `--left-iri`/`--right-iri`, but you may not use both option methods for one side.

### Missing Input Error

Both `--left` and `--right` input ontologies are required.


text:
module Rubex
  module AST
    module Expression
      class InstanceVar < Base
        def initialize(name)
          @name = name
        end

        def analyse_types(local_scope)
          @type = DataType::RubyObject.new
          @has_temp = true
        end

        def generate_evaluation_code(code, local_scope)
          code << "#{@c_code} = rb_iv_get(#{local_scope.self_name}, \"#{@name}\");"
          code.nl
        end

        def generate_assignment_code(rhs, code, local_scope)
          code << "rb_iv_set(#{local_scope.self_name}, \"#{@name}\","
          code << "#{rhs.c_code(local_scope)});"
          code.nl
        end

        def c_code(local_scope)
          code = super
          code << @c_code
          code
        end
      end # class InstanceVar
    end # module Expression
  end # module AST
end # module Rubex


text:
static void _throw_error(int i, int index)
{
	printf("[ERROR] Cannot access element %d, only %d elements exist!\n", index, i);
}

//Clean inside the linked list and free the memory
static void _clean_inside(LinkedList* ll)
{
	imImageDestroy(ll->contents);
	imImageDestroy(ll->thumbnail);

	IupDestroy(ll->iContents);
	IupDestroy(ll->iThumbnail);

	int i;
	for(i = 0; i < ll->cols * ll->rows; i++)
	{
		imImageDestroy(ll->grid[i]);
		IupDestroy(ll->iGrid[i]);
	}

	free(ll);
}

//Get a linked list by index, or throw an error on NULL
LinkedList* LL_get(LinkedList* head, int index)
{
	int i;
	LinkedList *new_loc;
	for(i = 0, new_loc = head; i < index; i++, new_loc = new_loc->next)
	{
		//If the current location is NULL, we have gone too far, so throw an error
		if(new_loc == NULL)
		{
			_throw_error(i,index);
			return NULL;
		}
	}

	//If the current location is still NULL, throw an error
	if(new_loc == NULL)
	{
		_throw_error(i,index);
		return NULL;
	}

	//Return the list
	return new_loc;
}

//Inserts an imImage before the given index
//Given a very big number, it'll just append to the list
//REQUIRES:	loc		A LinkedList pointer; if index is positive, give the head; otherwise, give the tail
//			image	The image to be inserted
//			index	Where to insert the image
//RETURNS:	The just made linked list
LinkedList* LL_insert(LinkedList** loc, imImage* image, int index)
{
	int i;
	LinkedList *old_loc, *new_loc;

	LinkedList *img = malloc(sizeof(LinkedList));
	img->contents = image;
	img->thumbnail = util_get_thumbnail(image);
	img->grid = util_split_to_grid(image, &img->rows, &img->cols);

	img->iContents = IupImageFromImImage(image);
	img->iThumbnail = IupImageFromImImage(img->thumbnail);
	img->iGrid = util_grid_images(img->grid, (img->rows * img->cols));

	//Seek out the address after which to insert the image
	for(i = 0, old_loc = NULL, new_loc = *loc; i < index; i++, old_loc = new_loc, new_loc = new_loc->next)
	{
		//If the current location is NULL, we went too far, so we'll assume we're going to append to it
		if(new_loc == NULL)
			break;
	}

	img->next = new_loc;

	//If the old location is null, then this becomes the head
	if(old_loc == NULL)
		*loc = img;
	//Otherwise, link the old location to this one
	else
		old_loc->next = img;

	return img;
}

//Deletes the linked list and its contents
void LL_remove(LinkedList** head, int index)
{
	int i;
	LinkedList *old_loc, *new_loc;
	for(i = 0, old_loc = NULL, new_loc = *head; i < index; i++, old_loc = new_loc, new_loc = new_loc->next)
	{
		//If the current location is NULL, we have gone too far, so throw an error
		if(new_loc == NULL)
		{
			_throw_error(i,index);
			return;
		}
	}

	//If the current location is still NULL, throw an error
	if(new_loc == NULL)
	{
		_throw_error(i,index);
		return;
	}

	//If we're at the head, try to set the next value as the head (or NULL)
	if(new_loc == *head)
		*head = new_loc->next;
	//Otherwise, replace the previous entry to the one over
	else if(old_loc != NULL)	//TODO: checking if old_loc isn't NULL is redundant because we already checked that it's not at the head
		old_loc->next = new_loc->next;

	//Delete the current entry
	_clean_inside(new_loc);
}

void LL_purge(LinkedList** head)
{
	LinkedList* loc = *head;
	while(loc != NULL)
	{
		LinkedList* old = loc;
		loc = loc->next;
		_clean_inside(old);
	}
	*head = NULL;
}


text:
package com.ikaimen.pattern.ProxyPattern;

/**
 * Created by ChenTao on 2017/7/15.
 * 代理类
 */
public class Proxy implements Subject {
    //需要代理的实现类
    private  Subject subject = null;

    //默认被代理者
    public Proxy(){
        this.subject = new Proxy();
    }

    //通过构造函数传递代理者
    public  Proxy(Object ... objects){

    }

    @Override
    public void request() {
        this.before();
        this.subject.request();
        this.after();

    }

    //预处理
    private void before(){
        //do something
    }

    //善后处理

    private void after(){
        //do somethong
    }
}


text:
module ShipCompliant
  # === ShipCompliant::SearchSalesOrderSummary
  #
  # Wraps the +SalesOrderSummary+ hash with a simple DSL
  # to provide easy access to various keys.
  class SearchSalesOrderSummary < Struct.new(:data)

    # Returns a +DateTime+ from the order +purchase_date+
    def purchase_date
      data[:purchase_date]
    end

    # Returns the +sales_order_key+
    def order_key
      data[:sales_order_key]
    end
    alias_method :sales_order_key, :order_key

    # Returns the parsed hash from the +ShipmentSummary+ element.
    #
    #   {
    #     compliance: 'ValueHere',
    #     requested_ship_date: DateTime,
    #     # etc...
    #   }
    def shipment_summary
      data[:shipments][:shipment_summary]
    end
  end
end


text:
(function() {

    var jsfiles = new Array(
        "util.js",
        "util/color.js",
        "util/style.js",
        "data/AutoCompleteProxy.js",
        "data/AutoCompleteReader.js",
        "data/GroupStyleReader.js",
        "data/RuleGroupReader.js",
        "data/FeatureTypeClassifier.js",
        "data/WFSFeatureStore.js",
        "data/WFSProtocolProxy.js",
        "menu/LayerMenu.js",
        "widgets/CrumbPanel.js",
        "widgets/EmbedMapDialog.js",
        "widgets/FeatureEditPopup.js",
        "widgets/FilterBuilder.js",
        "widgets/QueryPanel.js",
        "widgets/StylePropertiesDialog.js",
        "widgets/WMSLayerPanel.js",
        "widgets/WMSStylesDialog.js",
        "widgets/NewSourceDialog.js",
        "widgets/NewSourceWindow.js",
        "widgets/FillSymbolizer.js",
        "widgets/StrokeSymbolizer.js",
        "widgets/PointSymbolizer.js",
        "widgets/LayerUploadPanel.js",
        "widgets/LineSymbolizer.js",
        "widgets/PolygonSymbolizer.js",
        "widgets/RulePanel.js",
        "widgets/ScaleLimitPanel.js",
        "widgets/TextSymbolizer.js",
        "widgets/Viewer.js",
        "widgets/tree/TreeGridNodeUI.js",
        "widgets/tree/SymbolizerLoader.js",
        "widgets/grid/SymbolizerGrid.js",
        "widgets/form/AutoCompleteComboBox.js",
        "widgets/form/ComparisonComboBox.js",
        "widgets/form/ColorField.js",
        "widgets/form/FilterField.js",
        "widgets/form/FontComboBox.js",
        "widgets/form/GoogleGeocoderComboBox.js",
        "widgets/form/ViewerField.js",
        "widgets/form/ExtendedDateField.js",
        "widgets/grid/CapabilitiesGrid.js",
        "widgets/grid/FeatureGrid.js",
        "widgets/GoogleEarthPanel.js",
        "widgets/GoogleStreetViewPanel.js",
        "widgets/Histogram.js",
        "widgets/tips/SliderTip.js",
        "widgets/slider/TimeSlider.js",
        "widgets/PlaybackToolbar.js",
        "widgets/form/PlaybackModeComboBox.js",
        "widgets/PlaybackOptionsPanel.js",
        "widgets/slider/ClassBreakSlider.js",
        "widgets/TimelinePanel.js",
        "widgets/form/CSWFilterField.js",
        "widgets/CatalogueSearchPanel.js",
        "widgets/ScaleOverlay.js",
        "plugins/LayerSource.js",
        "plugins/BingSource.js",
        "plugins/WMSSource.js",
        "plugins/WMSCSource.js",
        "plugins/OSMSource.js",
        "plugins/GoogleSource.js",
        "plugins/OLSource.js",
        "plugins/MapBoxSource.js",
        "plugins/MapQuestSource.js",
        "plugins/CatalogueSource.js",
        "plugins/CSWCatalogueSource.js",
        "plugins/GeoNodeCatalogueSource.js",
        "plugins/TMSSource.js",
        "plugins/StyleWriter.js",
        "plugins/GeoServerStyleWriter.js",
        "plugins/Tool.js",
        "plugins/ClickableFeatures.js",
        "plugins/DeleteSelectedFeatures.js",
        "plugins/GoogleGeocoder.js",
        "plugins/GoogleEarth.js",
        "plugins/WMSFilterView.js",
        "plugins/WMSRasterStylesDialog.js",
        "plugins/WMSGetFeatureInfo.js",
        "plugins/FormFieldHelp.js",
        "plugins/SchemaAnnotations.js",
        "plugins/FeatureEditorGrid.js",
        "plugins/FeatureEditorForm.js",
        "plugins/VersionedEditor.js",
        "plugins/FeatureEditor.js",
        "plugins/FeatureGrid.js",
        "plugins/FeatureManager.js",
        "plugins/FeatureToField.js",
        "plugins/QueryForm.js",
        "plugins/LayerTree.js",
        "plugins/LayerManager.js",
        "plugins/AddLayers.js",
        "plugins/RemoveLayer.js",
        "plugins/SelectedFeatureActions.js",
        "plugins/SnappingAgent.js",
        "plugins/Styler.js",
        "plugins/NavigationHistory.js",
        "plugins/Zoom.js",
        "plugins/ZoomToExtent.js",
        "plugins/ZoomToDataExtent.js",
        "plugins/ZoomToLayerExtent.js",
        "plugins/ZoomToSelectedFeatures.js",
        "plugins/Measure.js",
        "plugins/Navigation.js",
        "plugins/LayerProperties.js",
        "plugins/MapProperties.js",
        "plugins/Legend.js",
        "plugins/Print.js",
        "plugins/LoadingIndicator.js",
        "plugins/Playback.js",
        "ColorManager.js",
        "locale/es.js",
        "locale/ca.js"
    );

    var scripts = document.getElementsByTagName("script");
    var parts = scripts[scripts.length-1].src.split("/");
    parts.pop();
    var path = parts.join("/");

    var len = jsfiles.length;
    var pieces = new Array(len);

    for (var i=0; i<len; i++) {
        pieces[i] = "<script src='" + path + "/" + jsfiles[i] + "'></script>";
    }
    document.write(pieces.join(""));

    if (GeoExt.Lang) {
        GeoExt.Lang.set(OpenLayers.Util.getParameters()["lang"] || GeoExt.Lang.locale);
    }

})();


text:
supported on:
- Opera 9
graceful degeneration to text input

An e-mail address, following the format of the addr-spec  token defined in RFC 2822 section 3.4.1 [RFC2822], but excluding the CFWS  subtoken everywhere, and excluding the FWS subtoken everywhere except in the quoted-string subtoken. UAs could, for example, offer e-mail addresses from the user's address book. (See below for notes on IDN.)


text:
package com.vladmihalcea.book.hpjp.spring.transaction.hibernate.service;

import com.vladmihalcea.book.hpjp.hibernate.forum.dto.PostDTO;
import com.vladmihalcea.book.hpjp.hibernate.transaction.forum.Post;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Vlad Mihalcea
 */
@Service
public interface ForumService {

    Post newPost(String title, String... tags);

    List<Post> findAllByTitle(String title);

    Post findById(Long id);

    PostDTO getPostDTOById(Long id);

    void processData();
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Unify | Welcome...</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/plugins/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/css/style.css">
    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/css/headers/header1.css">
    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/plugins/bootstrap/css/bootstrap-responsive.min.css">
    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/css/style_responsive.css">
    <link rel="shortcut icon" href="http://htmlstream.com/unify/favicon.ico">

    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/plugins/font-awesome/css/font-awesome.css">
    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/css/img-hover-effect.css">

    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/css/themes/default.css" id="style_color">
    <link rel="stylesheet" href="http://htmlstream.com/unify/assets/css/themes/headers/default.css" id="style_color-header-1">

Theme Colors

Languages

English

Spanish

Russian

German

Help

Login

                            Home

Option1: Landing Page

Option2: Header Option

Option3: Revolution Slider

Option4: Amazing Content

Option5: Mixed Content

Option6: Content with Sidebar

Option7: Aplle Style Slider

Home All In One

                            Pages

About Us

Services

Pricing

Coming Soon

FAQs

Search Result

Gallery

Registration

Login

404

Clients

Privacy Policy

Terms of Service

2 Columns (Left)

2 Columns (Right)

                            Features

Grid Layout

Typography

Thumbnails

Components

Navigation

Tables

Forms

Icons

Buttons

                            Portfolio

Portfolio

Portfolio Item

Portfolio 2 Columns

Portfolio 3 Columns

Portfolio 4 Columns

                            Blog

Blog

Blog Item

Blog Left Sidebar

Blog Item Left Sidebar

                            Contact

Contact Default

Contact Boxed Map

                            <form>
                                <input type="text" class="span3" placeholder="Search">
                                <button type="submit" class="btn-u">Go</button>
                            </form>

Nuestros Talleres

Home /

Portfolio /

Nuestros Talleres

Desarrollo de Software

At vero eos et accusamus et iusto odio dignissimos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

                Read More

Dibujo Técnico

At vero eos et accusamus et iusto odio dignissimos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

                Read More

Ebanisteria

At vero eos et accusamus et iusto odio dignissimos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

                Read More

Electricidad

At vero eos et accusamus et iusto odio dignissimos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

                Read More

Mecanica Automotriz

At vero eos et accusamus et iusto odio dignissimos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

                Read More

Mecanica Industrial

At vero eos et accusamus et iusto odio dignissimos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

                Read More

Metalisteria

At vero eos et accusamus et iusto odio dignissimos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

                Read More

Sistemas

At vero eos et accusamus et iusto odio dignissimos dolores et quas molestias excepturi sint occaecati cupiditate non provident.

                Read More

About

Unify is an incredibly beautiful responsive Bootstrap Template for corporate and creative professionals.

Monthly Newsletter

Subscribe to our newsletter and stay up to date with the latest news and deals!

				<form class="form-inline">

						<input type="text" placeholder="Email Address" class="input-medium">
						<button class="btn-u">Subscribe</button>

				</form>

Recent Blog Entries

Anim moon officia Unify is an incredibly beautiful responsive Bootstrap Template

Anim moon officia Unify is an incredibly beautiful responsive Bootstrap Template

Anim moon officia Unify is an incredibly beautiful responsive Bootstrap Template

Contact Us

                <address>
					25, Lorem Lis Street, Orange

					California, US

					Phone: 800 123 3456

					Fax: 800 123 3456

					Email: info@anybiz.com
                </address>

Stay Connected

2013 © Unify. ALL Rights Reserved. Privacy Policy | Terms of Service


text:
#include "test/core/end2end/end2end_tests.h"

#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>

#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/http/server/http_server_filter.h"
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/gpr/host_port.h"
#include "src/core/lib/surface/channel.h"
#include "src/core/lib/surface/server.h"
#include "test/core/util/port.h"
#include "test/core/util/test_config.h"

typedef struct fullstack_compression_fixture_data {
  char* localaddr;
  grpc_channel_args* client_args_compression;
  grpc_channel_args* server_args_compression;
} fullstack_compression_fixture_data;

static grpc_end2end_test_fixture chttp2_create_fixture_fullstack_compression(
    grpc_channel_args* client_args, grpc_channel_args* server_args) {
  grpc_end2end_test_fixture f;
  int port = grpc_pick_unused_port_or_die();
  fullstack_compression_fixture_data* ffd =
      static_cast<fullstack_compression_fixture_data*>(
          gpr_malloc(sizeof(fullstack_compression_fixture_data)));
  memset(ffd, 0, sizeof(fullstack_compression_fixture_data));

  gpr_join_host_port(&ffd->localaddr, "localhost", port);

  memset(&f, 0, sizeof(f));
  f.fixture_data = ffd;
  f.cq = grpc_completion_queue_create_for_next(nullptr);
  f.shutdown_cq = grpc_completion_queue_create_for_pluck(nullptr);

  return f;
}

void chttp2_init_client_fullstack_compression(grpc_end2end_test_fixture* f,
                                              grpc_channel_args* client_args) {
  fullstack_compression_fixture_data* ffd =
      static_cast<fullstack_compression_fixture_data*>(f->fixture_data);
  if (ffd->client_args_compression != nullptr) {
    grpc_core::ExecCtx exec_ctx;
    grpc_channel_args_destroy(ffd->client_args_compression);
  }
  ffd->client_args_compression = grpc_channel_args_set_compression_algorithm(
      client_args, GRPC_COMPRESS_GZIP);
  f->client = grpc_insecure_channel_create(
      ffd->localaddr, ffd->client_args_compression, nullptr);
}

void chttp2_init_server_fullstack_compression(grpc_end2end_test_fixture* f,
                                              grpc_channel_args* server_args) {
  fullstack_compression_fixture_data* ffd =
      static_cast<fullstack_compression_fixture_data*>(f->fixture_data);
  if (ffd->server_args_compression != nullptr) {
    grpc_core::ExecCtx exec_ctx;
    grpc_channel_args_destroy(ffd->server_args_compression);
  }
  ffd->server_args_compression = grpc_channel_args_set_compression_algorithm(
      server_args, GRPC_COMPRESS_GZIP);
  if (f->server) {
    grpc_server_destroy(f->server);
  }
  f->server = grpc_server_create(ffd->server_args_compression, nullptr);
  grpc_server_register_completion_queue(f->server, f->cq, nullptr);
  GPR_ASSERT(grpc_server_add_insecure_http2_port(f->server, ffd->localaddr));
  grpc_server_start(f->server);
}

void chttp2_tear_down_fullstack_compression(grpc_end2end_test_fixture* f) {
  grpc_core::ExecCtx exec_ctx;
  fullstack_compression_fixture_data* ffd =
      static_cast<fullstack_compression_fixture_data*>(f->fixture_data);
  grpc_channel_args_destroy(ffd->client_args_compression);
  grpc_channel_args_destroy(ffd->server_args_compression);
  gpr_free(ffd->localaddr);
  gpr_free(ffd);
}

/* All test configurations */
static grpc_end2end_test_config configs[] = {
    {"chttp2/fullstack_compression",
     FEATURE_MASK_SUPPORTS_DELAYED_CONNECTION |
         FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL |
         FEATURE_MASK_SUPPORTS_AUTHORITY_HEADER,
     nullptr, chttp2_create_fixture_fullstack_compression,
     chttp2_init_client_fullstack_compression,
     chttp2_init_server_fullstack_compression,
     chttp2_tear_down_fullstack_compression},
};

int main(int argc, char** argv) {
  size_t i;

  grpc_test_init(argc, argv);
  grpc_end2end_tests_pre_init();
  grpc_init();

  for (i = 0; i < sizeof(configs) / sizeof(*configs); i++) {
    grpc_end2end_tests(argc, argv, configs[i]);
  }

  grpc_shutdown();

  return 0;
}


text:
package com.iflytek.weef.dto;

import java.io.Serializable;

/**
 * Created by czhu2 on 2017/7/31.
 */
public class OutRuleDto  implements Serializable{
    private Long id;

    private String cityCode;/*城市英文字符标识*/

    private String cityName;/*城市中文标识*/

    //get,set
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
}