# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.

import re
import time

from cement.utils.misc import minimal_logger

from ..lib import elasticbeanstalk, iam, utils
from ..lib.aws import InvalidParameterValueError
from ..core import io
from ..objects.exceptions import TimeoutError, AlreadyExistsError, \
    NotAuthorizedError, NotSupportedError
from ..resources.strings import strings, responses, prompts
from . import commonops

LOG = minimal_logger(__name__)
DEFAULT_ROLE_NAME = 'aws-elasticbeanstalk-ec2-role'
DEFAULT_SERVICE_ROLE_NAME = 'aws-elasticbeanstalk-service-role'

def make_new_env(env_request, branch_default=False,
                 nohang=False, interactive=True, timeout=None):
    resolve_roles(env_request, interactive)

    # deploy code
    if not env_request.sample_application and not env_request.version_label:
        io.log_info('Creating new application version using project code')
        env_request.version_label = \
            commonops.create_app_version(env_request.app_name)

    if env_request.version_label is None or env_request.sample_application:
        env_request.version_label = \
            commonops.create_dummy_app_version(env_request.app_name)

    # Create env
    if env_request.key_name:
        commonops.upload_keypair_if_needed(env_request.key_name)

    io.log_info('Creating new environment')
    result, request_id = create_env(env_request,
                                    interactive=interactive)

    env_name = result.name  # get the (possibly) updated name

    # Edit configurations
    ## Get default environment
    default_env = commonops.get_current_branch_environment()
    ## Save env as branch default if needed
    if not default_env or branch_default:
        commonops.set_environment_for_current_branch(env_name)

    # Print status of env
    commonops.print_env_details(result, health=False)

    if nohang:
        return

    io.echo('Printing Status:')
    try:
        commonops.wait_for_success_events(request_id,
                                          timeout_in_minutes=timeout)
    except TimeoutError:
        io.log_error(strings['timeout.error'])

def create_env(env_request, interactive=True):
    # If a template is being used, we want to try using just the template
    if env_request.template_name:
        platform = env_request.platform
        env_request.platform = None
    else:
        platform = None
    while True:
        try:
            return elasticbeanstalk.create_environment(env_request)

        except InvalidParameterValueError as e:
            if e.message == responses['app.notexists'].replace(
                        '{app-name}', '\'' + env_request.app_name + '\''):
                # App doesnt exist, must be a new region.
                ## Lets create the app in the region
                commonops.create_app(env_request.app_name)
            elif e.message == responses['create.noplatform']:
                if platform:
                    env_request.platform = platform
                else:
                    raise
            elif interactive:
                LOG.debug('creating env returned error: ' + e.message)
                if re.match(responses['env.cnamenotavailable'], e.message):
                    io.echo(prompts['cname.unavailable'])
                    cname = io.prompt_for_cname()
                elif re.match(responses['env.nameexists'], e.message):
                    io.echo(strings['env.exists'])
                    current_environments = commonops.get_all_env_names()
                    unique_name = utils.get_unique_name(env_request.env_name,
                                                        current_environments)
                    env_request.env_name = io.prompt_for_environment_name(
                        default_name=unique_name)
                elif e.message == responses['app.notexists'].replace(
                            '{app-name}', '\'' + env_request.app_name + '\''):
                    # App doesnt exist, must be a new region.
                    ## Lets create the app in the region
                    commonops.create_app(env_request.app_name)
                else:
                    raise
            else:
                raise

        # Try again with new values

def get_default_profile():
    """  Get the default elasticbeanstalk IAM profile,
            Create it if it doesn't exist """

    # get list of profiles
    try:
        profile = DEFAULT_ROLE_NAME
        try:
            iam.create_instance_profile(profile)
            io.log_info('Created default instance profile.')
            role = get_default_role()
            iam.add_role_to_profile(profile, role)
        except AlreadyExistsError:
            pass
    except NotAuthorizedError:
        # Not a root account. Just assume role exists
        io.log_info('No IAM privileges: assuming default '
                    'instance profile exists.')
        return DEFAULT_ROLE_NAME

    return profile

def get_default_role():
    role = DEFAULT_ROLE_NAME
    document = '{"Version": "2008-10-17","Statement": [{"Action":' \
               ' "sts:AssumeRole","Principal": {"Service": ' \
               '"ec2.amazonaws.com"},"Effect": "Allow","Sid": ""}]}'
    try:
        iam.create_role(role, document)
    except AlreadyExistsError:
        pass
    return role

def get_service_role():
    try:
        roles = iam.get_role_names()
        if DEFAULT_SERVICE_ROLE_NAME not in roles:
            return None
    except NotAuthorizedError:
        # No permissions to list roles
        # Assume role exists, we will handle error at a deeper level
        pass

    return DEFAULT_SERVICE_ROLE_NAME

def create_default_service_role():
    """
    Create the default service role
    """
    io.log_info('Creating service role {} with default permissions.'
                .format(DEFAULT_SERVICE_ROLE_NAME))
    trust_document = _get_default_service_trust_document()
    json_policy = _get_default_service_role_policy()
    role_name = DEFAULT_SERVICE_ROLE_NAME
    policy_name = 'awsebcli_aws-elasticbeanstalk-service-role_{}'\
        .format(int(time.time()))
    try:
        iam.create_role_with_policy(role_name, trust_document,
                                    policy_name, json_policy)
    except NotAuthorizedError as e:
        # NO permissions to create or do something
        raise NotAuthorizedError(prompts['create.servicerole.nopermissions']
                                 .format(DEFAULT_SERVICE_ROLE_NAME, e))

    return DEFAULT_SERVICE_ROLE_NAME

def resolve_roles(env_request, interactive):
    """
    Resolves instance-profile and service-role
    :param env_request: environment request
    :param interactive: boolean
    """
    LOG.debug('Resolving roles')

    if env_request.instance_profile is None and \
            env_request.template_name is None:
        # Service supports no profile, however it is not good/recommended
        # Get the eb default profile
        env_request.instance_profile = get_default_profile()

    if (env_request.platform.has_healthd_support() and  # HealthD enabled
            (env_request.service_role is None) and
            (env_request.template_name is None)):
        role = get_service_role()
        if role is None:
            if interactive:
                io.echo()
                io.echo(prompts['create.servicerole.info'])
                input = io.get_input(prompts['create.servicerole.view'],
                                     default='')

                if input.strip('"').lower() == 'view':
                    io.echo(_get_default_service_role_policy())
                    io.get_input(prompts['general.pressenter'])

                role = create_default_service_role()
            else:
                raise NotSupportedError(prompts['create.servicerole.required'])

        env_request.service_role = role

def _get_default_service_trust_document():
    """
    Just a string representing the service role policy.
    Includes newlines for pretty printing :)
    """
    return \
'''{
    "Version": "2012-10-17",
    "Statement": [{
        "Sid": "",
        "Effect": "Allow",
        "Principal": {
            "Service": "elasticbeanstalk.amazonaws.com"
        },
        "Action": "sts:AssumeRole",
        "Condition": {
            "StringEquals": {
                "sts:ExternalId": "elasticbeanstalk"
            }
        }
    }]
}'''

def _get_default_service_role_policy():
    """
    Just a string representing the service role policy.
    Includes newlines for pretty printing :)
    """
    return \
'''{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Action": [
            "elasticloadbalancing:DescribeInstanceHealth",
            "ec2:DescribeInstances",
            "ec2:DescribeInstanceStatus",
            "ec2:GetConsoleOutput",
            "ec2:AssociateAddress",
            "ec2:DescribeAddresses",
            "ec2:DescribeSecurityGroups",
            "sqs:GetQueueAttributes",
            "sqs:GetQueueUrl",
            "autoscaling:DescribeAutoScalingGroups",
            "autoscaling:DescribeAutoScalingInstances",
            "autoscaling:DescribeScalingActivities",
            "autoscaling:DescribeNotificationConfigurations"
        ],
        "Resource": ["*"]
    }]
}'''


#!/usr/bin/env python
# Copyright 2016 The Dart project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# This script downloads the latest dev SDK from
# http://gsdview.appspot.com/dart-archive/channels/dev/raw/latest/sdk/
# into tools/sdks/. It is intended to be invoked from Jiri hooks in
# a Fuchsia checkout.

import os
import sys
import zipfile
import urllib
import utils

HOST_OS = utils.GuessOS()
HOST_ARCH = utils.GuessArchitecture()
SCRIPT_DIR = os.path.dirname(sys.argv[0])
DART_ROOT = os.path.realpath(os.path.join(SCRIPT_DIR, '..'))

DEFAULT_DART_VERSION = 'latest'
BASE_URL = 'http://gsdview.appspot.com/dart-archive/channels/dev/raw/%s/sdk/%s'

def host_os_for_sdk(host_os):
    if host_os.startswith('macos'):
        return 'mac'
    if host_os.startswith('win'):
        return 'windows'
    return host_os

# Python's zipfile doesn't preserve file permissions during extraction, so we
# have to do it manually.
def extract_file(zf, info, extract_dir):
    try:
        zf.extract(info.filename, path=extract_dir)
        out_path = os.path.join(extract_dir, info.filename)
        perm = info.external_attr >> 16L
        os.chmod(out_path, perm)
    except IOError as err:
        if 'dart-sdk/bin/dart' in err.filename:
            print(
                'Failed to extract the new Dart SDK dart binary. ' +
                'Kill stale instances (like the analyzer) and try the update again'
            )
            return False
        raise
    return True

def main(argv):
    host_os = host_os_for_sdk(HOST_OS)
    zip_file = ('dartsdk-%s-x64-release.zip' % HOST_OS)
    sha_file = zip_file + '.sha256sum'
    sdk_path = os.path.join(DART_ROOT, 'tools', 'sdks')
    local_sha_path = os.path.join(sdk_path, sha_file)
    remote_sha_path = os.path.join(sdk_path, sha_file + '.remote')
    zip_path = os.path.join(sdk_path, zip_file)

    sdk_version = DEFAULT_DART_VERSION
    sha_url = (BASE_URL % (sdk_version, sha_file))
    zip_url = (BASE_URL % (sdk_version, zip_file))

    local_sha = ''
    if os.path.isfile(local_sha_path):
        with open(local_sha_path, 'r') as fp:
            local_sha = fp.read()

    remote_sha = ''
    urllib.urlretrieve(sha_url, remote_sha_path)
    with open(remote_sha_path, 'r') as fp:
        remote_sha = fp.read()
    os.remove(remote_sha_path)

    if local_sha == '' or local_sha != remote_sha:
        print 'Downloading prebuilt Dart SDK from: ' + zip_url
        urllib.urlretrieve(zip_url, zip_path)
        with zipfile.ZipFile(zip_path, 'r') as zf:
            for info in zf.infolist():
                if not extract_file(zf, info, sdk_path):
                    return -1
        with open(local_sha_path, 'w') as fp:
            fp.write(remote_sha)
    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv))


from setuptools import setup

setup(
    # Packaging meta-data
    name='Vimcryption',
    version='0.1',
    description='Test package for vimcryption VIM plugin.',
    author='Tom Manner, Miguel Nistal',
    author_email='tom.s.manner@gmail.com, nistam328@gmail.com',
    url='https://www.github.com/tsmanner/vimcryption',
    # Travis Unit-Test Installation
    install_requires=[
        'anybadge==0.1.0.dev2',
        'codecov',
        'coverage>=4.5',
        'coverage-badge',
        'nose2',
        'nose2[coverage_plugin]>=0.6.5',
        'numpy',
        'pylint',
    ],
    packages=[
        'encryptionengine',
    ],
)


#!/usr/bin/env python
# coding: utf-8

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root for full license information.

import droid_speech
#import intent_sample
#import translation_sample
#import speech_synthesis_sample

from collections import OrderedDict
import platform

#eofkey = 'Ctrl-Z' if "Windows" == platform.system() else 'Ctrl-D'

droidspeechfunctions = OrderedDict([
    (droid_speech, [
        droid_speech.speech_recognize_once_from_mic,
        droid_speech.speech_recognize_once_from_file,
        droid_speech.speech_recognize_once_compressed_input,
        droid_speech.speech_recognize_once_from_file_with_customized_model,
        droid_speech.speech_recognize_once_from_file_with_custom_endpoint_parameters,
        droid_speech.speech_recognize_async_from_file,
        droid_speech.speech_recognize_continuous_from_file,
        droid_speech.speech_recognition_with_pull_stream,
        droid_speech.speech_recognition_with_push_stream,
        droid_speech.speech_recognize_keyword_from_microphone,
        droid_speech.speech_recognize_keyword_locally_from_microphone,
        droid_speech.pronunciation_assessment_from_microphone,
    ])
])

def select():
    modules = list(droidspeechfunctions.keys())

    try:
        selected_module = modules[0]
    except EOFError:
        raise
    except Exception as e:
        print(e)
        return

    try:
        selected_function = droidspeechfunctions[selected_module][10]
    except EOFError:
        raise
    except Exception as e:
        print(e)
        return

    try:
        selected_function()
    except Exception as e:
        print('Error running droid funtion: {}'.format(e))

    print()

while True:
    try:
        select()
    except EOFError:
        break


import itertools
from collections import OrderedDict

from rest_framework import filters, exceptions

from .mixin import ViewSetMixin

def get_sort_order(request, param):
    args = request.query_params.getlist(param)
    fields = itertools.chain(*(arg.split(',') for arg in args))
    order = tuple(field.strip() for field in fields if field)
    return order

class OrderingFilter(filters.OrderingFilter):

    @staticmethod
    def get_translated_sort_order(fields, field_map):
        return tuple(field_map.get(field, field) for field in fields)

    @staticmethod
    def get_reverse_translated_sort_order(fields, field_map):
        sort_field_reverse_map = {value: key for (key, value) in field_map.items()}
        return tuple(sort_field_reverse_map.get(field, field) for field in fields)

    @staticmethod
    def get_consistent_sort_order(fields):
        return fields + type(fields)(('pk',))

    def get_ordering(self, request, queryset, view):
        fields = get_sort_order(request, self.ordering_param)

        if fields:
            field_map = getattr(view, 'sort_field_map', {})

            fields = self.get_translated_sort_order(fields, field_map)
            ordering = self.remove_invalid_fields(queryset, fields, view, request)

            if len(ordering) != len(fields):
                ext_fields = self.get_reverse_translated_sort_order(fields, field_map)
                ext_ordering = self.get_reverse_translated_sort_order(ordering, field_map)

                errors = {}

                for ext_field in ext_fields:
                    if ext_field not in ext_ordering:
                        errors[ext_field] = 'invalid field'

                raise exceptions.ValidationError(errors)

            ordering = self.get_consistent_sort_order(ordering)

        else:
            ordering = self.get_default_ordering(view)

        consistent_sort = getattr(view, 'consistent_sort', True)
        if consistent_sort:
            ordering = self.get_consistent_sort_order(ordering)

        return ordering

class SortedModelMixin(ViewSetMixin):
    ordering = ()

    sort_field_map = {}
    consistent_sort = True

    def list(self, request, *args, **kwargs):
        sort = get_sort_order(request, OrderingFilter.ordering_param) or self.ordering

        context = OrderedDict(sort=','.join(sort))

        return self.decorated_list(SortedModelMixin, context, request, *args, **kwargs)


# Distributed under the MIT License.
# See LICENSE.txt for details.

import numpy as np
from numpy import sqrt, exp
from scipy.optimize import newton

# Isotropic Schwarzschild coordinates

def conformal_metric_isotropic(x, mass):
    return np.identity(3)

def inv_conformal_metric_isotropic(x, mass):
    return np.identity(3)

def deriv_conformal_metric_isotropic(x, mass):
    return np.zeros((3, 3, 3))

def extrinsic_curvature_trace_isotropic(x, mass):
    return 0.

def extrinsic_curvature_trace_gradient_isotropic(x, mass):
    return np.zeros(3)

def conformal_factor_isotropic(x, mass):
    r = np.linalg.norm(x)
    return 1. + 0.5 * mass / r

def conformal_factor_gradient_isotropic(x, mass):
    r = np.linalg.norm(x)
    return -0.5 * mass * x / r**3

def lapse_times_conformal_factor_isotropic(x, mass):
    r = np.linalg.norm(x)
    return 1. - 0.5 * mass / r

def lapse_times_conformal_factor_gradient_isotropic(x, mass):
    r = np.linalg.norm(x)
    return 0.5 * mass * x / r**3

def lapse_isotropic(x, mass):
    return (lapse_times_conformal_factor_isotropic(x, mass) /
            conformal_factor_isotropic(x, mass))

def shift_background(x, mass):
    return np.zeros(3)

def longitudinal_shift_background_minus_dt_conformal_metric(x, mass):
    return np.zeros((3, 3))

def shift_isotropic(x, mass):
    return np.zeros(3)

def shift_strain_isotropic(x, mass):
    return np.zeros((3, 3))

def longitudinal_shift_isotropic(x, mass):
    return np.zeros((3, 3))

def shift_dot_extrinsic_curvature_trace_gradient_isotropic(x, mass):
    return 0.

def longitudinal_shift_minus_dt_conformal_metric_square_isotropic(x, mass):
    return 0.

def longitudinal_shift_minus_dt_conformal_metric_over_lapse_square_isotropic(
    x, mass):
    return 0.

# Matter sources

def energy_density(x, mass):
    return 0.

def stress_trace(x, mass):
    return 0.

def momentum_density(x, mass):
    return np.zeros(3)

# Fixed sources

def conformal_factor_fixed_source(x, mass):
    return 0.

def lapse_times_conformal_factor_fixed_source(x, mass):
    return 0.

def shift_fixed_source(x, mass):
    return np.zeros(3)


# -*- coding: utf-8 -*-
#
# Copyright 2015 Red Hat, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
"""
Benchmark Memory functions.
"""

import re
import subprocess
import sys

import six

from hardware.benchmark import utils

def get_available_memory():
    """Return the total amount of available memory, in bytes."""
    with open('/proc/meminfo', 'r') as meminfo:
        for line in meminfo:
            if line.startswith('MemFree:'):
                return int(line.split()[1]) * 1024
    return -1

def check_mem_size(block_size, cpu_count):
    """Check if a test can run with a given block size and cpu count."""
    dsplit = re.compile(r'\d+')
    ssplit = re.compile(r'[A-Z]+')
    unit = ssplit.findall(block_size)
    unit_in_bytes = 1
    if unit[0] == 'K':
        unit_in_bytes = 1024
    elif unit[0] == 'M':
        unit_in_bytes = 1024 * 1024
    elif unit[0] == 'G':
        unit_in_bytes = 1024 * 1024 * 1024

    size_in_bytes = (unit_in_bytes * int(dsplit.findall(block_size)[0])
                     * cpu_count)
    if size_in_bytes > get_available_memory():
        return False

    return True

def run_sysbench_memory_threaded(hw_lst, max_time, block_size, cpu_count,
                                 processor_num=None):
    """Running memtest on a processor."""
    check_mem = check_mem_size(block_size, cpu_count)
    taskset = ''
    if processor_num is not None:
        if check_mem is False:
            msg = ("Avoid Benchmarking memory @%s "
                   "from CPU %d, not enough memory\n")
            sys.stderr.write(msg % (block_size, processor_num))
            return

        sys.stderr.write('Benchmarking memory @%s from CPU %d'
                         ' for %d seconds (%d threads)\n' %
                         (block_size, processor_num, max_time, cpu_count))
        taskset = 'taskset %s' % hex(1 << processor_num)
    else:
        if check_mem is False:
            msg = ("Avoid Benchmarking memory @%s "
                   "from all CPUs, not enough memory\n")
            sys.stderr.write(msg % block_size)
            return
        sys.stderr.write('Benchmarking memory @%s from all CPUs '
                         'for %d seconds (%d threads)\n'
                         % (block_size, max_time, cpu_count))

    _cmd = ('%s sysbench --max-time=%d --max-requests=100000000 '
            '--num-threads=%d --test=memory --memory-block-size=%s run')
    sysbench_cmd = subprocess.Popen(_cmd % (taskset, max_time,
                                            cpu_count, block_size),
                                    shell=True, stdout=subprocess.PIPE)

    for line in sysbench_cmd.stdout:
        if isinstance(line, six.binary_type):
            line = line.decode()
        if "transferred" in line:
            _, right = line.rstrip('\n').replace(' ', '').split('(')
            perf, _ = right.split('.')
            if processor_num is not None:
                hw_lst.append(('cpu',
                               'logical_%d' % processor_num,
                               'bandwidth_%s' % block_size,
                               perf))
            else:
                hw_lst.append(('cpu', 'logical',
                               'threaded_bandwidth_%s' % block_size,
                               perf))

def run_sysbench_memory_forked(hw_lst, max_time, block_size, cpu_count):
    """Running forked memtest on a processor."""
    if check_mem_size(block_size, cpu_count) is False:
        cmd = ('Avoid benchmarking memory @%s from all'
               ' CPUs (%d forked processes), not enough memory\n')
        sys.stderr.write(cmd % (block_size, cpu_count))
        return
    sys.stderr.write('Benchmarking memory @%s from all CPUs'
                     ' for %d seconds (%d forked processes)\n'
                     % (block_size, max_time, cpu_count))
    sysbench_cmd = '('
    for _ in range(cpu_count):
        _cmd = ('sysbench --max-time=%d --max-requests=100000000 '
                '--num-threads=1 --test=memory --memory-block-size=%s run &')
        sysbench_cmd += _cmd % (max_time, block_size)

    sysbench_cmd.rstrip('&')
    sysbench_cmd += ')'

    global_perf = 0
    process = subprocess.Popen(
        sysbench_cmd, shell=True, stdout=subprocess.PIPE)
    for line in process.stdout:
        if isinstance(line, six.binary_type):
            line = line.decode()
        if "transferred" in line:
            _, right = line.rstrip('\n').replace(' ', '').split('(')
            perf, _ = right.split('.')
            global_perf += int(perf)

    hw_lst.append(('cpu', 'logical', 'forked_bandwidth_%s' %
                   (block_size), str(global_perf)))

def mem_perf(hw_lst, max_time=5):
    """Report the memory performance."""
    all_cpu_testing_time = 5
    block_size_list = ['1K', '4K', '1M', '16M', '128M', '1G', '2G']
    logical = utils.get_value(hw_lst, 'cpu', 'logical', 'number')
    physical = utils.get_value(hw_lst, 'cpu', 'physical', 'number')
    if physical:
        eta = int(physical) * len(block_size_list) * max_time
        eta += 2 * (all_cpu_testing_time * len(block_size_list))
        sys.stderr.write('Memory Performance: %d logical CPU'
                         ' to test (ETA: %d seconds)\n'
                         % (int(physical), int(eta)))
        for cpu_nb in utils.get_one_cpu_per_socket(hw_lst):
            for block_size in block_size_list:
                run_sysbench_memory_threaded(hw_lst, max_time,
                                             block_size, 1, cpu_nb)

        # There is not need to test fork vs thread
        #  if only a single logical cpu is present
        if int(logical) > 1:
            for block_size in block_size_list:
                run_sysbench_memory_threaded(hw_lst, all_cpu_testing_time,
                                             block_size, int(logical))

            for block_size in block_size_list:
                run_sysbench_memory_forked(hw_lst, all_cpu_testing_time,
                                           block_size, int(logical))


# -*- coding: utf-8 -*-

"""
********************************
reslib.processing.loops
********************************

This module provides convenience functions for looping over data, typically a DataFrame (or reslib.data.Table), and automating things like progress reporting (via tqdm or status files) or parallelization.

:copyright: (c) 2019 by Maclean Gaulin.
:license: MIT, see LICENSE for more details.
"""


# uncompyle6 version 3.3.1
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06)
# [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
# Embedded file name: ../../shared/problems/CR/problem1068_CR.py
# Compiled at: 2019-03-13 18:01:49
# Size of source mod 2**32: 1148 bytes
__author__ = 'patras'
from domain_chargeableRobot import *
from timer import DURATION
from state import state
DURATION.TIME = {'put':2,
 'take':2,
 'perceive':2,
 'charge':2,
 'move':2,
 'moveToEmergency':2,
 'moveCharger':2,
 'addressEmergency':2,
 'wait':2}
DURATION.COUNTER = {'put':2,
 'take':2,
 'perceive':2,
 'charge':2,
 'move':2,
 'moveToEmergency':2,
 'moveCharger':2,
 'addressEmergency':2,
 'wait':2}
rv.LOCATIONS = [
 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
rv.EDGES = {1:[2],  2:[1, 3],  3:[2, 4],  4:[5, 3, 6, 7],  5:[4, 9],  6:[4, 10],  7:[4, 8],  8:[7],  9:[5],  10:[6]}
rv.OBJECTS = ['o1']
rv.ROBOTS = [
 'r1', 'r2']

def ResetState():
    state.loc = {'r1':1,
     'r2':1}
    state.charge = {'r1':2,  'r2':3}
    state.load = {'r1':NIL,  'r2':NIL}
    state.pos = {'c1':'r2',  'o1':5}
    state.containers = {1:[],  2:[],  3:[],  4:[],  5:['o1'],  6:[],  7:[],  8:[],  9:[],  10:[]}
    state.emergencyHandling = {'r1':False,  'r2':False}
    state.view = {}
    for l in rv.LOCATIONS:
        state.view[l] = False

tasks = {5: [['fetch', 'r1', 'o1']]}
eventsEnv = {}
# okay decompiling __pycache__/problem1068_CR.cpython-36.pyc