text:
<?xml version="1.0"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>javax.portlet</groupId>
		<artifactId>portlet-tck</artifactId>
		<version>3.0.4-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>tck-V2AddlPortletTests</artifactId>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>javax.portlet</groupId>
			<artifactId>portlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-servlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.portlet</groupId>
			<artifactId>tck-common</artifactId>
			<version>${project.version}</version>
			<scope>compile</scope>
		</dependency>
		<!-- for tooling purposes -->
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jsp-api</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-el-api</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.taglibs</groupId>
			<artifactId>taglibs-standard-spec</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.taglibs</groupId>
			<artifactId>taglibs-standard-impl</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.taglibs</groupId>
			<artifactId>taglibs-standard-jstlel</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.portals.pluto</groupId>
			<artifactId>pluto-taglib</artifactId>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<properties>
		<!-- This project contains additional test cases to run with the portlets -->
		<additional.testcase.uri>file:///${basedir}/src/main/resources/xml-resources/additionalTCs.xml</additional.testcase.uri>
		<!-- Set to true for modules that define all test cases in a file (TCs are not generated from the portlet.xml) -->
		<additional.testcases.only>true</additional.testcases.only>
		<!-- put all portlets from this module on the same page -->
		<page.file.xsl>plutoMultiPortletPage.xsl</page.file.xsl>
		<portlet.descriptor.dir>src/main/webapp/WEB-INF/pluto</portlet.descriptor.dir>
	</properties>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-antrun-plugin</artifactId>
				<executions>
					<execution>
						<id>prepare-package</id>
						<phase>prepare-package</phase>
						<goals>
							<goal>run</goal>
						</goals>
						<configuration>
							<target>
								<copy file="${basedir}/${portlet.descriptor.dir}/portlet.xml" tofile="${project.build.directory}/${project.build.finalName}/WEB-INF/portlet.xml" />
							</target>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
				</configuration>
			</plugin>
			<!-- Transform the portlet XML into test properties XML file -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>xml-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	<profiles>
		<profile>
			<id>pluto</id>
			<properties>
				<expected.option>javax.portlet.servletDefaultSessionScope</expected.option>
				<expected.value>PORTLET_SCOPE</expected.value>
			</properties>
			<dependencies>
				<dependency>
					<groupId>org.apache.taglibs</groupId>
					<artifactId>taglibs-standard-spec</artifactId>
					<scope>compile</scope>
				</dependency>
				<dependency>
					<groupId>org.apache.taglibs</groupId>
					<artifactId>taglibs-standard-impl</artifactId>
					<scope>compile</scope>
				</dependency>
				<dependency>
					<groupId>org.apache.taglibs</groupId>
					<artifactId>taglibs-standard-jstlel</artifactId>
					<scope>compile</scope>
				</dependency>
			</dependencies>
		</profile>
		<profile>
			<id>liferay</id>
			<properties>
				<expected.option>javax.portlet.escapeXml</expected.option>
				<expected.value>true</expected.value>
				<portlet.descriptor.dir>src/main/webapp/WEB-INF/liferay</portlet.descriptor.dir>
			</properties>
		</profile>
	</profiles>
</project>


text:
ActiveRecord::Schema.define(version: 20140629211718) do

  create_table "projects", force: true do |t|
    t.string   "name"
    t.date     "due_date"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "public",     default: false
  end

  create_table "roles", force: true do |t|
    t.integer  "user_id"
    t.integer  "project_id"
    t.string   "role_name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "roles", ["project_id"], name: "index_roles_on_project_id"
  add_index "roles", ["user_id"], name: "index_roles_on_user_id"

  create_table "tasks", force: true do |t|
    t.integer  "project_id"
    t.string   "title"
    t.integer  "size"
    t.datetime "completed_at"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "project_order"
    t.integer  "user_id"
  end

  add_index "tasks", ["project_id"], name: "index_tasks_on_project_id"

  create_table "users", force: true do |t|
    t.string   "email",                  default: "",    null: false
    t.string   "encrypted_password",     default: "",    null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,     null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.boolean  "admin",                  default: false
    t.string   "twitter_handle"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Rcms\Page;

use Rcms\Core\Ranks;
use Rcms\Core\Config;
use Rcms\Core\Text;
use Rcms\Core\Request;
use Rcms\Core\Website;
use Rcms\Core\Widget\WidgetRepository;
use Rcms\Core\Widget\WidgetRunner;
use Rcms\Template\WidgetsColumnTemplate;

class HomePage extends Page {

    const DOCUMENT_ID = 1;

    /**
     * @var PlacedWidget[] The widgets to display.
     */
    private $widgets;

    /**
     *
     * @var WidgetRunner Widgets installed on the website.
     */
    private $widgetRunner;

    /**
     * @var boolean Whether edit/delete links are shown.
     */
    private $editLinks;

    /**
     * @var string The title of the website.
     */
    private $siteTitle;

    public function init(Website $website, Request $request) {
        $this->widgetRunner = new WidgetRunner($website, $request);
        $this->siteTitle = $website->getConfig()->get(Config::OPTION_SITE_TITLE);

        $widgetsRepo = new WidgetRepository($website);
        $this->widgets = $widgetsRepo->getWidgetsInDocumentWithId(self::DOCUMENT_ID);
        $this->editLinks = $request->hasRank(Ranks::ADMIN);
    }

    public function getPageTitle(Text $text) {
        return ""; // The widgets will already provide a title
    }

    public function getShortPageTitle(Text $text) {
        return $this->siteTitle;
    }

    public function getTemplate(Text $text) {
        return new WidgetsColumnTemplate($text, self::DOCUMENT_ID, $this->widgetRunner, $this->widgets, $this->editLinks);
    }

    public function getPageType() {
        return Page::TYPE_HOME;
    }

    public function getMinimumRank() {
        return Ranks::LOGGED_OUT;
    }

}


text:
namespace swift { extern "C" {
#endif

typedef void (^__swift_shims_dispatch_block_t)(void);

#ifdef __OBJC__
typedef id __swift_shims_dispatch_data_t;
#else
typedef void *__swift_shims_dispatch_data_t;
#endif

static inline dispatch_queue_attr_t
_swift_dispatch_queue_concurrent(void) {
  return DISPATCH_QUEUE_CONCURRENT;
}

static inline dispatch_queue_t
_swift_dispatch_get_main_queue(void) {
  return dispatch_get_main_queue();
}

static inline dispatch_data_t
_swift_dispatch_data_empty(void) {
  return dispatch_data_empty;
}

static inline __swift_shims_dispatch_block_t _Nullable
_swift_dispatch_data_destructor_default(void) {
  return DISPATCH_DATA_DESTRUCTOR_DEFAULT;
}

static inline __swift_shims_dispatch_block_t
_swift_dispatch_data_destructor_free(void) {
  return _dispatch_data_destructor_free;
}

static inline __swift_shims_dispatch_block_t
_swift_dispatch_data_destructor_munmap(void) {
  return _dispatch_data_destructor_munmap;
}

#define SWIFT_DISPATCH_SOURCE_TYPE(t)                                          \
  static inline dispatch_source_type_t _swift_dispatch_source_type_##t(void) { \
    return DISPATCH_SOURCE_TYPE_##t;                                           \
  }

SWIFT_DISPATCH_SOURCE_TYPE(DATA_ADD)
SWIFT_DISPATCH_SOURCE_TYPE(DATA_OR)
SWIFT_DISPATCH_SOURCE_TYPE(DATA_REPLACE)
SWIFT_DISPATCH_SOURCE_TYPE(READ)
SWIFT_DISPATCH_SOURCE_TYPE(SIGNAL)
SWIFT_DISPATCH_SOURCE_TYPE(TIMER)
SWIFT_DISPATCH_SOURCE_TYPE(WRITE)

#if __APPLE__
SWIFT_DISPATCH_SOURCE_TYPE(MACH_SEND)
SWIFT_DISPATCH_SOURCE_TYPE(MACH_RECV)
SWIFT_DISPATCH_SOURCE_TYPE(MEMORYPRESSURE)
SWIFT_DISPATCH_SOURCE_TYPE(PROC)
SWIFT_DISPATCH_SOURCE_TYPE(VNODE)
#endif

extern void
_swift_dispatch_source_create_abort(void);

SWIFT_DISPATCH_RETURNS_RETAINED
static inline dispatch_source_t
_swift_dispatch_source_create(
    dispatch_source_type_t type,
	uintptr_t handle,
	unsigned long mask,
	dispatch_queue_t _Nullable queue)
{
  dispatch_source_t source = dispatch_source_create(type, handle, mask, queue);
  if (!source) {
    _swift_dispatch_source_create_abort();
  }
  return source;
}

static inline SWIFT_DISPATCH_RETURNS_RETAINED __swift_shims_dispatch_block_t
_swift_dispatch_block_create_with_qos_class(
    dispatch_block_flags_t flags, dispatch_qos_class_t qos,
    int relative_priority, __swift_shims_dispatch_block_t _Nonnull block) {
  return dispatch_block_create_with_qos_class(
      flags, qos, relative_priority, block);
}

static inline __swift_shims_dispatch_block_t
_swift_dispatch_block_create_noescape(
    dispatch_block_flags_t flags,
    __swift_shims_dispatch_block_t SWIFT_DISPATCH_NOESCAPE block) {
  return dispatch_block_create(flags, block);
}

static inline int _swift_dispatch_block_wait(
    __swift_shims_dispatch_block_t block,
    unsigned long long timeout) {
  return dispatch_block_wait(block, timeout);
}

static inline void _swift_dispatch_block_notify(
    __swift_shims_dispatch_block_t block,
    dispatch_queue_t queue,
    __swift_shims_dispatch_block_t notifier) {
  dispatch_block_notify(block, queue, notifier);
}

static inline void _swift_dispatch_block_cancel(
    __swift_shims_dispatch_block_t block) {
  dispatch_block_cancel(block);
}

static inline int _swift_dispatch_block_testcancel(
    __swift_shims_dispatch_block_t block) {
  return dispatch_block_testcancel(block);
}

static inline void _swift_dispatch_async(
    dispatch_queue_t queue,
    __swift_shims_dispatch_block_t block) {
  dispatch_async(queue, block);
}

static inline void _swift_dispatch_sync(
    dispatch_queue_t queue,
    __swift_shims_dispatch_block_t block) {
  dispatch_sync(queue, block);
}

static inline void _swift_dispatch_barrier_async(
    dispatch_queue_t queue,
    __swift_shims_dispatch_block_t block) {
  dispatch_barrier_async(queue, block);
}

static inline void _swift_dispatch_group_async(
    dispatch_group_t group,
    dispatch_queue_t queue,
    __swift_shims_dispatch_block_t block) {
  dispatch_group_async((dispatch_group_t)group, queue, block);
}

static inline void _swift_dispatch_group_notify(
    dispatch_group_t group,
    dispatch_queue_t queue,
    __swift_shims_dispatch_block_t block) {
  dispatch_group_notify(group, queue, block);
}

static inline void _swift_dispatch_after(
    dispatch_time_t when,
    dispatch_queue_t queue,
    __swift_shims_dispatch_block_t block) {
  dispatch_after(when, queue, block);
}

static inline void _swift_dispatch_apply_current(
    size_t iterations,
    void SWIFT_DISPATCH_NOESCAPE (^block)(long)) {
  dispatch_apply(iterations, (dispatch_queue_t _Nonnull)0, ^(size_t i){
    block((long)i);
  });
}

SWIFT_DISPATCH_RETURNS_RETAINED
static inline __swift_shims_dispatch_data_t
_swift_dispatch_data_create(
    const void *buffer,
    size_t size,
    dispatch_queue_t _Nullable queue,
    __swift_shims_dispatch_block_t _Nullable destructor) {
  return dispatch_data_create(buffer, size, queue, destructor);
}

typedef unsigned int (^__swift_shims_dispatch_data_applier)(__swift_shims_dispatch_data_t, size_t, const void *, size_t);

static inline unsigned int
_swift_dispatch_data_apply(
    __swift_shims_dispatch_data_t data,
    __swift_shims_dispatch_data_applier SWIFT_DISPATCH_NOESCAPE applier) {
  return dispatch_data_apply(data, ^bool(dispatch_data_t data, size_t off, const void *loc, size_t size){
    return applier(data, off, loc, size);
  });
}

static inline void _swift_dispatch_source_set_event_handler(
    dispatch_source_t source,
    __swift_shims_dispatch_block_t _Nullable block) {
  dispatch_source_set_event_handler(source, block);
}

static inline void _swift_dispatch_source_set_cancel_handler(
    dispatch_source_t source,
    __swift_shims_dispatch_block_t _Nullable block) {
  dispatch_source_set_cancel_handler(source, block);
}

static inline void _swift_dispatch_source_set_registration_handler(
    dispatch_source_t source,
    __swift_shims_dispatch_block_t _Nullable block) {
  dispatch_source_set_registration_handler(source, block);
}

#if defined(__ANDROID__)
extern void _dispatch_install_thread_detach_callback(dispatch_function_t cb);
#endif

static inline void _swift_dispatch_retain(dispatch_object_t object) {
  dispatch_retain(object);
}

static inline void _swift_dispatch_release(dispatch_object_t object) {
  dispatch_release(object);
}

#ifdef __cplusplus
}} // extern "C", namespace swift
#endif

#pragma clang assume_nonnull end

#endif // SWIFT_STDLIB_SHIMS_DISPATCHSHIMS_H


text:
package org.apache.camel.component.jpa;

import java.util.Map;
import java.util.concurrent.ExecutorService;

import javax.persistence.EntityManagerFactory;

import org.apache.camel.Endpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.DefaultComponent;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * A JPA Component
 */
@Component("jpa")
public class JpaComponent extends DefaultComponent {

    private static final Logger LOG = LoggerFactory.getLogger(JpaComponent.class);

    private ExecutorService pollingConsumerExecutorService;

    @Metadata
    private EntityManagerFactory entityManagerFactory;
    @Metadata
    private PlatformTransactionManager transactionManager;
    @Metadata(defaultValue = "true")
    private boolean joinTransaction = true;
    @Metadata
    private boolean sharedEntityManager;

    public JpaComponent() {
    }

    // Properties
    //-------------------------------------------------------------------------
    public EntityManagerFactory getEntityManagerFactory() {
        return entityManagerFactory;
    }

    /**
     * To use the {@link EntityManagerFactory}. This is strongly recommended to configure.
     */
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    public PlatformTransactionManager getTransactionManager() {
        return transactionManager;
    }

    /**
     * To use the {@link PlatformTransactionManager} for managing transactions.
     */
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public boolean isJoinTransaction() {
        return joinTransaction;
    }

    /**
     * The camel-jpa component will join transaction by default.
     * You can use this option to turn this off, for example if you use LOCAL_RESOURCE and join transaction
     * doesn't work with your JPA provider. This option can also be set globally on the JpaComponent,
     * instead of having to set it on all endpoints.
     */
    public void setJoinTransaction(boolean joinTransaction) {
        this.joinTransaction = joinTransaction;
    }

    public boolean isSharedEntityManager() {
        return sharedEntityManager;
    }

    /**
     * Whether to use Spring's SharedEntityManager for the consumer/producer.
     * Note in most cases joinTransaction should be set to false as this is not an EXTENDED EntityManager.
     */
    public void setSharedEntityManager(boolean sharedEntityManager) {
        this.sharedEntityManager = sharedEntityManager;
    }

    synchronized ExecutorService getOrCreatePollingConsumerExecutorService() {
        if (pollingConsumerExecutorService == null) {
            LOG.debug("Creating thread pool for JpaPollingConsumer to support polling using timeout");
            pollingConsumerExecutorService = getCamelContext().getExecutorServiceManager().newDefaultThreadPool(this, "JpaPollingConsumer");
        }
        return pollingConsumerExecutorService;
    }

    // Implementation methods
    //-------------------------------------------------------------------------

    @Override
    protected Endpoint createEndpoint(String uri, String path, Map<String, Object> options) throws Exception {
        JpaEndpoint endpoint = new JpaEndpoint(uri, this);
        endpoint.setJoinTransaction(isJoinTransaction());
        endpoint.setSharedEntityManager(isSharedEntityManager());

        // lets interpret the next string as a class
        if (ObjectHelper.isNotEmpty(path)) {
            // provide the class loader of this component to work in OSGi environments as camel-jpa must be able
            // to resolve the entity classes
            Class<?> type = getCamelContext().getClassResolver().resolveClass(path, JpaComponent.class.getClassLoader());
            if (type != null) {
                endpoint.setEntityType(type);
            }
        }
        setProperties(endpoint, options);
        return endpoint;
    }

    @Override
    protected void doInit() throws Exception {
        super.doInit();

        // lookup entity manager factory and use it if only one provided
        if (entityManagerFactory == null) {
            Map<String, EntityManagerFactory> map = getCamelContext().getRegistry().findByTypeWithName(EntityManagerFactory.class);
            if (map != null) {
                if (map.size() == 1) {
                    entityManagerFactory = map.values().iterator().next();
                    LOG.info("Using EntityManagerFactory found in registry with id ["
                            + map.keySet().iterator().next() + "] " + entityManagerFactory);
                } else {
                    LOG.debug("Could not find a single EntityManagerFactory in registry as there was {} instances.", map.size());
                }
            }
        } else {
            LOG.info("Using EntityManagerFactory configured: {}", entityManagerFactory);
        }

        // lookup transaction manager and use it if only one provided
        if (transactionManager == null) {
            Map<String, PlatformTransactionManager> map = getCamelContext().getRegistry().findByTypeWithName(PlatformTransactionManager.class);
            if (map != null) {
                if (map.size() == 1) {
                    transactionManager = map.values().iterator().next();
                    LOG.info("Using TransactionManager found in registry with id ["
                            + map.keySet().iterator().next() + "] " + transactionManager);
                } else {
                    LOG.debug("Could not find a single TransactionManager in registry as there was {} instances.", map.size());
                }
            }
        } else {
            LOG.info("Using TransactionManager configured on this component: {}", transactionManager);
        }

        // transaction manager could also be hidden in a template
        if (transactionManager == null) {
            Map<String, TransactionTemplate> map = getCamelContext().getRegistry().findByTypeWithName(TransactionTemplate.class);
            if (map != null) {
                if (map.size() == 1) {
                    transactionManager = map.values().iterator().next().getTransactionManager();
                    LOG.info("Using TransactionManager found in registry with id ["
                            + map.keySet().iterator().next() + "] " + transactionManager);
                } else {
                    LOG.debug("Could not find a single TransactionTemplate in registry as there was {} instances.", map.size());
                }
            }
        }

        // warn about missing configuration
        if (entityManagerFactory == null) {
            LOG.warn("No EntityManagerFactory has been configured on this JpaComponent. Each JpaEndpoint will auto create their own EntityManagerFactory.");
        }
        if (transactionManager == null) {
            LOG.warn("No TransactionManager has been configured on this JpaComponent. Each JpaEndpoint will auto create their own JpaTransactionManager.");
        }
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();

        if (pollingConsumerExecutorService != null) {
            getCamelContext().getExecutorServiceManager().shutdown(pollingConsumerExecutorService);
            pollingConsumerExecutorService = null;
        }
    }
}


text:
package org.whattf.datatype;

import org.relaxng.datatype.DatatypeException;

import java.util.Arrays;
import com.ibm.icu.lang.UCharacter;

public class KeyLabelList extends AbstractDatatype {

    /**
     * The singleton instance.
     */
    public static final KeyLabelList THE_INSTANCE = new KeyLabelList();

    private KeyLabelList() {
        super();
    }

    @Override
      public void checkValid(CharSequence literal) throws DatatypeException {
        String[] keylabels = literal.toString().split("\\s+");
        Arrays.sort(keylabels);
        for (int i = 0; i < keylabels.length; i++) {
          String label = keylabels[i];
          if (i > 0 && label.equals(keylabels[i-1])) {
            throw newDatatypeException(
                "Duplicate key label. Each key label must be unique.");
          }
          if (label.length() == 2) {
            char[] chars = label.toCharArray();
            if (!(UCharacter.isHighSurrogate(chars[0])
                  && UCharacter.isLowSurrogate(chars[1]))) {
              throw newDatatypeException(
                  "Key label has multiple characters. Each key label must be a single character.");
            }
          }
          if (label.length() > 2) {
            throw newDatatypeException(
                "Key label has multiple characters. Each key label must be a single character.");
          }
        }
      }

    @Override
    public String getName() {
        return "key label list";
    }

}


text:
namespace net {
struct RedirectInfo;
}

namespace content {

class AsyncRevalidationDriver;
class ResourceController;
class ThrottlingResourceHandler;

// A ResourceThrottle gets notified at various points during the process of
// loading a resource.  At each stage, it has the opportunity to defer the
// resource load.  The ResourceController interface may be used to resume a
// deferred resource load, or it may be used to cancel a resource load at any
// time.
class ResourceThrottle {
 public:
  virtual ~ResourceThrottle() {}

  // Called before the resource request is started.
  virtual void WillStartRequest(bool* defer) {}

  // Called when the request was redirected.  |redirect_info| contains the
  // redirect responses's HTTP status code and some information about the new
  // request that will be sent if the redirect is followed, including the new
  // URL and new method.
  virtual void WillRedirectRequest(const net::RedirectInfo& redirect_info,
                                   bool* defer) {}

  // Called when the response headers and meta data are available.
  virtual void WillProcessResponse(bool* defer) {}

  // Returns the name of the throttle, as a UTF-8 C-string, for logging
  // purposes.  nullptr is not allowed.  Caller does *not* take ownership of the
  // returned string.
  virtual const char* GetNameForLogging() const = 0;

  void set_controller_for_testing(ResourceController* c) {
    controller_ = c;
  }

 protected:
  ResourceThrottle() : controller_(nullptr) {}
  ResourceController* controller() { return controller_; }

 private:
  friend class AsyncRevalidationDriver;
  friend class ThrottlingResourceHandler;
  void set_controller(ResourceController* c) { controller_ = c; }

  ResourceController* controller_;
};

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_RESOURCE_THROTTLE_H_


text:
"""
Django settings for demo project.

Generated by 'django-admin startproject' using Django 2.2.11.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os
import sys

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SITE_PATH = os.path.abspath(os.path.dirname(__file__))
PROJECT_PATH = os.path.normpath(os.path.join(SITE_PATH, '..', '..'))
if PROJECT_PATH not in sys.path:
    sys.path.insert(0, PROJECT_PATH)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$9$l6-xguwuh4k^4=55#(thz^l=#kg-p=@=tbrd2m46-6!#x&g'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',

    'mapwidgets',

    'cities'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
ROOT_URLCONF = 'demo.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates/'),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'demo.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'mapwidget_db',
        'USER': 'mapwidgetdbu',
        'PASSWORD': 'mapwidgetdbu',
        'HOST': 'mapwidget_postgres',
        'PORT': '5432',
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LOCALE_PATHS = (
    "/django-map-widgets/mapwidgets/locale",
)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

GOOGLE_MAP_API_KEY = os.getenv('GOOGLE_MAP_API_KEY', None)
MAPBOX_API_KEY = os.getenv('MAPBOX_API_KEY', None)
MAP_WIDGETS = {
    "GooglePointFieldWidget": (
        ("zoom", 15),
        ("mapCenterLocation", [51.5073509, -0.12775829999998223]),
        ("markerFitZoom", 11),
        ("GooglePlaceAutocompleteOptions", {'componentRestrictions': {'country': 'uk'}}),
        ("streetViewControl", False)
    ),
    "MapboxPointFieldWidget": {
        "access_token": MAPBOX_API_KEY,
        "mapOptions": {
            "zoom": 10,
            "center": (51.515618, -0.091998)
        }
    },
    "GOOGLE_MAP_API_KEY": GOOGLE_MAP_API_KEY
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp">
        <ImageView
            android:id="@+id/typeImage"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_marginTop="8dp"
            android:layout_marginRight="24dp"
            android:src="@drawable/ic_action_call"/>
        <ImageView
            android:layout_marginTop="8dp"
            android:id="@+id/deleteImage"
            android:layout_width="24dp"
            android:layout_height="24dp"
            android:layout_marginLeft="16dp"
            android:layout_alignParentRight="true"/>

        <EditText
            android:id="@+id/data"
            android:layout_toRightOf="@+id/typeImage"
            android:layout_toLeftOf="@id/deleteImage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/phone"/>

        <Spinner
            android:layout_toRightOf="@id/typeImage"
            android:id="@+id/spinner"
            android:layout_marginTop="8dp"
            android:layout_width="160dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/data">

        </Spinner>

</RelativeLayout>


text:
require 'spec_helper'

describe QuestionsController do

	before(:each) do
		@test_user = User.create(username: 'sbeverly', email: 'skb14@pitt.edu')
		@test_user2 = User.create(username: 'afrankle', email: 'franks@dbc.com')

		@test_question = Question.create(body: 'Do all of these tests work?')
		@test_question.answers << Answer.create(user_id: 2, body: 'Let me google that for you')
		@comment = Comment.create(user_id: 1,
								commentable_type: 'Question',
								commentable_id: @test_question.id,
								body: 'These tests are so helpful!')
	end

	describe '#index' do
		it 'it pulls all questions from database' do
			@questions = Question.all
			expect(@questions).to eq Question.all
		end
	end

	describe '#create' do
		it 'saves the newly created question to the database' do
			expect(Question.find(@test_question.id).body).to eq 'Do all of these tests work?'
			expect { Question.create(body: 'Is this going to increment the count by 1?') }.to change { Question.count }.by(1)
		end
	end

	describe '#show' do
		it 'finds the requested question in the database' do
			expect(@test_question).to eq Question.find(@test_question.id)
		end

		it 'finds the answers associated with the requested question' do
			expect(@test_question.answers).to eq Answer.where(question_id: @test_question.id)
		end

		it 'finds the comments associated with the requested question' do
			expect(@test_question.comments.first).to eq Comment.where(body: 'These tests are so helpful!').first
		end
	end
end


text:
package org.metafacture.javaintegration;

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

import org.metafacture.framework.StreamReceiver;

/**
 * Stores the received stream events in a list.
 *
 * @author Christoph Böhme
 *
 */
public final class EventList implements StreamReceiver {

	private final List<Event> events = new ArrayList<Event>();

	private boolean closed;

	public List<Event> getEvents() {
		return Collections.unmodifiableList(events);
	}

	public boolean isClosed() {
		return closed;
	}

	@Override
	public void startRecord(final String identifier) {
		assert !closed;
		events.add(new Event(Event.Type.START_RECORD, identifier));
	}

	@Override
	public void endRecord() {
		assert !closed;
		events.add(new Event(Event.Type.END_RECORD));
	}

	@Override
	public void startEntity(final String name) {
		assert !closed;
		events.add(new Event(Event.Type.START_ENTITY, name));
	}

	@Override
	public void endEntity() {
		assert !closed;
		events.add(new Event(Event.Type.END_ENTITY));
	}

	@Override
	public void literal(final String name, final String value) {
		assert !closed;
		events.add(new Event(Event.Type.LITERAL, name, value));
	}

	@Override
	public void resetStream() {
		closed = false;
		events.clear();
	}

	@Override
	public void closeStream() {
		closed = true;
	}

	/**
	 * Data type for stream events.
	 *
	 * @author Christoph Böhme
	 */
	public static final class Event {

		/**
		 * Event types
		 */
		public enum Type {
			START_RECORD, END_RECORD, START_ENTITY, END_ENTITY, LITERAL
		}

		private final Type type;
		private final String name;
		private final String value;

		Event(final Type type) {
			this(type, null);
		}

		Event(final Type type, final String name) {
			this(type, name, null);
		}

		Event(final Type type, final String name, final String value) {
			this.type = type;
			this.name = name;
			this.value = value;
		}

		public Type getType() {
			return type;
		}

		public String getName() {
			return name;
		}

		public String getValue() {
			return value;
		}

		@Override
		public String toString() {
			final StringBuilder builder = new StringBuilder();
			builder.append(type);
			if (name != null) {
				builder.append("(" );
				builder.append(name);
				if (value != null) {
					builder.append("=");
					builder.append(value);
				}
				builder.append(")");
			}
			return builder.toString();
		}

	}

}


text: DROP TABLE corpora;


text:
//Generated by the Argon Build System

/*! \file gim_box_set.h
\author Francisco Leon Najera
*/
/*
This source file is part of GIMPACT Library.

For the latest info, see http://gimpact.sourceforge.net/

Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#include "btGImpactQuantizedBvh.h"
#include "LinearMath/btQuickprof.h"

#ifdef TRI_COLLISION_PROFILING
btClock g_q_tree_clock;

float g_q_accum_tree_collision_time = 0;
int g_q_count_traversing = 0;

void bt_begin_gim02_q_tree_time()
{
	g_q_tree_clock.reset();
}

void bt_end_gim02_q_tree_time()
{
	g_q_accum_tree_collision_time += g_q_tree_clock.getTimeMicroseconds();
	g_q_count_traversing++;
}

//! Gets the average time in miliseconds of tree collisions
float btGImpactQuantizedBvh::getAverageTreeCollisionTime()
{
	if(g_q_count_traversing == 0) return 0;

	float avgtime = g_q_accum_tree_collision_time;
	avgtime /= (float)g_q_count_traversing;

	g_q_accum_tree_collision_time = 0;
	g_q_count_traversing = 0;
	return avgtime;

//	float avgtime = g_q_count_traversing;
//	g_q_count_traversing = 0;
//	return avgtime;

}

#endif //TRI_COLLISION_PROFILING

/////////////////////// btQuantizedBvhTree /////////////////////////////////

void btQuantizedBvhTree::calc_quantization(
	GIM_BVH_DATA_ARRAY & primitive_boxes, btScalar boundMargin)
{
	//calc globa box
	btAABB global_bound;
	global_bound.invalidate();

	for (int i=0;i<primitive_boxes.size() ;i++ )
	{
		global_bound.merge(primitive_boxes[i].m_bound);
	}

	bt_calc_quantization_parameters(
		m_global_bound.m_min,m_global_bound.m_max,m_bvhQuantization,global_bound.m_min,global_bound.m_max,boundMargin);

}

int btQuantizedBvhTree::_calc_splitting_axis(
	GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex,  int endIndex)
{

	int i;

	btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.));
	btVector3 variance(btScalar(0.),btScalar(0.),btScalar(0.));
	int numIndices = endIndex-startIndex;

	for (i=startIndex;i<endIndex;i++)
	{
		btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max +
					 primitive_boxes[i].m_bound.m_min);
		means+=center;
	}
	means *= (btScalar(1.)/(btScalar)numIndices);

	for (i=startIndex;i<endIndex;i++)
	{
		btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max +
					 primitive_boxes[i].m_bound.m_min);
		btVector3 diff2 = center-means;
		diff2 = diff2 * diff2;
		variance += diff2;
	}
	variance *= (btScalar(1.)/	((btScalar)numIndices-1)	);

	return variance.maxAxis();
}

int btQuantizedBvhTree::_sort_and_calc_splitting_index(
	GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex,
	int endIndex, int splitAxis)
{
	int i;
	int splitIndex =startIndex;
	int numIndices = endIndex - startIndex;

	// average of centers
	btScalar splitValue = 0.0f;

	btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.));
	for (i=startIndex;i<endIndex;i++)
	{
		btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max +
					 primitive_boxes[i].m_bound.m_min);
		means+=center;
	}
	means *= (btScalar(1.)/(btScalar)numIndices);

	splitValue = means[splitAxis];

	//sort leafNodes so all values larger then splitValue comes first, and smaller values start from 'splitIndex'.
	for (i=startIndex;i<endIndex;i++)
	{
		btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max +
					 primitive_boxes[i].m_bound.m_min);
		if (center[splitAxis] > splitValue)
		{
			//swap
			primitive_boxes.swap(i,splitIndex);
			//swapLeafNodes(i,splitIndex);
			splitIndex++;
		}
	}

	//if the splitIndex causes unbalanced trees, fix this by using the center in between startIndex and endIndex
	//otherwise the tree-building might fail due to stack-overflows in certain cases.
	//unbalanced1 is unsafe: it can cause stack overflows
	//bool unbalanced1 = ((splitIndex==startIndex) || (splitIndex == (endIndex-1)));

	//unbalanced2 should work too: always use center (perfect balanced trees)
	//bool unbalanced2 = true;

	//this should be safe too:
	int rangeBalancedIndices = numIndices/3;
	bool unbalanced = ((splitIndex<=(startIndex+rangeBalancedIndices)) || (splitIndex >=(endIndex-1-rangeBalancedIndices)));

	if (unbalanced)
	{
		splitIndex = startIndex+ (numIndices>>1);
	}

	btAssert(!((splitIndex==startIndex) || (splitIndex == (endIndex))));

	return splitIndex;

}

void btQuantizedBvhTree::_build_sub_tree(GIM_BVH_DATA_ARRAY & primitive_boxes, int startIndex,  int endIndex)
{
	int curIndex = m_num_nodes;
	m_num_nodes++;

	btAssert((endIndex-startIndex)>0);

	if ((endIndex-startIndex)==1)
	{
	    //We have a leaf node
	    setNodeBound(curIndex,primitive_boxes[startIndex].m_bound);
		m_node_array[curIndex].setDataIndex(primitive_boxes[startIndex].m_data);

		return;
	}
	//calculate Best Splitting Axis and where to split it. Sort the incoming 'leafNodes' array within range 'startIndex/endIndex'.

	//split axis
	int splitIndex = _calc_splitting_axis(primitive_boxes,startIndex,endIndex);

	splitIndex = _sort_and_calc_splitting_index(
			primitive_boxes,startIndex,endIndex,
			splitIndex//split axis
			);

	//calc this node bounding box

	btAABB node_bound;
	node_bound.invalidate();

	for (int i=startIndex;i<endIndex;i++)
	{
		node_bound.merge(primitive_boxes[i].m_bound);
	}

	setNodeBound(curIndex,node_bound);

	//build left branch
	_build_sub_tree(primitive_boxes, startIndex, splitIndex );

	//build right branch
	 _build_sub_tree(primitive_boxes, splitIndex ,endIndex);

	m_node_array[curIndex].setEscapeIndex(m_num_nodes - curIndex);

}

//! stackless build tree
void btQuantizedBvhTree::build_tree(
	GIM_BVH_DATA_ARRAY & primitive_boxes)
{
	calc_quantization(primitive_boxes);
	// initialize node count to 0
	m_num_nodes = 0;
	// allocate nodes
	m_node_array.resize(primitive_boxes.size()*2);

	_build_sub_tree(primitive_boxes, 0, primitive_boxes.size());
}

////////////////////////////////////class btGImpactQuantizedBvh

void btGImpactQuantizedBvh::refit()
{
	int nodecount = getNodeCount();
	while(nodecount--)
	{
		if(isLeafNode(nodecount))
		{
			btAABB leafbox;
			m_primitive_manager->get_primitive_box(getNodeData(nodecount),leafbox);
			setNodeBound(nodecount,leafbox);
		}
		else
		{
			//const GIM_BVH_TREE_NODE * nodepointer = get_node_pointer(nodecount);
			//get left bound
			btAABB bound;
			bound.invalidate();

			btAABB temp_box;

			int child_node = getLeftNode(nodecount);
			if(child_node)
			{
				getNodeBound(child_node,temp_box);
				bound.merge(temp_box);
			}

			child_node = getRightNode(nodecount);
			if(child_node)
			{
				getNodeBound(child_node,temp_box);
				bound.merge(temp_box);
			}

			setNodeBound(nodecount,bound);
		}
	}
}

//! this rebuild the entire set
void btGImpactQuantizedBvh::buildSet()
{
	//obtain primitive boxes
	GIM_BVH_DATA_ARRAY primitive_boxes;
	primitive_boxes.resize(m_primitive_manager->get_primitive_count());

	for (int i = 0;i<primitive_boxes.size() ;i++ )
	{
		 m_primitive_manager->get_primitive_box(i,primitive_boxes[i].m_bound);
		 primitive_boxes[i].m_data = i;
	}

	m_box_tree.build_tree(primitive_boxes);
}

//! returns the indices of the primitives in the m_primitive_manager
bool btGImpactQuantizedBvh::boxQuery(const btAABB & box, btAlignedObjectArray<int> & collided_results) const
{
	int curIndex = 0;
	int numNodes = getNodeCount();

	//quantize box

	unsigned short quantizedMin[3];
	unsigned short quantizedMax[3];

	m_box_tree.quantizePoint(quantizedMin,box.m_min);
	m_box_tree.quantizePoint(quantizedMax,box.m_max);

	while (curIndex < numNodes)
	{

		//catch bugs in tree data

		bool aabbOverlap = m_box_tree.testQuantizedBoxOverlapp(curIndex, quantizedMin,quantizedMax);
		bool isleafnode = isLeafNode(curIndex);

		if (isleafnode && aabbOverlap)
		{
			collided_results.push_back(getNodeData(curIndex));
		}

		if (aabbOverlap || isleafnode)
		{
			//next subnode
			curIndex++;
		}
		else
		{
			//skip node
			curIndex+= getEscapeNodeIndex(curIndex);
		}
	}
	if(collided_results.size()>0) return true;
	return false;
}

//! returns the indices of the primitives in the m_primitive_manager
bool btGImpactQuantizedBvh::rayQuery(
	const btVector3 & ray_dir,const btVector3 & ray_origin ,
	btAlignedObjectArray<int> & collided_results) const
{
	int curIndex = 0;
	int numNodes = getNodeCount();

	while (curIndex < numNodes)
	{
		btAABB bound;
		getNodeBound(curIndex,bound);

		//catch bugs in tree data

		bool aabbOverlap = bound.collide_ray(ray_origin,ray_dir);
		bool isleafnode = isLeafNode(curIndex);

		if (isleafnode && aabbOverlap)
		{
			collided_results.push_back(getNodeData( curIndex));
		}

		if (aabbOverlap || isleafnode)
		{
			//next subnode
			curIndex++;
		}
		else
		{
			//skip node
			curIndex+= getEscapeNodeIndex(curIndex);
		}
	}
	if(collided_results.size()>0) return true;
	return false;
}

SIMD_FORCE_INLINE bool _quantized_node_collision(
	const btGImpactQuantizedBvh * boxset0, const btGImpactQuantizedBvh * boxset1,
	const BT_BOX_BOX_TRANSFORM_CACHE & trans_cache_1to0,
	int node0 ,int node1, bool complete_primitive_tests)
{
	btAABB box0;
	boxset0->getNodeBound(node0,box0);
	btAABB box1;
	boxset1->getNodeBound(node1,box1);

	return box0.overlapping_trans_cache(box1,trans_cache_1to0,complete_primitive_tests );
//	box1.appy_transform_trans_cache(trans_cache_1to0);
//	return box0.has_collision(box1);

}

//stackless recursive collision routine
static void _find_quantized_collision_pairs_recursive(
	const btGImpactQuantizedBvh * boxset0, const btGImpactQuantizedBvh * boxset1,
	btPairSet * collision_pairs,
	const BT_BOX_BOX_TRANSFORM_CACHE & trans_cache_1to0,
	int node0, int node1, bool complete_primitive_tests)
{

	if( _quantized_node_collision(
		boxset0,boxset1,trans_cache_1to0,
		node0,node1,complete_primitive_tests) ==false) return;//avoid colliding internal nodes

	if(boxset0->isLeafNode(node0))
	{
		if(boxset1->isLeafNode(node1))
		{
			// collision result
			collision_pairs->push_pair(
				boxset0->getNodeData(node0),boxset1->getNodeData(node1));
			return;
		}
		else
		{

			//collide left recursive

			_find_quantized_collision_pairs_recursive(
								boxset0,boxset1,
								collision_pairs,trans_cache_1to0,
								node0,boxset1->getLeftNode(node1),false);

			//collide right recursive
			_find_quantized_collision_pairs_recursive(
								boxset0,boxset1,
								collision_pairs,trans_cache_1to0,
								node0,boxset1->getRightNode(node1),false);

		}
	}
	else
	{
		if(boxset1->isLeafNode(node1))
		{

			//collide left recursive
			_find_quantized_collision_pairs_recursive(
								boxset0,boxset1,
								collision_pairs,trans_cache_1to0,
								boxset0->getLeftNode(node0),node1,false);

			//collide right recursive

			_find_quantized_collision_pairs_recursive(
								boxset0,boxset1,
								collision_pairs,trans_cache_1to0,
								boxset0->getRightNode(node0),node1,false);

		}
		else
		{
			//collide left0 left1

			_find_quantized_collision_pairs_recursive(
				boxset0,boxset1,
				collision_pairs,trans_cache_1to0,
				boxset0->getLeftNode(node0),boxset1->getLeftNode(node1),false);

			//collide left0 right1

			_find_quantized_collision_pairs_recursive(
				boxset0,boxset1,
				collision_pairs,trans_cache_1to0,
				boxset0->getLeftNode(node0),boxset1->getRightNode(node1),false);

			//collide right0 left1

			_find_quantized_collision_pairs_recursive(
				boxset0,boxset1,
				collision_pairs,trans_cache_1to0,
				boxset0->getRightNode(node0),boxset1->getLeftNode(node1),false);

			//collide right0 right1

			_find_quantized_collision_pairs_recursive(
				boxset0,boxset1,
				collision_pairs,trans_cache_1to0,
				boxset0->getRightNode(node0),boxset1->getRightNode(node1),false);

		}// else if node1 is not a leaf
	}// else if node0 is not a leaf
}

void btGImpactQuantizedBvh::find_collision(const btGImpactQuantizedBvh * boxset0, const btTransform & trans0,
		const btGImpactQuantizedBvh * boxset1, const btTransform & trans1,
		btPairSet & collision_pairs)
{

	if(boxset0->getNodeCount()==0 || boxset1->getNodeCount()==0 ) return;

	BT_BOX_BOX_TRANSFORM_CACHE trans_cache_1to0;

	trans_cache_1to0.calc_from_homogenic(trans0,trans1);

#ifdef TRI_COLLISION_PROFILING
	bt_begin_gim02_q_tree_time();
#endif //TRI_COLLISION_PROFILING

	_find_quantized_collision_pairs_recursive(
		boxset0,boxset1,
		&collision_pairs,trans_cache_1to0,0,0,true);
#ifdef TRI_COLLISION_PROFILING
	bt_end_gim02_q_tree_time();
#endif //TRI_COLLISION_PROFILING

}


text:
package plugins_account_network_ec2

import (
	"fmt"
	"time"

	"github.com/trackit/trackit/db"
	core "github.com/trackit/trackit/plugins/account/core"
	utils "github.com/trackit/trackit/plugins/utils"
	"github.com/trackit/trackit/usageReports/ec2"
)

const (
	// 10 Mebibyte
	networkLimit = 1.049e+7
)

func init() {
	// Register the plugin
	core.AccountPlugin{
		Name:        "EC2 Network",
		Description: "Get the list of EC2 instances with low network activity",
		Category:    utils.PluginsCategories["EC2"],
		Label:       "EC2 instance(s) with network activity",
		Func:        processNetworkEc2,
	}.Register()
}

// prepareResult sets the Result and Status in the pluginRes struct
func prepareResult(pluginRes *core.PluginResult) {
	if pluginRes.Checked == pluginRes.Passed {
		pluginRes.Status = "green"
		pluginRes.Result = "All your EC2 instances have network activity"
	} else {
		pluginRes.Result = fmt.Sprintf("You have %d EC2 instance with low network activity", pluginRes.Checked-pluginRes.Passed)
		pluginRes.Status = utils.StatusPercentSteps{50, 80}.GetStatus(pluginRes.Checked, pluginRes.Passed)
	}
}

// getUnusedEc2Recommendation searches for unused ec2 network in usage report
// It takes a *core.PluginResult and an array of instances as parameters
func getUnusedEc2Recommendation(pluginRes *core.PluginResult, instances []ec2.InstanceReport) {
	pluginRes.Details = make([]string, 0)
	for _, instance := range instances {
		if instance.Instance.Stats.Network.In == -1 || instance.Instance.Stats.Network.Out == -1 {
			continue
		}
		pluginRes.Checked++
		network := instance.Instance.Stats.Network.In + instance.Instance.Stats.Network.Out
		if network > networkLimit {
			pluginRes.Passed++
		} else {
			pluginRes.Details = append(pluginRes.Details, fmt.Sprintf("%s %s", instance.Instance.Id, instance.Instance.Tags["Name"]))
		}
	}
	prepareResult(pluginRes)
}

// processNetworkEc2 is the handler function for the Unused EC2 Network plugin
// it takes a core.PluginParams struct and returns a core.PluginResult struct
func processNetworkEc2(params core.PluginParams) (res core.PluginResult) {
	tx, err := db.Db.Begin()
	if err != nil {
		res.Status = "red"
		res.Error = fmt.Sprintln("Unable to retrieve EC2 instances : ", err.Error())
		return
	}
	_, instances, err := ec2.GetEc2Data(params.Context,
		ec2.Ec2QueryParams{[]string{params.AccountId}, nil, time.Now().UTC()},
		params.User, tx)
	if err != nil {
		res.Status = "red"
		res.Error = fmt.Sprintln("Unable to retrieve EC2 instances : ", err.Error())
		return
	}
	getUnusedEc2Recommendation(&res, instances)
	return
}


text:
import Ember from 'ember';
import config from 'travis/config/environment';
import { task } from 'ember-concurrency';

export default Ember.Component.extend({
  isPR: Ember.computed('tab', function () {
    return this.get('tab') === 'pull_requests';
  }),

  isBranch: Ember.computed('tab', function () {
    return this.get('tab') === 'branches';
  }),

  triggerBuild: task(function* () {
    const apiEndpoint = config.apiEndpoint;

    yield Ember.$.ajax(`${apiEndpoint}/repo/${this.get('repo.repo.id')}/requests`, {
      headers: {
        Authorization: `token ${this.get('repo.auth')}`,
        'Travis-API-Version': '3'
      },
      type: 'POST'
    });
  }).drop()
});


text:
require "curses"

require "tic_tac_toe/tui/setup"
require "tic_tac_toe/tui/board"
require "tic_tac_toe/tui/cursor"
require "tic_tac_toe/tui/status"

class TicTacToe
  class TUI # Textual User Inteface
    def initialize
      TUI::Setup.call
    end

    def listen
      loop do
        key = getch
        yield key
      end
    rescue Interrupt
    end

    def board!(*args)
      @board ||= TUI::Board.new(*args)
      @board.update(*args)
    end

    def cursor!(*args)
      @cursor ||= TUI::Cursor.new(@board.window)
      @cursor.update(*args)
    end

    def status!(*args)
      @status ||= TUI::Status.new(@board.window)
      @status.update(*args)
    end

    def clear
      @board.window.close
      Curses.clear
      Curses.refresh

      @board = @cursor = @status = nil
    end

    private

    def getch
      case key = @board.window.getch
      when String  # printable character
        key
      when Integer # special key
        Curses::Key.constants
          .find { |name| Curses::Key.const_get(name) == key }
      end
    end
  end
end


text:
package com.communote.server.persistence.global;

import com.communote.server.api.core.application.CommunoteRuntime;
import com.communote.server.api.core.config.type.ClientProperty;

/**
 * Helper class for the global id
 *
 * @author Communote GmbH - http://www.communote.com/
 *
 */
public final class GlobalIdHelper {

    /**
     * Build the global id String for the given type and id
     *
     * @param type
     *            the type of the id
     * @param id
     *            the id itself
     * @return the string, e.g. /serverId/blog/12
     */
    public static String buildGlobalIdIString(GlobalIdType type, Long id) {
        StringBuilder sb = new StringBuilder();
        sb.append("/");
        sb.append(getUnqiueIdentifier());
        sb.append("/");
        sb.append(type.getGlobalIdPath());
        sb.append("/");
        sb.append(id);
        return sb.toString();
    }

    /**
     * @return the unique identifier of this system
     */
    private static String getUnqiueIdentifier() {
        return CommunoteRuntime.getInstance().getConfigurationManager()
                .getClientConfigurationProperties()
                .getProperty(ClientProperty.UNIQUE_CLIENT_IDENTIFER);
    }

    /**
     * Helper class
     */
    private GlobalIdHelper() {
        // Nothing to implement here
    }

}


text:
/**
 */
package gluemodel.CIM.IEC61970.Wires;

import gluemodel.CIM.IEC61968.WiresExt.DistributionTransformerWinding;

/**
 *
 * A representation of the model object 'Ratio Tap Changer'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link gluemodel.CIM.IEC61970.Wires.RatioTapChanger#getRatioVariationCurve Ratio Variation Curve}

 *
{@link gluemodel.CIM.IEC61970.Wires.RatioTapChanger#getTransformerWinding Transformer Winding}

 *
{@link gluemodel.CIM.IEC61970.Wires.RatioTapChanger#getWinding Winding}

 *
{@link gluemodel.CIM.IEC61970.Wires.RatioTapChanger#getTculControlMode Tcul Control Mode}

 *

 *
 * @see gluemodel.CIM.IEC61970.Wires.WiresPackage#getRatioTapChanger()
 * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A tap changer that changes the voltage ratio impacting the voltage magnitude but not direclty the phase angle across the transformer..'"
 *        annotation="http://langdale.com.au/2005/UML Profile\040documentation='A tap changer that changes the voltage ratio impacting the voltage magnitude but not direclty the phase angle across the transformer..'"
 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A tap changer that changes the voltage ratio impacting the voltage magnitude but not direclty the phase angle across the transformer..' Profile\040documentation='A tap changer that changes the voltage ratio impacting the voltage magnitude but not direclty the phase angle across the transformer..'"
 * @generated
 */
public interface RatioTapChanger extends TapChanger {
	/**
	 * Returns the value of the 'Ratio Variation Curve' reference.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Wires.RatioVariationCurve#getRatioTapChanger Ratio Tap Changer}'.
	 *
	 *

	 * If the meaning of the 'Ratio Variation Curve' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Ratio Variation Curve' reference.
	 * @see #setRatioVariationCurve(RatioVariationCurve)
	 * @see gluemodel.CIM.IEC61970.Wires.WiresPackage#getRatioTapChanger_RatioVariationCurve()
	 * @see gluemodel.CIM.IEC61970.Wires.RatioVariationCurve#getRatioTapChanger
	 * @model opposite="RatioTapChanger"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A RatioTapChanger can have an associated RatioVariationCurve to define tap ratio variations with tap step changes.'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A RatioTapChanger can have an associated RatioVariationCurve to define tap ratio variations with tap step changes.'"
	 * @generated
	 */
	RatioVariationCurve getRatioVariationCurve();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Wires.RatioTapChanger#getRatioVariationCurve Ratio Variation Curve}' reference.
	 *
	 *
	 * @param value the new value of the 'Ratio Variation Curve' reference.
	 * @see #getRatioVariationCurve()
	 * @generated
	 */
	void setRatioVariationCurve(RatioVariationCurve value);

	/**
	 * Returns the value of the 'Transformer Winding' reference.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Wires.TransformerWinding#getRatioTapChanger Ratio Tap Changer}'.
	 *
	 *

	 * If the meaning of the 'Transformer Winding' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Transformer Winding' reference.
	 * @see #setTransformerWinding(TransformerWinding)
	 * @see gluemodel.CIM.IEC61970.Wires.WiresPackage#getRatioTapChanger_TransformerWinding()
	 * @see gluemodel.CIM.IEC61970.Wires.TransformerWinding#getRatioTapChanger
	 * @model opposite="RatioTapChanger"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='The transformer winding to which the ratio tap changer belongs.'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='The transformer winding to which the ratio tap changer belongs.'"
	 * @generated
	 */
	TransformerWinding getTransformerWinding();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Wires.RatioTapChanger#getTransformerWinding Transformer Winding}' reference.
	 *
	 *
	 * @param value the new value of the 'Transformer Winding' reference.
	 * @see #getTransformerWinding()
	 * @generated
	 */
	void setTransformerWinding(TransformerWinding value);

	/**
	 * Returns the value of the 'Winding' reference.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61968.WiresExt.DistributionTransformerWinding#getRatioTapChanger Ratio Tap Changer}'.
	 *
	 *

	 * If the meaning of the 'Winding' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Winding' reference.
	 * @see #setWinding(DistributionTransformerWinding)
	 * @see gluemodel.CIM.IEC61970.Wires.WiresPackage#getRatioTapChanger_Winding()
	 * @see gluemodel.CIM.IEC61968.WiresExt.DistributionTransformerWinding#getRatioTapChanger
	 * @model opposite="RatioTapChanger"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Winding to which this ratio tap changer belongs.'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Winding to which this ratio tap changer belongs.'"
	 * @generated
	 */
	DistributionTransformerWinding getWinding();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Wires.RatioTapChanger#getWinding Winding}' reference.
	 *
	 *
	 * @param value the new value of the 'Winding' reference.
	 * @see #getWinding()
	 * @generated
	 */
	void setWinding(DistributionTransformerWinding value);

	/**
	 * Returns the value of the 'Tcul Control Mode' attribute.
	 * The literals are from the enumeration {@link gluemodel.CIM.IEC61970.Wires.TransformerControlMode}.
	 *
	 *

	 * If the meaning of the 'Tcul Control Mode' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Tcul Control Mode' attribute.
	 * @see gluemodel.CIM.IEC61970.Wires.TransformerControlMode
	 * @see #setTculControlMode(TransformerControlMode)
	 * @see gluemodel.CIM.IEC61970.Wires.WiresPackage#getRatioTapChanger_TculControlMode()
	 * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Specifies the regulation control mode (voltage or reactive) of the RatioTapChanger.'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Specifies the regulation control mode (voltage or reactive) of the RatioTapChanger.'"
	 * @generated
	 */
	TransformerControlMode getTculControlMode();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Wires.RatioTapChanger#getTculControlMode Tcul Control Mode}' attribute.
	 *
	 *
	 * @param value the new value of the 'Tcul Control Mode' attribute.
	 * @see gluemodel.CIM.IEC61970.Wires.TransformerControlMode
	 * @see #getTculControlMode()
	 * @generated
	 */
	void setTculControlMode(TransformerControlMode value);

} // RatioTapChanger


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

<title>EncryptionInfo (POI API Documentation)</title>
<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.apache.poi.poifs.crypt

Class EncryptionInfo

java.lang.Object

org.apache.poi.poifs.crypt.EncryptionInfo

public class EncryptionInfo
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

EncryptionInfo(DirectoryNode dir)

EncryptionInfo(DirectoryNode dir,
              EncryptionMode encryptionMode)

EncryptionInfo(DirectoryNode dir,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)

EncryptionInfo(NPOIFSFileSystem fs)

EncryptionInfo(NPOIFSFileSystem fs,
              EncryptionMode encryptionMode)

EncryptionInfo(NPOIFSFileSystem fs,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)

EncryptionInfo(POIFSFileSystem fs)

EncryptionInfo(POIFSFileSystem fs,
              EncryptionMode encryptionMode)

EncryptionInfo(POIFSFileSystem fs,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)

Method Summary

Methods

Modifier and Type
Method and Description

protected static EncryptionInfoBuilder
getBuilder(EncryptionMode encryptionMode)

Decryptor
getDecryptor()

int
getEncryptionFlags()

Encryptor
getEncryptor()

EncryptionHeader
getHeader()

EncryptionVerifier
getVerifier()

int
getVersionMajor()

int
getVersionMinor()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

EncryptionInfo

public EncryptionInfo(POIFSFileSystem fs)
               throws java.io.IOException

Throws:

java.io.IOException

EncryptionInfo

public EncryptionInfo(NPOIFSFileSystem fs)
               throws java.io.IOException

Throws:

java.io.IOException

EncryptionInfo

public EncryptionInfo(DirectoryNode dir)
               throws java.io.IOException

Throws:

java.io.IOException

EncryptionInfo

public EncryptionInfo(POIFSFileSystem fs,
              EncryptionMode encryptionMode)
               throws java.io.IOException

Throws:

java.io.IOException

EncryptionInfo

public EncryptionInfo(NPOIFSFileSystem fs,
              EncryptionMode encryptionMode)
               throws java.io.IOException

Throws:

java.io.IOException

EncryptionInfo

public EncryptionInfo(DirectoryNode dir,
              EncryptionMode encryptionMode)
               throws EncryptedDocumentException

Throws:

EncryptedDocumentException

EncryptionInfo

public EncryptionInfo(POIFSFileSystem fs,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)
               throws EncryptedDocumentException

Throws:

EncryptedDocumentException

EncryptionInfo

public EncryptionInfo(NPOIFSFileSystem fs,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)
               throws EncryptedDocumentException

Throws:

EncryptedDocumentException

EncryptionInfo

public EncryptionInfo(DirectoryNode dir,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)
               throws EncryptedDocumentException

Throws:

EncryptedDocumentException

Method Detail

getBuilder

protected static EncryptionInfoBuilder getBuilder(EncryptionMode encryptionMode)
                                           throws java.lang.ClassNotFoundException,
                                                  java.lang.IllegalAccessException,
                                                  java.lang.InstantiationException

Throws:

java.lang.ClassNotFoundException

java.lang.IllegalAccessException

java.lang.InstantiationException

getVersionMajor

public int getVersionMajor()

getVersionMinor

public int getVersionMinor()

getEncryptionFlags

public int getEncryptionFlags()

getHeader

public EncryptionHeader getHeader()

getVerifier

public EncryptionVerifier getVerifier()

getDecryptor

public Decryptor getDecryptor()

getEncryptor

public Encryptor getEncryptor()

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 2014 The Apache Software Foundation or
        its licensors, as applicable.


text:
var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',
  entry: [
    'webpack-hot-middleware/client',
    './src/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: ['babel'],
        include: path.join(__dirname, 'src'),
        exclude: '/node_modules/'
      }
  ]
  }
};


text:
define(function () {
    return {
        makeLinkedList: function() {
            var linkedList = {};

            linkedList.length = 0;
            linkedList.head = null;
            linkedList.tail = null;

            linkedList.add = function(value) {
                var node = this.makeNode(value);

                if (this.head === null) {
                    this.head = node;
                } else {
                    this.tail.next = node;
                }
                this.tail = node;
                this.length += 1;
            };

            linkedList.prepend = function(value) {
                var node = this.makeNode(value);

                if (this.tail === null) {
                    this.tail = node;
                } else {
                    node.next = this.head;
                }
                this.head = node;
                this.length += 1;
            };

            linkedList.remove = function(value) {
                var self = this;

                var removeNode = function(currentNode, previousNode) {
                    if (self.head.value === currentNode.value) {
                        self.head = currentNode.next ? currentNode.next : null;
                    }
                    if (self.tail.value === currentNode.value) {
                        self.tail = previousNode ? previousNode : null;
                    }
                    if (previousNode) {
                        previousNode.next = currentNode.next;
                    }
                    self.length -= 1;
                };

                return self.iterate(value, removeNode, false);
            };

            linkedList.reverse = function() {
                var currentNode = this.head,
                    previousNode = null;

                while(currentNode) {
                    tempNode = currentNode.next;

                    if (tempNode === null) {
                        this.head = currentNode;
                        currentNode.next = previousNode ? previousNode : currentNode;
                        return this;
                    }

                    if (previousNode) {
                        currentNode.next = previousNode;
                    } else {
                        this.tail = currentNode;
                        currentNode.next = null;
                    }
                    previousNode = currentNode;
                    currentNode = tempNode;
                }

                return this;
            };

            linkedList.contains = function(value) {
                return this.iterate(value, false, true);
            };

            // Helper Functions
            linkedList.makeNode = function(value) {
                var node = {
                    value: value,
                    next: null
                };
                return node;
            };
            linkedList.iterate = function(value, iterator, returnBoolean) {
                var currentNode = this.head,
                    previousNode = null;

                while(currentNode) {
                    if (currentNode.value === value) {
                        if (iterator) { iterator(currentNode, previousNode); }
                        return returnBoolean ? true : currentNode;
                    } else {
                        previousNode = currentNode;
                        currentNode = currentNode.next;
                    }
                }
                return false;
            };

            return linkedList;
        }
    };
});


text:
/**
@module ember-metal
*/

import { assert } from './debug';
import { isPath, hasThis } from './path_cache';

const ALLOWABLE_TYPES = {
  object: true,
  function: true,
  string: true
};

// ..........................................................
// GET AND SET
//
// If we are on a platform that supports accessors we can use those.
// Otherwise simulate accessors by looking up the property directly on the
// object.

/**
  Gets the value of a property on an object. If the property is computed,
  the function will be invoked. If the property is not defined but the
  object implements the `unknownProperty` method then that will be invoked.

  ```javascript
  Ember.get(obj, "name");
  ```

  If you plan to run on IE8 and older browsers then you should use this
  method anytime you want to retrieve a property on an object that you don't
  know for sure is private. (Properties beginning with an underscore '_'
  are considered private.)

  On all newer browsers, you only need to use this method to retrieve
  properties if the property might not be defined on the object and you want
  to respect the `unknownProperty` handler. Otherwise you can ignore this
  method.

  Note that if the object itself is `undefined`, this method will throw
  an error.

  @method get
  @for Ember
  @param {Object} obj The object to retrieve from.
  @param {String} keyName The property key to retrieve
  @return {Object} the property value or `null`.
  @public
*/
export function get(obj, keyName) {
  assert(`Get must be called with two arguments; an object and a property key`, arguments.length === 2);
  assert(`Cannot call get with '${keyName}' on an undefined object.`, obj !== undefined && obj !== null);
  assert(`The key provided to get must be a string, you passed ${keyName}`, typeof keyName === 'string');
  assert(`'this' in paths is not supported`, !hasThis(keyName));

  let value = obj[keyName];
  let desc = (value !== null && typeof value === 'object' && value.isDescriptor) ? value : undefined;
  let ret;

  if (desc === undefined && isPath(keyName)) {
    return _getPath(obj, keyName);
  }

  if (desc) {
    return desc.get(obj, keyName);
  } else {
    ret = value;

    if (ret === undefined &&
        'object' === typeof obj && !(keyName in obj) && 'function' === typeof obj.unknownProperty) {
      return obj.unknownProperty(keyName);
    }

    return ret;
  }
}

export function _getPath(root, path) {
  let obj = root;
  let parts = path.split('.');

  for (let i = 0; i < parts.length; i++) {
    if (!isGettable(obj)) {
      return undefined;
    }

    obj = get(obj, parts[i]);

    if (obj && obj.isDestroyed) {
      return undefined;
    }
  }

  return obj;
}

function isGettable(obj) {
  if (obj == null) {
    return false;
  }

  return ALLOWABLE_TYPES[typeof obj];
}

/**
  Retrieves the value of a property from an Object, or a default value in the
  case that the property returns `undefined`.

  ```javascript
  Ember.getWithDefault(person, 'lastName', 'Doe');
  ```

  @method getWithDefault
  @for Ember
  @param {Object} obj The object to retrieve from.
  @param {String} keyName The name of the property to retrieve
  @param {Object} defaultValue The value to return if the property value is undefined
  @return {Object} The property value or the defaultValue.
  @public
*/
export function getWithDefault(root, key, defaultValue) {
  let value = get(root, key);

  if (value === undefined) { return defaultValue; }
  return value;
}

export default get;


text:
<!DOCTYPE html>

  <title>Enumerability</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="../css/blog-stylesheet.css">

Home | About Me | Blog | Portfolio | Contact

Ennumerability

Enumera-what???

12/10/2014

            So by this point we have pretty much established that Ruby is pretty awesome. The kind of girl you can bring home to Mom. She has all these great traits that you look for in a (programming) girl. She is easy to understand. Functional. And has class(es). Ok, joking aside, the language is sweet. One of the super cool things it can do is have collections. Also known as arrays and hashes (if you already forgot, take a look here). But let's be honest with ourselves, most programming languages have those in one form or another. What makes Ruby so special is something called the enumerable module. I know that sounds tricky, but by the time I'm done, I hope to have you understanding way more.

            So the enumerable module is a fancy way of saying that it has lots of iteration methods. "What is an iteration method," you ask. Let me show you. The .each method is the most basic example.

              array = [1,2,3,4,5]
              array.each |i| do
                puts i
              end

              1
              2
              3
              4
              5

            Basically what it does is for each i (this can be anything, it just represents an item in the array) do something. In this case, it was puts that item to the screen. Pretty neat right? Well, the enumerable module adds way more methods that are capable of far more. Today, I want to focus on the method .map.

            The .map method is going to allow you to take in a collection, modify it, then return a new array based on that method. Let's take a look using the same array as before:

              array.map { |x| x + 5 }

              [6,7,8,9,10]

            As you can see, .map took each element of the array, multiplied it by itself, then printed a new array for us. This can be very useful when you are trying to manipulate a large set of data. You can even store the results in a variable for later use.

            Hope this helped with your understanding of enumerables!

Working on my Gitness

DBC Fireside Chat

Class Vs Id

Arrays and Hashes

Thinking and Mindsets

Enumerability

Set Us Free

Ruby Classes

Feedback

Object-oriented vs Functional

Stereotype Threat

JavaScript vs Ruby

Values

What is Rails?

Conflict

Whatta Site

Good Questions

First Two Weeks

©2014 Zac Barnes


text:
from whacked4.ui import windows

import whacked4.utils as utils
import whacked4.config as config

import wx
import time
import random

class StatePreviewDialog(windows.StatePreviewDialogBase):
    """
    This dialog displays an animated preview of a state.
    """

    TICK_INTERVAL = 1000 / 35

    def __init__(self, parent):
        windows.StatePreviewDialogBase.__init__(self, parent)

        self.patch = None
        self.pwads = None

        # Thing for sound references.
        self.ref_thing_index = None
        self.ref_thing = None

        # Weapon for sound\offset references.
        self.ref_weapon_index = None
        self.ref_weapon = None

        self.first_state_index = -1
        self.state_index = -1

        # Precise timer data.
        self.timer_prev = 0
        self.elapsed = 0
        self.ticks = 0

        self.Sprite.set_baseline_factor(0.85)
        self.Sprite.set_scale(2)

        self.StateInfo.SetFont(config.FONT_MONOSPACED_BOLD)
        self.StateAction.SetFont(config.FONT_MONOSPACED_BOLD)
        self.StateSound.SetFont(config.FONT_MONOSPACED_BOLD)
        self.SpawnSound.SetFont(config.FONT_MONOSPACED_BOLD)

        self.SetEscapeId(windows.PREVIEW_CLOSE)

        self.Bind(wx.EVT_CHAR_HOOK, self.key_hook)

    def update(self, pwads):
        self.pwads = pwads

        self.Sprite.set_source(self.pwads)
        self.Sprite.Refresh()

    def key_hook(self, event):
        """
        Intercepts all key presses.
        """

        # Tilde restarts the animation from the state this dialog was called with.
        if event.GetKeyCode() == 96:
            self.begin_playback(self.first_state_index)
            self.anim_start()
        else:
            event.Skip()

    def begin_playback(self, state_index):
        """
        Starts playback from a state. Takes care of moving over 0 duration starting states.
        """

        self.set_state(state_index)
        while self.ticks == 0:
            state = self.patch.states[self.state_index]
            self.set_state(state['nextState'])

    def prepare(self, pwads, patch, state_index, thing_index=None, weapon_index=None):
        """
        Used to prepare a new animation to preview.
        """

        self.pwads = pwads
        self.patch = patch
        self.first_state_index = state_index

        self.ref_thing_index = thing_index
        if thing_index is not None:
            self.ref_thing = patch.things[thing_index]
        else:
            self.ref_thing = None

        if weapon_index is not None:
            self.ref_weapon = patch.weapons[weapon_index]
        else:
            self.ref_weapon = None

        self.Sprite.set_source(pwads)
        self.set_title()
        self.begin_playback(state_index)

    def set_title(self):
        if self.ref_thing is not None:
            title = 'Preview thing - {}'.format(self.ref_thing.name)
        elif self.ref_weapon is not None:
            title = 'Preview weapon - {}'.format(self.ref_weapon.name)
        else:
            title = 'Preview'

        self.SetLabel(title)

    def activate(self, event):
        """
        Window activation event.
        """

        self.anim_start()

    def anim_start(self):
        """
        Starts animation playback from the current state.
        """

        self.timer_prev = time.time()
        self.Timer.Start(1)

    def anim_stop(self):
        """
        Stops animation playback.
        """

        self.Timer.Stop()

    def set_state(self, state_index):
        """
        Sets a new state index.
        """

        if state_index <= 1 or state_index >= len(self.patch.states):
            self.ticks = -1
            self.anim_stop()
            return

        state = self.patch.states[state_index]
        sprite_index = state['sprite']
        sprite_name = self.patch.sprite_names[sprite_index]
        sprite_frame = state['spriteFrame'] & 0x3FFF

        offset_x = 0
        offset_y = 0

        # Weapons are rendered offset from the center.
        if self.ref_weapon and state['unused1'] != 0:
            offset_x = state['unused1'] / 65536
            offset_y = state['unused2'] / 65536

        self.Sprite.show_sprite(sprite_name, sprite_frame, offset_x, offset_y)

        self.StateIndex.SetLabel(str(state_index))
        self.StateInfo.SetLabel('{}{}'.format(sprite_name, chr(65 + sprite_frame)))

        action_label = ''

        # Play any state-related sound.
        if state['action'] is not None:

            # Support for RandomJump action that takes parameters to jump to a random next state.
            if state['action'] == 'RandomJump' and random.randint(0, 255) < state['unused2']:
                self.set_state(state['unused1'])
                return

            action_key = state['action']
            action = self.patch.engine.actions[action_key]

            action_label = action.name

            sound_label = ''
            sound_index = None

            spawn_sound_label = ''
            spawn_sound_index = None

            if action.sound is not None:
                parts = action.sound.split(':')
                if len(parts) != 2:
                    raise Exception('Invalid sound for action "{}".'.format(action_key))

                if parts[0] == 'sound':
                    sound_index = int(parts[1])

                elif parts[0] == 'thing':
                    if self.ref_thing_index is not None:
                        sound_index = self.ref_thing[parts[1]]
                    else:
                        sound_label = '{}:{}'.format(parts[0], parts[1])

                elif parts[0] == 'state':
                    sound_index = state[parts[1]]

            # Action spawns a thing.
            if action.spawns is not None:
                thing = self.patch.things[action.spawns]
                spawn_sound_index = thing['soundAlert']

            # Playback sounds for this action. Any specific sound overrides a spawned thing sound.
            if sound_index is not None:
                utils.sound_play(self.patch.sounds[sound_index - 1].name, self.pwads)
                sound_label = self.patch.sounds[sound_index - 1].name
            elif spawn_sound_index is not None:
                utils.sound_play(self.patch.sounds[spawn_sound_index - 1].name, self.pwads)
                spawn_sound_label = self.patch.sounds[spawn_sound_index - 1].name

            self.SpawnSound.SetLabel(spawn_sound_label.upper())
            self.StateSound.SetLabel(sound_label.upper())

        self.StateAction.SetLabel(action_label)

        self.state_index = state_index
        self.ticks = state['duration']

    def timer(self, event):
        """
        Timer event.
        """

        # Figure out the exact time that has passed since the last call to this event.
        # The Timer control may not be precise enough in it's timing, so we rely on Python's time.time() for
        # more accurate time accounting.
        self.elapsed += (time.time() - self.timer_prev) * 1000
        self.timer_prev = time.time()

        # If too much time has passed since the previous event, just do a single tick to prevent needless updating.
        if self.elapsed > 3000:
            self.elapsed = self.TICK_INTERVAL

        # Keep ticking until all elapsed time has been ticked through.
        while self.elapsed >= self.TICK_INTERVAL:
            self.elapsed -= self.TICK_INTERVAL
            self.advance_tick()

    def advance_tick(self):
        """
        Advances the animation a single tick.
        """

        self.ticks -= 1
        while self.ticks == 0:
            state = self.patch.states[self.state_index]
            self.set_state(state['nextState'])

    def close(self, event):
        """
        Close event.
        """

        self.anim_stop()
        self.EndModal(0)


text:
json2yaml package
=================

Submodules
----------

json2yaml.json2yaml module
--------------------------

.. automodule:: json2yaml.json2yaml
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: json2yaml
    :members:
    :undoc-members:
    :show-inheritance:


text:
import World from '../game/world'
import Score from '../game/score'
import Player from '../game/player';

import BaseState from './base';

import constants from '../constants';

export default class Game extends BaseState {

    init(score) {
        this.interval = 0;
        this.highScore = score
    }

    update() {
        super.update(this.gameover);
    }

    create() {
        super.create();
        if (this.highScore > this.score.getHighScore()) {
            this.score.highScore = this.highScore
        }
        this.isPlaying = true;
        this.lifeCounter = this.game.add.text(this.game.width*.1,this.game.height*.025, 'Lives: 1', {fill:'#fff', boundsAlignV:'center'})
    }

    render(){
        super.render();
        this.lifeCounter.text = 'Lives: ' + (~~(this.player.getSprite().health-1));
    }

    gameover() {
        this.state.start('highscoreenter', true, false, this.score.score)
    }

    shutdown() {

    }

}


text:
package org.keycloak.models;

import org.keycloak.provider.ProviderEvent;

import org.keycloak.storage.SearchableModelField;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public interface GroupModel extends RoleMapperModel {

    public static class SearchableFields {
        public static final SearchableModelField<GroupModel> ID             = new SearchableModelField<>("id", String.class);
        public static final SearchableModelField<GroupModel> REALM_ID       = new SearchableModelField<>("realmId", String.class);
        /** Parent group ID */
        public static final SearchableModelField<GroupModel> PARENT_ID      = new SearchableModelField<>("parentGroupId", String.class);
        public static final SearchableModelField<GroupModel> NAME           = new SearchableModelField<>("name", String.class);
        /**
         * Field for comparison with roles granted to this group.
         * A role can be checked for belonging only via EQ operator. Role is referred by their ID
         */
        public static final SearchableModelField<GroupModel> ASSIGNED_ROLE  = new SearchableModelField<>("assignedRole", String.class);

        /**
         * Search for attribute value. The parameters is a pair {@code (attribute_name, values...)} where {@code attribute_name}
         * is always checked for equality, and the value is checked per the operator.
         */
        public static final SearchableModelField<GroupModel> ATTRIBUTE       = new SearchableModelField<>("attribute", String[].class);
    }

    interface GroupRemovedEvent extends ProviderEvent {
        RealmModel getRealm();
        GroupModel getGroup();
        KeycloakSession getKeycloakSession();
    }

    interface GroupPathChangeEvent extends ProviderEvent {
        RealmModel getRealm();
        String getNewPath();
        String getPreviousPath();
        KeycloakSession getKeycloakSession();
    }

    Comparator<GroupModel> COMPARE_BY_NAME = Comparator.comparing(GroupModel::getName);

    String getId();

    String getName();

    void setName(String name);

    /**
     * Set single value of specified attribute. Remove all other existing values
     *
     * @param name
     * @param value
     */
    void setSingleAttribute(String name, String value);

    void setAttribute(String name, List<String> values);

    void removeAttribute(String name);

    /**
     * @param name
     * @return null if there is not any value of specified attribute or first value otherwise. Don't throw exception if there are more values of the attribute
     */
    String getFirstAttribute(String name);

    /**
     * Returns group attributes that match the given name as a stream.
     * @param name {@code String} Name of the attribute to be used as a filter.
     * @return Stream of all attribute values or empty stream if there are not any values. Never return {@code null}.
     */
    Stream<String> getAttributeStream(String name);

    Map<String, List<String>> getAttributes();

    GroupModel getParent();
    String getParentId();

    /**
     * Returns all sub groups for the parent group as a stream.
     * @return Stream of {@link GroupModel}. Never returns {@code null}.
     */
    Stream<GroupModel> getSubGroupsStream();

    /**
     * You must also call addChild on the parent group, addChild on RealmModel if there is no parent group
     *
     * @param group
     */
    void setParent(GroupModel group);

    /**
     * Automatically calls setParent() on the subGroup
     *
     * @param subGroup
     */
    void addChild(GroupModel subGroup);

    /**
     * Automatically calls setParent() on the subGroup
     *
     * @param subGroup
     */
    void removeChild(GroupModel subGroup);

    /**
     * @deprecated This interface is no longer necessary, collection-based methods were removed from the parent interface
     * and therefore the parent interface can be used directly
     */
    @Deprecated
    interface Streams extends GroupModel, RoleMapperModel {
    }
}


text:
function (e, doc, options) {
    e.stopPropagation();

    // Redirects to topic log view.
    document.location.href = getUrlByFilter({topic: doc.topic, tag: "note"});
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.ResourceManager.Compute.Tests.Helpers;
using NUnit.Framework;

namespace Azure.ResourceManager.Compute.Tests
{
    [ClientTestFixture(true, "2021-04-01", "2020-06-01")]
    public class AvailabilitySetCollectionTests : ComputeTestBase
    {
        public AvailabilitySetCollectionTests(bool isAsync, string apiVersion)
            : base(isAsync, AvailabilitySetResource.ResourceType, apiVersion)//, RecordedTestMode.Record)
        {
        }

        private async Task<AvailabilitySetCollection> GetAvailabilitySetCollectionAsync()
        {
            var resourceGroup = await CreateResourceGroupAsync();
            return resourceGroup.GetAvailabilitySets();
        }

        [TestCase]
        [RecordedTest]
        public async Task CreateOrUpdate()
        {
            var collection = await GetAvailabilitySetCollectionAsync();
            var setName = Recording.GenerateAssetName("testAS-");
            var input = ResourceDataHelper.GetBasicAvailabilitySetData(DefaultLocation);
            input.Tags.ReplaceWith(new Dictionary<string, string>
            {
                { "key", "value" }
            });
            var lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, setName, input);
            var availabilitySet = lro.Value;
            Assert.AreEqual(setName, availabilitySet.Data.Name);
        }

        [TestCase]
        [RecordedTest]
        public async Task Get()
        {
            var collection = await GetAvailabilitySetCollectionAsync();
            var setName = Recording.GenerateAssetName("testAS-");
            var input = ResourceDataHelper.GetBasicAvailabilitySetData(DefaultLocation);
            input.Tags.ReplaceWith(new Dictionary<string, string>
            {
                { "key", "value" }
            });
            var lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, setName, input);
            AvailabilitySetResource set1 = lro.Value;
            AvailabilitySetResource set2 = await collection.GetAsync(setName);

            ResourceDataHelper.AssertAvailabilitySet(set1.Data, set2.Data);
        }

        [TestCase]
        [RecordedTest]
        public async Task Exists()
        {
            var collection = await GetAvailabilitySetCollectionAsync();
            var setName = Recording.GenerateAssetName("testAS-");
            var input = ResourceDataHelper.GetBasicAvailabilitySetData(DefaultLocation);
            input.Tags.ReplaceWith(new Dictionary<string, string>
            {
                { "key", "value" }
            });
            var lro = await collection.CreateOrUpdateAsync(WaitUntil.Completed, setName, input);
            var availabilitySet = lro.Value;
            Assert.IsTrue(await collection.ExistsAsync(setName));
            Assert.IsFalse(await collection.ExistsAsync(setName + "1"));

            Assert.ThrowsAsync<ArgumentNullException>(async () => _ = await collection.ExistsAsync(null));
        }

        [TestCase]
        [RecordedTest]
        public async Task GetAll()
        {
            var collection = await GetAvailabilitySetCollectionAsync();
            var input = ResourceDataHelper.GetBasicAvailabilitySetData(DefaultLocation);
            input.Tags.ReplaceWith(new Dictionary<string, string>
            {
                { "key", "value" }
            });
            _ = await collection.CreateOrUpdateAsync(WaitUntil.Completed, Recording.GenerateAssetName("testAS-"), input);
            _ = await collection.CreateOrUpdateAsync(WaitUntil.Completed, Recording.GenerateAssetName("testAs-"), input);
            int count = 0;
            await foreach (var availabilitySet in collection.GetAllAsync())
            {
                count++;
            }
            Assert.GreaterOrEqual(count, 2);
        }

        [TestCase]
        [RecordedTest]
        public async Task GetAllInSubscription()
        {
            var collection = await GetAvailabilitySetCollectionAsync();
            var setName1 = Recording.GenerateAssetName("testAS-");
            var setName2 = Recording.GenerateAssetName("testAS-");
            var input = ResourceDataHelper.GetBasicAvailabilitySetData(DefaultLocation);
            input.Tags.ReplaceWith(new Dictionary<string, string>
            {
                { "key", "value" }
            });
            _ = await collection.CreateOrUpdateAsync(WaitUntil.Completed, setName1, input);
            _ = await collection.CreateOrUpdateAsync(WaitUntil.Completed, setName2, input);

            AvailabilitySetResource set1 = null, set2 = null;
            await foreach (var availabilitySet in DefaultSubscription.GetAvailabilitySetsAsync())
            {
                if (availabilitySet.Data.Name == setName1)
                    set1 = availabilitySet;
                if (availabilitySet.Data.Name == setName2)
                    set2 = availabilitySet;
            }

            Assert.NotNull(set1);
            Assert.NotNull(set2);
        }
    }
}