text:
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from msrestazure.azure_operation import AzureOperationPoller
import uuid

from .. import models

class ServerKeysOperations(object):
    """ServerKeysOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An objec model deserializer.
    :ivar api_version: The API version to use for the request. Constant value: "2015-05-01-preview".
    """

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "2015-05-01-preview"

        self.config = config

    def list_by_server(
            self, resource_group_name, server_name, custom_headers=None, raw=False, **operation_config):
        """Returns a list of server keys.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param server_name: The name of the server.
        :type server_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`ServerKeyPaged <azure.mgmt.sql.models.ServerKeyPaged>`
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/keys'
                path_format_arguments = {
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
                    'serverName': self._serialize.url("server_name", server_name, 'str'),
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.ServerKeyPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.ServerKeyPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized

    def get(
            self, resource_group_name, server_name, key_name, custom_headers=None, raw=False, **operation_config):
        """Returns a server key.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param server_name: The name of the server.
        :type server_name: str
        :param key_name: The name of the server key to be retrieved.
        :type key_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`ServerKey <azure.mgmt.sql.models.ServerKey>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/keys/{keyName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'serverName': self._serialize.url("server_name", server_name, 'str'),
            'keyName': self._serialize.url("key_name", key_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ServerKey', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

    def create_or_update(
            self, resource_group_name, server_name, key_name, parameters, custom_headers=None, raw=False, **operation_config):
        """Creates or updates a server key.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param server_name: The name of the server.
        :type server_name: str
        :param key_name: The name of the server key to be operated on (updated
         or created). The key name is required to be in the format of
         'vault_key_version'. For example, if the keyId is
         https://YourVaultName.vault.azure.net/keys/YourKeyName/01234567890123456789012345678901,
         then the server key name should be formatted as:
         YourVaultName_YourKeyName_01234567890123456789012345678901
        :type key_name: str
        :param parameters: The requested server key resource state.
        :type parameters: :class:`ServerKey <azure.mgmt.sql.models.ServerKey>`
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :rtype:
         :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
         instance that returns :class:`ServerKey
         <azure.mgmt.sql.models.ServerKey>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/keys/{keyName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'serverName': self._serialize.url("server_name", server_name, 'str'),
            'keyName': self._serialize.url("key_name", key_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(parameters, 'ServerKey')

        # Construct and send request
        def long_running_send():

            request = self._client.put(url, query_parameters)
            return self._client.send(
                request, header_parameters, body_content, **operation_config)

        def get_long_running_status(status_link, headers=None):

            request = self._client.get(status_link)
            if headers:
                request.headers.update(headers)
            return self._client.send(
                request, header_parameters, **operation_config)

        def get_long_running_output(response):

            if response.status_code not in [200, 202, 201]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            deserialized = None

            if response.status_code == 200:
                deserialized = self._deserialize('ServerKey', response)
            if response.status_code == 201:
                deserialized = self._deserialize('ServerKey', response)

            if raw:
                client_raw_response = ClientRawResponse(deserialized, response)
                return client_raw_response

            return deserialized

        if raw:
            response = long_running_send()
            return get_long_running_output(response)

        long_running_operation_timeout = operation_config.get(
            'long_running_operation_timeout',
            self.config.long_running_operation_timeout)
        return AzureOperationPoller(
            long_running_send, get_long_running_output,
            get_long_running_status, long_running_operation_timeout)

    def delete(
            self, resource_group_name, server_name, key_name, custom_headers=None, raw=False, **operation_config):
        """Deletes the server key with the given name.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param server_name: The name of the server.
        :type server_name: str
        :param key_name: The name of the server key to be deleted.
        :type key_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :rtype:
         :class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
         instance that returns None
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/keys/{keyName}'
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'serverName': self._serialize.url("server_name", server_name, 'str'),
            'keyName': self._serialize.url("key_name", key_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        def long_running_send():

            request = self._client.delete(url, query_parameters)
            return self._client.send(request, header_parameters, **operation_config)

        def get_long_running_status(status_link, headers=None):

            request = self._client.get(status_link)
            if headers:
                request.headers.update(headers)
            return self._client.send(
                request, header_parameters, **operation_config)

        def get_long_running_output(response):

            if response.status_code not in [200, 202, 204]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            if raw:
                client_raw_response = ClientRawResponse(None, response)
                return client_raw_response

        if raw:
            response = long_running_send()
            return get_long_running_output(response)

        long_running_operation_timeout = operation_config.get(
            'long_running_operation_timeout',
            self.config.long_running_operation_timeout)
        return AzureOperationPoller(
            long_running_send, get_long_running_output,
            get_long_running_status, long_running_operation_timeout)


text:
package org.olat.presentation.ims.cp;

import org.olat.presentation.framework.core.components.tree.TreeNode;
import org.olat.system.event.Event;

public class TreeNodeEvent extends Event {

    private final TreeNode chosenTreeNode;

    TreeNodeEvent(final TreeNode chosenTreeNode) {
        super("newtreenode");
        this.chosenTreeNode = chosenTreeNode;
    }

    /**
     * @return chosen tree node
     */
    public TreeNode getChosenTreeNode() {
        return chosenTreeNode;
    }

}

redpajama_set_name: RedPajamaGithub


text:
var Q_NAME = window["CONSTANTS"]["Q_NAME"];

// Title Notification
var intervalId;
var timeoutId;
Tracker.autorun(function(){

  clearInterval(intervalId);
  setDocumentTitle(Q_NAME);

  if (authorized.user()){
    var claimedTicket = Tickets.findOne({
      userId: Meteor.userId(),
      status: 'CLAIMED'
    });
    if (claimedTicket){
      var message = claimedTicket.claimName + " claimed your ticket!";

      // Desktop Notification
      notifyDesktop(message);

      intervalId = setInterval(function(){
        setDocumentTitle("(\u2713) " + Q_NAME);
        timeoutId = setTimeout(function(){
          setDocumentTitle(message);
        },1500)
      },3000);
    } else {
      setDocumentTitle(Q_NAME);
    }
  }

});

Tracker.autorun(function(){
  if (authorized.mentor()){
    var activeCount = Tickets.find({
      status: 'OPEN'
    }).count();
    setDocumentTitle("(" + activeCount + ") " + Q_NAME);
  }
});

function setDocumentTitle(text){
  document.title = text;
}

// Desktop Notifications
Tracker.autorun(function(){
  if (authorized.user()){
    // Check to see if the browser supports Notifications
    if (window["Notification"]){
      // Request permission
      Notification.requestPermission();
    }
  }
});

function notifyDesktop(body){
  if (window["Notification"]){
    if (Notification.permission == "granted"){
      var notification = new Notification(Q_NAME, {
        icon: CONSTANTS.NOTIFICATION_ICON,
        body: body
      });
    }
  }
}


text:
Ruby binding to OpenSLP (Service Location Protocol) library.

[![Gem Version](https://badge.fury.io/rb/slp.svg)](http://badge.fury.io/rb/slp)
[![Build Status](https://travis-ci.org/ManageIQ/slp.svg)](https://travis-ci.org/ManageIQ/slp)
[![Code Climate](http://img.shields.io/codeclimate/github/ManageIQ/slp.svg)](https://codeclimate.com/github/ManageIQ/slp)
[![Dependency Status](https://gemnasium.com/ManageIQ/slp.svg)](https://gemnasium.com/ManageIQ/slp)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'slp'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install slp

## Usage

`SLP` supports the following instance methods.

- open (on initialize)
- close
- find_services
- find_attributes
- parse_service_url

See [examples](examples)

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/ManageIQ/slp.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
namespace phi {

template <typename T, typename Context>
void AbsGradKernel(const Context& ctx,
                   const DenseTensor& x,
                   const DenseTensor& dout,
                   DenseTensor* dx);

template <typename T, typename Context>
void AbsDoubleGradKernel(const Context& ctx,
                         const DenseTensor& x,
                         const DenseTensor& ddx,
                         DenseTensor* ddout);

}  // namespace phi


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.components.scripts;

import com.google.appinventor.common.utils.StringUtils;
import com.google.appinventor.components.annotations.DesignerProperty;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import javax.tools.Diagnostic;
import javax.tools.FileObject;

/**
 * Tool to generate simple component descriptors as JSON.
 *
 * The output is a sequence of component descriptions enclosed in square
 * brackets and separated by commas. Each component description has the
 * following format:
 * { "name": "COMPONENT-TYPE-NAME",
 *   "version": "VERSION",
 *   "categoryString": "PALETTE-CATEGORY",
 *   "helpString": "DESCRIPTION",
 *   "showOnPalette": "true"|"false",
 *   "nonVisible": "true"|"false",
 *   "iconName": "ICON-FILE-NAME",
 *   "properties": [
 *     { "name": "PROPERTY-NAME",
 *        "editorType": "EDITOR-TYPE",
 *        "defaultValue": "DEFAULT-VALUE"},*
 *    ],
 *   "blockProperties": [
 *     { "name": "PROPERTY-NAME",
 *        "description": "DESCRIPTION",
 *        "type": "YAIL-TYPE",
 *        "rw": "read-only"|"read-write"|"write-only"|"invisible"},*
 *   ],
 *   "events": [
 *     { "name": "EVENT-NAME",
 *       "description": "DESCRIPTION",
 *       "params": [
 *         { "name": "PARAM-NAME",
 *           "type": "YAIL-TYPE"},*
 *       ]},+
 *   ],
 *   "methods": [
 *     { "name": "METHOD-NAME",
 *       "description": "DESCRIPTION",
 *       "params": [
 *         { "name": "PARAM-NAME",
 *       "type": "YAIL-TYPE"},*
 *     ]},+
 *   ]
 * }
 *
 * @author lizlooney@google.com (Liz Looney)
 * @author sharon@google.com (Sharon Perl) - added events, methods, non-designer
 *   properties (for use by browser-based blocks editor)
 */
public final class ComponentDescriptorGenerator extends ComponentProcessor {
  // Where to write results.
  private static final String OUTPUT_FILE_NAME = "simple_components.json";

  private void outputComponent(ComponentInfo component, StringBuilder sb) {
    sb.append("{ \"name\": \"");
    sb.append(component.name);
    sb.append("\",\n  \"version\": \"");
    sb.append(component.getVersion());
    sb.append("\",\n  \"categoryString\": \"");
    sb.append(component.getCategoryString());
    sb.append("\",\n  \"helpString\": ");
    sb.append(formatDescription(component.getHelpDescription()));
    sb.append(",\n  \"showOnPalette\": \"");
    sb.append(component.getShowOnPalette());
    sb.append("\",\n  \"nonVisible\": \"");
    sb.append(component.getNonVisible());
    sb.append("\",\n  \"iconName\": \"");
    sb.append(component.getIconName());
    sb.append("\",\n  \"properties\": [");
    String separator = "";
    for (Map.Entry<String, DesignerProperty> entry : component.designerProperties.entrySet()) {
      String propertyName = entry.getKey();
      DesignerProperty dp = entry.getValue();
      sb.append(separator);
      outputProperty(propertyName, dp, sb);
      separator = ",\n";
    }
    // We need additional information about properties in the blocks editor,
    // and we need all of them, not just the Designer properties. We output
    // the entire set separately for use by the blocks editor to keep things simple.
    sb.append("],\n  \"blockProperties\": [");
    separator = "";
    for (Property prop : component.properties.values()) {
      sb.append(separator);
      // Output properties that are not user-visible, but mark them as invisible
      // Note: carrying this over from the old Java blocks editor. I'm not sure
      // that we'll actually do anything with invisible properties in the blocks
      // editor. (sharon@google.com)
      outputBlockProperty(prop.name, prop, sb);
      separator = ",\n    ";
    }
    sb.append("],\n  \"events\": [");
    separator = "";
    for (Event event : component.events.values()) {
      sb.append(separator);
      outputBlockEvent(event.name, event, sb, !event.userVisible);
      separator = ",\n    ";
    }
    sb.append("],\n  \"methods\": [");
    separator = "";
    for (Method method : component.methods.values()) {
      sb.append(separator);
      outputBlockMethod(method.name, method, sb, !method.userVisible);
      separator = ",\n    ";
    }
    sb.append("]}\n");
  }

  private void outputProperty(String propertyName, DesignerProperty dp, StringBuilder sb) {
    sb.append("{ \"name\": \"");
    sb.append(propertyName);
    sb.append("\", \"editorType\": \"");
    sb.append(dp.editorType());
    sb.append("\", \"defaultValue\": \"");
    sb.append(dp.defaultValue().replace("\"", "\\\""));
    sb.append("\"}");
  }

  private void outputBlockProperty(String propertyName, Property prop, StringBuilder sb) {
    sb.append("{ \"name\": \"");
    sb.append(propertyName);
    sb.append("\", \"description\": ");
    sb.append(formatDescription(prop.getDescription()));
    sb.append(", \"type\": \"");
    sb.append(javaTypeToYailType(prop.getType()));
    sb.append("\", \"rw\": \"");
    sb.append(prop.isUserVisible() ? prop.getRwString() : "invisible");
    sb.append("\"}");
  }

  private void outputBlockEvent(String eventName, Event event, StringBuilder sb,
                                boolean deprecated) {
    sb.append("{ \"name\": \"");
    sb.append(eventName);
    sb.append("\", \"description\": ");
    sb.append(formatDescription(event.description));
    sb.append(", \"deprecated\": \"" + deprecated + "\"");
    sb.append(", \"params\": ");
    outputParameters(event.parameters, sb);
    sb.append("}\n");
  }

  private void outputBlockMethod(String methodName, Method method, StringBuilder sb,
                                 boolean deprecated) {
    sb.append("{ \"name\": \"");
    sb.append(methodName);
    sb.append("\", \"description\": ");
    sb.append(formatDescription(method.description));
    sb.append(", \"deprecated\": \"" + deprecated + "\"");
    sb.append(", \"params\": ");
    outputParameters(method.parameters, sb);
    if (method.getReturnType() != null) {
      sb.append(", \"returnType\": \"");
      sb.append(javaTypeToYailType(method.getReturnType()));
      sb.append("\"}");
    } else {
      sb.append("}");
    }
  }

  /*
   *  Output a parameter list (including surrounding [])
   */
  private void outputParameters(List<Parameter> params, StringBuilder sb) {
    sb.append("[");
    String separator = "";
    for (Parameter p : params) {
      sb.append(separator);
      sb.append("{ \"name\": \"");
      sb.append(p.name);
      sb.append("\", \"type\": \"");
      sb.append(javaTypeToYailType(p.type));
      sb.append("\"}");
      separator = ",";
    }
    sb.append("]");
  }

  @Override
  protected void outputResults() throws IOException {
    StringBuilder sb = new StringBuilder();

    sb.append('[');
    String separator = "";

    // Components are already sorted.
    for (Map.Entry<String, ComponentInfo> entry : components.entrySet()) {
      ComponentInfo component = entry.getValue();
      sb.append(separator);
      outputComponent(component, sb);
      separator = ",\n";
    }

    sb.append(']');

    FileObject src = createOutputFileObject(OUTPUT_FILE_NAME);
    Writer writer = src.openWriter();
    writer.write(sb.toString());
    writer.flush();
    writer.close();
    messager.printMessage(Diagnostic.Kind.NOTE, "Wrote file " + src.toUri());
  }

  /*
   * Format a description string as a json string. Note that the returned value
   * include surrounding double quotes.
   */
  private static String formatDescription(String description) {
    return StringUtils.toJson(description);
  }
}


text:
from django.contrib import admin

from django_peeringdb.models import (
    Facility,
    InternetExchange,
    InternetExchangeFacility,
    IXLan,
    IXLanPrefix,
    Network,
    NetworkContact,
    NetworkFacility,
    NetworkIXLan,
    Organization,
)

class HandleRefAdminMixIn:
    """Dummy MixIn that just hides HandleRef's fields."""

    exclude = ("status", "version")

class ModelAdminBase(HandleRefAdminMixIn, admin.ModelAdmin):
    def has_change_permission(self, request, obj=None):
        """Make everything read-only, as this is PeeringDB's data."""
        return False

# Organization view
class NetworkInline(HandleRefAdminMixIn, admin.TabularInline):
    model = Network
    fields = ("asn", "name", "aka")
    show_change_link = True

@admin.register(Organization)
class OrganizationAdmin(ModelAdminBase):
    search_fields = ("name",)
    list_display = ("name", "website")
    inlines = [
        NetworkInline,
    ]

# Facility view
@admin.register(Facility)
class FacilityAdmin(ModelAdminBase):
    search_fields = ("name", "address1")
    list_display = ("name", "org", "city", "address1")

# Network views
class NetworkContactInline(HandleRefAdminMixIn, admin.TabularInline):
    model = NetworkContact

class NetworkFacilityInline(HandleRefAdminMixIn, admin.TabularInline):
    model = NetworkFacility

class NetworkIXLanInline(HandleRefAdminMixIn, admin.TabularInline):
    model = NetworkIXLan

@admin.register(Network)
class NetworkAdmin(ModelAdminBase):
    search_fields = ("name", "aka", "asn")
    list_display = ("name", "aka", "asn")
    inlines = [
        NetworkFacilityInline,
        NetworkContactInline,
        NetworkIXLanInline,
    ]

# IX views
class IXLanInline(HandleRefAdminMixIn, admin.StackedInline):
    model = IXLan
    show_change_link = True

class InternetExchangeFacilityInline(HandleRefAdminMixIn, admin.TabularInline):
    model = InternetExchangeFacility

@admin.register(InternetExchange)
class InternetExchangeAdmin(ModelAdminBase):
    search_fields = (
        "name",
        "name_long",
    )
    list_display = ("name", "name_long", "city")
    inlines = [
        InternetExchangeFacilityInline,
        IXLanInline,
    ]

# IXLan views
class IXLanPrefixInline(HandleRefAdminMixIn, admin.StackedInline):
    model = IXLanPrefix

@admin.register(IXLan)
class IXLanAdmin(ModelAdminBase):
    search_fields = ("name", "ix__name")
    list_display = ("__str__", "ix")
    inlines = [
        IXLanPrefixInline,
    ]


text:
SELECT
    wiki,
    month,
    user_id,
    user_name,
    user_registration,
    SUM(revisions * archived) AS archived,
    SUM(revisions) AS revisions
FROM (
    SELECT
        LEFT(rev_timestamp, 6) AS month,
        DATABASE() AS wiki,
        rev_user AS user_id,
        FALSE AS archived,
        COUNT(*) AS revisions
    FROM revision
    GROUP BY LEFT(rev_timestamp, 6), rev_user

    UNION ALL

    SELECT
        LEFT(ar_timestamp, 6) AS month,
        DATABASE() AS wiki,
        ar_user AS user_id,
        TRUE AS archived,
        COUNT(*) AS revisions
    FROM archive
    GROUP BY LEFT(ar_timestamp, 6), ar_user
) AS editor_months
INNER JOIN user USING (user_id)
GROUP BY wiki, month, user_id
ORDER BY wiki, month;


text:
package com.github.daytron.revworks.view.main;

import com.github.daytron.revworks.data.ExternalLink;
import com.vaadin.server.ExternalResource;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.VerticalLayout;

/**
 * UI widget component for dashboard footer.
 *
 * @author Ryan Gilera
 */
@SuppressWarnings("serial")
public class FooterComponent extends VerticalLayout {

    /**
     * A class constructor that builds its UI components upon object creation.
     */
    public FooterComponent() {
        setWidth("100%");
        setSpacing(true);
        setStyleName("dashboard-footer");

        addComponent(createPrimaryLinks());
        addComponent(createBottomRow());
    }

    /**
     * Creates the top row of the footer and adds external links.
     *
     * @return HorizontalLayout object
     */
    private HorizontalLayout createPrimaryLinks() {
        final HorizontalLayout linkLayout = new HorizontalLayout();
        linkLayout.setWidth("100%");
        linkLayout.setSpacing(true);

        Label leftSpaceLabel = new Label(" ");
        leftSpaceLabel.setSizeFull();
        linkLayout.addComponent(leftSpaceLabel);

        Link gsmLondonMainLinkButton = new Link(ExternalLink.GSM_LONDON.getName(),
                new ExternalResource(ExternalLink.GSM_LONDON.getLink()));
        gsmLondonMainLinkButton.setTargetName("_blank");
        gsmLondonMainLinkButton.setSizeUndefined();

        Link studentPortalLinkButton = new Link(ExternalLink.STUDENT_PORTAL.getName(),
                new ExternalResource(ExternalLink.STUDENT_PORTAL.getLink()));
        studentPortalLinkButton.setTargetName("_blank");
        studentPortalLinkButton.setSizeUndefined();

        Link lecturerPortalLinkButton = new Link(ExternalLink.LECTURER_PORTAL.getName(),
                new ExternalResource(ExternalLink.LECTURER_PORTAL.getLink()));
        lecturerPortalLinkButton.setTargetName("_blank");
        lecturerPortalLinkButton.setSizeUndefined();

        Link gsmLearnLinkButton = new Link(ExternalLink.GSM_LEARN.getName(),
                new ExternalResource(ExternalLink.GSM_LEARN.getLink()));
        gsmLearnLinkButton.setTargetName("_blank");
        gsmLearnLinkButton.setSizeUndefined();

        linkLayout.addComponents(gsmLondonMainLinkButton, studentPortalLinkButton,
                lecturerPortalLinkButton, gsmLearnLinkButton);

        Label rightSpaceLabel = new Label(" ");
        rightSpaceLabel.setSizeFull();
        linkLayout.addComponent(rightSpaceLabel);

        linkLayout.setExpandRatio(leftSpaceLabel, 1);
        linkLayout.setExpandRatio(rightSpaceLabel, 1);

        return linkLayout;
    }

    /**
     * Creates the bottom row of the footer and adds external links.
     *
     * @return HorizontalLayout object
     */
    private HorizontalLayout createBottomRow() {
        final HorizontalLayout bottomRowLayout = new HorizontalLayout();
        bottomRowLayout.setWidth("100%");

        Label firstSpace = new Label(" ");
        firstSpace.setSizeFull();

        Label allRightsReservedLabel = new Label();
        allRightsReservedLabel.setValue("All Rights Reserved 2015. Created by Ryan Gilera [");
        allRightsReservedLabel.setSizeUndefined();

        Link githubLink = new Link(ExternalLink.MY_GITHUB_PAGE.getName(),
                new ExternalResource(ExternalLink.MY_GITHUB_PAGE.getLink()));
        githubLink.setTargetName("_blank");
        githubLink.setSizeUndefined();

        Label midBracketLabel = new Label("] [");
        midBracketLabel.setSizeUndefined();

        Link linkedinLink = new Link(ExternalLink.MY_LINKEDIN_PAGE.getName(),
                new ExternalResource(ExternalLink.MY_LINKEDIN_PAGE.getLink()));
        linkedinLink.setTargetName("_blank");
        linkedinLink.setSizeUndefined();

        Label endOfLabel = new Label("]");
        endOfLabel.setSizeFull();

        bottomRowLayout.addComponents(firstSpace, allRightsReservedLabel,
                githubLink, midBracketLabel, linkedinLink, endOfLabel);
        bottomRowLayout.setExpandRatio(firstSpace, 1);
        bottomRowLayout.setExpandRatio(endOfLabel, 1);
        return bottomRowLayout;
    }

}


text:
using System;
public class runme {
  static void Main() {
    ribclient.Begin("csharp.rib");
    ribclient.End();
  }
}


text:
'use strict'

const { expect } = require('../utils/mocha')

const isBigInt = (n) => {
  return n.constructor.name === 'BigNumber'
}

exports.expectIsBitswap = (err, stats) => {
  expect(err).to.not.exist()
  expect(stats).to.exist()
  expect(stats).to.have.a.property('provideBufLen')
  expect(stats).to.have.a.property('wantlist')
  expect(stats).to.have.a.property('peers')
  expect(stats).to.have.a.property('blocksReceived')
  expect(stats).to.have.a.property('dataReceived')
  expect(stats).to.have.a.property('blocksSent')
  expect(stats).to.have.a.property('dataSent')
  expect(stats).to.have.a.property('dupBlksReceived')
  expect(stats).to.have.a.property('dupDataReceived')

  expect(stats.provideBufLen).to.a('number')
  expect(stats.wantlist).to.be.an('array')
  expect(stats.peers).to.be.an('array')
  expect(isBigInt(stats.blocksReceived)).to.eql(true)
  expect(isBigInt(stats.dataReceived)).to.eql(true)
  expect(isBigInt(stats.blocksSent)).to.eql(true)
  expect(isBigInt(stats.dataSent)).to.eql(true)
  expect(isBigInt(stats.dupBlksReceived)).to.eql(true)
  expect(isBigInt(stats.dupDataReceived)).to.eql(true)
}

exports.expectIsBandwidth = (err, stats) => {
  expect(err).to.not.exist()
  expect(stats).to.exist()
  expect(stats).to.have.a.property('totalIn')
  expect(stats).to.have.a.property('totalOut')
  expect(stats).to.have.a.property('rateIn')
  expect(stats).to.have.a.property('rateOut')
  expect(isBigInt(stats.totalIn)).to.eql(true)
  expect(isBigInt(stats.totalOut)).to.eql(true)
  expect(isBigInt(stats.rateIn)).to.eql(true)
  expect(isBigInt(stats.rateOut)).to.eql(true)
}

exports.expectIsRepo = (err, res) => {
  expect(err).to.not.exist()
  expect(res).to.exist()
  expect(res).to.have.a.property('numObjects')
  expect(res).to.have.a.property('repoSize')
  expect(res).to.have.a.property('repoPath')
  expect(res).to.have.a.property('version')
  expect(res).to.have.a.property('storageMax')
  expect(isBigInt(res.numObjects)).to.eql(true)
  expect(isBigInt(res.repoSize)).to.eql(true)
  expect(isBigInt(res.storageMax)).to.eql(true)
  expect(res.repoPath).to.be.a('string')
  expect(res.version).to.be.a('string')
}


text:
<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use \unclead\multipleinput\MultipleInput;
use \unclead\multipleinput\TabularInput;

/* @var $this yii\web\View */
/* @var $model common\repositories\BlockFooterRepository */
/* @var $form yii\bootstrap\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?php echo $form->errorSummary($model); ?>

            <?php echo $form->field($model, 'active_partners')->checkbox()->label('Партнеры')?>

            <?php echo $form->field($model, 'header2')->textInput(['maxlength' => true])->label('Заголовок') ?>

                <?php foreach($partners as $k => $item): ?>
                    <div class="partner_box" id="partner_id_<?= $item['id'] ?>">
                        <img src="<?= $item['logo_url'] . '/' . $item['logo_path']  ?>">
                        URL:<?= $item['url'] ?>

                            <div class="btn btn-success btn-sm " onclick="getEditPartnerForm(<?= $item['id'] ?>)">

                            <div class="btn btn-danger btn-sm " onclick="deletePartner(<?= $item['id'] ?>)">

                <?php endforeach; ?>

            <button type="button" class="btn btn-success pull-right"  onclick="getEditPartnerForm(0)">
                + Добавить партнера
            </button>

        <?php echo Html::submitButton($model->isNewRecord ? Yii::t('backend', 'Create') : Yii::t('backend', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Партнер

                ...

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

<?php
$this->registerJs("
        $('#editPartnerModal').on('show.bs.modal', function (e) {
            //getEditPartnerForm(0);
        });
    ");
?>


text:
"""
   Tests for raxutils.py
   Called via nosetests tests/test_raxutils.py
"""

# Global imports
import unittest
import json
# Local imports
from app import raxutils

TEST_DC = 'replace_with_dc'
TEST_PRJ = 'replace_with_cloud_project'
TEST_VM = 'replace_with_valid_vm_ID_GUID'

class TestRAXUtils(unittest.TestCase):
    """ Standard test class, for all utils functions """

    def test_retrieve_cloud_hostmap(self):
        """ Test retrieval from rackspace cloud api """
        ids, names = raxutils.retrieve_cloud_hostmap(dc_id=TEST_DC,
                                                     account_filter=None,
                                                     allow_cache=False)
        self.assertGreater(len(ids), 1)
        zm_id, zm_nm = raxutils.retrieve_cloud_hostmap(dc_id=TEST_DC,
                                                       account_filter=TEST_PRJ,
                                                       allow_cache=False)
        for host in ids.iterkeys():
            self.assertGreaterEqual(len(ids[host]),
                                    len(zm_id[host]))
            self.assertGreaterEqual(len(names[host]),
                                    len(zm_nm[host]))

    def test_check_host_capacity(self):
        """ Test the API checking if vm is on overloaded host """
        # allow standard weighting, checking TEST_VM
        retval = raxutils.check_host_capacity(dc_id=TEST_DC, vmid=TEST_VM,
                                              max_weight=None)
        self.assertEqual(retval, "OK")

        # now change weighting to allow
        retval = raxutils.check_host_capacity(dc_id=TEST_DC, vmid=TEST_VM,
                                              max_weight=5)
        self.assertEqual(retval, "OVERLOADED")

    def test_get_overloaded_hosts(self):
        """ Test the API retrieving overloaded hosts we want to avoid """
        # allow standard weighting, checking overload
        avoid_hosts = raxutils.get_overloaded_hosts(dc_id=TEST_DC,
                                                    max_weight=None)
        self.assertGreater(len(avoid_hosts), 3)

        # shouldn't be any hosts with more than 50 units of server load
        avoid_hosts = raxutils.get_overloaded_hosts(dc_id=TEST_DC,
                                                    max_weight=50)
        self.assertEqual(avoid_hosts, '[]')

    def test_get_vm_hostmap(self):
        """ Test the API charting VMs per host"""
        all_hosts = raxutils.get_vm_hostmap(dc_id=TEST_DC,
                                            account_filter=None)
        for host in json.loads(all_hosts):
            self.assertGreaterEqual(host['Load'], 1)

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


text:
package org.gluewine.gxo_server;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.gluewine.core.ContextInitializer;
import org.gluewine.core.Glue;
import org.gluewine.core.RepositoryListener;
import org.gluewine.core.RunOnActivate;
import org.gluewine.core.RunOnDeactivate;
import org.gluewine.core.RemoteCallValidator;
import org.gluewine.gxo.CloseBean;
import org.gluewine.gxo.CompressedBlockInputStream;
import org.gluewine.gxo.CompressedBlockOutputStream;
import org.gluewine.gxo.ExecBean;
import org.gluewine.gxo.GxoException;
import org.gluewine.gxo.InitBean;
import org.gluewine.gxo.LocalAccess;
import org.gluewine.sessions.SessionExpiredException;
import org.gluewine.sessions.SessionManager;
import org.gluewine.sessions.Unsecured;
import org.gluewine.utils.AnnotationUtility;
import org.gluewine.utils.ErrorLogger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
import com.thoughtworks.xstream.io.xml.StaxDriver;

/**
 * Default implementation of the GxoServer.
 *
 * @author fks/Serge de Schaetzen
 *
 */
public class GxoServerImpl implements Runnable, GxoServer, RepositoryListener<Object>, XStreamConverterProvider
{
    // ===========================================================================
    /**
     * Converts SQL Dates.
     */
    private static class MySqlDateConverter extends DateConverter
    {
        /**
         * Creates an instance.
         */
        MySqlDateConverter()
        {
            super();
        }

        @Override
        @SuppressWarnings("rawtypes")
        public boolean canConvert(Class type)
        {
            boolean result = super.canConvert(type)
                || java.util.Date.class.isAssignableFrom(type);
            return result;
        }
    }

    /**
     * The set of registered instantiatable classes.
     */
    private Map<String, Class<?>> instantiatables = new HashMap<String, Class<?>>();

    /**
     * The set of registered method invocation validators.
     */
    private Set<RemoteCallValidator> validators = new HashSet<RemoteCallValidator>();

    /**
     * The set of registered xsteam converter providers.
     */
    private Set<XStreamConverterProvider> providers = new HashSet<XStreamConverterProvider>();

    /**
     * The logger instance to use.
     */
    private Logger logger = Logger.getLogger(getClass().getName());

    /**
     * Max number of millis that the connection is allowed to be idle.
     */
    private int maxIdle = 300000;

    /**
     * The set of open sockets.
     */
    private Set<Socket> openSockets = new HashSet<Socket>();

    /**
     * The port the server is listening to.
     */
    private int port;

    /**
     * The socket of the server.
     */
    private ServerSocket server = null;

    /**
     * Map of available services. The services are indexed on their 'SimpleName',
     * ie. the name without package prefix.
     */
    private Map<String, Object> services = new HashMap<String, Object>();

    /**
     * Flag indicating that the server should stop.
     */
    private boolean stopRequested = false;

    /**
     * The XStream serializer/deserializer.
     */
    private XStream stream = null;

    /**
     * The session manager.
     */
    private SessionManager sessionManager;

    /**
     * The property file to use.
     */
    @Glue(properties = "gxo.properties", refresh = "propertiesChanged")
    private Properties properties;

    // ===========================================================================
    /**
     * Creates an instance.
     *
     * @throws Throwable If a problem occurs.
     */
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "SIC_INNER_SHOULD_BE_STATIC_ANON")
    public GxoServerImpl() throws Throwable
    {
        stream = new XStream(new StaxDriver());
    }

    // ===========================================================================
    /**
     * Deactivates the server and requests the server socket to be closed.
     * The server can no longer be used after this method has been invoked.
     */
    @RunOnDeactivate
    public void deactivate()
    {
        stopRequested = true;
        logger.debug("Stopping GXO Server.");
        if (server != null)
        {
           try
           {
               server.close();
           }
           catch (Throwable e)
           {
               logger.warn(e);
           }
        }
        logger.debug("GXO Server stop requested.");

        synchronized (openSockets)
        {
            for (Socket s : openSockets)
            {
                try
                {
                    s.close();
                }
                catch (Throwable e)
                {
                    logger.warn(e);
                }
            }
        }

        try
        {
            LocalAccess.getInstance().close();
        }
        catch (IOException e)
        {
            logger.warn(e);
        }
    }

    // ===========================================================================
    /**
     * Returns true if a stop has been requested.
     *
     * @return True if stop requested.
     */
    public boolean isStopRequested()
    {
        return stopRequested;
    }

    // ===========================================================================
    /**
     * Returns the set of interfaces implemented by the class (and all
     * of its parent classes).
     *
     * @param c The class to process.
     * @param set The set to update. If null a set is created.
     * @return The set of unique classnames.
     */
    private Set<Class<?>> getInterfaces(Class<?> c, Set<Class<?>> set)
    {
        if (set == null) set = new HashSet<Class<?>>();

        for (Class<?> interf : c.getInterfaces())
            set.add(interf);

        if (c.getSuperclass() != null)
            getInterfaces(c.getSuperclass(), set);

        return set;
    }

    // ===========================================================================
    @Override
    public XStream getXStream()
    {
        return stream;
    }

    // ===========================================================================
    /**
     * Initializes the server.
     *
     * @throws IOException If an error occurs reading the properties file.
     */
    @RunOnActivate
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_UNWRITTEN_FIELD")
    public void initialize() throws IOException
    {
        stopRequested = false;
        port = Integer.parseInt(properties.getProperty("port", "1966"));
        maxIdle = Integer.parseInt(properties.getProperty("maxidle", "300")) * 1000;
        Thread th = new Thread(this, "GXO Server Thread");
        th.start();
    }

    // ===========================================================================
    /**
     * Processes local requests. Local requests are passed on a named pipe.
     */
    @RunOnActivate(runThreaded = true)
    public void processLocalRequests()
    {
        // The map containing the instantiated services.
        Map<String, Object> instantiated = new HashMap<String, Object>();

        try
        {
            LocalAccess la = LocalAccess.getInstance();
            InputStreamReader in = new InputStreamReader(la.getClientInputStream(), "UTF-8");
            OutputStreamWriter out = new OutputStreamWriter(la.getClientOutputStream(), "UTF-8");

            while (!stopRequested)
            {
                try
                {
                    Object ob = stream.fromXML(in);

                    if (ob instanceof ExecBean) processExecBean(out, instantiated, (ExecBean) ob);
                    else if (ob instanceof InitBean) processInitBean(out, instantiated, (InitBean) ob);
                }
                catch (Throwable e)
                {
                    if (la.isClosed())
                    {
                        in = new InputStreamReader(la.getClientInputStream(), "UTF-8");
                        out = new OutputStreamWriter(la.getClientOutputStream(), "UTF-8");
                    }

                    else if (!stopRequested)
                        la.close();
                }
            }
        }
        catch (Throwable e)
        {
            ErrorLogger.log(getClass(), e);
        }
    }

    // ===========================================================================
    /**
     * Processes the given exec bean and writes the result on the given output stream.
     * The map contains the list of objects that were instantiated in this session.
     *
     * @param out The output stream to write to.
     * @param instantiated The map of instantiated objects.
     * @param bean The bean to process.
     * @throws IOException Thrown if an error occurs writing back to the caller.
     */
    public void processExecBean(OutputStreamWriter out, Map<String, Object> instantiated, ExecBean bean) throws IOException
    {
        try
        {
            processExecBean(instantiated, bean, out);
        }
        catch (SessionExpiredException e)
        {
            GxoException ge = new GxoException(e);
            stream.toXML(ge, out);
        }
        catch (Throwable e)
        {
            ErrorLogger.log(getClass(), e);
            GxoException ge = new GxoException(toRegularException(e));
            stream.toXML(ge, out);
        }
        out.flush();
    }

    // ===========================================================================
    /**
     * Processes the given init bean and writes the result on the given output stream.
     * The map contains the list of objects already instantiated.
     *
     * @param out The output stream to write to.
     * @param instantiated The map of instantiated objects.
     * @param bean The bean to process.
     * @throws IOException Thrown if an error occurs writing back to the caller.
     */
    @ContextInitializer
    public void processInitBean(OutputStreamWriter out, Map<String, Object> instantiated, InitBean bean) throws IOException
    {
        try
        {
            Object result = processInitBean(instantiated, bean);
            stream.toXML(result, out);
        }
        catch (Throwable e)
        {
            ErrorLogger.log(getClass(), e);
            GxoException ge = new GxoException(toRegularException(e));
            stream.toXML(ge, out);
        }
        out.flush();
    }

    // ===========================================================================
    /**
     * Processes a socket. This will read ExecBeans and dispatch them
     * to the right service, until a CloseBean is received or the socket is closed.
     *
     * @param socket The socket to process.
     */
    private void process(Socket socket)
    {
        CompressedBlockInputStream cin = null;
        CompressedBlockOutputStream cout = null;
        try
        {
            socket.setKeepAlive(true);
            cin = new CompressedBlockInputStream(socket.getInputStream());
            cout = new CompressedBlockOutputStream(socket.getOutputStream(), 1024);
            InputStreamReader in = new InputStreamReader(cin, "UTF-8");
            OutputStreamWriter out = new OutputStreamWriter(cout, "UTF-8");

            // The map containing the instantiated services.
            Map<String, Object> instantiated = new HashMap<String, Object>();
            if (maxIdle > 0) socket.setSoTimeout(maxIdle);

            while (true)
            {
                Object ob = stream.fromXML(in);

                if (ob instanceof ExecBean) processExecBean(out, instantiated, (ExecBean) ob);

                else if (ob instanceof InitBean) processInitBean(out, instantiated, (InitBean) ob);

                else if (ob instanceof CloseBean)
                {
                    if (logger.isDebugEnabled())
                        logger.debug("Closing socket");

                    socket.close();
                    socket = null;
                    return;
                }
            }
        }
        catch (Throwable e)
        {
            if (e.getMessage() == null || (e.getMessage().indexOf("Read timed out") < 0 && e.getMessage().indexOf("Connection reset") < 0) && e.getMessage().indexOf("ParseError at [row,col]:[1,1]") < 0)
                ErrorLogger.log(getClass(), e);
        }

        finally
        {
            if (socket != null)
            {
                try
                {
                    socket.close();
                }
                catch (Throwable e)
                {
                    logger.warn(e);
                }
                synchronized (openSockets)
                {
                    openSockets.remove(socket);
                }
            }
        }
    }

    // ===========================================================================
    /**
     * Processes the exec bean specified and returns the output of the command.
     *
     * @param instantiated The map of services instantiated in this session.
     * @param bean The bean to process.
     * @param out the output stream to serialise the result to.
     */
    private void processExecBean(Map<String, Object> instantiated, ExecBean bean, OutputStreamWriter out)
    {
        if (logger.isDebugEnabled())
            logger.debug("Executing " + bean.getService() + ":" + bean.getMethod());

        Object o = instantiated.get(bean.getService());
        if (o == null) o = services.get(bean.getService());

        if (o != null)
        {
            try
            {
                Method m = o.getClass().getMethod(bean.getMethod(), bean.getParamTypes());

                if (AnnotationUtility.getAnnotation(Unsecured.class, m, o) == null)
                {
                    if (sessionManager != null)
                    {
                        sessionManager.setCurrentSessionId(bean.getSessionId());
                        sessionManager.checkAndTickSession(bean.getSessionId());
                    }
                }

                for (RemoteCallValidator validator : validators)
                    validator.validateCall("GXO", o, m, bean.getParams());

                invokeMethod(out, m, o, bean.getParams());
                if (logger.isTraceEnabled())
                    logger.trace(bean.getService() + ":" + bean.getMethod() + " finished");
            }
            catch (SessionExpiredException e)
            {
                ErrorLogger.log(getClass(), e);
                throw e;
            }
            catch (InvocationTargetException e)
            {
                ErrorLogger.log(getClass(), e);
                GxoException ge = new GxoException(toRegularException(e.getCause()));
                stream.toXML(ge, out);
            }
            catch (Throwable e)
            {
                ErrorLogger.log(getClass(), e);
                GxoException ge = new GxoException(toRegularException(e));
                stream.toXML(ge, out);
            }
        }
        else
        {
            logger.warn("Undefined service " + bean.getService());
            GxoException ge = new GxoException("Undefined service " + bean.getService());
            stream.toXML(ge, out);
        }
    }

    /**
     * Calls a method and serialises the output.
     * @param out the stream to write to.
     * @param m the method to call.
     * @param o the object to call the method on.
     * @param params the method parameters.
     * @throws InvocationTargetException if the call fails.
     * @throws IllegalAccessException if the call fails.
     */
    @ContextInitializer
    public void invokeMethod(OutputStreamWriter out, Method m, Object o, Object[] params) throws InvocationTargetException, IllegalAccessException
    {
        Object result = m.invoke(o, params);
        stream.toXML(result, out);
    }

    // ===========================================================================
    /**
     * Processes the init bean specified and returns the result.
     *
     * @param instantiated The map to update.
     * @param bean The bean to process.
     * @return The result.
     */
    private Object processInitBean(Map<String, Object> instantiated, InitBean bean)
    {
        Object result = null;
        if (logger.isDebugEnabled()) logger.debug("Received init request for " + bean.getClassName());
        if (instantiatables.containsKey(bean.getClassName()))
        {
            Class<?> cl = instantiatables.get(bean.getClassName());
            Object instance = null;
            try
            {
                if (bean.getParamTypes() == null || bean.getParamTypes().length == 0)
                    instance = cl.newInstance();

                else
                {
                    if (logger.isDebugEnabled())
                    {
                        StringBuilder b = new StringBuilder("Looking for constructor: ");
                        for (Class<?> c : bean.getParamTypes())
                            b.append(c.getName()).append(" ");
                        logger.debug(b.toString().trim());
                    }
                    Constructor<?> c = cl.getConstructor(bean.getParamTypes());
                    instance = c.newInstance(bean.getParamValues());
                }

                if (instance != null)
                {
                    String id = UUID.randomUUID().toString();
                    if (logger.isDebugEnabled()) logger.debug("Registering instance with id " + id);
                    instantiated.put(id, instance);
                    result = id;
                }
                else
                    result = new GxoException("Could not instantiate " + cl.getName());
            }
            catch (Throwable e)
            {
                ErrorLogger.log(getClass(), e);
                result = toRegularException(e);
            }

        }
        else
            result = new GxoException("Undefined instantiatable " + bean.getClassName());

        return result;
    }

    // ===========================================================================
    @Override
    public void registered(Object o)
    {
        if (o instanceof XStreamProvider)
            initializeStream((XStreamProvider) o);

        if (o instanceof XStreamConverterProvider)
        {
            ((XStreamConverterProvider) o).registerConverters(stream);
            providers.add((XStreamConverterProvider) o);
        }

        Set<Class<?>> interfs = getInterfaces(o.getClass(), null);
        synchronized (services)
        {
            for (Class<?> interf : interfs)
                services.put(interf.getName(), o);
        }

        if (o instanceof RemoteCallValidator)
            validators.add((RemoteCallValidator) o);

        if (o instanceof SessionManager)
            sessionManager = (SessionManager) o;
    }

    // ===========================================================================
    /**
     * Initializes a new XStream using the given provider.
     *
     * @param provider The provider to use.
     */
    private void initializeStream(XStreamProvider provider)
    {
        stream = provider.getXStream();
        // Reregister all available converters:
        for (XStreamConverterProvider prov : providers)
            prov.registerConverters(stream);
    }

    // ===========================================================================
    @Override
    public void run()
    {
        logger.info("Starting GXO Server on port: " + port);
        while (!stopRequested)
        {
            try
            {
                server = new ServerSocket(port);
                //server.setSoTimeout(1000);
                while (!stopRequested)
                {
                    try
                    {
                        final Socket socket = server.accept();
                        synchronized (openSockets)
                        {
                            openSockets.add(socket);
                        }
                        Thread thread = new Thread()
                        {
                            public void run()
                            {
                                if (logger.isDebugEnabled())
                                    logger.debug("Accepting incoming session from " + socket.getRemoteSocketAddress().toString());
                                try
                                {
                                    process(socket);
                                }
                                catch (Throwable e)
                                {
                                    ErrorLogger.log(GxoServerImpl.class, e);
                                }
                            }
                        };
                        thread.start();
                    }
                    catch (SocketTimeoutException e)
                    {
                        // allowed to fail/
                    }
                    catch (Throwable e)
                    {
                        if (!stopRequested)
                            ErrorLogger.log(getClass(), e);
                    }
                }
            }
            catch (Throwable e)
            {
                if (!stopRequested)
                {
                    ErrorLogger.log(getClass(), e);
                    try
                    {
                        Thread.sleep(5000);
                    }
                    catch (Throwable t)
                    {
                        logger.warn(t);
                    }
                }
            }
        }
        logger.info("GXOServer stopped");
    }

    // ===========================================================================
    @Override
    public void setInstantiatableService(Class<?> cl)
    {
        Set<Class<?>> interfaces = getInterfaces(cl, null);
        for (Class<?> interf : interfaces)
            instantiatables.put(interf.getName(), cl);
    }

    // ===========================================================================
    /**
     * Converts the throwable given to a regular Throwable.
     * @param e The throwable to convert.
     * @return The converted Throwable.
     */
    private Throwable toRegularException(Throwable e)
    {
        Throwable n = new Throwable(e.getClass().getName() + ": " + e.getMessage());
        if (e.getCause() != null)
            n.initCause(toRegularException(e.getCause()));

        n.setStackTrace(e.getStackTrace());

        return n;
    }

    // ===========================================================================
    @Override
    public void unregistered(Object o)
    {
        if (o instanceof XStreamConverterProvider)
            providers.remove((XStreamConverterProvider) o);

        Set<Class<?>> interfs = getInterfaces(o.getClass(), null);
        synchronized (services)
        {
            for (Class<?> interf : interfs)
                services.remove(interf.getName());
        }

        if (o instanceof RemoteCallValidator)
            validators.remove((RemoteCallValidator) o);
    }

    // ===========================================================================
    @Override
    public void unsetInstantiatableService(Class<?> cl)
    {
        Set<Class<?>> interfaces = getInterfaces(cl, null);
        for (Class<?> interf : interfaces)
            instantiatables.remove(interf.getName());
    }

    // ===========================================================================
    @Override
    public void registerConverters(XStream stream)
    {
        stream.registerConverter(new MySqlDateConverter());

        stream.alias("date", java.sql.Date.class, java.util.Date.class);
        stream.alias("date", java.sql.Time.class, java.util.Date.class);
        stream.alias("date", java.sql.Timestamp.class, java.util.Date.class);

        final Class<?> emptyListType = Collections.EMPTY_LIST.getClass();
        stream.alias(emptyListType.getName(), emptyListType);

        stream.registerConverter(new ReflectionConverter(stream.getMapper(), stream.getReflectionProvider())
        {
            @Override
            @SuppressWarnings("rawtypes")
            public boolean canConvert(Class type)
            {
                return type == emptyListType;
            }
        });
    }

    // ===========================================================================
    /**
     * Invoked when the properties have changed.
     */
    public void propertiesChanged()
    {
        deactivate();
        try
        {
            initialize();
        }
        catch (IOException e)
        {
            ErrorLogger.log(getClass(), e);
        }
    }
}


text:
cask "dendroscope" do
  version "3.7.6"
  sha256 "e00f35e3ae6658818868859dfde6611cb9d4d35025dc3ef947735917d58b0a44"

  url "https://software-ab.informatik.uni-tuebingen.de/download/dendroscope/Dendroscope_macos_#{version.dots_to_underscores}.dmg"
  name "Dendroscope"
  desc "Interactive viewer for rooted phylogenetic trees and networks"
  homepage "https://www.wsi.uni-tuebingen.de/lehrstuehle/algorithms-in-bioinformatics/software/dendroscope/"

  livecheck do
    url "https://software-ab.informatik.uni-tuebingen.de/download/dendroscope3/welcome.html"
    strategy :page_match do |page|
      v = page[/href=.*?Dendroscope_macos_(\d+(?:_\d+)*)\.dmg/i, 1]
      v.tr("_", ".")
    end
  end

  installer script: {
    executable: "Dendroscope Installer.app/Contents/MacOS/JavaApplicationStub",
    args:       ["-q"],
  }

  uninstall script: {
    executable: "#{appdir}/Dendroscope/Dendroscope Uninstaller.app/Contents/MacOS/JavaApplicationStub",
    args:       ["-q"],
  }

  caveats do
    depends_on_java
  end
end


text:
/* ===========================================================================
 *
 * JQuery Quick Pagination
 * Version 1.0.1
 * Quick and dirty pagination for pretty much any set of elements on the page.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_quick_paginate/
 *
 * ---------------------------------------------------------------------------
 *
 * LICENCE:
 *
 * Released under a MIT Licence. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_quick_paginate/licence.txt
 *
 * ---------------------------------------------------------------------------
 *
 * EXAMPLES OF USE:
 *
 * jQuery('.news_item').quickpaginate(); // would paginate all items on the page with the class of 'news_item'
 *
 * jQuery('div#quick_slideshow img').quickpaginate(); // would paginate all img elements within the div with an id of 'quick_slideshow'
 *
 * // Paginate everything with the class of "news_item",
 * // 5 per 'page' and without the page counter.
 * jQuery('.news_item').quickpaginate( { perpage: 5, showcounter: false } );
 *
 * // Paginate all img elements and the element with the id of "info",
 * // with the prev/next/counter element appended to the element with the id of "pager_here"
 * jQuery('img, #info').quickpaginate({ pager : $("#pager_here") });
 *
 */

jQuery.fn.quickpaginate = function( settings ) {

	settings = jQuery.extend({

		perpage: 6,

		pager : null,

		showcounter : true,

		prev : "qp_next",

		next : "qp_prev",

		pagenumber : "qp_pagenumber",

		totalnumber : "qp_totalnumber",

		counter : "qp_counter"

	}, settings);

	var cm;

	var total;

	var last = false;

	var first = true;

	var items = jQuery(this);

	var nextbut;

	var prevbut;

	var init = function()
	{
		items.show();

		total = items.size();

		if ( items.size() > settings.perpage )
		{
			items.filter(":gt("+(settings.perpage-1)+")").hide();

			cm = settings.perpage;

			setNav();
		}
	};

	var goNext = function()
	{
		if ( !last )
		{
			var nm = cm + settings.perpage;
			items.hide();

			items.slice( cm, nm ).show();
			cm = nm;

			if ( cm >= total  )
			{
				last = true;
				nextbut.addClass("qp_disabled");
			}

			if ( settings.showcounter ) settings.pager.find("."+settings.pagenumber).text(cm/settings.perpage);

			prevbut.removeClass("qp_disabled");
			first = false;
		}
	};

	var goPrev = function()
	{
		if ( !first )
		{
			var nm = cm-settings.perpage;
			items.hide();

			items.slice( (nm - settings.perpage), nm ).show();
			cm = nm;

			if ( cm == settings.perpage  )
			{
				first = true;
				prevbut.addClass("qp_disabled");
			}

			if ( settings.showcounter ) settings.pager.find("."+settings.pagenumber).text(cm/settings.perpage);

			nextbut.removeClass("qp_disabled");
			last = false;
		}
	};

	var setNav = function()
	{
		if ( settings.pager === null )
		{
			settings.pager = jQuery('

');
			items.eq( items.size() -1 ).after(settings.pager);
		}
		//上一页和下一页文字
		var pagerNav = $('[上页][下页]');

		jQuery(settings.pager).append( pagerNav );

		if ( settings.showcounter )
		{
			var counter = '/';

			settings.pager.find("."+settings.prev).after( counter );

			settings.pager.find("."+settings.pagenumber).text( 1 );
			settings.pager.find("."+settings.totalnumber).text( Math.ceil(total / settings.perpage) );
		}

		nextbut = settings.pager.find("."+settings.next);

		prevbut = settings.pager.find("."+settings.prev);

		prevbut.addClass("qp_disabled");

		nextbut.click(function(){
			goNext();
			return false;
		});

		prevbut.click(function(){
			goPrev();
			return false;
		});

	};

	init(); //运行函数
};


text:
'use strict';

/* global JuttleAdapterAPI */
var ASTVisitor = JuttleAdapterAPI.compiler.StaticFilterCompiler;

class Query extends ASTVisitor {
    constructor() {
        super();

        this.ops = {
            '==': '=',
            'AND': 'AND',
            'OR': 'OR',
            '!=': '!=',
            '<' : '<',
            '>' : '>',
            '>=' : '>=',
            '<=' : '<=',
            'NOT': 'NOT'
            //'=~' : '=~',
            //'!~' : '!~',
            //'IN': undefined,
        };
    }

    // XXX/bkutil: ensure index field is there
    compile(ast, opts) {
        var op, where;

        var options = opts || {};
        var fields = options.fields;
        var optimizations = options.optimizations || {};

        var params = { hasIndex: false};

        where = this.visit(ast, op, options, params);

        if (!params.hasIndex) {
            throw new Error('Missing required field "index"');
        }

        if (where === undefined) {
            return '';
        }

        where = `search ${String(where)}`;

        if (fields) {
            where = `${where} | fields ${fields}`;
        }

        where = `${where} | sort + _time`;

        if (optimizations.head) {
            where = `${where} | head ${optimizations.head.limit}`;
        }

        if (optimizations.tail) {
            where = `${where} | tail ${optimizations.tail.limit}`;
        }

        return where;
    }

    visitNumberLiteral(node, op, options, params) {
        return node.value;
    }

    visitNullLiteral(node, op, options, params) {
        return 'null';
    }

    visitVariable(node, op, options, params) {
        return `"${node.name}"`;
    }

    visitField(node, op, options, params) {
        if (node.name === 'index') { params.hasIndex = true; }

        return `${node.name}`;
    }

    visitBooleanLiteral(node, op, options, params) {
        return node.value;
    }

    visitFilterLiteral(node, op, options, params) {
        return this.visit(node.ast, op, options, params);
    }

    visitStringLiteral(node, op, options, params) {
        return `"${node.value}"`;
    }

    visitFulltextFilterTerm(node, op, options, params) {
        return `${node.text}`;
    }

    visitBinaryExpression(node, op, options, params) {
        var operator = this.ops[node.operator];

        if (!operator) { throw new Error(`Operator ${node.operator} not supported by Splunk SPL`); }

        var str = '';

        var left = this.visit(node.left, operator, options, params);
        var right = this.visit(node.right, operator, options, params);

        if (typeof left !== 'undefined') {
            str += this._addParens(node.left) ? `(${left})` : left;
        }
        if (typeof left !== 'undefined' && typeof right !== 'undefined') {
            str += ` ${operator} `;
        }
        if (typeof right !== 'undefined') {
            str += this._addParens(node.right) ? `(${right})` : right;
        }

        return str;
    }

    _addParens(node) {
        return node.type === 'BinaryExpression'
            && (node.operator === 'AND' || node.operator === 'OR');
    }

    visit(node, op, options, params) {
        return this[`visit${node.type}`].apply(this, arguments);
    }
}

module.exports = Query;


text:
@charset "utf-8";

/* base reset */
body {color:#323232;background:#fff;text-align:left;}
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td,hr,button,article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section {margin:0;padding:0;outline:none;}
article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section {display:block;}
audio,canvas,video {display:inline-block;*display:inline;*zoom:1;}
body,button,input,select,textarea {font:12px/1.5 "Helvetica Neue",Helvetica,Arial,"Hiragino Sans GB",\5b8b\4f53,sans-serif;}
input,button,select,textarea {font-size:100%;color:#636363;outline:none;}
textarea {resize:none;}
table {border-collapse:collapse;border-spacing:0;}
fieldset,img {border:0;}
iframe {display:block;}
abbr,acronym {border:0;font-variant:normalå;}
del {text-decoration:line-through;}
address,caption,cite,code,dfn,em,strong,th,var {font-style:normal;font-weight:500;}
ol,ul {list-style:none;}
caption,th {text-align:left;}
h1,h2,h3,h4,h5,h6 {font-size:100%;font-weight:500;}
q:before,q:after {content:"";}
sub,sup {font-size:75%;line-height:0;position:relative;vertical-align:baseline;}
sup {top:-0.5em;}
sub {bottom:-0.25em;}
a {text-decoration:none;color:#0073b6;}
a:hover {text-decoration:underline;}


text:
package me.chris.MoneyManager;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class MMListener implements Listener
{
	@EventHandler(priority = EventPriority.HIGHEST)
	public void playerJoin(PlayerJoinEvent event)
	{
		Player p = event.getPlayer();

		if (p.isOp())
		{
			String lastestVersion = "";
			try
			{
				lastestVersion = HelperMethods.updateCheck();
			}
			catch (Throwable t)
			{
				return;
			}

			if (!lastestVersion.equalsIgnoreCase(Vars.version))
			{
				p.sendMessage("§5=====================================================");
				p.sendMessage("§4 Warning!§f This isnt the lastest version of MoneyManager!");
				p.sendMessage("§c " + lastestVersion + "§f Is out! (This is §c" + Vars.version + "§f)");
				p.sendMessage("§5=====================================================");
			}
		}
	}
}


text:
body{padding-top:60px;font:14px "Lucida Grande",Helvetica,Arial,sans-serif;}
@media (max-width:979px){body{padding-top:0 !important;}}a{color:#00B7FF;}
div{display:block;}div .aClass{color:#fff;}


text: <bx_include_auto:cover.html />


text:
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
    var msViewportStyle = document.createElement('style')
    msViewportStyle.appendChild(
        document.createTextNode(
            '@-ms-viewport{width:auto!important}'
        )
    )
    document.head.appendChild(msViewportStyle)
}


text:
import httplib as http

from flask import request
from modularodm import Q
from modularodm.storage.base import KeyExistsException

from framework.exceptions import HTTPError
from framework.auth.decorators import must_be_logged_in
from website.project import decorators
from website.util.sanitize import assert_clean
from website.addons.dataverse import client
from website.addons.dataverse.provider import DataverseProvider
from website.addons.dataverse.serializer import DataverseSerializer
from website.oauth.models import ExternalAccount

@must_be_logged_in
def dataverse_get_user_accounts(auth):
    """ Returns the list of all of the current user's authorized Dataverse accounts """

    return DataverseSerializer(
        user_settings=auth.user.get_addon('dataverse')
    ).serialized_user_settings

@must_be_logged_in
def dataverse_add_user_account(auth, **kwargs):
    """Verifies new external account credentials and adds to user's list"""
    user = auth.user
    provider = DataverseProvider()

    host = request.json.get('host').rstrip('/')
    api_token = request.json.get('api_token')

    # Verify that credentials are valid
    client.connect_or_401(host, api_token)

    # Note: `DataverseSerializer` expects display_name to be a URL
    try:
        provider.account = ExternalAccount(
            provider=provider.short_name,
            provider_name=provider.name,
            display_name=host,       # no username; show host
            oauth_key=host,          # hijacked; now host
            oauth_secret=api_token,  # hijacked; now api_token
            provider_id=api_token,   # Change to username if Dataverse allows
        )
        provider.account.save()
    except KeyExistsException:
        # ... or get the old one
        provider.account = ExternalAccount.find_one(
            Q('provider', 'eq', provider.short_name) &
            Q('provider_id', 'eq', api_token)
        )
        assert provider.account is not None

    if provider.account not in user.external_accounts:
        user.external_accounts.append(provider.account)
        user.save()

    return {}

@must_be_logged_in
@decorators.must_be_valid_project
@decorators.must_have_addon('dataverse', 'node')
def dataverse_get_config(node_addon, auth, **kwargs):
    """API that returns the serialized node settings."""
    result = DataverseSerializer(
        user_settings=auth.user.get_addon('dataverse'),
        node_settings=node_addon,
    ).serialized_node_settings
    return {'result': result}, http.OK

@decorators.must_have_permission('write')
@decorators.must_have_addon('dataverse', 'user')
@decorators.must_have_addon('dataverse', 'node')
def dataverse_get_datasets(node_addon, **kwargs):
    """Get list of datasets from provided Dataverse alias"""
    alias = request.json.get('alias')

    connection = client.connect_from_settings(node_addon)
    dataverse = client.get_dataverse(connection, alias)
    datasets = client.get_datasets(dataverse)
    ret = {
        'alias': alias,  # include alias to verify dataset container
        'datasets': [{'title': dataset.title, 'doi': dataset.doi} for dataset in datasets],
    }
    return ret, http.OK

@decorators.must_have_permission('write')
@decorators.must_have_addon('dataverse', 'user')
@decorators.must_have_addon('dataverse', 'node')
def dataverse_set_config(node_addon, auth, **kwargs):
    """Saves selected Dataverse and dataset to node settings"""

    user_settings = node_addon.user_settings
    user = auth.user

    if user_settings and user_settings.owner != user:
        raise HTTPError(http.FORBIDDEN)

    try:
        assert_clean(request.json)
    except AssertionError:
        # TODO: Test me!
        raise HTTPError(http.NOT_ACCEPTABLE)

    alias = request.json.get('dataverse').get('alias')
    doi = request.json.get('dataset').get('doi')

    if doi is None:
        return HTTPError(http.BAD_REQUEST)

    connection = client.connect_from_settings(node_addon)
    dataverse = client.get_dataverse(connection, alias)
    dataset = client.get_dataset(dataverse, doi)

    node_addon.dataverse_alias = dataverse.alias
    node_addon.dataverse = dataverse.title

    node_addon.dataset_doi = dataset.doi
    node_addon.dataset_id = dataset.id
    node_addon.dataset = dataset.title

    node = node_addon.owner
    node.add_log(
        action='dataverse_dataset_linked',
        params={
            'project': node.parent_id,
            'node': node._primary_key,
            'dataset': dataset.title,
        },
        auth=auth,
    )

    node_addon.save()

    return {'dataverse': dataverse.title, 'dataset': dataset.title}, http.OK


text:
UsersFindFacebookFriendsView = Backbone.View.extend({
	events: {
		'click .nav': 'navigate'
	},

	title: 'Find Facebook Friends | YumHacker',

	description: 'Connect with your Facebook friends to find ' + Client.get('formatted_address') + ' restaurants and bars endorsed by people you trust. Get restaurant and bar photos, reviews, hours and more!',

	initialize: function () {
		this.render();

		App.eventAggregator.trigger('domchange:title', this.title);
        App.eventAggregator.trigger('domchange:description', this.description);

		this.collection = new UserFacebookFriendsCollection();

		this.user_facebook_friends_list_view = new UsersFacebookFriendsListView({
			el: '#find_user_results_container',
			collection: this.collection
		});
	},

	render: function () {
		this.$el.html(render('users/find_facebook_friends'));
	},

	navigate: function (e) {
		e.preventDefault();
		App.navigate('/' + e.target.search, { trigger: true });
	}
});


text:
//
//  IdentificationTabBarController.m
//  Identification
//
//  Created by 朴文一 on 16/1/8.
//  Copyright © 2016年 com.IdentificationofCulturalRelics. All rights reserved.
//

#import "IdentificationTabBarController.h"
#import "IdentificationNavigationController.h"
#import "HomeRootViewController.h"
#import "TrainRootViewController.h"
#import "IdentificationRootViewController.h"
#import "DealRootViewController.h"
#import "MeViewController.h"

@interface IdentificationTabBarController ()<UITabBarControllerDelegate>

@end

@implementation IdentificationTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    HomeRootViewController *homeVc =[[HomeRootViewController alloc]init];
    IdentificationNavigationController *home = [[IdentificationNavigationController alloc]initWithRootViewController:homeVc];
    home.title = @"首页";
    homeVc.tabBarItem.image = [UIImage imageNamed:@"tabbar_home@3x.png"];
    homeVc.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_home_pressed@3x.png"];

    IdentificationRootViewController *identificationVC = [[IdentificationRootViewController alloc]init];
    IdentificationNavigationController *identification = [[IdentificationNavigationController alloc]initWithRootViewController:identificationVC];
    identificationVC.title = @"鉴定";
    identificationVC.tabBarItem.image = [UIImage imageNamed:@"tabbar_evaluate@3x.png"];
    identificationVC.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_evaluate_pressed@3x.png"];

    TrainRootViewController *trainVc = [[TrainRootViewController alloc]init];
    IdentificationNavigationController *train = [[IdentificationNavigationController alloc]initWithRootViewController:trainVc];
    trainVc.title = @"培训";
    trainVc.tabBarItem.image = [UIImage imageNamed:@"tabbar_train@3x.png"];
    trainVc.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_train_pressed@3x.png"];

    DealRootViewController *dealVc = [[DealRootViewController alloc]init];
    IdentificationNavigationController *deal = [[IdentificationNavigationController alloc]initWithRootViewController:dealVc];
    dealVc.title = @"交易";
    dealVc.tabBarItem.image = [UIImage imageNamed:@"tabbar_deal@3x.png"];
    dealVc.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_deal_pressed@3x.png"];

    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    MeViewController *MeVC = [story instantiateViewControllerWithIdentifier:@"MeVC"];
    IdentificationNavigationController *me = [[IdentificationNavigationController alloc]initWithRootViewController:MeVC];
    me.title = @"我的";
    me.navigationBarHidden = YES;
    me.tabBarItem.image = [UIImage imageNamed:@"tabbar_my@3x.png"];
    me.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_my_pressed@3x.png"];

    self.viewControllers = @[home, identification, train, deal,me];
    self.delegate = self;

}
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    UIViewController *tbSelectedController = tabBarController.selectedViewController;
    if ([tbSelectedController isEqual:viewController]) {
        return NO;
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package org.hibernate.brmeyer.demo;

import org.hibernate.Session;
import org.hibernate.brmeyer.demo.entity.lazy.User;

/**
 * @author Brett Meyer
 */
public class SimpleLazy extends AbstractLazyDemo {

	/**
	 * Similar to {@link Eager}, demonstrating a typical, over-simplified, over-scoped DAO method.  However, for
	 * demo-purposes, all collections are LAZY (as they usually should be), resulting in a single select.
	 */
	public boolean getUser(int id) {
		final Session session = openSession();
		session.getTransaction().begin();
		final User user = (User) session.get( User.class, id );

		// this will fetch tools
//		user.getTools().size();

		// this will extra lazy fetch projects
//		user.getComments().get( 0 );

		session.getTransaction().commit();

		return user != null;
	}

	public static void main (String[] args) {
		final SimpleLazy demo = new SimpleLazy();
		int userId = demo.persistData();
		demo.getUser( userId );

		System.exit(0);
	}
}


text:
// copyright (c) 2009-2010 satoshi nakamoto
// copyright (c) 2009-2014 the moorecoin core developers
// distributed under the mit software license, see the accompanying
// file copying or http://www.opensource.org/licenses/mit-license.php.

#ifndef moorecoin_init_h
#define moorecoin_init_h

#include <string>

class cscheduler;
class cwallet;

namespace boost
{
class thread_group;
} // namespace boost

extern cwallet* pwalletmain;

void startshutdown();
bool shutdownrequested();
void shutdown();
bool appinit2(boost::thread_group& threadgroup, cscheduler& scheduler);

/** the help message mode determines what help message to show */
enum helpmessagemode {
    hmm_moorecoind,
    hmm_moorecoin_qt
};

/** help for options shared between ui and daemon (for -help) */
std::string helpmessage(helpmessagemode mode);
/** returns licensing information (for -version) */
std::string licenseinfo();

#endif // moorecoin_init_h


text:
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;

namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
    [TestFixture]
    public class NonReadonlyReferencedInGetHashCodeTests : CSharpDiagnosticTestBase
    {

        [Test]
        public void TestInspectorCase1()
        {
            Analyze<NonReadonlyReferencedInGetHashCodeAnalyzer>(@"using System;
public class TestClass1
{
	public int a = 1;
}

public class TestClass2
{
	public override int GetHashCode()
	{
		TestClass1 c = new TestClass1();
		int b = 1;
		b++;
		return c.$a$;
	}
}
");
        }

        [Test]
        public void TestInspectorCase2()
        {
            Analyze<NonReadonlyReferencedInGetHashCodeAnalyzer>(@"using System;
public class TestClass1
{
	public int a = 1;
}

public class TestClass2
{
	private int b;
	public override int GetHashCode()
	{
		TestClass1 c = new TestClass1();
		$b$++;
		return c.$a$;
	}
}");
        }

        [Test]
        public void TestInspectorCase3()
        {
            Analyze<NonReadonlyReferencedInGetHashCodeAnalyzer>(@"using System;
public class TestClass1
{
	public int a = 1;
}

public class TestClass2
{
	public override int GetHashCode()
	{
		TestClass1 c = new TestClass1();
		int b = 1;
		b++;
		return c.GetHashCode();
	}
}");
        }

        [Test]
        public void TestInspectorCase4()
        {
            Analyze<NonReadonlyReferencedInGetHashCodeAnalyzer>(@"
public class Test1
{
	public int a = 1;
}

public class Test2
{
	private int q;
	public Test1 r;
	public override int GetHashCode()
	{
		Test1 c = new Test1();
		$q$ = 1 + $q$ + $r$.$a$;
		return c.$a$;
	}
}

public class Test3
{
	private int q;
	public Test2 r;
	public override int GetHashCode()
	{
		Test1 c = new Test1();
		c.GetHashCode();
		$q$ = 1 + $q$ + $r$.$r$.$a$;
		return c.$a$;
	}
}");
        }

        [Test]
        public void TestDisable()
        {
            Analyze<NonReadonlyReferencedInGetHashCodeAnalyzer>(@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace resharper_test
{
	class Foo
	{
		private readonly int fooval;
		private int tmpval;
#pragma warning disable " + CSharpDiagnosticIDs.NonReadonlyReferencedInGetHashCodeAnalyzerID + @"
		public override int GetHashCode()
		{
			int a = 6;
			tmpval = a + 3;
			a = tmpval + 5;
			return fooval;
		}
	}
}
");
        }

        [Test]
        public void TestConst()
        {
            Analyze<NonReadonlyReferencedInGetHashCodeAnalyzer>(@"using System;
public class TestClass1
{
	public const int a = 1;

	public override int GetHashCode()
	{
		return a;
	}
}
");
        }

        [Test]
        public void TestReadOnly()
        {
            Analyze<NonReadonlyReferencedInGetHashCodeAnalyzer>(@"using System;
public class TestClass1
{
	public readonly int a = 1;

	public override int GetHashCode()
	{
		return a;
	}
}
");
        }
    }
}