text:
require 'active_support/test_case'

module ActionController
  class NonInferrableControllerError < ActionControllerError
    def initialize(name)
      @name = name
      super "Unable to determine the controller to test from #{name}. " +
        "You'll need to specify it using 'tests YourController' in your " +
        "test case definition. This could mean that #{inferred_controller_name} does not exist " +
        "or it contains syntax errors"
    end

    def inferred_controller_name
      @name.sub(/Test$/, '')
    end
  end

  # Superclass for ActionController functional tests. Functional tests allow you to
  # test a single controller action per test method. This should not be confused with
  # integration tests (see ActionController::IntegrationTest), which are more like
  # "stories" that can involve multiple controllers and mutliple actions (i.e. multiple
  # different HTTP requests).
  #
  # == Basic example
  #
  # Functional tests are written as follows:
  # 1. First, one uses the +get+, +post+, +put+, +delete+ or +head+ method to simulate
  #    an HTTP request.
  # 2. Then, one asserts whether the current state is as expected. "State" can be anything:
  #    the controller's HTTP response, the database contents, etc.
  #
  # For example:
  #
  #   class BooksControllerTest < ActionController::TestCase
  #     def test_create
  #       # Simulate a POST response with the given HTTP parameters.
  #       post(:create, :book => { :title => "Love Hina" })
  #
  #       # Assert that the controller tried to redirect us to
  #       # the created book's URI.
  #       assert_response :found
  #
  #       # Assert that the controller really put the book in the database.
  #       assert_not_nil Book.find_by_title("Love Hina")
  #     end
  #   end
  #
  # == Special instance variables
  #
  # ActionController::TestCase will also automatically provide the following instance
  # variables for use in the tests:
  #
  # @controller::
  #      The controller instance that will be tested.
  # @request::
  #      An ActionController::TestRequest, representing the current HTTP
  #      request. You can modify this object before sending the HTTP request. For example,
  #      you might want to set some session properties before sending a GET request.
  # @response::
  #      An ActionController::TestResponse object, representing the response
  #      of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
  #      after calling +post+. If the various assert methods are not sufficient, then you
  #      may use this object to inspect the HTTP response in detail.
  #
  # (Earlier versions of Rails required each functional test to subclass
  # Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
  #
  # == Controller is automatically inferred
  #
  # ActionController::TestCase will automatically infer the controller under test
  # from the test class name. If the controller cannot be inferred from the test
  # class name, you can explicity set it with +tests+.
  #
  #   class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
  #     tests WidgetController
  #   end
  class TestCase < ActiveSupport::TestCase
    # When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline
    # (bystepping the regular exception handling from rescue_action). If the request.remote_addr is anything else, the regular
    # rescue_action process takes place. This means you can test your rescue_action code by setting remote_addr to something else
    # than 0.0.0.0.
    #
    # The exception is stored in the exception accessor for further inspection.
    module RaiseActionExceptions
      attr_accessor :exception

      def rescue_action_without_handler(e)
        self.exception = e

        if request.remote_addr == "0.0.0.0"
          raise(e)
        else
          super(e)
        end
      end
    end

    setup :setup_controller_request_and_response

    @@controller_class = nil

    class << self
      # Sets the controller class name. Useful if the name can't be inferred from test class.
      # Expects +controller_class+ as a constant. Example: <tt>tests WidgetController</tt>.
      def tests(controller_class)
        self.controller_class = controller_class
      end

      def controller_class=(new_class)
        prepare_controller_class(new_class)
        write_inheritable_attribute(:controller_class, new_class)
      end

      def controller_class
        if current_controller_class = read_inheritable_attribute(:controller_class)
          current_controller_class
        else
          self.controller_class = determine_default_controller_class(name)
        end
      end

      def determine_default_controller_class(name)
        name.sub(/Test$/, '').constantize
      rescue NameError
        raise NonInferrableControllerError.new(name)
      end

      def prepare_controller_class(new_class)
        new_class.send :include, RaiseActionExceptions
      end
    end

    def setup_controller_request_and_response
      @controller = self.class.controller_class.new
      @controller.request = @request = TestRequest.new
      @response = TestResponse.new

      @controller.params = {}
      @controller.send(:initialize_current_url)
    end

    # Cause the action to be rescued according to the regular rules for rescue_action when the visitor is not local
    def rescue_action_in_public!
      @request.remote_addr = '208.77.188.166' # example.com
    end
 end
end


text:
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  opacity: <float>,
 *
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,
 *  depthWrite: <bool>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>
 * }
 */

THREE.MeshDepthMaterial = function ( parameters ) {

	THREE.Material.call( this );

	this.type = 'MeshDepthMaterial';

	this.morphTargets = false;
	this.wireframe = false;
	this.wireframeLinewidth = 1;

	this.setValues( parameters );

};

THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.MeshDepthMaterial.prototype.clone = function () {

	var material = new THREE.MeshDepthMaterial();

	THREE.Material.prototype.clone.call( this, material );

	material.wireframe = this.wireframe;
	material.wireframeLinewidth = this.wireframeLinewidth;

	return material;

};

redpajama_set_name: RedPajamaGithub


text:
{
  "type": "Educational event",
  "duration": "PT30M",
  "id": "20130606-introduction-to-gruntjs",
  "name": "Introduction to GruntJS",
  "layout": "page.html",
  "description": "Optimize a web page with a single command. Grunt is the Makefile for JS projects. In this talk I present what is Grunt, which is its philosophy, and a small example how to use it. And the best of it, how to build and optimize everything with a simple command.",
  "superEvent": {
    "type": "Social event",
    "url": "/event/20130606-barcelonajs",
    "id": "20130606-barcelonajs",
    "name": "BarcelonaJS"
  },
  "inLanguage": "en",
  "workPerformed": {
    "type": "CreativeWork",
    "learningResourceType": "presentation",
    "url": "http://drpicox.github.io/gruntjs-presentation-introduction/#/grunt"
  },
  "performer": {
    "type": "Person",
    "name": "Dr. David Rodenas",
    "id": "20130606-introduction-to-gruntjs",
    "twitter": "drpicox",
    "sameAs": "https://twitter.com/@drpicox",
    "url": "/talk/20130606-introduction-to-gruntjs.html",
    "image": "https://pbs.twimg.com/profile_images/2767400938/49663d817fffad1f539c983b203b3067.jpeg"
  },
  "recordedIn": {
    "type": "CreativeWork",
    "video": {
      "type": "VideoObject",
      "id": "https://github.com/drpicox/gruntjs-presentation-introduction"
    }
  }
}
---
# Introduction to GruntJS

Optimize a web page with a single command. Grunt is the Makefile for JS projects. In this talk I present what is Grunt, which is its philosophy, and a small example how to use it. And the best of it, how to build and optimize everything with a simple command.


text:
<?php

namespace Guzzle\Plugin\Cache;

use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;

/**
 * Default strategy used to determine of an HTTP request can be cached
 */
class DefaultCanCacheStrategy implements CanCacheStrategyInterface
{
    public function canCacheRequest(RequestInterface $request)
    {
        // Only GET and HEAD requests can be cached
        if ($request->getMethod() != RequestInterface::GET && $request->getMethod() != RequestInterface::HEAD) {
            return false;
        }

        // Never cache requests when using no-store
        if ($request->hasHeader('Cache-Control') && $request->getHeader('Cache-Control')->hasDirective('no-store')) {
            return false;
        }

        return true;
    }

    public function canCacheResponse(Response $response)
    {
        return $response->isSuccessful() && $response->canCache();
    }
}


text:
import { call, put, takeEvery } from 'redux-saga/effects';

import { getSessionUser, getUserProfile } from '../utils/ajax';
import { jwt } from './cookieValues';
import {
  fetchUserComplete,
  fetchUserError,
  fetchProfileForUserError,
  fetchProfileForUserComplete
} from './';

function* fetchSessionUser() {
  if (!jwt) {
    yield put(fetchUserComplete({ user: {}, username: '' }));
    return;
  }
  try {
    const {
      user = {},
      result = '',
      sessionMeta = {}
    } = yield call(getSessionUser);
    const appUser = user[result] || {};
    yield put(
      fetchUserComplete({ user: appUser, username: result, sessionMeta })
    );
  } catch (e) {
    yield put(fetchUserError(e));
  }
}

function* fetchOtherUser({ payload: maybeUser = '' }) {
  try {
    const maybeUserLC = maybeUser.toLowerCase();

    const { entities: { user = {} } = {}, result = '' } = yield call(
      getUserProfile,
      maybeUserLC
    );
    const otherUser = user[result] || {};
    yield put(
      fetchProfileForUserComplete({ user: otherUser, username: result })
    );
  } catch (e) {
    yield put(fetchProfileForUserError(e));
  }
}

export function createFetchUserSaga(types) {
  return [
    takeEvery(types.fetchUser, fetchSessionUser),
    takeEvery(types.fetchProfileForUser, fetchOtherUser)
  ];
}


text:
class VmCloudController < ApplicationController
  include VmCommon # common methods for vm controllers
  include VmRemote # methods for VM remote access
  include VmShowMixin
  include Mixins::BreadcrumbsMixin

  before_action :check_privileges
  before_action :get_session_data
  after_action :cleanup_action
  after_action :set_session_data

  def self.table_name
    @table_name ||= "vm_cloud"
  end

  def index
    flash_to_session
    redirect_to(:action => 'explorer')
  end

  def attach
    assert_privileges("instance_attach")
    @volume_choices = {}
    @record = @vm = find_record_with_rbac(VmCloud, params[:id])
    @vm.cloud_tenant.cloud_volumes.where(:status => 'available').each { |v| @volume_choices[v.name] = v.id }

    @in_a_form = true
    drop_breadcrumb(
      :name => _("Attach Cloud Volume to Instance \"%{instance_name}\"") % {:instance_name => @vm.name},
      :url  => "/vm_cloud/attach"
    )
    @in_a_form = true
    @refresh_partial = "vm_common/attach"
  end
  alias instance_attach attach

  def detach
    assert_privileges("instance_detach")
    @volume_choices = {}
    @record = @vm = find_record_with_rbac(VmCloud, params[:id])
    attached_volumes = @vm.hardware.disks.select(&:backing).map(&:backing)
    attached_volumes.each { |volume| @volume_choices[volume.name] = volume.id }
    if attached_volumes.empty?
      add_flash(_("Instance \"%{instance_name}\" has no attached Cloud Volumes") % {:instance_name => @vm.name})
      javascript_flash
    end

    @in_a_form = true
    drop_breadcrumb(
      :name => _("Detach Cloud Volume from Instance \"%{instance_name}\"") % {:instance_name => @vm.name},
      :url  => "/vm_cloud/detach"
    )
    @in_a_form = true
    @refresh_partial = "vm_common/detach"
  end
  alias instance_detach detach

  def attach_volume
    assert_privileges("instance_attach")
    @vm = find_record_with_rbac(VmCloud, params[:id])
  end

  def detach_volume
    assert_privileges("instance_detach")
    @vm = find_record_with_rbac(VmCloud, params[:id])
  end

  def flash_and_redirect(message)
    session[:edit] = nil
    add_flash(message)
    @record = @sb[:action] = nil
    replace_right_cell
  end

  private

  def textual_group_list
    [
      %i[properties lifecycle] +
        (@record.kind_of?(VmCloud) ? %i[vm_cloud_relationships] : %i[template_cloud_relationships]) +
        %i[vmsafe miq_custom_attributes ems_custom_attributes labels],
      %i[compliance power_management security configuration diagnostics tags]
    ]
  end
  helper_method :textual_group_list

  def features
    [
      {
        :role  => "instances_accord",
        :name  => :instances,
        :title => _("Instances by Provider")
      },
      {
        :role  => "images_accord",
        :name  => :images,
        :title => _("Images by Provider")
      },
      {
        :role  => "instances_filter_accord",
        :name  => :instances_filter,
        :title => _("Instances")
      },
      {
        :role  => "images_filter_accord",
        :name  => :images_filter,
        :title => _("Images")
      }
    ].map { |hsh| ApplicationController::Feature.new_with_hash(hsh) }
  end

  # redefine get_filters from VmShow
  def get_filters
    session[:instances_filters]
  end

  def prefix_by_nodetype(nodetype)
    case TreeBuilder.get_model_for_prefix(nodetype).underscore
    when "miq_template" then "images"
    when "vm"           then "instances"
    end
  end

  def set_elements_and_redirect_unauthorized_user
    @nodetype, _id = parse_nodetype_and_id(params[:id])
    prefix = prefix_by_nodetype(@nodetype)

    # Position in tree that matches selected record
    if role_allows?(:feature => "instances_accord") && prefix == "instances"
      set_active_elements_authorized_user('instances_tree', 'instances')
    elsif role_allows?(:feature => "images_accord") && prefix == "images"
      set_active_elements_authorized_user('images_tree', 'images')
    elsif role_allows?(:feature => "#{prefix}_filter_accord")
      set_active_elements_authorized_user("#{prefix}_filter_tree", "#{prefix}_filter")
    else
      if (prefix == "vms" && role_allows?(:feature => "vms_instances_filter_accord")) ||
         (prefix == "templates" && role_allows?(:feature => "templates_images_filter_accord"))
        redirect_to(:controller => 'vm_or_template', :action => "explorer", :id => params[:id])
      else
        redirect_to(:controller => 'dashboard', :action => "auth_error")
      end
      return true
    end

    resolve_node_info(params[:id])
  end

  def tagging_explorer_controller?
    @explorer
  end

  def skip_breadcrumb?
    breadcrumb_prohibited_for_action?
  end

  def breadcrumbs_options
    {
      :breadcrumbs    => [
        {:title => _("Compute")},
        {:title => _("Cloud")},
        {:title => _("Instances")},
      ],
      :include_record => true,
      :x_node         => x_node_right_cell
    }
  end

  menu_section :clo
  feature_for_actions %w[instances_filter_accord images_filter_accord], *ADV_SEARCH_ACTIONS
  feature_for_actions 'vm_show', :groups, :users, :patches
  feature_for_actions ['instance_protect', 'image_protect'], :protect
  feature_for_actions ['instance_timeline', 'image_timeline'], :tl_chooser
  feature_for_actions ['instance_perf', 'image_perf'], :perf_top_chart
  has_custom_buttons
end


text:
namespace common {

class Instance;
class Extension;

}  // namespace common

// This function should be implemented by each extension and should return
// an appropriate Extension subclass.
common::Extension* CreateExtension();

namespace common {

class Extension {
 public:
  Extension();
  virtual ~Extension();

  // These should be called in the subclass constructor.
  void SetExtensionName(const char* name);
  void SetJavaScriptAPI(const char* api);
  void SetExtraJSEntryPoints(const char** entry_points);
  bool RegisterPermissions(const char* perm_table);

  // This API should be called in the message handler of extension
  bool CheckAPIAccessControl(const char* api_name);

  virtual Instance* CreateInstance();

  static std::string GetRuntimeVariable(const char* var_name, unsigned len);

 private:
  friend int32_t ::XW_Initialize(XW_Extension extension,
                                 XW_GetInterface get_interface);

  // XW_Extension callbacks.
  static void OnShutdown(XW_Extension xw_extension);
  static void OnInstanceCreated(XW_Instance xw_instance);
  static void OnInstanceDestroyed(XW_Instance xw_instance);
  static void HandleMessage(XW_Instance xw_instance, const char* msg);
  static void HandleSyncMessage(XW_Instance xw_instance, const char* msg);
};

class Instance {
 public:
  Instance();
  virtual ~Instance();

  void PostMessage(const char* msg);
  void SendSyncReply(const char* reply);

  virtual void Initialize() {}
  virtual void HandleMessage(const char* msg) = 0;
  virtual void HandleSyncMessage(const char* msg) {}

  XW_Instance xw_instance() const { return xw_instance_; }

 private:
  friend class Extension;

  XW_Instance xw_instance_;
};

}  // namespace common

#endif  // COMMON_EXTENSION_H_


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>VariableContext (IceSoap 1.1.1 API)</title>
<meta name="date" content="2016-04-21">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jaxen

Interface VariableContext

All Known Implementing Classes:

SimpleVariableContext

public interface VariableContext

Resolves variable bindings within an XPath expression.

  Variables within an XPath expression are denoted using
  notation such as $varName or
  $nsPrefix:varName, and may
  refer to a Boolean, Double, String,
  node-set (List) or individual XML node.

  When a variable is bound to a node-set, the
  actual Java object returned should be a java.util.List
  containing XML nodes from the object-model (e.g. dom4j, JDOM, DOM, etc.)
  being used with the XPath.

  A variable may validly be assigned the null value,
  but an unbound variable (one that this context does not know about)
  should cause an UnresolvableException to be thrown.

  Implementations of this interface should implement Serializable.

Author:

bob mcwhirter, James Strachan

See Also:

SimpleVariableContext,
NamespaceContext

Method Summary

Methods

Modifier and Type
Method and Description

Object
getVariableValue(String namespaceURI,
                String prefix,
                String localName)

An implementation should return the value of an XPath variable
  based on the namespace URI and local name of the variable-reference
  expression.

Method Detail

getVariableValue

Object getVariableValue(String namespaceURI,
                      String prefix,
                      String localName)
                        throws UnresolvableException

An implementation should return the value of an XPath variable
  based on the namespace URI and local name of the variable-reference
  expression.

  It must not use the prefix parameter to select a variable,
  because a prefix could be bound to any namespace; the prefix parameter
  could be used in debugging output or other generated information.
  The prefix may otherwise be ignored.

Parameters:

namespaceURI - the namespace URI to which the prefix parameter
                       is bound in the XPath expression. If the variable
                       reference expression had no prefix, the namespace
                       URI is null.

prefix - the prefix that was used in the variable reference
                       expression; this value is ignored and has no effect

localName - the local name of the variable-reference
                       expression. If there is no prefix, then this is
                       the whole name of the variable.

Returns:

the variable's value (which can be null)

Throws:

UnresolvableException - when the variable cannot be resolved

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016. All rights reserved.


text:
import socket
import sys
import time
import subprocess
import os

# function to get free port from ycmd
def GetUnusedLocalhostPort():
  sock = socket.socket()
  # This tells the OS to give us any free port in the range [1024 - 65535]
  sock.bind(('', 0))
  port = sock.getsockname()[1]
  sock.close()
  return port

SERVER = ('127.0.0.1', GetUnusedLocalhostPort())

# A wrapper for subprocess.Popen that works around a Popen bug on Windows.
def SafePopen(*args, **kwargs):
    if kwargs.get('stdin') is None:
        kwargs['stdin'] = subprocess.PIPE if sys.platform == 'win32' else None

    return subprocess.Popen( *args, **kwargs )

class JavaviBridge():

    sock = None
    popen = None

    def setupServer(self, javabin, args, classpath):
        environ = os.environ
        if 'CLASSPATH' in environ:
            environ['CLASSPATH'] = environ['CLASSPATH'] + (';' if sys.platform == 'win32' else ':') + classpath
        else:
            environ['CLASSPATH'] = classpath
        self.popen = SafePopen(javabin + ' ' + args + ' ' + str(SERVER[1]), shell=True, env=environ, stdout = subprocess.PIPE, stderr = subprocess.PIPE)

    def pid(self):
        return self.popen.pid

    def port(self):
        return SERVER[1]

    def poll(self):
        return self.popen.poll() is None

    def terminateServer(self):
        self.popen.terminate()

    def makeSocket(self):
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as msg:
            self.sock = None

        try:
            self.sock.connect(SERVER)
            time.sleep(.1)
        except socket.error as msg:
            self.sock.close()
            self.sock = None

        if self.sock is None:
            print('could not open socket, try again')
            return

        self.sock.setblocking(0)

    def send(self, data):
        if self.sock is None:
            print("creating socket")
            self.makeSocket()
            if self.sock is None:
                return ''

        self.sock.sendall(data + '\n')
        totalData = []
        while 1:
            try:
                data = self.sock.recv(4096)
                if not data or len(data) == 0:
                    break

                totalData.append(data)
                time.sleep(.01)
            except:
                if totalData: break

        self.sock.close()
        self.sock = None
        return ''.join(totalData)


text:
package damhonglinh.view;

import damhonglinh.model.Model;

import javax.swing.*;
import java.awt.*;

/**
 * User: Dam Linh
 * Date: 17/04/14
 */
public class OrganizeTab extends JPanel {

    private Model model;

    public OrganizeTab(Model model) {
        this.model = model;
        setBackground(Color.WHITE);

    }
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.olia.processflyer.shared.bpmn.template.impl;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.rpc.IsSerializable;
import com.olia.processflyer.shared.bpmn.template.Node;
import com.olia.processflyer.shared.bpmn.template.NodeType;
import com.olia.processflyer.shared.bpmn.template.NodeVisitor;
import com.olia.processflyer.shared.bpmn.template.RenderingInformation;
import com.olia.processflyer.shared.bpmn.template.element.Label;
import com.olia.processflyer.shared.bpmn.template.element.NodeConnector;

/**
 * DOCME
 *
 * @author Philipp Kanne
 */
public abstract class AbstractBaseNode<NODE_TYPE extends NodeType> implements Node<NODE_TYPE>, IsSerializable
{
    private String uniqueIdentifier;

    private List<NodeConnector> incoming = new ArrayList<NodeConnector>();

    private List<NodeConnector> outgoing = new ArrayList<NodeConnector>();

    private Label label = null;

    private RenderingInformation renderingData = null;

    private NODE_TYPE type;

    public AbstractBaseNode()
    {
        super();
    }

    @Override
    public String getUniqueIdentifier()
    {
        return uniqueIdentifier;
    }

    public void setUniqueIdentifier(String uniqueIdentifier)
    {
        this.uniqueIdentifier = uniqueIdentifier;
    }

    @Override
    public List<NodeConnector> getIncoming()
    {
        return incoming;
    }

    public void setIncoming(List<NodeConnector> incoming)
    {
        this.incoming = incoming;
    }

    @Override
    public List<NodeConnector> getOutgoing()
    {
        return outgoing;
    }

    public void setOutgoing(List<NodeConnector> outgoing)
    {
        this.outgoing = outgoing;
    }

    public boolean addOutgoing(NodeConnector newConnection)
    {
        if (newConnection != null)
        {
            return outgoing.add(newConnection);
        }
        return false;
    }

    public boolean addIncoming(NodeConnector newConnection)
    {
        if (newConnection != null)
        {
            return incoming.add(newConnection);
        }
        return false;
    }

    @Override
    public Label getLabel()
    {
        return label;
    }

    public void setLabel(Label label)
    {
        this.label = label;
    }

    public boolean hasLabel()
    {
        return label != null;
    }

    @Override
    public void accept(NodeVisitor visitor)
    {
        visitor.visit(this);
    }

    @Override
    public RenderingInformation getRenderingData()
    {
        return renderingData;
    }

    public void setRenderingData(RenderingInformation renderingData)
    {
        this.renderingData = renderingData;
    }

    @Override
    public NODE_TYPE getType()
    {
        return type;
    }

    public void setType(NODE_TYPE type)
    {
        this.type = type;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((uniqueIdentifier == null) ? 0 : uniqueIdentifier.hashCode());
        return result;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (obj == null)
        {
            return false;
        }
        if (getClass() != obj.getClass())
        {
            return false;
        }
        AbstractBaseNode other = (AbstractBaseNode) obj;
        if (uniqueIdentifier == null)
        {
            if (other.uniqueIdentifier != null)
            {
                return false;
            }
        }
        else if (!uniqueIdentifier.equals(other.uniqueIdentifier))
        {
            return false;
        }
        return true;
    }

    @Override
    public String toString()
    {
        return "Node [uniqueIdentifier=" + uniqueIdentifier + ", type=" + getType() + "]";
    }

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

    @Override
    public boolean isConnector()
    {
        return false;
    }

    @Override
    public boolean isStartNode()
    {
        return false;
    }

    @Override
    public boolean isEndNode()
    {
        return false;
    }

}


text:
package org.wso2.carbon.apimgt.usage.publisher;

import org.apache.axis2.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.rest.AbstractHandler;
import org.apache.synapse.rest.RESTConstants;
import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants;
import org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityUtils;
import org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.usage.publisher.dto.RequestPublisherDTO;
import org.wso2.carbon.apimgt.usage.publisher.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.usage.publisher.internal.UsageComponent;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class APIMgtUsageHandler extends AbstractHandler {

    private static final Log log = LogFactory.getLog(APIMgtUsageHandler.class);

    private volatile APIMgtUsageDataPublisher publisher;

    public boolean handleRequest(MessageContext mc) {

        boolean enabled = DataPublisherUtil.getApiManagerAnalyticsConfiguration().isAnalyticsEnabled();

        /*setting global analytic enabled status. Which use at by the by bam mediator in
        synapse to enable or disable destination based stat publishing*/
        mc.setProperty("isStatEnabled", Boolean.toString(enabled));

        boolean skipEventReceiverConnection = DataPublisherUtil.getApiManagerAnalyticsConfiguration().
                isSkipEventReceiverConnection();

        String publisherClass = UsageComponent.getAmConfigService().
                getAPIAnalyticsConfiguration().getPublisherClass();
        try {
            long currentTime = System.currentTimeMillis();

            if (!enabled || skipEventReceiverConnection) {
                return true;
            }

            if (publisher == null) {
                // The publisher initializes in the first request only
                synchronized (this) {
                    if (publisher == null) {
                        try {
                            log.debug("Instantiating Data Publisher");
                            publisher = (APIMgtUsageDataPublisher) APIUtil.getClassForName(publisherClass).newInstance();
                            publisher.init();
                        } catch (ClassNotFoundException e) {
                            log.error("Class not found " + publisherClass);
                        } catch (InstantiationException e) {
                            log.error("Error instantiating " + publisherClass);
                        } catch (IllegalAccessException e) {
                            log.error("Illegal access to " + publisherClass);
                        }
                    }
                }
            }

            AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(mc);
            String consumerKey = "";
            String username = "";
            String applicationName = "";
            String applicationId = "";
            String tier = "";
            if (authContext != null) {
                consumerKey = authContext.getConsumerKey();
                username = authContext.getUsername();
                applicationName = authContext.getApplicationName();
                applicationId = authContext.getApplicationId();
                tier = authContext.getTier();
            }
            String hostName = DataPublisherUtil.getHostAddress();
            org.apache.axis2.context.MessageContext axis2MsgContext = ((Axis2MessageContext) mc).getAxis2MessageContext();
            Map headers = (Map) (axis2MsgContext).
                    getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            String userAgent = (String) headers.get(APIConstants.USER_AGENT);
            String context = (String) mc.getProperty(RESTConstants.REST_API_CONTEXT);
            String api_version = (String) mc.getProperty(RESTConstants.SYNAPSE_REST_API);
            String fullRequestPath = (String) mc.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);
            int tenantDomainIndex = fullRequestPath.indexOf("/t/");
            String apiPublisher = (String) mc.getProperty(APIMgtGatewayConstants.API_PUBLISHER);
            String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            if (tenantDomainIndex != -1) {
                String temp = fullRequestPath.substring(tenantDomainIndex + 3, fullRequestPath.length());
                tenantDomain = temp.substring(0, temp.indexOf("/"));
            }

            if (apiPublisher == null) {
                apiPublisher = getAPIProviderFromRESTAPI(api_version);
            }

            if (apiPublisher != null && !apiPublisher.endsWith(tenantDomain)) {
                apiPublisher = apiPublisher + "@" + tenantDomain;
            }

            int index = api_version.indexOf("--");

            if (index != -1) {
                api_version = api_version.substring(index + 2);
            }

            String api = api_version.split(":")[0];
            index = api.indexOf("--");
            if (index != -1) {
                api = api.substring(index + 2);
            }
            String version = (String) mc.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
            String resource = extractResource(mc);
            String method = (String) (axis2MsgContext.getProperty(
                    Constants.Configuration.HTTP_METHOD));
            String userTenantDomain = MultitenantUtils.getTenantDomain(username);
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().
                    getTenantId(userTenantDomain);

            Object throttleOutProperty = mc.getProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY);
            boolean throttleOutHappened = false;
            if (throttleOutProperty != null && throttleOutProperty instanceof Boolean) {
                throttleOutHappened = (Boolean) throttleOutProperty;
            }

            RequestPublisherDTO requestPublisherDTO = new RequestPublisherDTO();
            requestPublisherDTO.setConsumerKey(consumerKey);
            requestPublisherDTO.setContext(context);
            requestPublisherDTO.setApi_version(api_version);
            requestPublisherDTO.setApi(api);
            requestPublisherDTO.setVersion(version);
            requestPublisherDTO.setResourcePath(resource);
            requestPublisherDTO.setMethod(method);
            requestPublisherDTO.setRequestTime(currentTime);
            requestPublisherDTO.setUsername(username);
            requestPublisherDTO.setTenantDomain((MultitenantUtils.getTenantDomain(apiPublisher)));
            requestPublisherDTO.setHostName(hostName);
            requestPublisherDTO.setApiPublisher(apiPublisher);
            requestPublisherDTO.setApplicationName(applicationName);
            requestPublisherDTO.setApplicationId(applicationId);
            requestPublisherDTO.setUserAgent(userAgent);
            requestPublisherDTO.setTier(tier);
            requestPublisherDTO.setContinuedOnThrottleOut(throttleOutHappened);

            publisher.publishEvent(requestPublisherDTO);

            //Metering related publishing is no longer used.
            /*//We check if usage metering is enabled for billing purpose
            if (DataPublisherUtil.isEnabledMetering()) {
                //If usage metering enabled create new usage stat object and publish to bam
                APIManagerRequestStats stats = new APIManagerRequestStats();
                stats.setRequestCount(1);
                stats.setTenantId(tenantId);
                try {
                    //Publish stat to bam
                    PublisherUtils.publish(stats, tenantId);
                } catch (Exception e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e);
                    }
                    log.error("Error occurred while publishing request statistics. Full stacktrace available in debug logs. " + e.getMessage());
                }
            }*/

        } catch (Throwable e) {
            log.error("Cannot publish event. " + e.getMessage(), e);
        }
        return true;
    }

    private String getAPIProviderFromRESTAPI(String api_version) {
        int index = api_version.indexOf("--");
        if (index != -1) {
            String apiProvider = api_version.substring(0, index);
            if (apiProvider.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT)) {
                apiProvider = apiProvider.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT,
                                      APIConstants.EMAIL_DOMAIN_SEPARATOR);
            }
            return apiProvider;
        }
        return null;
    }

    public boolean handleResponse(MessageContext mc) {
        return true;

    }

    private String extractResource(MessageContext mc) {
        String resource = "/";
        Pattern pattern = Pattern.compile("^/.+?/.+?([/?].+)$");
        Matcher matcher = pattern.matcher((String) mc.getProperty(RESTConstants.REST_FULL_REQUEST_PATH));
        if (matcher.find()) {
            resource = matcher.group(1);
        }
        return resource;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.heed.justquotes.activities.MainActivity"
    tools:showIn="@layout/activity_main" />


text:
using EasyLOB.Data;
using System.Collections.Generic;

namespace EasyLOB.Identity.Data
{
    public partial class UserClaim
    {
        #region Profile

        public static IZProfile Profile { get; private set; } = new ZProfile
        (
            Name: "UserClaim",
            IsIdentity: true,
            Keys: new List<string> { "Id" },
            Lookup: "UserId",
            LINQOrderBy: "UserId",
            LINQWhere: "Id == @0",
            Associations: new List<string>
            {
                "User"
            },
            Collections: new Dictionary<string, bool> { },
            Properties: new List<IZProfileProperty>
            {
                //                   Grd    Grd    Grd  Edt    Edt    Edt
                //                   Vis    Src    Wdt  Vis    RO     CSS         Name
                new ZProfileProperty(false, true , 100, false, false, "col-md-1", "Id"),
                new ZProfileProperty(false, false, 200, true , false, "col-md-4", "UserId"),
                new ZProfileProperty(true , true , 100, false, false, "col-md-4", "UserLookupText"),
                new ZProfileProperty(true , true , -10, true , false, "col-md-1", "ClaimType"),
                new ZProfileProperty(true , true , -10, true , false, "col-md-1", "ClaimValue")
            }
        );

        #endregion Profile
    }
}


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

<phpunit bootstrap="vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="GraphProcessing Test Suite">
            <directory>tests/GraphProcessing/</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
package org.springframework.beans.factory.xml;

import org.junit.Before;
import org.junit.Test;

import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.io.ClassPathResource;

import static org.junit.Assert.*;

/**
 * @author Rob Harrop
 * @author Juergen Hoeller
 */
public class BeanNameGenerationTests {

	private DefaultListableBeanFactory beanFactory;

	@Before
	public void setUp() {
		this.beanFactory = new DefaultListableBeanFactory();
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
		reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
		reader.loadBeanDefinitions(new ClassPathResource("beanNameGeneration.xml", getClass()));
	}

	@Test
	public void naming() {
		String className = GeneratedNameBean.class.getName();

		String targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "0";
		GeneratedNameBean topLevel1 = (GeneratedNameBean) beanFactory.getBean(targetName);
		assertNotNull(topLevel1);

		targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "1";
		GeneratedNameBean topLevel2 = (GeneratedNameBean) beanFactory.getBean(targetName);
		assertNotNull(topLevel2);

		GeneratedNameBean child1 = topLevel1.getChild();
		assertNotNull(child1.getBeanName());
		assertTrue(child1.getBeanName().startsWith(className));

		GeneratedNameBean child2 = topLevel2.getChild();
		assertNotNull(child2.getBeanName());
		assertTrue(child2.getBeanName().startsWith(className));

		assertFalse(child1.getBeanName().equals(child2.getBeanName()));
	}

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items>
   <item>
      <provider>Youtube</provider>
      <title>Romanian Pro Wrestling</title>
      <id>UCWSpfTNcypRjru03Vj1CxPQ</id>
      <logo>-jRZhnD2BTak/AAAAAAAAAAI/AAAAAAAAAAA/c38-em5TEh8/s100-c-k-no-mo-rj-c0xffffff/photo.jpg</logo>
      <customlogo></customlogo>
   </item>
</items>


text:
/*
The API keys used below (openWeatherAPI and nytAPI) are located in the apiKeys.js file
which I have added to the .gitignore file so they aren't exposed on GitHub.
*/

$(function(){
	var latitude;
	var longitude;
	var weatherURL;
	var mapsURL;
	var nytUrl;
	var city;
	var farenheit;
	var celsius;
	var kelvin;
	var main;
	var description;
	var nytHeaderElem = $('#nytimes-header');
	var body = $('body');
	var icon;

	navigator.geolocation.getCurrentPosition(success,error);

	function success(position){
		latitude=position.coords.latitude;
		longitude=position.coords.longitude;
		weatherURL='http://api.openweathermap.org/data/2.5/weather?lat='+latitude+'&lon='+longitude+'&APPID='+openWeatherAPI;
		mapsURL = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + '%2C' + longitude + '&language=en';
		gMaps();
	}

	function error(){
		$("#city").html("Please use a different browser than Chrome or allow location tracking.");
	}

	// Open Weather Map API
	function openWeather(){
			$.getJSON(weatherURL).done(function(data){
					icon=data.weather[0].icon;
					picture="url(http://openweathermap.org/img/w/"+icon+".png)";
					description=data.weather[0].description;
					kelvin=data.main.temp;
					celsius=(kelvin-273.15).toFixed(1);
					farenheit=(1.8*(kelvin-273)+32).toFixed(1);
					$("#cityState").html(city+", "+state);
					$("#country").html(country);
					$("#weather").html(farenheit+"&#176 F");
					$("#description").html(description);
					$(".icon").css({"background-image":picture});
			})
	}
	// New York Times API
	function nyt(){
		    nytUrl = 'http://api.nytimes.com/svc/search/v2/articlesearch.json?&q='+city+','+state+'&page=0&api-key='+nytAPI;
		    $.getJSON(nytUrl).done(function(data){
		        var articles=[];
		        $.each(data.response.docs,function(key){
		            articles.push("
"+data.response.docs[key].headline.main+"

"+data.response.docs[key].snippet+"
");
		        });
		        $("
",{
		            "class": "article-list",
		            html: articles.join("")
		        }).appendTo(body);
			    }).error(function(){
			        $(nytHeaderElem).text("New York Times articles could not be loaded.");
			    });
	}
	// Google Maps API
	function gMaps(){
		$.getJSON(mapsURL).done(function(location) {
            	country = location.results[0].address_components[6].short_name;
            	state = location.results[0].address_components[5].long_name;
            	city = location.results[0].address_components[3].long_name;
            	openWeather();
				nyt();
            })
	}

	// toggle between Farenheit and Celsius
	var isClicked = false;
	$('#weather').on("click",function(){
		if (isClicked == false){
			$(this).html(celsius+"&#176 C");
			isClicked = true;
		}
		else{
			$(this).html(farenheit+"&#176 F");
			isClicked = false;
		}
	});
});


text:
#ifndef __X_MEGA_TEXTURE__
#define __X_MEGA_TEXTURE__

#pragma once

#include "common/xString.h"

class xMegaTexture
{
public:

  /* enum
  {
    ID = 0xabcdef01
  }; */

  struct Cluster
  {
    int x, y;
    byte * image;

    Cluster(){ x = y = 0; image = NULL; }
    ~Cluster(){ delete [] image; }
  };

  static int FindClusterNum(Cluster ** clusters, int size, int x, int y)
  {
    for(int i = 0; i < size; i++)
    {
      if(clusters[i] && clusters[i]->x == x && clusters[i]->y == y)
        return i;
    }
    return -1;
  }

  struct MipLayer
  {
    int width, height;
    // int mip;
    int x, y;

    Cluster ** clusters;

    MipLayer()
    {
      width = height = 0;
      x = y = 0;
      // mip = 0;
      clusters = NULL;
    }
    ~MipLayer()
    {
      int size = width * height;
      for(int i = 0; i < size; i++)
      {
        delete clusters[i];
      }
      delete [] clusters;
    }

    Cluster * FindCluster(int x, int y)
    {
      int i = FindClusterNum(clusters, width * height, x, y);
      return i >= 0 ? clusters[i] : NULL;
    }
  };

protected:

  /* enum
  {
    CLUSTER_ERROR_POS = -1000000
  };

  struct Header
  {
    int id;
    int fullWidth;
    int fullHeight;
    int clusterSize;
    int flags;
  }; */

  MipLayer * layers;
  int layersNumber;

  xString filename;
  int clusterSize;
  int layerSize;

  byte * FillErrorCluster(byte * buf);
  byte * LoadMip(byte * buf, int mip, int x, int y);

  // byte * Cluster(MipLayer * layer, int i, int j);

public:

  xMegaTexture();
  ~xMegaTexture();

  void Init(const xString& p_filename, int p_layersNumber, int p_clusterSize, int p_layerSize);

  // void UpdateLayers(int x, int y, int width, int height);
  void UpdateLayer(int layerNum, int x, int y, int width, int height);
  void GetTexture(int layerNum, int x, int y, int width, int height,
    byte * dst, int pitch, int dstWidth, int dstHeight, int pixelBits);

  int ClusterSize() const { return clusterSize; }

  static bool Make(const xString& filename,
    const xString& dstPrefix, int clusterSize = 128);
};

#endif // __X_MEGA_TEXTURE__


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../../../../libc/constant.EADV.html">

Redirecting to ../../../../../../../libc/constant.EADV.html...


text:
#ifndef __CINT__
#include <AliRsnListOutput.h>
#include <AliRsnValuePair.h>
#include <AliRsnValueEvent.h>
#include <AliRsnMiniAnalysisTask.h>
#endif

void AddRsnPairsPhi(AliAnalysisTaskSE *task,
                    Bool_t isMC,
                    Bool_t isMixing,
                    AliPID::EParticleType pType1,
                    Int_t listID1,
                    AliPID::EParticleType pType2,
                    Int_t listID2,
                    AliRsnCutSet *cutsEvent=0,
                    AliRsnCutSet *cutsPair=0,
                    TString suffix = "") {

   Printf("id1=%d id2=%d",listID1,listID2);

   // retrieve mass from PDG database
   Int_t         pdg  = 333;
   TDatabasePDG *db   = TDatabasePDG::Instance();
   TParticlePDG *part = db->GetParticle(pdg);
   Double_t mass = part->Mass();
   Bool_t valid;
   Int_t isRsnMini = AliAnalysisManager::GetGlobalInt("rsnUseMiniPackage",valid);

   if (isRsnMini) {
      AddPairOutputMiniPhi(task,isMC,isMixing,pType1,listID1,pType2,listID2,pdg,mass,cutsPair,suffix);
   } else {
      // this function is common and it is located in RsnConfig.C
      // as ouptup AddPairOutputPhi from this macro will be taken
      AddPair(task,isMC,isMixing,pType1,listID1,pType2,listID2,pdg,mass,cutsEvent,cutsPair,suffix);
   }
}
void AddPairOutputPhi(AliRsnLoopPair *pair)
{
   Bool_t valid;
   Int_t isFullOutput = AliAnalysisManager::GetGlobalInt("rsnOutputFull",valid);
   Int_t isPP = AliAnalysisManager::GetGlobalInt("rsnIsPP",valid);
   Int_t useRapidity = AliAnalysisManager::GetGlobalInt("rsnUseRapidity",valid);

   // axes
   AliRsnValuePair *axisIM = new AliRsnValuePair("IM", AliRsnValuePair::kInvMass);
   AliRsnValuePair *axisPt = new AliRsnValuePair("PT", AliRsnValuePair::kPt);
   AliRsnValuePair *axisEta = new AliRsnValuePair("ETA", AliRsnValuePair::kEta);
   AliRsnValuePair *axisRapidity = new AliRsnValuePair("Y", AliRsnValuePair::kY);

   AliRsnValueEvent *axisCentrality = 0;
   if (!isPP) axisCentrality = new AliRsnValueEvent("MULTI",AliRsnValueEvent::kCentralityV0);

   axisIM     ->SetBins(300, 0.9, 1.2);
//   axisIM     ->SetBins(1000, 0.9, 1.9);
   axisPt     ->SetBins(120, 0.0, 12.0);
//    axisEta    ->SetBins(400, -2.0, 2.0);
   axisEta    ->SetBins(400, -0.5, 0.5);
   axisRapidity    ->SetBins(10, -0.5, 0.5);

   if (axisCentrality) axisCentrality->SetBins(20,0,100);

   // output: 2D histogram of inv. mass vs. pt
   AliRsnListOutput *outPair = 0;
   if (!isFullOutput) {
      outPair = new AliRsnListOutput("pair", AliRsnListOutput::kHistoDefault);
      outPair->AddValue(axisIM);
   } else {
      outPair = new AliRsnListOutput("pair", AliRsnListOutput::kHistoSparse);
      outPair->AddValue(axisIM);
      outPair->AddValue(axisPt);
      if (useRapidity) outPair->AddValue(axisRapidity);
      else outPair->AddValue(axisEta);
      if (axisCentrality) outPair->AddValue(axisCentrality);
   }
   // add outputs to loop
   pair->AddOutput(outPair);
}

void AddPairOutputMiniPhi(AliAnalysisTaskSE *task, Bool_t isMC,Bool_t isMixing, AliPID::EParticleType pType1,Int_t listID1, AliPID::EParticleType pType2,Int_t listID2, Int_t pdgMother,Double_t massMother, AliRsnCutSet *cutsPair=0,TString suffix = "") {

   Bool_t valid;
   Int_t isFullOutput = AliAnalysisManager::GetGlobalInt("rsnOutputFull",valid);
   Int_t useMixing = AliAnalysisManager::GetGlobalInt("rsnUseMixing",valid);
   Int_t isPP = AliAnalysisManager::GetGlobalInt("rsnIsPP",valid);

   Int_t useRapidity = AliAnalysisManager::GetGlobalInt("rsnUseRapidity",valid);

   AliRsnMiniAnalysisTask *taskRsnMini =  (AliRsnMiniAnalysisTask *)task;

   if (isPP) taskRsnMini->UseMultiplicity("QUALITY");
   else {
      taskRsnMini->UseCentrality("V0M");
      Int_t multID = taskRsnMini->CreateValue(AliRsnMiniValue::kMult, kFALSE);
      AliRsnMiniOutput *outMult = taskRsnMini->CreateOutput("eventMult", "HIST", "EVENT");
      outMult->AddAxis(multID, 100, 0.0, 100.0);
      Int_t paID = taskRsnMini->CreateValue(AliRsnMiniValue::kPlaneAngle, kFALSE);
      AliRsnMiniOutput *outPa = taskRsnMini->CreateOutput("planeAngle", "HIST", "EVENT");
      outPa->AddAxis(paID, 100, 0, TMath::Pi());
   }

   /* invariant mass   */ Int_t imID   = taskRsnMini->CreateValue(AliRsnMiniValue::kInvMass, kFALSE);
   /* IM resolution    */ Int_t resID  = taskRsnMini->CreateValue(AliRsnMiniValue::kInvMassDiff, kTRUE);
   /* transv. momentum */ Int_t ptID   = taskRsnMini->CreateValue(AliRsnMiniValue::kPt, kFALSE);
   /* centrality       */ Int_t centID = taskRsnMini->CreateValue(AliRsnMiniValue::kMult, kFALSE);
   /* eta              */ Int_t etaID = taskRsnMini->CreateValue(AliRsnMiniValue::kEta, kFALSE);
   /* rapidity         */ Int_t yID = taskRsnMini->CreateValue(AliRsnMiniValue::kY, kFALSE);

   // use an array for more compact writing, which are different on mixing and charges
   // [0] = unlike
   // [1] = mixing
   // [2] = like ++
   // [3] = like --
   Bool_t  use     [5] = { 1      ,  useMixing      ,  1      ,  1      ,  isMC  };
   TString name    [5] = {"Unlike", "Mixing", "LikePP", "LikeMM", "Trues"};
   TString comp    [5] = {"PAIR"  , "MIX"   , "PAIR"  , "PAIR"  , "TRUE" };
   Char_t  charge1 [5] = {'+'     , '+'     , '+'     , '-'     , '+'    };
   Char_t  charge2 [5] = {'-'     , '-'     , '+'     , '-'     , '-'    };

   // common definitions
   TString outputType = "HIST";
   if (isFullOutput) outputType = "SPARSE";

   Int_t nIM   = 300; Double_t minIM   = 0.9, maxIM =  1.2;
//    Int_t nEta   = 400; Double_t minEta   = -2.0, maxEta =  2.0;
   Int_t nEta   = 400; Double_t minEta   = -0.5, maxEta =  0.5;
   Int_t nY   = 10; Double_t minY   = -0.5, maxY =  0.5;
//   Int_t nIM   = 1000; Double_t minIM   = 0.9, maxIM =  1.9;
   Int_t nPt   = 120; Double_t minPt   = 0.0, maxPt = 12.0;
   Int_t nCent = 100; Double_t minCent = 0.0, maxCent = 100.0;
   Int_t nRes  = 200; Double_t maxRes  = 0.01;

   // retrieve mass from PDG database
   Int_t         pdg  = 333;
   TDatabasePDG *db   = TDatabasePDG::Instance();
   TParticlePDG *part = db->GetParticle(pdg);

   Printf(suffix.Data());
   // create standard outputs
   for (Int_t i = 0; i < 5; i++) {
      if (!use[i]) continue;
      // create output
      AliRsnMiniOutput *out = taskRsnMini->CreateOutput(Form("%s_%s", suffix.Data(),name[i].Data() ), outputType.Data(), comp[i].Data());
      // selection settings
      out->SetCutID(0, listID1);
      out->SetCutID(1, listID1);
      out->SetDaughter(0, AliRsnDaughter::kKaon);
      out->SetDaughter(1, AliRsnDaughter::kKaon);
      out->SetCharge(0, charge1[i]);
      out->SetCharge(1, charge2[i]);
      out->SetMotherPDG(pdg);
      out->SetMotherMass(part->Mass());
      // pair cuts
      if (cutsPair) out->SetPairCuts(cutsPair);
      // axis X: invmass
      out->AddAxis(imID, nIM, minIM, maxIM);

      if (isFullOutput) {
         // axis Y: transverse momentum
         out->AddAxis(ptID, nPt, minPt, maxPt);

         if (useRapidity) out->AddAxis(yID, nY, minY, maxY);
         else  out->AddAxis(etaID, nEta, minEta, maxEta);
         // axis Z: centrality
         if (!isPP) out->AddAxis(centID, nCent, minCent, maxCent);
      }
   }

   // add output for resolution
   if (isMC) {
      AliRsnMiniOutput *outRes = taskRsnMini->CreateOutput(Form("phi_Res%s", suffix.Data()), outputType.Data(), "TRUE");
      // selection settings
      outRes->SetCutID(0, listID1);
      outRes->SetCutID(1, listID1);
      outRes->SetDaughter(0, AliRsnDaughter::kKaon);
      outRes->SetDaughter(1, AliRsnDaughter::kKaon);
      outRes->SetCharge(0, '+');
      outRes->SetCharge(1, '-');
      outRes->SetMotherPDG(pdg);
      outRes->SetMotherMass(part->Mass());
      // pair cuts
      if (cutsPair) outRes->SetPairCuts(cutsPair);
      // axis X: resolution
      outRes->AddAxis(resID, nRes, -maxRes, maxRes);

      if (isFullOutput) {
         // axis Y: transverse momentum
         outRes->AddAxis(ptID, nPt, minPt, maxPt);
         if (useRapidity) outRes->AddAxis(yID, nY, minY, maxY);
         else  outRes->AddAxis(etaID, nEta, minEta, maxEta);
         // axis Z: centrality
         if (!isPP) outRes->AddAxis(centID, nCent, minCent, maxCent);
      }
   }

   //
   // -- Create output for MC generated ------------------------------------------------------------
   //

   if (isMC) {
      // create ouput
      AliRsnMiniOutput *outMC = taskRsnMini->CreateOutput(Form("phi_MCGen%s", suffix.Data()), outputType.Data(), "MOTHER");
      // selection settings
      outMC->SetDaughter(0, AliRsnDaughter::kKaon);
      outMC->SetDaughter(1, AliRsnDaughter::kKaon);
      outMC->SetMotherPDG(pdg);
      outMC->SetMotherMass(part->Mass());
      // pair cuts
      if (cutsPair) outMC->SetPairCuts(cutsPair);
      // axis X: invmass
      outMC->AddAxis(imID, nIM, minIM, maxIM);
      if (isFullOutput) {
         // axis Y: transverse momentum
         outMC->AddAxis(ptID, nPt, minPt, maxPt);
         if (useRapidity) outMC->AddAxis(yID, nY, minY, maxY);
         else  outMC->AddAxis(etaID, nEta, minEta, maxEta);
         // axis Z: centrality
         if (!isPP) outMC->AddAxis(centID, nCent, minCent, maxCent);
      }
   }

}


text:
package com.github.golimpio.atm.services;

import com.github.golimpio.atm.model.Cash;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

class Dispenser {

    private AtomicLong numberOfNotes = new AtomicLong(0L);
    private Cash.Note note;
    private Dispenser next = null;
    private long notesToDispense = 0;

    Dispenser(Cash.Note note) {
        this.note = note;
    }

    /**
     * Calculate the number of notes to dispense for this withdraw.
     *
     * @param value The total in cash to dispense (withdraw)
     * @return The amount/balance that couldn't be dispensed
     */
    long calculate(long value) throws AtmException {
        long balance = value;
        notesToDispense = 0;

        if (value >= note.getValue()) {
            notesToDispense = value / note.getValue();
            while (notesToDispense > 0) {
                if (notesToDispense > numberOfNotes.get()) {
                    notesToDispense = numberOfNotes.get();
                }
                balance = value - notesToDispense * note.getValue();
                if (balance < 0)
                    throw new AtmException("Internal error: balance is negative for " + note);
                if (balance == 0)
                    break;

                long predeterminedBalance = predetermine(balance);
                if (predeterminedBalance == 0)
                    break;

                notesToDispense--;
                balance = value - notesToDispense * note.getValue();
            }
        }
        return (next != null) ? next.calculate(balance) : balance;
    }

    long predetermine(long value) {
        long balance = value;

        if (value >= note.getValue()) {
            long dispenseNotes = value / note.getValue();
            if (dispenseNotes > numberOfNotes.get()) {
                dispenseNotes = numberOfNotes.get();
            }
            balance = value - dispenseNotes * note.getValue();
        }
        return (next != null) ? next.predetermine(balance) : balance;
    }

    List<Cash> dispense() {
        List<Cash> moneyDispensed = new ArrayList<>();

        if (notesToDispense > 0) {
            moneyDispensed.add(new Cash(note, notesToDispense));
            numberOfNotes.addAndGet(notesToDispense * -1);
            notesToDispense = 0;
        }

        if (next != null)
            moneyDispensed.addAll(next.dispense());

        return moneyDispensed;
    }

    void setNextHandle(Dispenser dispenser) {
        next = dispenser;
    }

    long getNumberOfNotes() {
        return numberOfNotes.get();
    }

    long addNotes(long quantity) {
        return numberOfNotes.addAndGet(quantity);
    }
}


text:
"enable aexpr";
import chai, {expect} from 'src/external/chai.js';
import sinon from 'src/external/sinon-3.2.1.js';
import sinonChai from 'src/external/sinon-chai.js';
chai.use(sinonChai);

import { PIScheme, makeRef } from 'polymorphic-identifiers';
import { uuid } from 'utils';

describe("PI", function() {

  it("is defined", () => {
    expect(PIScheme).to.be.ok;
    expect(makeRef).to.be.ok;
  });

  it("detects accesses", () => {
    class fourtyTwo extends PIScheme {
      read() {
        return 42;
      }
    }

    expect(makeRef(fourtyTwo, {
      thisReference: this,
      evalFunction: str => eval(str)
    })``.access).to.equal(42)

  });

  it("can access the `this` reference", () => {
    class prop extends PIScheme {
      initialize() {
        this.prop = this.strings.first;
      }
      read() {
        return this.thisReference[this.prop];
      }
      write(value) {
        return this.thisReference[this.prop] = value;
      }
    }

    // read
    const o = {
      foo: 17,
      func() {
        return makeRef(prop, {
          thisReference: this,
          evalFunction: str => eval(str)
        })`foo`.access;
      },
      write(value) {
        makeRef(prop, {
          thisReference: this,
          evalFunction: str => eval(str)
        })`bar`.access = value;
      }
    };
    expect(o.func()).to.equal(17)

    // write
    o.write(23)
    expect(o.bar).to.equal(23)
  });

  it("can access locals with eval", () => {
    class local extends PIScheme {
      initialize() {
        this.local = this.strings.first;
      }
      read() {
        return this.evalFunction(this.local);
      }
      write(value) {
        const id = uuid();
        self[id] = value;
        try {
          return this.evalFunction(this.local + ` = self['${id}']`);
        } finally {
          delete self[id];
        }
      }
    }

    let v1 = 'v1', v2 = 42;

    // read
    expect(makeRef(local, {
          thisReference: this,
          evalFunction: str => eval(str)
        })`v1`.access).to.equal('v1')

    // write
    makeRef(local, {
          thisReference: this,
          evalFunction: str => eval(str)
        })`v2`.access = "v2";
    expect(v2).to.equal('v2');

    // read/write
    makeRef(local, {
          thisReference: this,
          evalFunction: str => eval(str)
        })`v2`.access += '.2';
    expect(v2).to.equal('v2.2');
  });

  it("ignore normal tagged template strings", () => {
    function foo() {
      return 'bar';
    }

    expect(makeRef(foo, {
      thisReference: this,
      evalFunction: str => eval(str)
    })``.access).to.equal('bar')
  });

});
describe("AEs", function() {

  it("AExprs insert default constructors", () => {
    class A {
      constructor(prop) {
        this.prop = prop;
      }
    }
    class B extends A {}

    const b = new B(42);
    expect(b.prop).to.equal(42);
  });

});


text:
<?php

namespace CurrencyCloud\Model;

use Countable;
use IteratorAggregate;

abstract class PaginatedData implements Countable, IteratorAggregate
{

    /**
     * @var Pagination
     */
    private $pagination;

    /**
     * @param Pagination $pagination
     */
    public function __construct(Pagination $pagination)
    {
        $this->pagination = $pagination;
    }

    /**
     * @return Pagination
     */
    public function getPagination()
    {
        return $this->pagination;
    }
}


text:
<#PSScriptInfo
.VERSION 1.0.0
.GUID 355eb49c-b71a-4d92-adf0-9a2dbd0b7918
.AUTHOR DSC Community
.COMPANYNAME DSC Community
.COPYRIGHT Copyright the DSC Community contributors. All rights reserved.
.TAGS DSCConfiguration
.LICENSEURI https://github.com/dsccommunity/NetworkingDsc/blob/main/LICENSE
.PROJECTURI https://github.com/dsccommunity/NetworkingDsc
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES First version.
.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core
#>

#Requires -module NetworkingDsc

<#
    .DESCRIPTION
    This configuration changes the JumboPacket Size.
#>
Configuration NetAdapterAdvancedProperty_JumboPacket_Config
{
    Import-DSCResource -ModuleName NetworkingDsc

    Node localhost
    {
        NetAdapterAdvancedProperty JumboPacket9014
        {
            NetworkAdapterName  = 'Ethernet'
            RegistryKeyword     = "*JumboPacket"
            RegistryValue       = 9014
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<bitmap android:src="@drawable/taskmanager_help_list_ic_split_mtrl" android:tint="@color/recents_help_body_split_icon_color"
  xmlns:android="http://schemas.android.com/apk/res/android" />


text:
package com.github.soap2jms.model;

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

import javax.activation.DataHandler;
import javax.jms.JMSException;
import javax.jms.TextMessage;

import org.apache.commons.io.IOUtils;

import com.github.soap2jms.common.ByteArrayDataSource;

public class S2JTextMessage extends S2JMessage implements TextMessage {

	public S2JTextMessage(final String correlationId, final int deliveryMode, final long expiration,
			final Map<String, Object> headers, final String clientId, final String messageId, final Integer priority,
			final boolean redelivered, final long timestamp, final String type, final String body) {
		super(correlationId, deliveryMode, expiration, headers, clientId, messageId, priority, redelivered, timestamp,
				type, new DataHandler(new ByteArrayDataSource(body)));
	}

	public S2JTextMessage(final String clientId, final String body) {
		super(clientId, new DataHandler(new ByteArrayDataSource(body)));
	}

	@Override
	public String getText() throws JMSException {
		String text = null;
		final DataHandler messageBody = this.body;
		try {
			if (messageBody != null && messageBody.getInputStream() != null) {
				text = IOUtils.toString(messageBody.getInputStream(), "UTF-8");
			}
		} catch (final IOException e) {
			final JMSException e1 = new JMSException("Client error deserializing body", "1");
			e1.initCause(e);
			e1.setLinkedException(e);
			throw e1;
		}
		return text;
	}

	@Override
	@SuppressWarnings("rawtypes")
	public boolean isBodyAssignableTo(final Class c) throws JMSException {
		final DataHandler messageBody = this.body;
		try {
			if (messageBody == null || messageBody.getInputStream() == null) {
				return true;
			}
			return String.class.equals(c) || Object.class.equals(c);
		} catch (final IOException e) {
			final JMSException e1 = new JMSException("Client error deserializing body", "1");
			e1.initCause(e);
			e1.setLinkedException(e);
			throw e1;
		}
	}

	@Override
	public void setText(final String string) throws JMSException {
		throw new UnsupportedOperationException();
	}

}


text:
from conduit.apps.core.renderers import ConduitJSONRenderer

class UserJSONRenderer(ConduitJSONRenderer):
    charset = 'utf-8'
    object_label = 'user'
    pagination_object_label = 'users'
    pagination_count_label = 'usersCount'

    def render(self, data, media_type=None, renderer_context=None):
        # If we recieve a `token` key as part of the response, it will by a
        # byte object. Byte objects don't serializer well, so we need to
        # decode it before rendering the User object.
        token = data.get('token', None)

        if token is not None and isinstance(token, bytes):
            # Also as mentioned above, we will decode `token` if it is of type
            # bytes.
            data['token'] = token.decode('utf-8')

        return super(UserJSONRenderer, self).render(data)


text:
{% load mapit_i18n %}
{% blocktrans trimmed %}
Versions have appeared in other countries, such as
Norway, and in 2012 we released a
global version based on OpenStreetMap data.
{% endblocktrans %}

This is a modified version run by Code for South Africa. The source code is
available at github.com/Code4SA/mapit-za.


text:
__version__ = '0.0.1'

import os
from .base import (get_config_paths, check_output_dir, ComputingEnvironemtError,
                   get_training_features, partition)
from .cluster import localized
from . import simfunctions
from .simfunctions import level3_sim_file_batches, level3_sim_GCD_file
from . import datafunctions
from .datafunctions import level3_data_file_batches, level3_data_GCD_file
from .io import (load_data, load_sim, apply_quality_cuts,
                 dataframe_to_X_y, load_trained_model)
from .composition_encoding import (get_comp_list, comp_to_label, label_to_comp,
                                   decode_composition_groups)
from .livetime import get_livetime_file, get_detector_livetime
from .efficiencies import get_efficiencies_file, get_detector_efficiencies
from .plotting import get_color_dict, plot_steps, get_colormap, get_color
from .pipelines import get_pipeline
from .model_selection import (get_CV_frac_correct, cross_validate_comp,
                              get_param_grid, gridsearch_optimize)
from .spectrumfunctions import (get_flux, model_flux, counts_to_flux,
                                broken_power_law_flux)
from .data_functions import ratio_error
from .unfolding import unfolded_counts_dist, response_matrix
from .mapfunctions import (equatorial_to_healpy, smooth_map, mask_map,
                           plot_skymap)

from .binning import get_energybins, get_comp_bins, get_zenith_bins, get_bins

paths = get_config_paths()
color_dict = get_color_dict()


text:
woosh.addTests('jq-142', {
	'$preTest': function(prevTest, nextTest) {
		if (!prevTest) {
			document.getElementById('msg').style.display = 'none';
			window.htmlForTest = document.getElementById('htmlForTest');
			htmlForTest.style.height = 'auto';
			window.htmlStr = htmlForTest.innerHTML;
		}
		else {
			htmlForTest.innerHTML = htmlStr;
		}
		window.elementToAnim = $('#elementToAnim');
	},
	'Compiling animation': new woosh.TimeTest(1, function() {
		elementToAnim.animate({
			width: 800,
			height: 0,
			'margin-left': '1em'
		}, {duration: 2000}).stop();
	}),
	'Animation framerate': new woosh.VisualTest(1, function(test) {
		var frames = 0;

		elementToAnim.animate({
			width: 800,
			height: 0,
			'margin-left': '1em'
		}, {
			duration: 2000,
			step: function() {
				frames++;
			},
			complete: function() {
				// divide frames by 3, it calls step per property
				test.setResult( (frames / 3) / 2, 'fps', true ).endTest();
			}
		});
	})
});


text:
@class NSString;

@interface Follow : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(nonatomic) unsigned int index; // @dynamic index;
@property(nonatomic) unsigned int step; // @dynamic step;
@property(retain, nonatomic) NSString *username; // @dynamic username;

@end


text:
package com.jyong.coolweather.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.jyong.coolweather.model.City;
import com.jyong.coolweather.model.County;
import com.jyong.coolweather.model.Province;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 加勇 on 2015/9/6.
 */
public class CoolWeatherDB {
    public static final String DB_NAME = "cool_weather";
    public static final int VERSION = 1;
    private static CoolWeatherDB coolWeatherDB;
    private SQLiteDatabase db;

    private CoolWeatherDB(Context context) {
        CoolWeatherOpenHelper helper = new CoolWeatherOpenHelper(context, DB_NAME, null, VERSION);
        db = helper.getWritableDatabase();
    }

    /**
     * 获取CoolWeatherDB的实例
     *
     * @param context
     * @return
     */
    public synchronized static CoolWeatherDB getInstance(Context context) {
        if (coolWeatherDB == null) {
            coolWeatherDB = new CoolWeatherDB(context);
        }
        return coolWeatherDB;
    }

    public static boolean deleteDB(Context context) {
        return context.deleteDatabase(DB_NAME);
    }

    /**
     * 保存province对象到数据库
     *
     * @param province
     */
    public void saveProvince(Province province) {
        if (province != null) {
            ContentValues values = new ContentValues();
            values.put("province_name", province.getProvinceName());
            values.put("province_code", province.getProvinceCode());
            db.insert("Province", null, values);
        }
    }

    public void deleteAllProvince() {
        db.delete("Province", null, null);
    }

    /**
     * 获取全国省份的信息
     *
     * @return
     */
    public List<Province> loadProvinces() {
        List<Province> list = new ArrayList<Province>();
        Cursor cursor = db.query("Province", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Province province = new Province();
                province.setId(cursor.getColumnIndex("id"));
                province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
                province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code")));
                list.add(province);
            } while (cursor.moveToNext());
            if (cursor != null) {
                cursor.close();
            }
        }
        return list;
    }

    /**
     * 保存city到数据库
     *
     * @param city
     */
    public void saveCity(City city) {
        if (city != null) {
            ContentValues values = new ContentValues();
            values.put("city_name", city.getCityName());
            values.put("city_code", city.getCityCode());
            values.put("province_id", city.getProvinceID());
            db.insert("City", null, values);
        }
    }

    /**
     * 获取某省下面的城市信息
     *
     * @param provinceID
     * @return
     */
    public List<City> loadCities(int provinceID) {
        List<City> list = new ArrayList<City>();
        Cursor cursor = db.query("City", null, "province_id = ?", new String[]{String.valueOf(provinceID)}, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                City city = new City();
                city.setId(cursor.getInt(cursor.getColumnIndex("id")));
                city.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
                city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code")));
                city.setProvinceID(provinceID);
                list.add(city);
            } while (cursor.moveToNext());
        }
        if (cursor != null) {
            cursor.close();
        }
        return list;
    }

    /**
     * 保存county到数据库
     *
     * @param county
     */
    public void saveCounty(County county) {
        if (county != null) {
            ContentValues values = new ContentValues();
            values.put("county_name", county.getCountyName());
            values.put("county_code", county.getCountyCode());
            values.put("city_id", county.getCityID());
            db.insert("County", null, values);
        }
    }

    /**
     * 获取cityID下面的县城信息
     *
     * @param cityID
     * @return
     */
    public List<County> loadCounties(int cityID) {
        List<County> list = new ArrayList<County>();
        Cursor cursor = db.query("County", null, "city_id = ?", new String[]{String.valueOf(cityID)}, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                County county = new County();
                county.setId(cursor.getInt(cursor.getColumnIndex("id")));
                county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name")));
                county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code")));
                county.setCityID(cityID);
                list.add(county);
            } while (cursor.moveToNext());
        }
        if (cursor != null) {
            cursor.close();
        }
        return list;
    }

}


text:
package com.facebook.buck.testutil;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.facebook.buck.io.file.MoreFiles;
import com.facebook.buck.model.BuckVersion;
import com.facebook.buck.util.BuckConstant;
import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.spi.FileSystemProvider;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;

/**
 * {@link AbstractWorkspace} is a directory that contains a Buck project, complete with build files.
 * It requires that its implementations provide a way of running a buckCommand.
 *
 *
It provides ways of adding testdata to the Buck projects, complete with BuildFiles, and ways
 * of overriding the copied .buckconfig by adding configs to a BuckConfigLocal.
 */
public abstract class AbstractWorkspace {
  protected static final String FIXTURE_SUFFIX = "fixture";
  protected static final String EXPECTED_SUFFIX = "expected";

  protected Path destPath;
  private final Map<String, Map<String, String>> localConfigs = new HashMap<>();

  /**
   * Constructor for AbstractWorkspace
   *
   * @param destPath is the folder where the project will be stored. It is generally a temporary
   *     folder
   */
  protected AbstractWorkspace(Path destPath) {
    this.destPath = destPath;
  }

  /**
   * Constructor for AbstractWorkspace. Please note that if you use this constructor, you MUST set
   * destPath before using methods that rely on it.
   */
  protected AbstractWorkspace() {}

  private Map<String, String> getBuckConfigLocalSection(String section) {
    Map<String, String> newValue = new HashMap<>();
    Map<String, String> oldValue = localConfigs.putIfAbsent(section, newValue);
    if (oldValue != null) {
      return oldValue;
    }
    return newValue;
  }

  private void saveBuckConfigLocal() throws IOException {
    StringBuilder contents = new StringBuilder();
    for (Map.Entry<String, Map<String, String>> section : localConfigs.entrySet()) {
      contents.append("[").append(section.getKey()).append("]\n\n");
      for (Map.Entry<String, String> option : section.getValue().entrySet()) {
        contents.append(option.getKey()).append(" = ").append(option.getValue()).append("\n");
      }
      contents.append("\n");
    }
    writeContentsToPath(contents.toString(), ".buckconfig.local");
  }

  /**
   * Overrides buckconfig options with the given value at the given section's option.
   *
   * @param section is the section name where option is defined
   * @param key is the option name
   * @param value is the new value for the option
   * @throws IOException when saving the new BuckConfigLocal has an issue
   */
  public void addBuckConfigLocalOption(String section, String key, String value)
      throws IOException {
    getBuckConfigLocalSection(section).put(key, value);
    saveBuckConfigLocal();
  }

  /**
   * Removes overriding buckconfig options at the given section's option. If the option is not being
   * overridden, then nothing happens.
   *
   * @param section is the section name where option is defined
   * @param key is the option name
   * @throws IOException when saving the new BuckConfigLocal has an issue
   */
  public void removeBuckConfigLocalOption(String section, String key) throws IOException {
    getBuckConfigLocalSection(section).remove(key);
    saveBuckConfigLocal();
  }

  /** Stamp the buck-out directory if it exists and isn't stamped already */
  private void stampBuckVersion() throws IOException {
    if (!Files.exists(destPath.resolve(BuckConstant.getBuckOutputPath()))) {
      return;
    }
    try (OutputStream outputStream =
        new BufferedOutputStream(
            Channels.newOutputStream(
                Files.newByteChannel(
                    destPath.resolve(BuckConstant.getBuckOutputPath().resolve(".currentversion")),
                    ImmutableSet.<OpenOption>of(
                        StandardOpenOption.CREATE, StandardOpenOption.WRITE))))) {
      outputStream.write(BuckVersion.getVersion().getBytes(Charsets.UTF_8));
    }
  }

  private void ensureNoLocalBuckConfig() throws IOException {
    if (Files.exists(getPath(".buckconfig.local"))) {
      throw new IllegalStateException(
          "Found a .buckconfig.local in the Workspace template, which is illegal."
              + "  Use addBuckConfigLocalOption instead."
              + "  This can also happen if workspace.setUp() is called twice.");
    }
  }

  private void addDefaultLocalBuckConfigs() throws IOException {
    // Disable the directory cache by default.  Tests that want to enable it can call
    // `enableDirCache` on this object.  Only do this if a .buckconfig.local file does not already
    // exist, however (we assume the test knows what it is doing at that point).
    addBuckConfigLocalOption("cache", "mode", "");

    // Limit the number of threads by default to prevent multiple integration tests running at the
    // same time from creating a quadratic number of threads. Tests can disable this using
    // `disableThreadLimitOverride`.
    addBuckConfigLocalOption("build", "threads", "2");
  }

  private void ensureWatchmanConfig() throws IOException {
    // We have to have .watchmanconfig on windows, otherwise we have problems with deleting stuff
    // from buck-out while watchman indexes/touches files.
    if (!Files.exists(getPath(".watchmanconfig"))) {
      writeContentsToPath("{\"ignore_dirs\":[\"buck-out\",\".buckd\"]}", ".watchmanconfig");
    }
  }

  private FileSystem getOrCreateJarFileSystem(URI jarURI) throws IOException {
    try {
      return FileSystems.getFileSystem(jarURI);
    } catch (FileSystemNotFoundException e) {
      Map<String, String> env = new HashMap<>();
      env.put("create", "true");
      return FileSystems.newFileSystem(jarURI, env);
    }
  }

  private void copyTemplateContentsToDestPath(
      FileSystemProvider provider, Path templatePath, Path contentPath) throws IOException {
    String fileName = contentPath.getFileName().toString();
    String extension = com.google.common.io.Files.getFileExtension(fileName);
    if (extension.equals(EXPECTED_SUFFIX)) {
      return;
    }

    Path outputPath = contentPath;
    if (extension.equals(FIXTURE_SUFFIX)) {
      outputPath =
          contentPath
              .getParent()
              .resolve(com.google.common.io.Files.getNameWithoutExtension(fileName));
    }
    outputPath = templatePath.relativize(outputPath);

    try (InputStream inStream = provider.newInputStream(contentPath);
        FileOutputStream outStream =
            new FileOutputStream(destPath.resolve(outputPath.toString()).toString())) {
      byte[] buffer = new byte[inStream.available()];
      inStream.read(buffer);
      outStream.write(buffer);
    }
  }

  /**
   * This will copy the template directory, renaming files named {@code foo.fixture} to {@code foo}
   * in the process. Files whose names end in {@code .expected} will not be copied.
   */
  public void addTemplateToWorkspace(Path templatePath) throws IOException {
    // renames those with FIXTURE_SUFFIX, removes those with EXPECTED_SUFFIX
    MoreFiles.copyRecursively(
        templatePath,
        destPath,
        (Path path) -> {
          String fileName = path.getFileName().toString();
          String extension = com.google.common.io.Files.getFileExtension(fileName);
          switch (extension) {
            case FIXTURE_SUFFIX:
              return path.getParent()
                  .resolve(com.google.common.io.Files.getNameWithoutExtension(fileName));
            case EXPECTED_SUFFIX:
              return null;
            default:
              return path;
          }
        });

    stampBuckVersion();

    if (Platform.detect() == Platform.WINDOWS) {
      // Hack for symlinks on Windows.
      SimpleFileVisitor<Path> copyDirVisitor =
          new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs)
                throws IOException {
              // On Windows, symbolic links from git repository are checked out as normal files
              // containing a one-line path. In order to distinguish them, paths are read and
              // pointed
              // files are trued to locate. Once the pointed file is found, it will be copied to
              // target.
              // On NTFS length of path must be greater than 0 and less than 4096.
              if (attrs.size() > 0 && attrs.size() <= 4096) {
                String linkTo = new String(Files.readAllBytes(path), UTF_8);
                Path linkToFile;
                try {
                  linkToFile = templatePath.resolve(linkTo);
                } catch (InvalidPathException e) {
                  // Let's assume we were reading a normal text file, and not something meant to be
                  // a
                  // link.
                  return FileVisitResult.CONTINUE;
                }
                if (Files.isRegularFile(linkToFile)) {
                  Files.copy(linkToFile, path, StandardCopyOption.REPLACE_EXISTING);
                } else if (Files.isDirectory(linkToFile)) {
                  Files.delete(path);
                  MoreFiles.copyRecursively(linkToFile, path);
                }
              }
              return FileVisitResult.CONTINUE;
            }
          };
      Files.walkFileTree(destPath, copyDirVisitor);
    }

    ensureNoLocalBuckConfig();
    addDefaultLocalBuckConfigs();
    ensureWatchmanConfig();
  }

  /**
   * Copies a template to the Workspace regardless of what provider the template has its path
   * defined with. This is needed since using the "regular" copying mechanics with our destPath and
   * a non-default FileSystemProvider causes a ProviderMismatchException
   */
  private void copyTemplateToWorkspace(FileSystemProvider provider, Path templatePath)
      throws IOException {
    Queue<Path> contentQueue = new ArrayDeque<>();
    addDirectoryContentToQueue(provider, templatePath, contentQueue);
    while (!contentQueue.isEmpty()) {
      Path contentPath = contentQueue.remove();
      if (Files.isDirectory(contentPath)) {
        Files.createDirectory(destPath.resolve(templatePath.relativize(contentPath).toString()));
        addDirectoryContentToQueue(provider, contentPath, contentQueue);
      } else {
        copyTemplateContentsToDestPath(provider, templatePath, contentPath);
      }
    }
  }

  /**
   * This will copy the template directory, renaming files named {@code foo.fixture} to {@code foo}
   * in the process. Files whose names end in {@code .expected} will not be copied.
   *
   *
Assumes that {@param testDataResource} is contained in a jar.
   */
  public void addTemplateToWorkspace(URL testDataResource, String templateName) throws Exception {
    // not using "!/" as the ZipFileProvider (which is what is used for Jar files) treats "/" as the
    // root of the jar, and we want to keep it in the split
    String[] jarSplit = testDataResource.toURI().toString().split("!");
    URI jarURI = URI.create(jarSplit[0]);
    FileSystem testDataFS = getOrCreateJarFileSystem(jarURI);
    FileSystemProvider provider = testDataFS.provider();
    Path templatePath = testDataFS.getPath(jarSplit[1].toString(), templateName);

    copyTemplateToWorkspace(provider, templatePath);
    stampBuckVersion();
    ensureNoLocalBuckConfig();
    addDefaultLocalBuckConfigs();
    ensureWatchmanConfig();
  }

  private void addDirectoryContentToQueue(
      FileSystemProvider provider, Path dirPath, Queue<Path> contentQueue) throws IOException {
    try (DirectoryStream<Path> dirStream = provider.newDirectoryStream(dirPath, entry -> true)) {
      for (Path contents : dirStream) {
        contentQueue.add(contents);
      }
    }
  }

  /**
   * Runs Buck with the specified list of command-line arguments.
   *
   * @param args to pass to {@code buck}, so that could be {@code ["build", "//path/to:target"]},
   *     {@code ["project"]}, etc.
   * @return the result of running Buck, which includes the exit code, stdout, and stderr.
   */
  public abstract ProcessResult runBuckCommand(String... args) throws Exception;

  /**
   * Runs Buck with the specified list of command-line arguments with the given map of environment
   * variables.
   *
   * @param environment set of environment variables to override
   * @param args to pass to {@code buck}, so that could be {@code ["build", "//path/to:target"]},
   *     {@code ["project"]}, etc.
   * @return the result of running Buck, which includes the exit code, stdout, and stderr.
   */
  public abstract ProcessResult runBuckCommand(
      ImmutableMap<String, String> environment, String... args) throws Exception;

  /**
   * Gets the path the workspace is held.
   *
   * @return the path the workspace is held
   */
  public Path getDestPath() {
    return destPath;
  }

  /**
   * Resolves the given path relative to the path the workspace is held.
   *
   * @param pathRelativeToWorkspaceRoot is the path relative to the workspace's destPath
   * @return absolute path of the given path relative to the workspace's destPath
   */
  public Path getPath(Path pathRelativeToWorkspaceRoot) {
    return destPath.resolve(pathRelativeToWorkspaceRoot);
  }

  /**
   * Resolves the given path relative to the path the workspace is held.
   *
   * @param pathRelativeToWorkspaceRoot is the path relative to the workspace's destPath
   * @return absolute path of the given path relative to the workspace's destPath
   */
  public Path getPath(String pathRelativeToWorkspaceRoot) {
    return destPath.resolve(pathRelativeToWorkspaceRoot);
  }

  /**
   * Resolves the given path relative to the path the workspace is held and returns its contents
   *
   * @param pathRelativeToWorkspaceRoot is the path relative to the workspace's destPath
   * @return file contents at absolute path of the given path relative to the workspace's destPath
   */
  public String getFileContents(Path pathRelativeToWorkspaceRoot) throws IOException {
    return getFileContentsWithAbsolutePath(getPath(pathRelativeToWorkspaceRoot));
  }

  /**
   * Resolves the given path relative to the path the workspace is held and returns its contents
   *
   * @param pathRelativeToWorkspaceRoot is the path relative to the workspace's destPath
   * @return file contents at absolute path of the given path relative to the workspace's destPath
   */
  public String getFileContents(String pathRelativeToWorkspaceRoot) throws IOException {
    return getFileContentsWithAbsolutePath(getPath(pathRelativeToWorkspaceRoot));
  }

  private String getFileContentsWithAbsolutePath(Path path) throws IOException {
    String platformExt = null;
    switch (Platform.detect()) {
      case LINUX:
        platformExt = "linux";
        break;
      case MACOS:
        platformExt = "macos";
        break;
      case WINDOWS:
        platformExt = "win";
        break;
      case FREEBSD:
        platformExt = "freebsd";
        break;
      case UNKNOWN:
        // Leave platformExt as null.
        break;
    }
    if (platformExt != null) {
      String extension = com.google.common.io.Files.getFileExtension(path.toString());
      String basename = com.google.common.io.Files.getNameWithoutExtension(path.toString());
      Path platformPath =
          extension.length() > 0
              ? path.getParent()
                  .resolve(String.format("%s.%s.%s", basename, platformExt, extension))
              : path.getParent().resolve(String.format("%s.%s", basename, platformExt));
      if (platformPath.toFile().exists()) {
        path = platformPath;
      }
    }
    return new String(Files.readAllBytes(path), UTF_8);
  }

  /**
   * Copies the file at source (relative to workspace root) to dest (relative to workspace root)
   *
   * @param source source path of file relative to workspace root
   * @param dest destination path of file relative to workspace root
   * @throws IOException
   */
  public void copyFile(String source, String dest) throws IOException {
    Path destination = getPath(dest);
    Files.deleteIfExists(destination);
    Files.copy(getPath(source), destination);
  }

  /**
   * Copies the files at source (absolute) to pathRelativeToWorkspaceRoot
   *
   * @param source source path of file relative to workspace root
   * @param pathRelativeToWorkspaceRoot destination directory of files relative to workspace root
   * @throws IOException
   */
  public void copyRecursively(Path source, Path pathRelativeToWorkspaceRoot) throws IOException {
    MoreFiles.copyRecursively(source, destPath.resolve(pathRelativeToWorkspaceRoot));
  }

  /**
   * Moves the file at source (relative to workspace root) to dest (relative to workspace root)
   *
   * @param source source path of file relative to workspace root
   * @param dest destination path of file relative to workspace root
   * @throws IOException
   */
  public void move(String source, String dest) throws IOException {
    Files.move(getPath(source), getPath(dest));
  }

  /**
   * Replaces all instances of target with replacement at the given path
   *
   * @param pathRelativeToWorkspaceRoot path of file to replace contents of
   * @param target string to replace
   * @param replacement string to replace with
   * @return True if any contents of the file were replaced, False otherwise
   * @throws IOException
   */
  public boolean replaceFileContents(
      String pathRelativeToWorkspaceRoot, String target, String replacement) throws IOException {
    String fileContents = getFileContents(pathRelativeToWorkspaceRoot);
    String newFileContents = fileContents.replace(target, replacement);
    writeContentsToPath(newFileContents, pathRelativeToWorkspaceRoot);
    return !newFileContents.equals(fileContents);
  }

  /**
   * Create file (or overwrite existing file) with given contents at
   *
   * @param contents contents to write to the file
   * @param pathRelativeToWorkspaceRoot destination path of file relative to workspace root
   * @param options options (the same ones that Files.write takes)
   * @throws IOException
   */
  public void writeContentsToPath(
      String contents, String pathRelativeToWorkspaceRoot, OpenOption... options)
      throws IOException {
    Files.write(getPath(pathRelativeToWorkspaceRoot), contents.getBytes(UTF_8), options);
  }

  /** @return the specified path resolved against the root of this workspace. */
  public Path resolve(Path pathRelativeToWorkspaceRoot) {
    return destPath.resolve(pathRelativeToWorkspaceRoot);
  }

  /** @return the specified path resolved against the root of this workspace. */
  public Path resolve(String pathRelativeToWorkspaceRoot) {
    return destPath.resolve(pathRelativeToWorkspaceRoot);
  }
}


text:
git remote add dokku dokku@stack.chester.how:stack
git push dokku master


text:
class Class
  def get_subclass name
    name.is_a?(Class) ? ((name < self) && name) : (descendants.detect { |kla| kla.name == name })
  end

  def get_subclass! name
    get_subclass(name) || (raise "unknown subclass #{name.inspect} of #{self.name}")
  end
end


text:
"""Fixtures common across tests."""

import numpy as np
import pytest
import seals  # noqa: F401
import torch
from stable_baselines3.common.vec_env import VecEnv

from imitation.data.wrappers import RolloutInfoWrapper
from imitation.util import logger, util

CARTPOLE_ENV_NAME = "seals/CartPole-v0"

@pytest.fixture(params=[1, 4], ids=lambda n: f"vecenv({n})")
def cartpole_venv(request, rng) -> VecEnv:
    num_envs = request.param
    return util.make_vec_env(
        CARTPOLE_ENV_NAME,
        n_envs=num_envs,
        post_wrappers=[lambda env, _: RolloutInfoWrapper(env)],
        rng=rng,
    )

@pytest.fixture(scope="session", autouse=True)
def torch_single_threaded():
    """Make PyTorch execute code single-threaded.

    This allows us to run the test suite with greater across-test parallelism.
    This is faster, since:
        - There are diminishing returns to more threads within a test.
        - Many tests cannot be multi-threaded (e.g. most not using PyTorch training),
          and we have to set between-test parallelism based on peak resource
          consumption of tests to avoid spurious failures.
    """
    torch.set_num_threads(1)
    torch.set_num_interop_threads(1)

@pytest.fixture()
def custom_logger(tmpdir: str) -> logger.HierarchicalLogger:
    return logger.configure(tmpdir)

@pytest.fixture()
def rng() -> np.random.Generator:
    return np.random.default_rng()


text:
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import React, { Component } from 'react';
import RecordProcedure from '../components/RecordProcedure';
import * as FileLocationActions from '../actions/fileLocation';

function mapStateToProps(state) {
  return {
    filePath: state.filePath
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(FileLocationActions, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(RecordProcedure)