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

<title>JarLoader (KToolJa 1.0.0 API)</title>
<meta name="date" content="2017-03-28">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

kariminf.ktoolja.plugins

Class JarLoader

java.lang.Object

kariminf.ktoolja.plugins.JarLoader

public class JarLoader
extends java.lang.Object

A class for loading jar files as plugins

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

private class
JarLoader.JarFileFilter

This class is used to filter the jars that implements the wanted extension.

Field Summary

Fields

Modifier and Type
Field and Description

private java.net.URLClassLoader
classLoader

private java.lang.String
extName

private java.lang.String
extVersion

Constructor Summary

Constructors

Constructor and Description

JarLoader(java.lang.String location,
         java.lang.String extensionName,
         java.lang.String extensionVersion)

Creates a new JarLoader

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

private <T> T
FindService(java.lang.String packageName,
           java.lang.Class<T> cls)

Searches for an instance of the class that implements a service (or a class cls).

<T> T
getClassService(Info info,
               java.lang.Class<T> cls)

Gets an instance of the class that implements a service (or a class cls)

<T extends Info>
T
getInfoService(java.lang.String indicator,
              java.lang.Class<T> infoClass)

Gets an instance of the class that implements Info in the Jar,
 given a language

private <T> T
getServiceByName(java.lang.String className,
                java.lang.Class<T> cls)

Gets an instance of the class that implements a service (or a class cls)
 by its name

private java.net.URLClassLoader
loadJars(java.lang.String location)

Loads all jar files that have the wanted extension's name and version.

Methods inherited from class java.lang.Object

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

Field Detail

classLoader

private java.net.URLClassLoader classLoader

extName

private java.lang.String extName

extVersion

private java.lang.String extVersion

Constructor Detail

JarLoader

public JarLoader(java.lang.String location,
                 java.lang.String extensionName,
                 java.lang.String extensionVersion)

Creates a new JarLoader

Parameters:

location - the location where we can find the Jar Files (must end with "/")

extensionName - to compare it with "Extension-Name" in
 META-INF/MANIFEST.MF file of the Jar

extensionVersion - to compare it with "Specification-Version" in
            META-INF/MANIFEST.MF file of the Jar

Method Detail

getInfoService

public <T extends Info> T getInfoService(java.lang.String indicator,
                                         java.lang.Class<T> infoClass)

Gets an instance of the class that implements Info in the Jar,
 given a language

Parameters:

indicator - it is used as a mean to detect if the info class is what
 we are looking for

infoClass - the class that extends Info

Returns:

an instance of "infoClass" specific for the language needed

getClassService

public <T> T getClassService(Info info,
                             java.lang.Class<T> cls)

Gets an instance of the class that implements a service (or a class cls)

Parameters:

info - the info file where we want to get the service

cls - the class representing the service we looking for

Returns:

an instance of the class that implements a service cls

getServiceByName

private <T> T getServiceByName(java.lang.String className,
                               java.lang.Class<T> cls)

Gets an instance of the class that implements a service (or a class cls)
 by its name

Parameters:

className - the class name

cls - the class which we are looking for its service

Returns:

an instance of the class cls

FindService

private <T> T FindService(java.lang.String packageName,
                          java.lang.Class<T> cls)

Searches for an instance of the class that implements a service (or a class cls).
 This is used when we fail to get the instance using the name

Parameters:

packageName - the name of the jar file

cls - the class which we are looking for its service

Returns:

an instance of the class cls

loadJars

private java.net.URLClassLoader loadJars(java.lang.String location)

Loads all jar files that have the wanted extension's name and version.

Parameters:

location - the folder where we search for jars

Returns:

a class loader

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

package com.microsoft.azure.management.dns.models;

/**
* An MX record.
*/
public class MxRecord {
    private String exchange;

    /**
    * Required. Gets or sets the domain name of the mail host, without a
    * terminating dot.
    * @return The Exchange value.
    */
    public String getExchange() {
        return this.exchange;
    }

    /**
    * Required. Gets or sets the domain name of the mail host, without a
    * terminating dot.
    * @param exchangeValue The Exchange value.
    */
    public void setExchange(final String exchangeValue) {
        this.exchange = exchangeValue;
    }

    private int preference;

    /**
    * Required. Gets or sets the preference metric for this record.
    * @return The Preference value.
    */
    public int getPreference() {
        return this.preference;
    }

    /**
    * Required. Gets or sets the preference metric for this record.
    * @param preferenceValue The Preference value.
    */
    public void setPreference(final int preferenceValue) {
        this.preference = preferenceValue;
    }

    /**
    * Initializes a new instance of the MxRecord class.
    *
    */
    public MxRecord() {
    }

    /**
    * Initializes a new instance of the MxRecord class with required arguments.
    *
    * @param preference Gets or sets the preference metric for this record.
    * @param exchange Gets or sets the domain name of the mail host, without a
    * terminating dot.
    */
    public MxRecord(int preference, String exchange) {
        if (exchange == null) {
            throw new NullPointerException("exchange");
        }
        this.setPreference(preference);
        this.setExchange(exchange);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symfony\Component\Process;

/**
 * Process builder.
 *
 * @author Kris Wallsmith <kris@symfony.com>
 */
class ProcessBuilder
{
    private $arguments;
    private $cwd;
    private $env;
    private $stdin;
    private $timeout;
    private $options;
    private $inheritEnv;

    public function __construct(array $arguments = array())
    {
        $this->arguments = $arguments;

        $this->timeout = 60;
        $this->options = array();
        $this->inheritEnv = false;
    }

    /**
     * Adds an unescaped argument to the command string.
     *
     * @param string $argument A command argument
     */
    public function add($argument)
    {
        $this->arguments[] = $argument;

        return $this;
    }

    public function setWorkingDirectory($cwd)
    {
        $this->cwd = $cwd;

        return $this;
    }

    public function inheritEnvironmentVariables($inheritEnv = true)
    {
        $this->inheritEnv = $inheritEnv;

        return $this;
    }

    public function setEnv($name, $value)
    {
        if (null === $this->env) {
            $this->env = array();
        }

        $this->env[$name] = $value;

        return $this;
    }

    public function setInput($stdin)
    {
        $this->stdin = $stdin;

        return $this;
    }

    public function setTimeout($timeout)
    {
        $this->timeout = $timeout;

        return $this;
    }

    public function setOption($name, $value)
    {
        $this->options[$name] = $value;

        return $this;
    }

    public function getProcess()
    {
        if (!count($this->arguments)) {
            throw new \LogicException('You must add() command arguments before calling getProcess().');
        }

        $options = $this->options;

        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
            $options['bypass_shell'] = true;

            $arguments = $this->arguments;
            $command = array_shift($arguments);

            $script = '"'.$command.'"';
            if ($arguments) {
                $script .= ' '.implode(' ', array_map('escapeshellarg', $arguments));
            }

            $script = 'cmd /V:ON /E:ON /C "'.$script.'"';
        } else {
            $script = implode(' ', array_map('escapeshellarg', $this->arguments));
        }

        $env = $this->inheritEnv && $_ENV ? ($this->env ?: array()) + $_ENV : $this->env;

        return new Process($script, $this->cwd, $env, $this->stdin, $this->timeout, $options);
    }
}


text:
import time
import re
import os

import web
from web.utils import Storage

from karesansui.lib.rest import Rest, auth
from karesansui.lib.firewall.iptables import KaresansuiIpTables
from karesansui.gadget.hostby1firewallrule import validates_rule
from karesansui.lib.utils import get_ifconfig_info, dict_ksort

class HostBy1Firewall(Rest):

    @auth
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id

        kit = KaresansuiIpTables()

        if os.path.exists(kit.firewall_xml_file) is False:
            self.view.have_config = False
        else:
            kit.firewall_xml = kit.read_firewall_xml()
            # --
            self.view.iptables = Storage(
                is_running=kit.is_running(),
                is_configured=kit.is_configured(),
                )
            self.view.have_config = True

            if self.is_mode_input() is True:

                self.view.default_rule_id = len(kit.get_rules()) + 1
                self.view.targets = kit.basic_targets['filter']
                self.view.protocols = kit.chain_protos
                devtype_regexs = {
                    "phy":"^(lo|eth)",
                    "vir":"^(xenbr|virbr|vif|veth)",
                    }
                devtype_phy_regex = re.compile(r"%s" % devtype_regexs['phy'])
                devtype_vir_regex = re.compile(r"%s" % devtype_regexs['vir'])

                devs = {}
                devs['phy'] = []
                devs['vir'] = []
                devs['oth'] = []
                cidrs = []
                ips = []
                for dev,dev_info in get_ifconfig_info().iteritems():
                    try:
                        if devtype_phy_regex.match(dev):
                            devs['phy'].append(dev)
                        elif devtype_vir_regex.match(dev):
                            devs['vir'].append(dev)
                        else:
                            devs['oth'].append(dev)

                        if dev_info['ipaddr'] is not None:
                            if not dev_info['ipaddr'] in ips:
                                ips.append(dev_info['ipaddr'])
                        if dev_info['cidr'] is not None:
                            if not dev_info['cidr'] in cidrs:
                                cidrs.append(dev_info['cidr'])
                    except:
                        pass
                devs['phy'].sort()
                devs['vir'].sort()
                devs['oth'].sort()
                self.view.devs = [{'Physical' : devs['phy']},
                                  {'Virtual' : devs['vir']},
                                  {'Other' : devs['oth']},
                                  ]

                self.view.cidrs = cidrs
                self.view.ips = ips

        # --
        return True

    @auth
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        if not validates_rule(self, is_newrule=True):
            return web.badrequest(self.view.alert)

        kit = KaresansuiIpTables()
        kit.firewall_xml = kit.read_firewall_xml()

        rule_info = {"target" : self.input.target,
                     "protocol" : self.input.protocol,
                     "source" : self.input.source,
                     "destination" : self.input.destination,
                     "source-port" : self.input.sport,
                     "destination-port" : self.input.dport,
                     "in-interface" : self.input.inif,
                     "out-interface" : self.input.outif,
                     }

        if self.input.rule_id == "":
            rule_id = kit.add_rule(rule_info)
        else:
            rule_id = kit.insert_rule(int(self.input.rule_id),rule_info)

        kit.write_firewall_xml()

        self.view.host_id = host_id

        return web.created('%s/%d' % (web.ctx.path, rule_id,))

urls = (
    '/host/(\d+)/firewall/?(\.part)$', HostBy1Firewall,
    )


text:
package com.heaven7.java.visitor;

import com.heaven7.java.visitor.collection.KeyValuePair;

/**
 * fire/emit visitor
 * @author heaven7
 *
 * @param <K> the key type
 * @param <V> the value type
 * @since 1.1.1
 */
public interface MapFireVisitor<K, V> extends FireVisitor<KeyValuePair<K, V>>{

	/**
	 * fire the  key-value pair with target parameter .
	 * @param pair the key-value pair
	 * @param param the extra parameter.
	 */
	Boolean visit(KeyValuePair<K, V> pair, Object param);
}


text:
import os
import sys
import time
import logging
import logging.handlers
import cPickle
import random

import requests
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(asctime)-15s %(pathname)s:%(lineno)d - %(message)s')
handler = logging.handlers.SysLogHandler(address='/dev/log')
log = logging.getLogger(__name__)
log.addHandler(handler)

COOKIES_FILENAME = os.path.join(os.path.dirname(__file__), '.cookies.pkl')

def login_with_credentials(browser):
    log.info('Entering username')
    username = browser.find_element_by_name('username')
    username.send_keys(os.environ['USERNAME'])
    # browser.save_screenshot('uname.png')

    log.info('Entering password')
    password = browser.find_element_by_name('password')
    password.send_keys(os.environ['PASSWORD'])
    password.submit()

    # log.info('Save screenshot with home')
    time.sleep(10)
    # browser.save_screenshot('home.png')

    log.info('Saving cookies into file %s', COOKIES_FILENAME)
    cPickle.dump(browser.get_cookies() , open(COOKIES_FILENAME, 'wb'))

def login_with_cookies(browser):
    cookies = cPickle.load(open(COOKIES_FILENAME, 'rb'))
    for cookie in cookies:
        browser.add_cookie(cookie)

def like_one_post(browser, img):
    """
    Given an opened post, finds the like button, clicks on it and presses the right arrow
    in order to navigate to the next page
    :return: url of just liked image
    """
    url = None
    try:
        like = browser.find_element_by_css_selector('.coreSpriteHeartOpen')
        like.click()
        url = browser.current_url
    except:
        log.error('Image was already liked or some other error: %s', browser.current_url)

    # browser.save_screenshot(str(time.time()) + '.png')
    img.send_keys(Keys.ARROW_RIGHT)
    return url

def select_random_hashtag():
    """
    Returns a random hashtag from the latest posts or travel if none was found
    """
    r = requests.get('https://api.instagram.com/v1/users/self/media/recent?access_token={}'.format(os.environ['ACCESS_TOKEN']))
    if r.status_code == 200:
        data = r.json()
        tags = set()
        for media in data.get('data'):
            tags.update(media.get('tags'))
        return random.choice(list(tags))

    return 'travel'

def main():
    # select random hashtag from latest posts
    hashtag = select_random_hashtag()
    log.info('Hashtag #%s was selected', hashtag)

    display = Display(visible=0, size=(1024, 768))
    display.start()

    browser = webdriver.Firefox()
    log.info('Begin. Opening instagram.com')
    browser.get('https://instagram.com')

    if os.path.isfile(COOKIES_FILENAME):
        # load cookies
        log.info('Loading cookies and redirecting to instagram explore page')
        login_with_cookies(browser)
    else:
        log.info('Login with username and password')
        login_with_credentials(browser)

    # navigate to hashtag page, and wait 5s to load
    browser.get('https://www.instagram.com/explore/tags/{}/'.format(hashtag))
    log.info('Navigated to #%s', hashtag)
    time.sleep(5)

    # find first post
    img = browser.find_element_by_css_selector('article a')
    img.click()

    log.info('Found first image')

    # find first 3-9 photos to like
    for i in xrange(1, random.randint(4, 10)):
        # wait somewere between 5-10 sec
        time.sleep(random.randint(5, 11))

        # like the current active post, and move to the other
        url = like_one_post(browser, img)
        log.info('Liked image #%s, url: %s', i, url)

    # log.info('Saving screenshot')
    # browser.save_screenshot('home.png')
    log.info('Done!')

    browser.quit()

    display.stop()

if __name__ == '__main__':
    main()


text:
plplot-ffi
==========

LuaJIT wrapper for [PLplot](http://plplot.sourceforge.net/)

## Installation

This package requires PLplot to be installed in your system. You can download it from the project [website](http://plplot.sourceforge.net/), and also install it using brew in OS X:

```
brew install plplot
```

or apt in Ubuntu:

```
apt-get install libplplot12 plplot12-driver-cairo
```

The PLplot functions will draw the plots into cairo surfaces. The [torch-oocairo](https://github.com/akfidjeland/torch-oocairo) provides Lua bindings for Torch.

## C API

The first thing to do in order to access the PLplot C API is requiring the `plplot.api` Lua package:

```lua
local pl = require 'plplot.api'
```

Then the namespace `pl` will contain the functions in the PLplot C API. The functions in this API are usually prefixed by `pl`, for example `plinit` will now be accesible via `pl.init`, `plenv` via `pl.env` and so on. The only exception is `plend`, accesible via `pl.plend`.

## High level interface

This package tries to provide a similar interface to that in [torch/gnuplot](http://github.com/torch/gnuplot). In the following examples, `cairoContext` will always be a structure obtained by calling to the function `context_create` in [torch-oocairo](https://github.com/akfidjeland/torch-oocairo).

### Line plots

```lua
local plplot = require 'plplot'

...

local x = torch.DoubleTensor{0,1,2,3,4,5,6,7,8,9,10}
local plots = {}
for i = 1,3 do
    plots[i] = {x, torch.mul(x,i), '*-'}
end

plplot.init(cairoContext, 800, 800)
plplot.plot(plots)
plplot.labels('Line Plot', 'X axis', 'Y axis')
plplot.close()
```

![Line plots example](img/line.png)

The third element in the table defining each plots defines the format of that plot:

- `'|'` for using boxes.

- `'-'` for using lines.

- Any other character will be printed in all the points of the plot. This behaviour can be combined
  with lines. For example, `'-*'` will print characters `*` separated by lines.

If only one tensor is defined, then x values {0,1,2...} will be assumed.

### Histograms

```lua
local plplot = require 'plplot'

...

plplot.init(cairoContext, 800, 800)
plplot.hist(torch.randn(10000), 20)
plplot.labels('Histogram', 'X axis', 'Y axis')
plplot.close()
```

![Histogram example](img/hist.png)

### Surfaces

```lua
local plplot = require 'plplot'

...

x = torch.linspace(-1,1)
z = torch.sin(torch.zeros(x:size(1),x:size(1)):addr(x,x)*math.pi*2)

plplot.init(cairoContext, WIDTH, HEIGTH)
plplot.splot({x,x,z})
plplot.labels3d('x', 'y', 'z')
plplot.title('z=sin(xy)')
plplot.close()
```

![Surface example](img/surf.png)

If only one tensor is defined, then x and y values {0,1,2...} will be assumed.

### Labels

There are three functions to add labels to the plot:

* `plplot.title(title)`: Adds a title.

* `plplot.labels(title, xlabel, ylabel)`: Adds a title and labels for the two axis in a 2D plot.

* `plplot.3dlabels(xlabel, ylabel, zlabel)`: Adds labels for all the axis in a 3D plot.

### Colors

The function `plplot.colors(axisColor, color)` changes the colors used for the plot. The colors are represented
by tables with three numbers from 0 to 255 corresponding to the RGB components. The parameter `axisColor` determines
the color that the library will use to print the axis and the labels. The second parameter is a list of colors that
will be used in the same order to show the plots.


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// var Comment = new Schema({
//   userId: Number,
//   author: String,
//   tradeId: Number,
//   upvotedIds: [Number],
//   downvotedIds [Number]
// })

var Trade = new Schema({
  userId: Number,
  author: String,
  public: Boolean,
  teams: [{
    teamName: String,
    teamId: Number,
    playersIn: [Number],
    playersOut: [Number],
    picksIn: [{
      from: Number,
      type: String,
      year: Number,
      round: Number,
      originalOwner: String,
      description: String
    }],
    picksOut: [{
      to: Number,
      type: String,
      year: Number,
      round: Number,
      originalOwner: String,
      description: String
    }]
  }]
});

module.exports.Trade = mongoose.model('Trade', Trade);


text:
(function($) {
   $.fn.upload_button = function( options ) {
      var settings = {
         'id' : '' + Math.random(),
         'action' : '',
         'name' : 'file',
         'response_type' : 'json',
         'height' : '22px',
         'top_margin' : '2px',
      };
      if ( options ) $.extend( settings, options);
      var self = this;
      self.css( {
         'z-index' : '1',
         'position' : 'absolute',
         'left' : '0px',
         'width' : settings.width,
         'height' : settings.height,
         'top-margin' : settings.top_margin,
      });
      self.wrap( "<form method='post' enctype='multipart/form-data' action='" + settings.action + "' target='" + settings.id  + "_iframe'></form>" );
      for ( var param in settings.params ) {
         self.before( "<input name='" + param + "' value='" + settings.params[param] + "' type='hidden'/>" );
      }
      self.after( "" );
      self.siblings( 'iframe' ).load( function() {
         var response = $(this.contentDocument).find('body').html();
         if ( settings.response_type=='json' ) {
            response = response.replace( /^[^{]*/, '' );
            response = response.replace( /[^}]*$/, '' );
            eval( 'response = ' + response );
         }
         if ( settings.oncomplete ) settings.oncomplete( response );
      });

      var height = parseInt( self.css( 'height' ).replace( /[a-z]/i, '' ) );
      var width = parseInt( self.css( 'width' ).replace( /[a-z]/i, '' ) );
      self.after( "Uploading..." );
      self.wrap( "

" );
      self.before( "<input type='file' name='" + settings.name + "' style='width:" + ( width + 10 ) + "px;left:-5px;z-index:2;position:absolute;-moz-opacity:0;opacity:0;filter:alpha(opacity:0);'/>" );
      self.prev().mouseover( function() { self.addClass( 'hover' ); } ).mouseout( function () { self.removeClass( 'hover' ); } );

      self.siblings( 'input[type=file]' ).change( function() { self.parents('form').submit(); } );

      return this;
   };
})(jQuery);


text:
Rails::Application.routes.draw do |map|
  resources :authorizations
	resources :users

  match '/login', :controller => 'sessions', :action => 'new'
  match 'logout', :controller => 'sessions', :action => 'destroy'

  match '/auth/:provider/callback', :to => 'sessions#create'
end


text:
package com.randomchoice.lunch;

import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;

@Entity
public class Restaurant {
	@Id public String name;

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
}


text:
from distutils.core import setup
try:
    from setuptools import find_packages
except ImportError:
    print ("Please install Distutils and setuptools"
           " before installing this package")
    raise

setup(
    name='relay.runner',
    version='0.1.10.dev0',
    description=(
        'A smart thermostat.  Given a metric, or some timeseries that should'
        ' approach a given target, add heat or coolant as necessary'
        ' You can use Relay to auto-scale workers in large'
        ' distributed systems or do anything a thermostat might do.'
    ),
    long_description="Check the project homepage for details",
    keywords=[
        'relay', 'pid', 'pid controller', 'thermostat', 'tuning',
        'oscilloscope', 'auto-scale'],

    author='Alex Gaudio',
    author_email='adgaudio@gmail.com',
    url='http://github.com/sailthru/relay',

    packages=find_packages(),
    include_package_data=True,
    install_requires=['argparse_tools>=1.0.6', 'colorlog', 'numpy'],

    extras_require={
        'webui': ['pyzmq'],
    },
    tests_require=['nose'],
    test_suite="nose.main",
    zip_safe=True,

    entry_points = {
        'console_scripts': [
            'relay = relay.__main__:go',
        ],
        'setuptools.installation': [
            'eggsecutable = relay.__main__:go',
        ],
    },
)


text:
#pragma once
#include <aws/fsx/FSx_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace FSx
{
namespace Model
{

  /**
   *
The configuration that Amazon FSx uses to join a FSx for Windows File Server
   * file system or an ONTAP storage virtual machine (SVM) to a self-managed
   * (including on-premises) Microsoft Active Directory (AD) directory. For more
   * information, see
   * Using Amazon FSx with your self-managed Microsoft Active Directory or Managing
   * SVMs.

See Also:
   AWS
   * API Reference

   */
  class AWS_FSX_API SelfManagedActiveDirectoryConfiguration
  {
  public:
    SelfManagedActiveDirectoryConfiguration();
    SelfManagedActiveDirectoryConfiguration(Aws::Utils::Json::JsonView jsonValue);
    SelfManagedActiveDirectoryConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The fully qualified domain name of the self-managed AD directory, such as
     * corp.example.com.

     */
    inline const Aws::String& GetDomainName() const{ return m_domainName; }

    /**
     *
The fully qualified domain name of the self-managed AD directory, such as
     * corp.example.com.

     */
    inline bool DomainNameHasBeenSet() const { return m_domainNameHasBeenSet; }

    /**
     *
The fully qualified domain name of the self-managed AD directory, such as
     * corp.example.com.

     */
    inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    /**
     *
The fully qualified domain name of the self-managed AD directory, such as
     * corp.example.com.

     */
    inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = std::move(value); }

    /**
     *
The fully qualified domain name of the self-managed AD directory, such as
     * corp.example.com.

     */
    inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }

    /**
     *
The fully qualified domain name of the self-managed AD directory, such as
     * corp.example.com.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}

    /**
     *
The fully qualified domain name of the self-managed AD directory, such as
     * corp.example.com.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithDomainName(Aws::String&& value) { SetDomainName(std::move(value)); return *this;}

    /**
     *
The fully qualified domain name of the self-managed AD directory, such as
     * corp.example.com.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithDomainName(const char* value) { SetDomainName(value); return *this;}

    /**
     *
(Optional) The fully qualified distinguished name of the organizational unit
     * within your self-managed AD directory. Amazon FSx only accepts OU as the direct
     * parent of the file system. An example is
     * OU=FSx,DC=yourdomain,DC=corp,DC=com. To learn more, see RFC 2253. If none is provided,
     * the FSx file system is created in the default location of your self-managed AD
     * directory.

Only Organizational Unit (OU) objects can be the
     * direct parent of the file system that you're creating.

     */
    inline const Aws::String& GetOrganizationalUnitDistinguishedName() const{ return m_organizationalUnitDistinguishedName; }

    /**
     *
(Optional) The fully qualified distinguished name of the organizational unit
     * within your self-managed AD directory. Amazon FSx only accepts OU as the direct
     * parent of the file system. An example is
     * OU=FSx,DC=yourdomain,DC=corp,DC=com. To learn more, see RFC 2253. If none is provided,
     * the FSx file system is created in the default location of your self-managed AD
     * directory.

Only Organizational Unit (OU) objects can be the
     * direct parent of the file system that you're creating.

     */
    inline bool OrganizationalUnitDistinguishedNameHasBeenSet() const { return m_organizationalUnitDistinguishedNameHasBeenSet; }

    /**
     *
(Optional) The fully qualified distinguished name of the organizational unit
     * within your self-managed AD directory. Amazon FSx only accepts OU as the direct
     * parent of the file system. An example is
     * OU=FSx,DC=yourdomain,DC=corp,DC=com. To learn more, see RFC 2253. If none is provided,
     * the FSx file system is created in the default location of your self-managed AD
     * directory.

Only Organizational Unit (OU) objects can be the
     * direct parent of the file system that you're creating.

     */
    inline void SetOrganizationalUnitDistinguishedName(const Aws::String& value) { m_organizationalUnitDistinguishedNameHasBeenSet = true; m_organizationalUnitDistinguishedName = value; }

    /**
     *
(Optional) The fully qualified distinguished name of the organizational unit
     * within your self-managed AD directory. Amazon FSx only accepts OU as the direct
     * parent of the file system. An example is
     * OU=FSx,DC=yourdomain,DC=corp,DC=com. To learn more, see RFC 2253. If none is provided,
     * the FSx file system is created in the default location of your self-managed AD
     * directory.

Only Organizational Unit (OU) objects can be the
     * direct parent of the file system that you're creating.

     */
    inline void SetOrganizationalUnitDistinguishedName(Aws::String&& value) { m_organizationalUnitDistinguishedNameHasBeenSet = true; m_organizationalUnitDistinguishedName = std::move(value); }

    /**
     *
(Optional) The fully qualified distinguished name of the organizational unit
     * within your self-managed AD directory. Amazon FSx only accepts OU as the direct
     * parent of the file system. An example is
     * OU=FSx,DC=yourdomain,DC=corp,DC=com. To learn more, see RFC 2253. If none is provided,
     * the FSx file system is created in the default location of your self-managed AD
     * directory.

Only Organizational Unit (OU) objects can be the
     * direct parent of the file system that you're creating.

     */
    inline void SetOrganizationalUnitDistinguishedName(const char* value) { m_organizationalUnitDistinguishedNameHasBeenSet = true; m_organizationalUnitDistinguishedName.assign(value); }

    /**
     *
(Optional) The fully qualified distinguished name of the organizational unit
     * within your self-managed AD directory. Amazon FSx only accepts OU as the direct
     * parent of the file system. An example is
     * OU=FSx,DC=yourdomain,DC=corp,DC=com. To learn more, see RFC 2253. If none is provided,
     * the FSx file system is created in the default location of your self-managed AD
     * directory.

Only Organizational Unit (OU) objects can be the
     * direct parent of the file system that you're creating.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithOrganizationalUnitDistinguishedName(const Aws::String& value) { SetOrganizationalUnitDistinguishedName(value); return *this;}

    /**
     *
(Optional) The fully qualified distinguished name of the organizational unit
     * within your self-managed AD directory. Amazon FSx only accepts OU as the direct
     * parent of the file system. An example is
     * OU=FSx,DC=yourdomain,DC=corp,DC=com. To learn more, see RFC 2253. If none is provided,
     * the FSx file system is created in the default location of your self-managed AD
     * directory.

Only Organizational Unit (OU) objects can be the
     * direct parent of the file system that you're creating.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithOrganizationalUnitDistinguishedName(Aws::String&& value) { SetOrganizationalUnitDistinguishedName(std::move(value)); return *this;}

    /**
     *
(Optional) The fully qualified distinguished name of the organizational unit
     * within your self-managed AD directory. Amazon FSx only accepts OU as the direct
     * parent of the file system. An example is
     * OU=FSx,DC=yourdomain,DC=corp,DC=com. To learn more, see RFC 2253. If none is provided,
     * the FSx file system is created in the default location of your self-managed AD
     * directory.

Only Organizational Unit (OU) objects can be the
     * direct parent of the file system that you're creating.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithOrganizationalUnitDistinguishedName(const char* value) { SetOrganizationalUnitDistinguishedName(value); return *this;}

    /**
     *
(Optional) The name of the domain group whose members are granted
     * administrative privileges for the file system. Administrative privileges include
     * taking ownership of files and folders, setting audit controls (audit ACLs) on
     * files and folders, and administering the file system remotely by using the FSx
     * Remote PowerShell. The group that you specify must already exist in your domain.
     * If you don't provide one, your AD domain's Domain Admins group is used.

     */
    inline const Aws::String& GetFileSystemAdministratorsGroup() const{ return m_fileSystemAdministratorsGroup; }

    /**
     *
(Optional) The name of the domain group whose members are granted
     * administrative privileges for the file system. Administrative privileges include
     * taking ownership of files and folders, setting audit controls (audit ACLs) on
     * files and folders, and administering the file system remotely by using the FSx
     * Remote PowerShell. The group that you specify must already exist in your domain.
     * If you don't provide one, your AD domain's Domain Admins group is used.

     */
    inline bool FileSystemAdministratorsGroupHasBeenSet() const { return m_fileSystemAdministratorsGroupHasBeenSet; }

    /**
     *
(Optional) The name of the domain group whose members are granted
     * administrative privileges for the file system. Administrative privileges include
     * taking ownership of files and folders, setting audit controls (audit ACLs) on
     * files and folders, and administering the file system remotely by using the FSx
     * Remote PowerShell. The group that you specify must already exist in your domain.
     * If you don't provide one, your AD domain's Domain Admins group is used.

     */
    inline void SetFileSystemAdministratorsGroup(const Aws::String& value) { m_fileSystemAdministratorsGroupHasBeenSet = true; m_fileSystemAdministratorsGroup = value; }

    /**
     *
(Optional) The name of the domain group whose members are granted
     * administrative privileges for the file system. Administrative privileges include
     * taking ownership of files and folders, setting audit controls (audit ACLs) on
     * files and folders, and administering the file system remotely by using the FSx
     * Remote PowerShell. The group that you specify must already exist in your domain.
     * If you don't provide one, your AD domain's Domain Admins group is used.

     */
    inline void SetFileSystemAdministratorsGroup(Aws::String&& value) { m_fileSystemAdministratorsGroupHasBeenSet = true; m_fileSystemAdministratorsGroup = std::move(value); }

    /**
     *
(Optional) The name of the domain group whose members are granted
     * administrative privileges for the file system. Administrative privileges include
     * taking ownership of files and folders, setting audit controls (audit ACLs) on
     * files and folders, and administering the file system remotely by using the FSx
     * Remote PowerShell. The group that you specify must already exist in your domain.
     * If you don't provide one, your AD domain's Domain Admins group is used.

     */
    inline void SetFileSystemAdministratorsGroup(const char* value) { m_fileSystemAdministratorsGroupHasBeenSet = true; m_fileSystemAdministratorsGroup.assign(value); }

    /**
     *
(Optional) The name of the domain group whose members are granted
     * administrative privileges for the file system. Administrative privileges include
     * taking ownership of files and folders, setting audit controls (audit ACLs) on
     * files and folders, and administering the file system remotely by using the FSx
     * Remote PowerShell. The group that you specify must already exist in your domain.
     * If you don't provide one, your AD domain's Domain Admins group is used.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithFileSystemAdministratorsGroup(const Aws::String& value) { SetFileSystemAdministratorsGroup(value); return *this;}

    /**
     *
(Optional) The name of the domain group whose members are granted
     * administrative privileges for the file system. Administrative privileges include
     * taking ownership of files and folders, setting audit controls (audit ACLs) on
     * files and folders, and administering the file system remotely by using the FSx
     * Remote PowerShell. The group that you specify must already exist in your domain.
     * If you don't provide one, your AD domain's Domain Admins group is used.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithFileSystemAdministratorsGroup(Aws::String&& value) { SetFileSystemAdministratorsGroup(std::move(value)); return *this;}

    /**
     *
(Optional) The name of the domain group whose members are granted
     * administrative privileges for the file system. Administrative privileges include
     * taking ownership of files and folders, setting audit controls (audit ACLs) on
     * files and folders, and administering the file system remotely by using the FSx
     * Remote PowerShell. The group that you specify must already exist in your domain.
     * If you don't provide one, your AD domain's Domain Admins group is used.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithFileSystemAdministratorsGroup(const char* value) { SetFileSystemAdministratorsGroup(value); return *this;}

    /**
     *
The user name for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain. This account must have the
     * permission to join computers to the domain in the organizational unit provided
     * in OrganizationalUnitDistinguishedName, or in the default location
     * of your AD domain.

     */
    inline const Aws::String& GetUserName() const{ return m_userName; }

    /**
     *
The user name for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain. This account must have the
     * permission to join computers to the domain in the organizational unit provided
     * in OrganizationalUnitDistinguishedName, or in the default location
     * of your AD domain.

     */
    inline bool UserNameHasBeenSet() const { return m_userNameHasBeenSet; }

    /**
     *
The user name for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain. This account must have the
     * permission to join computers to the domain in the organizational unit provided
     * in OrganizationalUnitDistinguishedName, or in the default location
     * of your AD domain.

     */
    inline void SetUserName(const Aws::String& value) { m_userNameHasBeenSet = true; m_userName = value; }

    /**
     *
The user name for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain. This account must have the
     * permission to join computers to the domain in the organizational unit provided
     * in OrganizationalUnitDistinguishedName, or in the default location
     * of your AD domain.

     */
    inline void SetUserName(Aws::String&& value) { m_userNameHasBeenSet = true; m_userName = std::move(value); }

    /**
     *
The user name for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain. This account must have the
     * permission to join computers to the domain in the organizational unit provided
     * in OrganizationalUnitDistinguishedName, or in the default location
     * of your AD domain.

     */
    inline void SetUserName(const char* value) { m_userNameHasBeenSet = true; m_userName.assign(value); }

    /**
     *
The user name for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain. This account must have the
     * permission to join computers to the domain in the organizational unit provided
     * in OrganizationalUnitDistinguishedName, or in the default location
     * of your AD domain.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithUserName(const Aws::String& value) { SetUserName(value); return *this;}

    /**
     *
The user name for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain. This account must have the
     * permission to join computers to the domain in the organizational unit provided
     * in OrganizationalUnitDistinguishedName, or in the default location
     * of your AD domain.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithUserName(Aws::String&& value) { SetUserName(std::move(value)); return *this;}

    /**
     *
The user name for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain. This account must have the
     * permission to join computers to the domain in the organizational unit provided
     * in OrganizationalUnitDistinguishedName, or in the default location
     * of your AD domain.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithUserName(const char* value) { SetUserName(value); return *this;}

    /**
     *
The password for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain.

     */
    inline const Aws::String& GetPassword() const{ return m_password; }

    /**
     *
The password for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain.

     */
    inline bool PasswordHasBeenSet() const { return m_passwordHasBeenSet; }

    /**
     *
The password for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain.

     */
    inline void SetPassword(const Aws::String& value) { m_passwordHasBeenSet = true; m_password = value; }

    /**
     *
The password for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain.

     */
    inline void SetPassword(Aws::String&& value) { m_passwordHasBeenSet = true; m_password = std::move(value); }

    /**
     *
The password for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain.

     */
    inline void SetPassword(const char* value) { m_passwordHasBeenSet = true; m_password.assign(value); }

    /**
     *
The password for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithPassword(const Aws::String& value) { SetPassword(value); return *this;}

    /**
     *
The password for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithPassword(Aws::String&& value) { SetPassword(std::move(value)); return *this;}

    /**
     *
The password for the service account on your self-managed AD domain that
     * Amazon FSx will use to join to your AD domain.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithPassword(const char* value) { SetPassword(value); return *this;}

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline const Aws::Vector<Aws::String>& GetDnsIps() const{ return m_dnsIps; }

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline bool DnsIpsHasBeenSet() const { return m_dnsIpsHasBeenSet; }

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline void SetDnsIps(const Aws::Vector<Aws::String>& value) { m_dnsIpsHasBeenSet = true; m_dnsIps = value; }

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline void SetDnsIps(Aws::Vector<Aws::String>&& value) { m_dnsIpsHasBeenSet = true; m_dnsIps = std::move(value); }

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithDnsIps(const Aws::Vector<Aws::String>& value) { SetDnsIps(value); return *this;}

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline SelfManagedActiveDirectoryConfiguration& WithDnsIps(Aws::Vector<Aws::String>&& value) { SetDnsIps(std::move(value)); return *this;}

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline SelfManagedActiveDirectoryConfiguration& AddDnsIps(const Aws::String& value) { m_dnsIpsHasBeenSet = true; m_dnsIps.push_back(value); return *this; }

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline SelfManagedActiveDirectoryConfiguration& AddDnsIps(Aws::String&& value) { m_dnsIpsHasBeenSet = true; m_dnsIps.push_back(std::move(value)); return *this; }

    /**
     *
A list of up to three IP addresses of DNS servers or domain controllers in
     * the self-managed AD directory.

     */
    inline SelfManagedActiveDirectoryConfiguration& AddDnsIps(const char* value) { m_dnsIpsHasBeenSet = true; m_dnsIps.push_back(value); return *this; }

  private:

    Aws::String m_domainName;
    bool m_domainNameHasBeenSet = false;

    Aws::String m_organizationalUnitDistinguishedName;
    bool m_organizationalUnitDistinguishedNameHasBeenSet = false;

    Aws::String m_fileSystemAdministratorsGroup;
    bool m_fileSystemAdministratorsGroupHasBeenSet = false;

    Aws::String m_userName;
    bool m_userNameHasBeenSet = false;

    Aws::String m_password;
    bool m_passwordHasBeenSet = false;

    Aws::Vector<Aws::String> m_dnsIps;
    bool m_dnsIpsHasBeenSet = false;
  };

} // namespace Model
} // namespace FSx
} // namespace Aws


text:
class FlagsControllerTest < ActionController::TestCase
  include Devise::TestHelpers
  fixtures :maps, :layers, :roles, :permissions

  test "create new flag" do
    sign_in users(:adminuser)
    map = maps(:map1)
    post :create, :flag => { :reason => "error"}, :map_id => map

    flag = assigns(:flag)
    assert "Map", flag.flaggable_type

    assert_response :redirect
    assert_redirected_to map
    assert flash[:notice].include?("saved")
  end

  test "index"do
    sign_in users(:user1)
    get :index
    assert_response :redirect
    assert_redirected_to root_path
    assert flash[:error].include?("Sorry you do not have permission")
    sign_out users(:user1)

    sign_in users(:adminuser)
    get :index
    assert_response :ok

    flags = assigns(:flags)
    assert_not_nil flags
  end

  test "admin can close a flag" do
    sign_in users(:adminuser)
    flag = flags(:map1_flag)
    put :close, :id => flag.id
    assert_response :redirect
    assert_redirected_to flags_url
    assert flash[:notice].include?("closed")
  end
end


text:
'use strict';

var _ = require( './utils' );
var Game = require( './game' );
var Object3D = require( './object3d' );
var Geometry = require( './geometry/geometry' );
var Mesh = require( './objects/mesh' );
var Color = require( './math/color' );
var Vector3 = require( './math/vector3' );
var DirectionalLight = require( './lights/directional-light' );
var LambertMaterial = require( './materials/lambert-material' );
var addDiamondGeometry = require( './geometry/diamond-geometry' );
var createLevel = require( './levels/level' );
var Player = require( './gameplay/player' );
var fbm = require( './math/fbm' );
var colors = require( './gameplay/colors' );
var createSkybox = require( './gameplay/skybox' );
var animate = require( './gameplay/animate' );

var Audio = require( './audio/audio' );

var TWO_PI = 2 * Math.PI;

var $ = document.querySelector.bind( document );

function noop() {}

var _vector = new Vector3();
var _color = new Color();

function on( el, type, listener ) {
  el.addEventListener( type, listener );
}

function off( el, type, listener ) {
  el.removeEventListener( type, listener );
}

function append( parent, el ) {
  parent.appendChild( el );
}

function prepend( parent, el ) {
  parent.insertBefore( el, parent.firstChild );
}

function create( type ) {
  return document.createElement( type || 'div' );
}

function innerHTML( el, html ) {
  el.innerHTML = html;
}

function textContent( el, text ) {
  el.textContent = text;
}

function addClass( el, className ) {
  el.classList.add( className );
}

function removeClass( el, className ) {
  el.classList.remove( className );
}

function modulo( n, d ) {
  return ( ( n % d ) + d ) % d;
}

function angularDistance( a, b ) {
  return Math.abs( modulo( b - a + Math.PI, TWO_PI ) - Math.PI );
}

var keys = [];
var game = new Game();
game.setSize( window.innerWidth, window.innerHeight );

var container = $( '#g' );
append( container, game.canvas );

var blocks;
var levelRotation = 0;
var levelRadius = 8;
var blockCount = 32;

var cameraStartFOV = 10;
var cameraEndFOV = 60;
var cameraStartZ = 32;
var cameraEndZ = 12;
var cameraTarget = new Vector3().copy( Vector3.Y );

var rotationSpeed = Math.PI / 2;
var touchRotationSpeed = 48 * rotationSpeed;
var levelAngularVelocity = 0;
var levelAngularDamping = 3 * Math.PI;

// State.
var lives;
var isFirstPlay = true;
var isCheckingCollisions = false;
var shouldUpdateColor = false;

var score;
var highScore = 0;

function createControls() {
  var down = false;
  var px;

  function getX( event ) {
    return ( event.touches && event.touches.length ) ?
      event.touches[0].clientX :
      event.clientX;
  }

  function start( event ) {
    if ( isPlaying() ) {
      event.preventDefault();
    }

    px = getX( event );
    down = true;
  }

  function move( event ) {
    if ( !down ) {
      return;
    }

    event.preventDefault();

    if ( !isCheckingCollisions ) {
      return;
    }

    var x = getX( event );
    var dx = x - px;
    px = x;
    levelAngularVelocity = dx / window.innerWidth * touchRotationSpeed;
  }

  function end() {
    if ( isPlaying() ) {
      event.preventDefault();
    }

    down = false;
  }

  on( document, 'touchstart', start );
  on( document, 'touchmove', move );
  on( document, 'touchend', end );
  on( document, 'mousedown', start );
  on( document, 'mousemove', move );
  on( document, 'mouseup', end );
}

function getClosestBlockAtAngle( angle ) {
  angle = angle || 0;

  var minAngle = Infinity;
  var min;

  blocks.map(function( block ) {
    var theta = ( block.theta + levelRotation ) % TWO_PI;
    block.position.x = levelRadius * Math.sin( theta );
    block.position.z = levelRadius * Math.cos( theta );
    block.rotation.y = theta;
    block.updateQuaternion();

    block.material.emissive.setRGB( 0, 0, 0 );

    var angle = angularDistance( theta, 0 );
    block.angularDistance = angle;

    if ( angle < minAngle ) {
      minAngle = angle;
      min = block;
    }
  });

  return min;
}

function updateBlocks() {
  var min = getClosestBlockAtAngle();

  if ( min ) {
    min.material.emissive.setRGB( 0.3, 0.3, 0.3 );
  }
}

var material = new LambertMaterial({
  color: new Color( 0.8, 0.8, 0.8 ),
  overdraw: 0.5
});

function createDiamond( scene, x, y, z, radius, top, bottom, rotation ) {
  var mesh = new Mesh(
    addDiamondGeometry( new Geometry(), radius, top, bottom, 4 ),
    material
  );

  mesh.position.set( x, y, z );
  mesh.rotation.y = rotation;
  mesh.updateQuaternion();

  scene.add( mesh );

  return mesh;
}

var renderLives = (function() {
  var hearts = create();
  addClass( hearts, 'hts' );
  append( document.body, hearts );

  return function( count ) {
    innerHTML( hearts, '' );

    for ( var i = 0; i < count; i++ ) {
      var heart = create();
      addClass( heart, 'ht' );
      textContent( heart, '\u2665' );
      append( hearts, heart );
    }
  };
})();

var scene;
var player;

createControls();

function reset() {
  lives = 5;
  score = 0;
  isCheckingCollisions = !isFirstPlay;
  animate.reset();

  scene = game.scene = new Object3D();
  scene.fogDensity = 0.005;

  blocks = createLevel( scene, levelRadius, blockCount );
  levelRotation = 0;

  // Lights.
  var light = new DirectionalLight( new Color( 1, 0.8, 0.8 ) );
  light.position.set( -4, 4, 5 );
  scene.add( light );

  game.ambient.setRGB( 0.1, 0.3, 0.4 );

  // Camera.
  var camera = game.camera;
  camera.fov = isFirstPlay ? cameraStartFOV : cameraEndFOV;
  camera.position.set( 0, 1, isFirstPlay ? cameraStartZ : cameraEndZ );
  camera.up.x = 0.05;
  cameraTarget.copy( Vector3.Y );
  camera.lookAt( cameraTarget );
  camera.updateProjectionMatrix();

  // Diamonds.
  var diamondCenterY = -2;
  var diamondLeftY = -1.8;
  var diamondRightY = -2.4;
  var diamondCenter = createDiamond( scene, 0, diamondCenterY, 0.5, 1.8, 5, 6, 0.2 );
  var diamondLeft = createDiamond( scene, -2.7, diamondLeftY, -2, 1.5, 2.8, 4, 0.3 );
  var diamondRight = createDiamond( scene, 2.3, diamondRightY, -2.5, 1.7, 4.3, 5, 0.1 );

  // Skybox.
  createSkybox( scene );

  player = new Player();
  player.t = 0;
  player.mesh.position.y = 2 * fbm( 0, 8 ) + 0.01;
  player.mesh.position.z = 8.1;
  scene.add( player );
  scene.add( player.mesh );

  var closestBlock = getClosestBlockAtAngle();
  if ( closestBlock ) {
    player.color( closestBlock.colorIndex() );
  }

  game.onUpdate = function( dt ) {
    animate.update( dt );

    if ( isCheckingCollisions ) {
      if ( keys[ 37 ] || keys[ 65 ] ) {
        levelAngularVelocity = rotationSpeed;
      } else if ( keys[ 39 ] || keys[ 68 ] ) {
        levelAngularVelocity = -rotationSpeed;
      }
    }

    levelRotation += levelAngularVelocity * dt;
    levelAngularVelocity *= 1 - ( levelAngularDamping * dt );

    // Update camera target.
    _vector.copy( cameraTarget );
    _vector.x = -levelAngularVelocity;

    cameraTarget.lerp( _vector, dt );
    camera.lookAt( cameraTarget );

    updateBlocks();
    var closestBlock = getClosestBlockAtAngle();

    player.mesh.position.y += player.velocity * dt;
    player.velocity -= 4 * dt;

    player.mesh.position.y = Math.max(
      player.mesh.position.y,
      closestBlock.y + 0.01
    );

    var isColliding = player.mesh.position.y - 0.02 <= closestBlock.y;

    if ( isColliding ) {
      player.velocity = 4;
    }

    // Check for collisions.
    if ( isCheckingCollisions ) {
      // Check if the right color.
      if ( isColliding ) {
        shouldUpdateColor = true;

        if ( !player.mesh.material.color.equals( closestBlock.material.color ) ) {
          Audio.playError();
          lives--;
        } else {
          // Update color.
          var newColorIndex;
          do {
            newColorIndex = _.randInt( 0, colors.length - 1 );
          } while (
            _color
              .fromArray( colors[ newColorIndex ] )
              .equals( closestBlock.material.color )
          );

          score++;
          if ( score > highScore ) {
            highScore = score;
          }
        }
      }

      if ( shouldUpdateColor && player.velocity < 0 ) {
        player.color( newColorIndex );
        shouldUpdateColor = false;
      }
    }

    var diamondTime = game.t / 1000;
    diamondCenter.position.y = diamondCenterY + 0.2 * Math.cos( diamondTime );
    diamondLeft.position.y = diamondLeftY + 0.1 * Math.cos( 0.8 * diamondTime + 1 );
    diamondRight.position.y = diamondRightY + 0.2 * Math.cos( 0.4 * diamondTime );

    Audio.update( dt );

    renderScore();
    renderLives( lives );

    if ( lives <= 0 ) {
      end();
    }
  };
}

function createButton( el, id, text, action ) {
  var button = create( 'button' );
  button.id = id;
  textContent( button, text );
  on( button, 'click', action );
  prepend( el, button );
  return button;
}

// Create menu.
var menu = create();
menu.id = 'm';
addClass( menu, 'c' );
append( document.body, menu );

// Score elements.
var scoreEl = create();
scoreEl.id = 's';
append( container, scoreEl );

var highScoreEl = create();
highScoreEl.id = 'hs';
append( container, highScoreEl );

function renderScore() {
  textContent( scoreEl, 'Score: ' + score );
  textContent( highScoreEl, 'High Score: ' + highScore );
}

function start() {
  play();

  if ( !isFirstPlay ) {
    reset();
    animate(function( t ) {
      var emissive = ( ( Math.floor( t * 16 ) % 2 ) < 1 ) ? 0 : 0.5;
      player.mesh.material.emissive.setRGB( emissive, emissive, emissive );
      player.mesh.material.opacity = Math.max( emissive + 0.5, 0.8 );
    }, 3, function startCollisions() {
      isCheckingCollisions = true;
      shouldUpdateColor = true;
    });
    return;
  }

  animate(function( t ) {
    t = _.smootherstep( t, 0, 1 );

    var camera = game.camera;
    camera.fov = _.lerp( cameraStartFOV, cameraEndFOV, t * t * t );
    camera.position.z = _.lerp( cameraStartZ, cameraEndZ, t );
    camera.updateProjectionMatrix();
  }, 1, function() {
    isFirstPlay = false;
    isCheckingCollisions = true;
    shouldUpdateColor = true;
  });
}

function isPlaying() {
  return isCheckingCollisions && game.running;
}

function play() {
  game.play();
  addClass( menu, 'h' );
}

function pause() {
  if ( game.running ) {
    game.pause();
    removeClass( menu, 'h' );

    if ( !isFirstPlay ) {
      textContent( playButton, 'Continue' );
      off( playButton, 'click', start );
      on( playButton, 'click', play );
    }
  }
}

function end() {
  game.pause();
  textContent( playButton, 'Restart' );
  off( playButton, 'click', play );
  on( playButton, 'click', start );
  removeClass( menu, 'h' );
  isCheckingCollisions = false;
}

var playButton = createButton( menu, 'p', 'Play', start );

reset();
game.play();

on( window, 'blur', pause );

on( window, 'resize', function() {
  game.setSize( window.innerWidth, window.innerHeight );
  game.draw();
});

on( document, 'keydown', function( event ) {
  keys[ event.keyCode ] = true;
});

on( document, 'keyup', function( event ) {
  keys[ event.keyCode ] = false;

  // Space. Resume.
  if ( event.keyCode === 32 && !isPlaying() ) {
    if ( isFirstPlay || !lives ) {
      start();
    } else {
      isCheckingCollisions = true;
      play();
    }
  }
});


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

<title>com.mxgraph.layout.hierarchical.model Class Hierarchy (JGraph X 3.3.1.1 API Specification)</title>
<meta name="date" content="2015-06-23">
<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

JGraph X 3.3.1.1

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.mxgraph.layout.hierarchical.model

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.util.AbstractCollection<E> (implements java.util.Collection<E>)

java.util.AbstractSet<E> (implements java.util.Set<E>)

java.util.HashSet<E> (implements java.lang.Cloneable, java.io.Serializable, java.util.Set<E>)

java.util.LinkedHashSet<E> (implements java.lang.Cloneable, java.io.Serializable, java.util.Set<E>)

com.mxgraph.layout.hierarchical.model.mxGraphHierarchyRank

com.mxgraph.layout.hierarchical.model.mxGraphAbstractHierarchyCell

com.mxgraph.layout.hierarchical.model.mxGraphHierarchyEdge

com.mxgraph.layout.hierarchical.model.mxGraphHierarchyNode

com.mxgraph.layout.hierarchical.model.mxGraphHierarchyModel

Interface Hierarchy

com.mxgraph.layout.hierarchical.model.mxGraphHierarchyModel.CellVisitor

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

JGraph X 3.3.1.1

Prev

Next

Frames

No Frames

All Classes

Copyright (c) 2010 Gaudenz Alder. All rights reserved.


text:
package org.jboss.pnc.common.json.moduleconfig;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import org.jboss.pnc.common.json.moduleconfig.helper.HttpDestinationConfig;
import org.jboss.pnc.common.monitor.PollingMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Configuration for DockerEnvironmentDriver
 *
 * @author Matej Lazar
 *
 */
@Getter
public class OpenshiftEnvironmentDriverModuleConfig extends EnvironmentDriverModuleConfigBase {

    private static final Logger log = LoggerFactory.getLogger(OpenshiftEnvironmentDriverModuleConfig.class);

    public static final String MODULE_NAME = "openshift-environment-driver";
    private static final int DEFAULT_BUILDER_POD_MEMORY = 4;
    private static final int DEFAULT_CREATION_POD_RETRY = 1;

    private String restEndpointUrl;
    private String buildAgentHost;
    private String buildAgentBindPath;
    private String executorThreadPoolSize;

    private String podNamespace;
    private String restAuthToken;
    private String containerPort;
    private boolean keepBuildAgentInstance;
    private boolean exposeBuildAgentOnPublicUrl;
    private final int builderPodMemory;

    /** How many retries to attempt to get all services fully up and running */
    private int creationPodRetry;
    /** Time how long to wait until all services are fully up and running (in seconds) */
    private int pollingMonitorTimeout;
    /** Interval to wait betweeen subsequent checks of the condition in the PollingMonitor (in seconds) */
    private int pollingMonitorCheckInterval;

    public OpenshiftEnvironmentDriverModuleConfig(
            @JsonProperty("restEndpointUrl") String restEndpointUrl,
            @JsonProperty("buildAgentHost") String buildAgentHost,
            @JsonProperty("imageId") String imageId,
            @JsonProperty("firewallAllowedDestinations") String firewallAllowedDestinations,
            @JsonProperty("allowedHttpOutgoingDestinations") List<HttpDestinationConfig> allowedHttpOutgoingDestinations,
            @JsonProperty("proxyServer") String proxyServer,
            @JsonProperty("proxyPort") String proxyPort,
            @JsonProperty("nonProxyHosts") String nonProxyHosts,
            @JsonProperty("podNamespace") String podNamespace,
            @JsonProperty("buildAgentBindPath") String buildAgentBindPath,
            @JsonProperty("executorThreadPoolSize") String executorThreadPoolSize,
            @JsonProperty("restAuthToken") String restAuthToken,
            @JsonProperty("containerPort") String containerPort,
            @JsonProperty("workingDirectory") String workingDirectory,
            @JsonProperty("disabled") Boolean disabled,
            @JsonProperty("keepBuildAgentInstance") Boolean keepBuildAgentInstance,
            @JsonProperty("exposeBuildAgentOnPublicUrl") Boolean exposeBuildAgentOnPublicUrl,
            @JsonProperty("creationPodRetry") String creationPodRetry,
            @JsonProperty("builderPodMemory") Integer builderPodMemory,
            @JsonProperty("pollingMonitorTimeout") String pollingMonitorTimeout,
            @JsonProperty("pollingMonitorCheckInterval") String pollingMonitorCheckInterval) {
        super(
                imageId,
                firewallAllowedDestinations,
                allowedHttpOutgoingDestinations,
                proxyServer,
                proxyPort,
                nonProxyHosts,
                workingDirectory,
                disabled);

        this.restEndpointUrl = restEndpointUrl;
        this.buildAgentHost = buildAgentHost;
        this.buildAgentBindPath = buildAgentBindPath;
        this.executorThreadPoolSize = executorThreadPoolSize;
        this.podNamespace = podNamespace;
        this.restAuthToken = restAuthToken;
        this.containerPort = containerPort;
        this.keepBuildAgentInstance = keepBuildAgentInstance != null ? keepBuildAgentInstance : false;
        this.exposeBuildAgentOnPublicUrl = exposeBuildAgentOnPublicUrl != null ? exposeBuildAgentOnPublicUrl : false;
        this.builderPodMemory = builderPodMemory == null ? DEFAULT_BUILDER_POD_MEMORY : builderPodMemory;

        this.creationPodRetry = DEFAULT_CREATION_POD_RETRY;
        if (creationPodRetry != null) {
            try {
                this.creationPodRetry = Integer.parseInt(creationPodRetry);
            } catch (NumberFormatException e) {
                log.error(
                        "Couldn't parse the value of creation pod retry from the configuration. Using default ({} retries)",
                        DEFAULT_CREATION_POD_RETRY);
            }
        }

        this.pollingMonitorTimeout = PollingMonitor.DEFAULT_TIMEOUT;
        if (pollingMonitorTimeout != null) {
            try {
                this.pollingMonitorTimeout = Integer.parseInt(pollingMonitorTimeout);
            } catch (NumberFormatException e) {
                log.error(
                        "Couldn't parse the value of polling monitor timeout. Using default ({} seconds)",
                        PollingMonitor.DEFAULT_TIMEOUT);
            }
        }

        this.pollingMonitorCheckInterval = PollingMonitor.DEFAULT_CHECK_INTERVAL;
        if (pollingMonitorCheckInterval != null) {
            try {
                this.pollingMonitorCheckInterval = Integer.parseInt(pollingMonitorCheckInterval);
            } catch (NumberFormatException e) {
                log.error(
                        "Couldn't parse the value of polling monitor check interval. Using default ({} seconds)",
                        PollingMonitor.DEFAULT_CHECK_INTERVAL);
            }
        }

        log.debug("Created new instance {}", toString());
    }

    public String getRestEndpointUrl() {
        return restEndpointUrl;
    }

    public String getBuildAgentHost() {
        return buildAgentHost;
    }

    public String getPncNamespace() {
        return podNamespace;
    }

    public String getRestAuthToken() {
        return restAuthToken;
    }

    public String getContainerPort() {
        return containerPort;
    }

    public String getBuildAgentBindPath() {
        return buildAgentBindPath;
    }

    public String getExecutorThreadPoolSize() {
        return executorThreadPoolSize;
    }

    public boolean getKeepBuildAgentInstance() {
        return keepBuildAgentInstance;
    }

    public boolean getExposeBuildAgentOnPublicUrl() {
        return exposeBuildAgentOnPublicUrl;
    }

    public int getCreationPodRetry() {
        return creationPodRetry;
    }

    public int getPollingMonitorTimeout() {
        return pollingMonitorTimeout;
    }

    public int getPollingMonitorCheckInterval() {
        return pollingMonitorCheckInterval;
    }

    @Override
    public String toString() {
        return "OpenshiftEnvironmentDriverModuleConfig{" + "restEndpointUrl='" + restEndpointUrl + '\'' + ", imageId='"
                + imageId + '\'' + ", firewallAllowedDestinations='" + firewallAllowedDestinations + '\''
                + ", allowedHttpOutgoingDestinations='" + allowedHttpOutgoingDestinations + '\'' + ", proxyServer='"
                + proxyServer + '\'' + ", proxyPort='" + proxyPort + '\'' + ", nonProxyHosts='" + nonProxyHosts + '\''
                + ", podNamespace='" + podNamespace + '\'' + ", buildAgentHost='" + buildAgentHost + '\''
                + ", buildAgentBindPath='" + buildAgentBindPath + '\'' + ", executorThreadPoolSize='"
                + executorThreadPoolSize + '\'' + ", restAuthToken= HIDDEN " + ", containerPort='" + containerPort
                + '\'' + ", disabled='" + disabled + '\'' + ", keepBuildAgentInstance='" + keepBuildAgentInstance + '\''
                + ", exposeBuildAgentOnPublicUrl='" + exposeBuildAgentOnPublicUrl + '\'' + ", creationPodRetry="
                + creationPodRetry + ", pollingMonitorTimeout=" + pollingMonitorTimeout
                + ", pollingMonitorCheckInterval=" + pollingMonitorCheckInterval + '}';
    }

}


text:
<?php

declare (strict_types=1);
namespace PHPStan\PhpDocParser\Ast\PhpDoc;

use PHPStan\PhpDocParser\Ast\NodeAttributes;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
class MethodTagValueNode implements \PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode
{
    use NodeAttributes;
    /** @var bool */
    public $isStatic;
    /** @var TypeNode|null */
    public $returnType;
    /** @var string */
    public $methodName;
    /** @var MethodTagValueParameterNode[] */
    public $parameters;
    /** @var string (may be empty) */
    public $description;
    public function __construct(bool $isStatic, ?\PHPStan\PhpDocParser\Ast\Type\TypeNode $returnType, string $methodName, array $parameters, string $description)
    {
        $this->isStatic = $isStatic;
        $this->returnType = $returnType;
        $this->methodName = $methodName;
        $this->parameters = $parameters;
        $this->description = $description;
    }
    public function __toString() : string
    {
        $static = $this->isStatic ? 'static ' : '';
        $returnType = $this->returnType !== null ? "{$this->returnType} " : '';
        $parameters = \implode(', ', $this->parameters);
        $description = $this->description !== '' ? " {$this->description}" : '';
        return "{$static}{$returnType}{$this->methodName}({$parameters}){$description}";
    }
}


text:
'use strict';

var path = require('path');
var fs = require('fs');

var gulp = require('gulp');
var mainBowerFiles = require('main-bower-files');

var uglify = require('gulp-uglify');
var concatSourcemaps = require('gulp-concat-sourcemap');
var concat = require('gulp-concat');
var gulpIf = require('gulp-if');

var sass = require('gulp-sass');
var postcss	= require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('autoprefixer');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');

var NODES_BOWER_PACKAGES = require('./bower_components/nodes-ui/bower.json');
var PROJECT_BOWER_PACKAGES = require('./bower.json');
var IGNORED_BOWER_PACKAGES = [
    "!**/bower_components/bootstrap/dist/js/bootstrap.js",
    "!**/bower_components/blueimp-tmpl/js/tmpl.js"
];

gulp.task('vendor-scripts', function() {

    var MERGED_PKGS = PROJECT_BOWER_PACKAGES;

    var jsFileName = 'vendor.js';

    for(var pkg in NODES_BOWER_PACKAGES.dependencies) {
        if(!PROJECT_BOWER_PACKAGES.dependencies.hasOwnProperty(pkg)) {
            MERGED_PKGS.dependencies[pkg] = NODES_BOWER_PACKAGES.dependencies[pkg];
        }
    }

    try {
        fs.writeFileSync('bower.json', JSON.stringify(MERGED_PKGS, null, '\t'));
    } catch(err) {
        return console.log('Error updating project bower.json file!', err);
    }

    var filterFiles = ['**/*.js', '!**/*.js.map'].concat(IGNORED_BOWER_PACKAGES);

    return gulp.src(mainBowerFiles({filter: filterFiles}))
        .pipe(concat(jsFileName, {sourcesContent: true}))
        .pipe(uglify()).on('error', console.error.bind(console))
        .pipe(gulp.dest('./Public/js'));

});

gulp.task('project-scripts', function() {
    var jsFileName = 'project.js';

    var jsSources = [
        './Resources/Assets/Js/**/*.js',
        '!./Resources/Assets/Js/Pages/**/*.js'
    ];

    return gulp.src(jsSources)
        .pipe(concat(jsFileName))
        .pipe(uglify()).on('error', console.error.bind(console))
        .pipe(gulp.dest('./Public/js'));

});

gulp.task('project-pages-scripts', function() {

    var jsSources = [
        './Resources/Assets/Js/Pages/**/*.js'
    ];

    return gulp.src(jsSources)
        .pipe(uglify()).on('error', console.error.bind(console))
        .pipe(gulp.dest('./Public/js'));
});

gulp.task('styles', function() {

    var scssSource = [
        './Resources/Assets/Scss/main.scss'
    ];

    return gulp.src(scssSource)
        .pipe(sourcemaps.init())
        .pipe(sass({
            outputStyle: 'compressed',
            includePaths: ['bower_components', 'node_modules']
        })).on('error', console.error.bind(console))
        .pipe(postcss([
            autoprefixer({
                browsers: ['last 2 versions', 'ie >= 10']
            })
        ]))
        .pipe(sourcemaps.write())
        .pipe(rename('styles.css'))
        .pipe(gulp.dest('./Public/css'));
});

gulp.task('watch', function() {
    gulp.watch('./bower_components/**/*.js', ['vendor-scripts']);
    gulp.watch([
        './Resources/Assets/Js/**/*.js',
        '!./Resources/Assets/Js/Pages/**/*.js'
    ], ['project-scripts']);
    gulp.watch('./Resources/Assets/Js/Pages/**/*.js', ['project-pages-scripts']);
    gulp.watch(['./bower_components/**/*.scss', './Resources/Assets/Scss/**/*.scss'], ['styles']);
});

// Convenience tasks
gulp.task('build-js', ['vendor-scripts', 'project-scripts', 'project-pages-scripts']);
gulp.task('build-css', ['styles']);
gulp.task('build', ['build-js', 'build-css']);

gulp.task('default', ['build', 'watch']);


text:
'''fit and predict with many models

INVOCATION
  python fit-predict.py {training_data} {neighborhood} {model} {prediction_month}

where
 training_data     in {train, all} specifies which data in Working/samples2 to use
 neighborhood      in {global, city_name} specifies whether to train a model on all cities or just the specified city
 model             in {en, gb, rf} specified which model to use
 prediction_month  like YYYYMM specfies the month for which all samples are predicted

EXAMPLES OF INVOCATIONS
 python fit-predict.py train-global en 200701   # fit on training data global en models and predict Jan 2007
 python fit-predict.py all-MALIBU gb 200903      # fit on train + test data using just MALIBU data

INPUTS
 WORKING/samples2/train.csv or
 WORKING/samples2/all.csv

OUTPUTS

  WORKING/fit-predict[-test]/{training-data}-{neighborhood}-{model}-{prediction_month}/feature_names.pickle
   A tuple with X feature names in order (use to decode the fitted_attributes)
  WORKING/fit-predict[-test]/{training-data}-{neighborhood}-{model}-{prediction_month}/transaction_ids.pickle
   A list of TransactionId(apn, date) of the query transactions
 WORKING/fit-predict[-test]/{training-data}-{neighborhood}-{model}-{prediction_month}/actuals.pickle
   A numpy 1D array with the actual prices, parallel to the transaction_ids

 WORKING/fit-predict[-test]/{training_data}-{neighborhood}-{model}-{prediction_month}/predictions-attributes.pickle
   A file with pickled tuples (hps_str, predictions: vector, fitted_attribues: dict) or
                              (hps_str, error: str)
   for transactions in the {prediction_month}
   where
     'fitted_attributes': dict of fitted attributes
         for en: 'coef_', 'interecept_'
         for gb: 'feature_importances_'
      A string represents that an exception occured. It is the text of the exception message.
'''

from __future__ import division

import argparse
import cPickle as pickle
import datetime
import gc
import os
import pandas as pd
import pdb
from pprint import pprint
import random
import sklearn
import sklearn.ensemble
import sklearn.linear_model
import sys
import time

import arg_type
from Bunch import Bunch
import dirutility
from Features import Features
import HPs
import layout_transactions
from Logger import Logger
from lower_priority import lower_priority
from Month import Month
from Path import Path
from Timer import Timer
from TransactionId import TransactionId

def make_control(argv):
    'return a Bunch'

    print argv
    parser = argparse.ArgumentParser()
    parser.add_argument('invocation')
    parser.add_argument('training_data', choices=arg_type.training_data_choices)
    parser.add_argument('neighborhood', type=arg_type.neighborhood)
    parser.add_argument('model', choices=arg_type.model_choices)
    parser.add_argument('prediction_month', type=arg_type.month)
    parser.add_argument('--test', action='store_true')
    parser.add_argument('--trace', action='store_true')
    parser.add_argument('--dry', action='store_true')     # don't write output
    arg = parser.parse_args(argv)
    arg.me = arg.invocation.split('.')[0] + '-v2'

    if arg.trace:
        pdb.set_trace()

    random_seed = 123
    random.seed(random_seed)

    dir_working = Path().dir_working()
    fit_dir = (
        os.path.join(dir_working, arg.me + '-test') if arg.test else
        os.path.join(dir_working, arg.me)
    )
    result_dir = '%s-%s-%s-%s' % (arg.training_data, arg.neighborhood, arg.model, arg.prediction_month)
    path_out_dir = os.path.join(fit_dir, result_dir, '')
    dirutility.assure_exists(path_out_dir)

    return Bunch(
        arg=arg,
        path_in_query_samples=os.path.join(dir_working, 'samples2', 'all.csv'),
        path_in_training_samples=os.path.join(dir_working, 'samples2', arg.training_data + '.csv'),
        path_out_actuals=os.path.join(path_out_dir, 'actuals.pickle'),
        path_out_transaction_ids=os.path.join(path_out_dir, 'transaction_ids.pickle'),
        path_out_predictions_attributes=os.path.join(path_out_dir, "predictions-attributes.pickle"),
        path_out_dir=path_out_dir,
        path_out_feature_names=os.path.join(path_out_dir, 'feature_names.pickle'),
        path_out_log=os.path.join(path_out_dir, '0log.txt'),
        random_seed=random_seed,
        timer=Timer(),
    )

class FittingError(Exception):
    def __init__(self, message):
        super(FittingError, self).__init__(message)

def select_in_time_period(df, last_month_str, n_months_back):
    'return subset of DataFrame df that are in the time period'
    first_date_float = float(Month(last_month_str).decrement(n_months_back).as_int() * 100 + 1)
    next_month = Month(last_month_str).increment()
    last_date = datetime.date(next_month.year, next_month.month, 1) - datetime.timedelta(1)
    last_date_float = last_date.year * 10000.0 + last_date.month * 100.0 + last_date.day

    sale_date_column = layout_transactions.sale_date
    sale_dates_float = df[sale_date_column]  # type is float
    assert isinstance(sale_dates_float.iloc[0], float)

    mask1 = sale_dates_float >= first_date_float
    mask2 = sale_dates_float <= last_date_float
    mask_in_range = mask1 & mask2
    df_in_range = df.loc[mask_in_range]
    return df_in_range

def select_in_city(df, city):
    'return subset of DataFrame df that are in the city'
    pdb.set_trace()
    cities = df[layout_transactions.city]
    mask = cities == city
    df_in_city = df.loc[mask]
    return df_in_city

def select_in_time_period_and_in_city(df, last_month, n_months_back, neighborhood):
    'return new df with the specified training data'
    verbose = False
    in_time_period = select_in_time_period(
        df.copy(),
        last_month,
        n_months_back,
    )
    in_neighborhood = (
        in_time_period if neighborhood == 'global' else
        select_in_city(in_time_period, neighborhood)
    )
    if verbose:
        print 'neighborhood %s: %d in time period, %d also in neighborhood' % (
            'all' if neighborhood is None else neighborhood,
            len(in_time_period),
            len(in_neighborhood),
        )
    return in_neighborhood

def fit_en(X, y, hps, random_seed):
    'return fitted ElastNet model'
    assert len(hps) == 5
    model = sklearn.linear_model.ElasticNet(
        alpha=hps['alpha'],
        l1_ratio=hps['l1_ratio'],
        random_state=random_seed,
        # all these parameters are at the default value format skikit-learn version 0.18.1
        fit_intercept=True,
        normalize=False,
        max_iter=1000,
        copy_X=False,
        tol=0.0001,
        warm_start=False,
        selection='cyclic',
    )
    fitted = model.fit(X, y)
    return fitted

def fit_gb(X, y, hps, random_seed):
    'return fitted GradientBoostingRegressor model'
    assert len(hps) == 7
    model = sklearn.ensemble.GradientBoostingRegressor(
        learning_rate=hps['learning_rate'],
        n_estimators=hps['n_estimators'],
        max_depth=hps['max_depth'],
        max_features=hps['max_features'],
        random_state=random_seed,
        # all these parameters are at the default value for skikit-learn version 0.18.1
        loss='ls',
        criterion='friedman_mse',
        min_samples_split=2,
        min_samples_leaf=1,
        min_weight_fraction_leaf=0,
        subsample=1.0,
        max_leaf_nodes=None,
        min_impurity_split=1e-7,
        alpha=0.9,
        init=None,
        verbose=0,
        presort='auto',
    )
    fitted = model.fit(X, y)
    return fitted

def fit_rf(X, y, hps, random_seed):
    'return fitted RandomForestRegressor model'
    assert len(hps) == 6
    model = sklearn.ensemble.RandomForestRegressor(
        n_estimators=hps['n_estimators'],
        max_features=hps['max_features'],
        max_depth=hps['max_depth'],
        random_state=random_seed,
        # all these parameters are at the default value for skikit-learn version 0.18.1
        criterion='mse',
        min_samples_split=2,
        min_samples_leaf=1,
        min_weight_fraction_leaf=0,
        max_leaf_nodes=None,
        min_impurity_split=1e-7,
        bootstrap=True,
        oob_score=False,
        n_jobs=1,
        verbose=0,
        warm_start=False,
    )
    fitted = model.fit(X, y)
    return fitted

def make_n_hps(model):
    'return number of hyperparameters'
    count = 0
    for hps in HPs.iter_hps_model(model):
        count += 1
    return count

def fit_and_predict(training_samples, query_samples, hps, control):
    'return (predictions, attributes, n_training_samples)'
    def X_y(df):
        return Features().extract_and_transform(df, hps['units_X'], hps['units_y'])

    relevant_training_samples = select_in_time_period_and_in_city(
        training_samples,
        Month(control.arg.prediction_month).decrement(1),
        hps['n_months_back'],
        control.arg.neighborhood,
    )
    if len(relevant_training_samples) == 0:
        message = 'no relevant samples hps:%s neighborhood: %s prediction_month %s' % (
            HPs.to_str(hps),
            control.arg.neighborhood,
            control.arg.prediction_month,
        )
        raise FittingError(message)

    X_train, y_train = X_y(relevant_training_samples)
    X_query, actuals = X_y(query_samples)

    fitter = (
        fit_en if control.arg.model == 'en' else
        fit_gb if control.arg.model == 'gb' else
        fit_rf
    )
    fitted = fitter(X_train, y_train, hps, control.random_seed)
    attributes = (
        {'coef_': fitted.coef_, 'intercept_': fitted.intercept_} if control.arg.model == 'en' else
        {'feature_importances_': fitted.feature_importances_}
    )
    predictions = fitted.predict(X_query)
    return predictions, attributes, len(relevant_training_samples)

def do_work(control):
    'write fitted models to file system'
    def make_transaction_ids(df):
        'return dates and apns for the query samples'
        result = []
        for index, row in df.iterrows():
            next = TransactionId(
                sale_date=row[layout_transactions.sale_date],
                apn=row[layout_transactions.apn],
            )
            result.append(next)
        return result

    def read_csv(path):
        df = pd.read_csv(
            path,
            nrows=100 if control.arg.test else None,
            usecols=None,  # TODO: change to columns we actually use
            low_memory=False
        )
        print 'read %d samples from file %s' % (len(df), path)
        return df

    def in_prediction_month(query_samples, prediction_YYYYMM):
        'return DataFrame of sample in the month we are predicting'
        def splitYYYYMMDD(dates):
            year_factor = 10000.0
            years = (dates / year_factor).astype('int64')
            month_factor = 100.0
            months = ((dates - years * year_factor) / month_factor).astype('int64')
            return years, months

        def splitYYYYMM(date_str):
            date = int(date_str)
            year_factor = 100.0
            year = int(date / year_factor)
            month = int(date - year * year_factor)
            return year, month

        sale_dates = query_samples[layout_transactions.sale_date]
        query_years, query_months = splitYYYYMMDD(sale_dates)
        prediction_year, prediction_month = splitYYYYMM(prediction_YYYYMM)
        mask_year = query_years == prediction_year
        mask_month = query_months == prediction_month
        mask = mask_year & mask_month
        result = query_samples.loc[mask]
        return result

    # reduce process priority, to try to keep the system responsive
    lower_priority()

    with open(control.path_out_feature_names, 'w') as f:
        feature_names = Features().ege_names('swpn')
        pickle.dump(feature_names, f)

    training_samples = read_csv(control.path_in_training_samples)

    query_samples_all = read_csv(control.path_in_query_samples)
    query_samples = in_prediction_month(query_samples_all, control.arg.prediction_month)
    print 'read %s query samples of which %d are in the prediction month %s' % (
        len(query_samples_all),
        len(query_samples),
        control.arg.prediction_month,
    )
    with open(control.path_out_transaction_ids, 'w') as f:
        transaction_ids = make_transaction_ids(query_samples)
        pickle.dump(transaction_ids, f)
    with open(control.path_out_actuals, 'w') as f:
        X, actuals = Features().extract_and_transform(query_samples, 'natural', 'natural')
        pickle.dump(actuals, f)

    count_fitted = 0
    n_hps = make_n_hps(control.arg.model)

    # determine hps we have already fitted and predicted
    already_seen = set()
    if os.path.exists(control.path_out_predictions_attributes):
        with open(control.path_out_predictions_attributes, 'r') as f:
            unpickler = pickle.Unpickler(f)
            try:
                while True:
                    hps_str, predictions, fitted_attributes = unpickler.load()
                    print 'existing', hps_str
                    already_seen.add(hps_str)
            except EOFError as e:
                pass
    print 'have already seen %d hps_str values' % len(already_seen)

    # fit and predict HPs that we have not already seen
    with open(control.path_out_predictions_attributes, 'w') as results_file:
        pickler = pickle.Pickler(results_file)
        for hps in HPs.iter_hps_model(control.arg.model):
            count_fitted += 1
            start_time = time.clock()  # wall clock time on Windows, processor time on Unix
            hps_str = HPs.to_str(hps)
            if hps_str in already_seen:
                print 'skipping already seen: %s' % hps_str
                continue
            try:
                predictions, fitted_attributes, n_training_samples = fit_and_predict(
                    training_samples,
                    query_samples,
                    hps, control,
                )
                pickler.dump((hps_str, predictions, fitted_attributes))
                pickler.clear_memo()  # don't build up a large data structure
                print 'fit-predict #%4d/%4d on:%6d in: %6.2f %s %s %s %s hps: %s ' % (
                    count_fitted,
                    n_hps,
                    n_training_samples,
                    time.clock() - start_time,
                    control.arg.training_data,
                    control.arg.neighborhood,
                    control.arg.model,
                    control.arg.prediction_month,
                    hps_str,
                )
            except Exception as e:
                print 'exception: %s' % e
                pdb.set_trace()
                pickler.dump((hps_str, e))

            # collect to get memory usage stable, so that we can run this program many time in parallel
            gc.collect()
            if control.arg.test and count_fitted == 5:
                print 'breaking because we are testing'
                break

def main(argv):
    control = make_control(argv)
    sys.stdout = Logger(control.path_out_log)  # now print statements also write to the log file
    print control
    lap = control.timer.lap

    do_work(control)

    lap('work completed')
    if control.arg.test:
        print 'DISCARD OUTPUT: test'
    print control
    print 'done'
    return

if __name__ == '__main__':
    if False:
        # avoid pyflakes warnings
        pdb.set_trace()
        pprint()

    main(sys.argv)