text:
import os
import sys

import mock
from osc_lib.tests import utils as osc_lib_test_utils
from oslo_utils import importutils
import wrapt

from openstackclient import shell

DEFAULT_AUTH_URL = "http://127.0.0.1:5000/v2.0/"
DEFAULT_PROJECT_ID = "xxxx-yyyy-zzzz"
DEFAULT_PROJECT_NAME = "project"
DEFAULT_DOMAIN_ID = "aaaa-bbbb-cccc"
DEFAULT_DOMAIN_NAME = "default"
DEFAULT_USER_DOMAIN_ID = "aaaa-bbbb-cccc"
DEFAULT_USER_DOMAIN_NAME = "domain"
DEFAULT_PROJECT_DOMAIN_ID = "aaaa-bbbb-cccc"
DEFAULT_PROJECT_DOMAIN_NAME = "domain"
DEFAULT_USERNAME = "username"
DEFAULT_PASSWORD = "password"

DEFAULT_CLOUD = "altocumulus"
DEFAULT_REGION_NAME = "ZZ9_Plural_Z_Alpha"
DEFAULT_TOKEN = "token"
DEFAULT_SERVICE_URL = "http://127.0.0.1:8771/v3.0/"
DEFAULT_AUTH_PLUGIN = "v2password"
DEFAULT_INTERFACE = "internal"

DEFAULT_COMPUTE_API_VERSION = ""
DEFAULT_IDENTITY_API_VERSION = ""
DEFAULT_IMAGE_API_VERSION = ""
DEFAULT_VOLUME_API_VERSION = ""
DEFAULT_NETWORK_API_VERSION = ""

LIB_COMPUTE_API_VERSION = ""
LIB_IDENTITY_API_VERSION = ""
LIB_IMAGE_API_VERSION = ""
LIB_VOLUME_API_VERSION = ""
LIB_NETWORK_API_VERSION = ""

CLOUD_1 = {
    'clouds': {
        'scc': {
            'auth': {
                'auth_url': DEFAULT_AUTH_URL,
                'project_name': DEFAULT_PROJECT_NAME,
                'username': 'zaphod',
            },
            'region_name': 'occ-cloud',
            'donut': 'glazed',
            'interface': 'public',
        }
    }
}

PUBLIC_1 = {
    'public-clouds': {
        'megadodo': {
            'auth': {
                'auth_url': DEFAULT_AUTH_URL,
                'project_name': DEFAULT_PROJECT_NAME,
            },
            'region_name': 'occ-public',
            'donut': 'cake',
        }
    }
}

# The option table values is a tuple of (<value>, <test-opt>, <test-env>)
# where <value> is the test value to use, <test-opt> is True if this option
# should be tested as a CLI option and <test-env> is True of this option
# should be tested as an environment variable.

# Global options that should be parsed before shell.initialize_app() is called
global_options = {
    '--os-cloud': (DEFAULT_CLOUD, True, True),
    '--os-region-name': (DEFAULT_REGION_NAME, True, True),
    '--os-default-domain': (DEFAULT_DOMAIN_NAME, True, True),
    '--os-cacert': ('/dev/null', True, True),
    '--timing': (True, True, False),
    '--os-profile': ('SECRET_KEY', True, False),
    '--os-interface': (DEFAULT_INTERFACE, True, True)
}

def get_cloud(log_file):
    CLOUD = {
        'clouds': {
            'megacloud': {
                'cloud': 'megadodo',
                'auth': {
                    'project_name': 'heart-o-gold',
                    'username': 'zaphod',
                },
                'region_name': 'occ-cloud,krikkit,occ-env',
                'log_file': log_file,
                'log_level': 'debug',
                'cert': 'mycert',
                'key': 'mickey',
            }
        }
    }
    return CLOUD

# Wrap the osc_lib make_shell() function to set the shell class since
# osc-lib's TestShell class doesn't allow us to specify it yet.
# TODO(dtroyer): remove this once the shell_class_patch patch is released
#                in osc-lib
def make_shell_wrapper(func, inst, args, kwargs):
    if 'shell_class' not in kwargs:
        kwargs['shell_class'] = shell.OpenStackShell
    return func(*args, **kwargs)

wrapt.wrap_function_wrapper(
    osc_lib_test_utils,
    'make_shell',
    make_shell_wrapper,
)

class TestShell(osc_lib_test_utils.TestShell):

    # Full name of the OpenStackShell class to test (cliff.app.App subclass)
    shell_class_name = "openstackclient.shell.OpenStackShell"

    # TODO(dtroyer): remove this once the shell_class_patch patch is released
    #                in osc-lib
    app_patch = shell_class_name

    def setUp(self):
        super(TestShell, self).setUp()
        # TODO(dtroyer): remove this once the shell_class_patch patch is
        #                released in osc-lib
        self.shell_class = importutils.import_class(self.shell_class_name)

    def _assert_admin_token_auth(self, cmd_options, default_args):
        with mock.patch(
                self.shell_class_name + ".initialize_app",
                self.app,
        ):
            _shell = osc_lib_test_utils.make_shell(
                shell_class=self.shell_class,
            )
            _cmd = cmd_options + " list role"
            osc_lib_test_utils.fake_execute(_shell, _cmd)
            print("_shell: %s" % _shell)

            self.app.assert_called_with(["list", "role"])
            self.assertEqual(
                default_args.get("token", ''),
                _shell.options.token,
                "token",
            )
            self.assertEqual(
                default_args.get("endpoint", ''),
                _shell.options.endpoint,
                "endpoint",
            )

    def _assert_token_auth(self, cmd_options, default_args):
        with mock.patch(
                self.app_patch + ".initialize_app",
                self.app,
        ):
            _shell = osc_lib_test_utils.make_shell(
                shell_class=self.shell_class,
            )
            _cmd = cmd_options + " list role"
            osc_lib_test_utils.fake_execute(_shell, _cmd)
            print("_shell: %s" % _shell)

            self.app.assert_called_with(["list", "role"])
            self.assertEqual(
                default_args.get("token", ''),
                _shell.options.token,
                "token"
            )
            self.assertEqual(
                default_args.get("auth_url", ''),
                _shell.options.auth_url,
                "auth_url"
            )

    def _assert_cli(self, cmd_options, default_args):
        with mock.patch(
                self.shell_class_name + ".initialize_app",
                self.app,
        ):
            _shell = osc_lib_test_utils.make_shell(
                shell_class=self.shell_class,
            )
            _cmd = cmd_options + " list server"
            osc_lib_test_utils.fake_execute(_shell, _cmd)

            self.app.assert_called_with(["list", "server"])
            self.assertEqual(default_args["compute_api_version"],
                             _shell.options.os_compute_api_version)
            self.assertEqual(default_args["identity_api_version"],
                             _shell.options.os_identity_api_version)
            self.assertEqual(default_args["image_api_version"],
                             _shell.options.os_image_api_version)
            self.assertEqual(default_args["volume_api_version"],
                             _shell.options.os_volume_api_version)
            self.assertEqual(default_args["network_api_version"],
                             _shell.options.os_network_api_version)

class TestShellOptions(TestShell):

    def setUp(self):
        super(TestShellOptions, self).setUp()
        self.useFixture(osc_lib_test_utils.EnvFixture())

    def _test_options_init_app(self, test_opts):
        for opt in test_opts.keys():
            if not test_opts[opt][1]:
                continue
            key = osc_lib_test_utils.opt2attr(opt)
            if isinstance(test_opts[opt][0], str):
                cmd = opt + " " + test_opts[opt][0]
            else:
                cmd = opt
            kwargs = {
                key: test_opts[opt][0],
            }
            self._assert_initialize_app_arg(cmd, kwargs)

    def _test_options_get_one_cloud(self, test_opts):
        for opt in test_opts.keys():
            if not test_opts[opt][1]:
                continue
            key = osc_lib_test_utils.opt2attr(opt)
            if isinstance(test_opts[opt][0], str):
                cmd = opt + " " + test_opts[opt][0]
            else:
                cmd = opt
            kwargs = {
                key: test_opts[opt][0],
            }
            self._assert_cloud_config_arg(cmd, kwargs)

    def _test_env_init_app(self, test_opts):
        for opt in test_opts.keys():
            if not test_opts[opt][2]:
                continue
            key = osc_lib_test_utils.opt2attr(opt)
            kwargs = {
                key: test_opts[opt][0],
            }
            env = {
                osc_lib_test_utils.opt2env(opt): test_opts[opt][0],
            }
            os.environ = env.copy()
            self._assert_initialize_app_arg("", kwargs)

    def _test_env_get_one_cloud(self, test_opts):
        for opt in test_opts.keys():
            if not test_opts[opt][2]:
                continue
            key = osc_lib_test_utils.opt2attr(opt)
            kwargs = {
                key: test_opts[opt][0],
            }
            env = {
                osc_lib_test_utils.opt2env(opt): test_opts[opt][0],
            }
            os.environ = env.copy()
            self._assert_cloud_config_arg("", kwargs)

class TestShellTokenAuthEnv(TestShell):

    def setUp(self):
        super(TestShellTokenAuthEnv, self).setUp()
        env = {
            "OS_TOKEN": DEFAULT_TOKEN,
            "OS_AUTH_URL": DEFAULT_AUTH_URL,
        }
        self.useFixture(osc_lib_test_utils.EnvFixture(env.copy()))

    def test_env(self):
        flag = ""
        kwargs = {
            "token": DEFAULT_TOKEN,
            "auth_url": DEFAULT_AUTH_URL,
        }
        self._assert_token_auth(flag, kwargs)

    def test_only_token(self):
        flag = "--os-token xyzpdq"
        kwargs = {
            "token": "xyzpdq",
            "auth_url": DEFAULT_AUTH_URL,
        }
        self._assert_token_auth(flag, kwargs)

    def test_only_auth_url(self):
        flag = "--os-auth-url http://cloud.local:555"
        kwargs = {
            "token": DEFAULT_TOKEN,
            "auth_url": "http://cloud.local:555",
        }
        self._assert_token_auth(flag, kwargs)

    def test_empty_auth(self):
        os.environ = {}
        flag = ""
        kwargs = {
            "token": '',
            "auth_url": '',
        }
        self._assert_token_auth(flag, kwargs)

class TestShellTokenEndpointAuthEnv(TestShell):

    def setUp(self):
        super(TestShellTokenEndpointAuthEnv, self).setUp()
        env = {
            "OS_TOKEN": DEFAULT_TOKEN,
            "OS_ENDPOINT": DEFAULT_SERVICE_URL,
        }
        self.useFixture(osc_lib_test_utils.EnvFixture(env.copy()))

    def test_env(self):
        flag = ""
        kwargs = {
            "token": DEFAULT_TOKEN,
            "endpoint": DEFAULT_SERVICE_URL,
        }
        self._assert_admin_token_auth(flag, kwargs)

    def test_only_token(self):
        flag = "--os-token xyzpdq"
        kwargs = {
            "token": "xyzpdq",
            "endpoint": DEFAULT_SERVICE_URL,
        }
        self._assert_token_auth(flag, kwargs)

    def test_only_url(self):
        flag = "--os-endpoint http://cloud.local:555"
        kwargs = {
            "token": DEFAULT_TOKEN,
            "endpoint": "http://cloud.local:555",
        }
        self._assert_token_auth(flag, kwargs)

    def test_empty_auth(self):
        os.environ = {}
        flag = ""
        kwargs = {
            "token": '',
            "endpoint": '',
        }
        self._assert_token_auth(flag, kwargs)

class TestShellCli(TestShell):

    def setUp(self):
        super(TestShellCli, self).setUp()
        env = {
            "OS_COMPUTE_API_VERSION": DEFAULT_COMPUTE_API_VERSION,
            "OS_IDENTITY_API_VERSION": DEFAULT_IDENTITY_API_VERSION,
            "OS_IMAGE_API_VERSION": DEFAULT_IMAGE_API_VERSION,
            "OS_VOLUME_API_VERSION": DEFAULT_VOLUME_API_VERSION,
            "OS_NETWORK_API_VERSION": DEFAULT_NETWORK_API_VERSION,
        }
        self.useFixture(osc_lib_test_utils.EnvFixture(env.copy()))

    def test_default_env(self):
        flag = ""
        kwargs = {
            "compute_api_version": DEFAULT_COMPUTE_API_VERSION,
            "identity_api_version": DEFAULT_IDENTITY_API_VERSION,
            "image_api_version": DEFAULT_IMAGE_API_VERSION,
            "volume_api_version": DEFAULT_VOLUME_API_VERSION,
            "network_api_version": DEFAULT_NETWORK_API_VERSION,
        }
        self._assert_cli(flag, kwargs)

    def test_empty_env(self):
        os.environ = {}
        flag = ""
        kwargs = {
            "compute_api_version": LIB_COMPUTE_API_VERSION,
            "identity_api_version": LIB_IDENTITY_API_VERSION,
            "image_api_version": LIB_IMAGE_API_VERSION,
            "volume_api_version": LIB_VOLUME_API_VERSION,
            "network_api_version": LIB_NETWORK_API_VERSION
        }
        self._assert_cli(flag, kwargs)

class TestShellArgV(TestShell):
    """Test the deferred help flag"""

    def test_shell_argv(self):
        """Test argv decoding

        Python 2 does nothing with argv while Python 3 decodes it into
        Unicode before we ever see it.  We manually decode when running
        under Python 2 so verify that we get the right argv types.

        Use the argv supplied by the test runner so we get actual Python
        runtime behaviour; we only need to check the type of argv[0]
        which will always be present.
        """

        with mock.patch(
                self.shell_class_name + ".run",
                self.app,
        ):
            # Ensure type gets through unmolested through shell.main()
            argv = sys.argv
            shell.main(sys.argv)
            self.assertEqual(type(argv[0]), type(self.app.call_args[0][0][0]))

            # When shell.main() gets sys.argv itself it should be decoded
            shell.main()
            self.assertEqual(type(u'x'), type(self.app.call_args[0][0][0]))


text:
package com.sum.cordova.leancloud;

import java.util.HashMap;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.avos.avoscloud.AVAnalytics;

/**
 * This class echoes a string called from JavaScript.
 */
public class LeanAnalytics extends CordovaPlugin {

    public static final String ACTION_VIEW_START = "onViewStart";
    public static final String ACTION_VIEW_END = "onViewEnd";
    public static final String ACTION_EVENT = "event";
    public static final String ACTION_EVENT_START = "onEventStart";
    public static final String ACTION_EVENT_END = "onEventEnd";
    public static final String ACTION_KV_EVENT_START = "onKVEventStart";
    public static final String ACTION_KV_EVENT_END = "onKVEventEnd";

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals(ACTION_VIEW_START)) {
            this.onViewStart(args.getString(0), callbackContext);
            return true;
        }
        if (action.equals(ACTION_VIEW_END)) {
            this.onViewEnd(args.getString(0), callbackContext);
            return true;
        }
        if (action.equals(ACTION_EVENT)) {
            if (args.length() == 1) {
                this.event(args.getString(0), callbackContext);
            } else if (args.length() == 2) {
                this.event(args.getString(0), args.getString(1), callbackContext);
            }
            return true;
        }
        if (action.equals(ACTION_EVENT_START)) {
            if (args.length() == 1) {
                this.onEventStart(args.getString(0), callbackContext);
            } else if (args.length() == 2) {
                this.onEventStart(args.getString(0), args.getString(1), callbackContext);
            }
            return true;
        }
        if (action.equals(ACTION_EVENT_END)) {
            if (args.length() == 1) {
                this.onEventEnd(args.getString(0), callbackContext);
            } else if (args.length() == 2) {
                this.onEventEnd(args.getString(0), args.getString(1), callbackContext);
            }
            return true;
        }
        if (action.equals(ACTION_KV_EVENT_START)) {
            this.onKVEventStart(args.getString(0), args.getString(1), args.getString(2), args.getString(3), callbackContext);
            return true;
        }
        if (action.equals(ACTION_KV_EVENT_END)) {
            this.onKVEventEnd(args.getString(0), args.getString(1), callbackContext);
            return true;
        }
        return false;
    }

    private void onViewStart(final String viewId, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onFragmentStart(viewId);
                callbackContext.success();
            }
        });
    }

    private void onViewEnd(final String viewId, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onFragmentEnd(viewId);
                callbackContext.success();
            }
        });
    }

    private void event(final String eventId, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onEvent(cordova.getActivity(), eventId);
                callbackContext.success();
            }
        });
    }

    private void event(final String eventId, final String label, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onEvent(cordova.getActivity(), eventId, label);
                callbackContext.success();
            }
        });
    }

    private void onEventStart(final String eventId, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onEventBegin(cordova.getActivity(), eventId);
                callbackContext.success();
            }
        });
    }

    private void onEventStart(final String eventId, final String label, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onEventBegin(cordova.getActivity(), eventId, label);
                callbackContext.success();
            }
        });
    }

    private void onEventEnd(final String eventId, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onEventEnd(cordova.getActivity(), eventId);
                callbackContext.success();
            }
        });
    }

    private void onEventEnd(final String eventId, final String label, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onEventEnd(cordova.getActivity(), eventId, label);
                callbackContext.success();
            }
        });
    }

    private void onKVEventStart(final String eventId, final String keyName, final String attr, final String value, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                HashMap<String, String> kv = new HashMap<String, String>();
                AVAnalytics.onKVEventBegin(cordova.getActivity(), eventId, kv, keyName);
                callbackContext.success();
            }
        });
    }

    private void onKVEventEnd(final String eventId, final String keyName, final CallbackContext callbackContext) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                AVAnalytics.onKVEventEnd(cordova.getActivity(), eventId, keyName);
                callbackContext.success();
            }
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
import sys
import traceback

import pytest

from astropy.utils.codegen import make_function_with_signature

def test_make_function_with_signature_lineno():
    """
    Tests that a function made with ``make_function_with_signature`` is give
    the correct line number into the module it was created from (i.e. the line
    ``make_function_with_signature`` was called from).
    """

    def crashy_function(*args, **kwargs):
        1 / 0

    # Make a wrapper around this function with the signature:
    # crashy_function(a, b)
    # Note: the signature is not really relevant to this test
    wrapped = make_function_with_signature(crashy_function, ('a', 'b'))
    line = """
    wrapped = make_function_with_signature(crashy_function, ('a', 'b'))
    """.strip()

    try:
        wrapped(1, 2)
    except Exception:
        exc_cls, exc, tb = sys.exc_info()
        assert exc_cls is ZeroDivisionError
        # The *last* line in the traceback should be the 1 / 0 line in
        # crashy_function; the next line up should be the line that the
        # make_function_with_signature call was one
        tb_lines = traceback.format_tb(tb)
        assert '1 / 0' in tb_lines[-1]
    else:
        pytest.fail('This should have caused an exception')


text:
package com.estore.activity;
/*
系统通知页面
 */

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.estore.R;
import com.estore.httputils.HttpUrlUtils;
import com.estore.pojo.Message;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

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

/**
 * Created by mawuyang on 2016-10-28.
 */
public class SystemInformActivity extends Activity {
    private ImageView informReturn;
    private ListView lv;
   final List<Message> messagelist=new ArrayList<Message>();
    private BaseAdapter myAdapter=new Myaddapter();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_inform);
        initView();
        initEvent();
        myAdapter.notifyDataSetChanged();
        getMessageInfo();
    }

    private void initView() {
        informReturn = ((ImageView) findViewById(R.id.iv_informreturn));
        lv=((ListView) findViewById(R.id.lv));

    }
    private void initEvent() {
        informReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
    private class Myaddapter extends BaseAdapter {

        private TextView title;
        private TextView content;
        private TextView time;

        @Override
        public int getCount() {
            return messagelist.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewGroup) {
            view=View.inflate(SystemInformActivity.this,R.layout.layout_inform_item,null);
            title = ((TextView) view.findViewById(R.id.tv_title));
            content = ((TextView) view.findViewById(R.id.tv_content));
            time = ((TextView) view.findViewById(R.id.tv_time));
            Message message=messagelist.get(position);

            Log.i("cc","message======"+message);
            title.setText(message.getTitle());
            content.setText(message.getContent());
            time.setText(message.getTime());

            return view;
        }
    }
    private void getMessageInfo() {
        final String url= HttpUrlUtils.HTTP_URL+"/findallmessageservlet";
        Log.i("cc", "url: "+url);
        RequestParams request=new RequestParams(url);
        x.http().get(request, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Log.i("SystemInform=======","result"+result);
                Gson gson=new Gson();
                List<Message> mm=gson.fromJson(result,new TypeToken<List<Message>>(){}.getType());
                messagelist.addAll(mm);
                Log.i("cc","messageList========"+messagelist);
                if(myAdapter==null){
                    myAdapter=new Myaddapter();
                }else {
                 myAdapter.notifyDataSetChanged();
                }
                lv.setAdapter(myAdapter);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}


text:
package com.google.idea.common.experiments;

import static com.google.idea.common.experiments.ExperimentsUtil.hashExperimentName;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * An experiment loader that handles hashing the experiment names, for sources that store the data
 * unhashed.
 */
abstract class HashingExperimentLoader implements ExperimentLoader {

  @Override
  public Map<String, String> getExperiments() {
    return getUnhashedExperiments()
        .entrySet()
        .stream()
        .collect(Collectors.toMap(e -> hashExperimentName(e.getKey()), Map.Entry::getValue));
  }

  abstract Map<String, String> getUnhashedExperiments();
}


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

public class ArrayOfPerfSampleInfo {
  public PerfSampleInfo[] PerfSampleInfo;

  public PerfSampleInfo[] getPerfSampleInfo() {
    return this.PerfSampleInfo;
  }

  public PerfSampleInfo getPerfSampleInfo(int i) {
    return this.PerfSampleInfo[i];
  }

  public void setPerfSampleInfo(PerfSampleInfo[] PerfSampleInfo) {
    this.PerfSampleInfo=PerfSampleInfo;
  }
}


text:
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------

import contextlib
import logging
import os
try:
    from urlparse import urljoin, urlparse
except ImportError:
    from urllib.parse import urljoin, urlparse

from oauthlib import oauth2
import requests

from .authentication import Authentication
from .pipeline import ClientHTTPAdapter, ClientRequest
from .http_logger import log_request, log_response
from .exceptions import (
    TokenExpiredError,
    ClientRequestError,
    raise_with_traceback)

_LOGGER = logging.getLogger(__name__)

class ServiceClient(object):
    """REST Service Client.
    Maintains client pipeline and handles all requests and responses.

    :param Configuration config: Service configuration.
    :param Authentication creds: Authenticated credentials.
    """

    _protocols = ['http://', 'https://']

    def __init__(self, creds, config):
        self.config = config
        self.creds = creds if creds else Authentication()

        self._adapter = ClientHTTPAdapter(config)
        self._headers = {}

        self._adapter.add_hook("request", log_request)
        self._adapter.add_hook("response", log_response, precall=False)

    def _format_data(self, data):
        """Format field data according to whether it is a stream or
        a string for a form-data request.

        :param data: The request field data.
        :type data: str or file-like object.
        """
        content = [None, data]
        if hasattr(data, 'read'):
            content.append("application/octet-stream")
            try:
                if data.name[0] != '<' and data.name[-1] != '>':
                    content[0] = os.path.basename(data.name)
            except (AttributeError, TypeError):
                pass
        return tuple(content)

    def _request(self, url, params):
        """Create ClientRequest object.

        :param str url: URL for the request.
        :param dict params: URL query parameters.
        """
        request = ClientRequest()

        if url:
            request.url = self.format_url(url)

        if params:
            request.format_parameters(params)

        return request

    def _configure_session(self, session, **config):
        """Apply configuration to session.

        :param requests.Session session: Current request session.
        :param config: Specific configuration overrides.
        """
        kwargs = self.config.connection()
        for opt in ['timeout', 'verify', 'cert']:
            kwargs[opt] = config.get(opt, kwargs[opt])
        for opt in ['cookies', 'files']:
            kwargs[opt] = config.get(opt)
        kwargs['stream'] = True
        kwargs['allow_redirects'] = config.get(
            'allow_redirects', bool(self.config.redirect_policy))

        session.headers.update(self._headers)
        session.headers['User-Agent'] = self.config.user_agent
        session.headers['Accept'] = 'application/json'
        session.max_redirects = config.get(
            'max_redirects', self.config.redirect_policy())
        session.proxies = config.get(
            'proxies', self.config.proxies())
        session.trust_env = config.get(
            'use_env_proxies', self.config.proxies.use_env_settings)
        redirect_logic = session.resolve_redirects

        def wrapped_redirect(resp, req, **kwargs):
            attempt = self.config.redirect_policy.check_redirect(resp, req)
            return redirect_logic(resp, req, **kwargs) if attempt else []

        session.resolve_redirects = wrapped_redirect
        self._adapter.max_retries = config.get(
            'retries', self.config.retry_policy())
        for protocol in self._protocols:
            session.mount(protocol, self._adapter)

        return kwargs

    def send_formdata(self, request, headers={}, content={}, **config):
        """Send data as a multipart form-data request.
        We only deal with file-like objects or strings at this point.
        The requests is not yet streamed.

        :param ClientRequest request: The request object to be sent.
        :param dict headers: Any headers to add to the request.
        :param dict content: Dictionary of the fields of the formdata.
        :param config: Any specific config overrides.
        """
        file_data = {f: self._format_data(d) for f, d in content.items()}
        try:
            del headers['Content-Type']
        except KeyError:
            pass
        return self.send(request, headers, None, files=file_data, **config)

    def send(self, request, headers=None, content=None, **config):
        """Prepare and send request object according to configuration.

        :param ClientRequest request: The request object to be sent.
        :param dict headers: Any headers to add to the request.
        :param content: Any body data to add to the request.
        :param config: Any specific config overrides
        """
        response = None
        session = self.creds.signed_session()
        kwargs = self._configure_session(session, **config)

        request.add_headers(headers if headers else {})
        if not kwargs.get('files'):
            request.add_content(content)
        try:

            try:
                response = session.request(
                    request.method, request.url,
                    data=request.data,
                    headers=request.headers,
                    **kwargs)
                return response

            except (oauth2.rfc6749.errors.InvalidGrantError,
                    oauth2.rfc6749.errors.TokenExpiredError) as err:
                error = "Token expired or is invalid. Attempting to refresh."
                _LOGGER.warning(error)

            try:
                session = self.creds.refresh_session()
                kwargs = self._configure_session(session)

                response = session.request(
                    request.method, request.url,
                    request.data,
                    request.headers,
                    **kwargs)
                return response
            except (oauth2.rfc6749.errors.InvalidGrantError,
                    oauth2.rfc6749.errors.TokenExpiredError) as err:
                msg = "Token expired or is invalid."
                raise_with_traceback(TokenExpiredError, msg, err)

        except (requests.RequestException,
                oauth2.rfc6749.errors.OAuth2Error) as err:
            msg = "Error occurred in request."
            raise_with_traceback(ClientRequestError, msg, err)
        finally:
            if not response or response._content_consumed:
                session.close()

    def stream_download(self, data, callback):
        """Generator for streaming request body data.

        :param data: A response object to be streamed.
        :param callback: Custom callback for monitoring progress.
        """
        block = self.config.connection.data_block_size
        if not data._content_consumed:
            with contextlib.closing(data) as response:
                for chunk in response.iter_content(block):
                    if not chunk:
                        break
                    if callback and callable(callback):
                        callback(chunk, response=response)
                    yield chunk
        else:
            for chunk in data.iter_content(block):
                if not chunk:
                    break
                if callback and callable(callback):
                    callback(chunk, response=data)
                yield chunk
        data.close()
        self._adapter.close()

    def stream_upload(self, data, callback):
        """Generator for streaming request body data.

        :param data: A file-like object to be streamed.
        :param callback: Custom callback for monitoring progress.
        """
        while True:
            chunk = data.read(self.config.connection.data_block_size)
            if not chunk:
                break
            if callback and callable(callback):
                callback(chunk, response=None)
            yield chunk

    def format_url(self, url, **kwargs):
        """Format request URL with the client base URL, unless the
        supplied URL is already absolute.

        :param str url: The request URL to be formatted if necessary.
        """
        url = url.format(**kwargs)
        parsed = urlparse(url)
        if not parsed.scheme or not parsed.netloc:
            url = url.lstrip('/')
            base = self.config.base_url.format(**kwargs).rstrip('/')
            url = urljoin(base + '/', url)
        return url

    def add_hook(self, event, hook, precall=True, overwrite=False):
        """
        Add event callback.

        :param str event: The pipeline event to hook. Currently supports
         'request' and 'response'.
        :param callable hook: The callback function.
        """
        self._adapter.add_hook(event, hook, precall, overwrite)

    def remove_hook(self, event, hook):
        """
        Remove event callback.

        :param str event: The pipeline event to hook. Currently supports
         'request' and 'response'.
        :param callable hook: The callback function.
        """
        self._adapter.remove_hook(event, hook)

    def add_header(self, header, value):
        """Add a persistent header - this header will be applied to all
        requests sent during the current client session.

        :param str header: The header name.
        :param str value: The header value.
        """
        self._headers[header] = value

    def get(self, url=None, params={}):
        """Create a GET request object.

        :param str url: The request URL.
        :param dict params: Request URL parameters.
        """
        request = self._request(url, params)
        request.method = 'GET'
        return request

    def put(self, url=None, params={}):
        """Create a PUT request object.

        :param str url: The request URL.
        :param dict params: Request URL parameters.
        """
        request = self._request(url, params)
        request.method = 'PUT'
        return request

    def post(self, url=None, params={}):
        """Create a POST request object.

        :param str url: The request URL.
        :param dict params: Request URL parameters.
        """
        request = self._request(url, params)
        request.method = 'POST'
        return request

    def head(self, url=None, params={}):
        """Create a HEAD request object.

        :param str url: The request URL.
        :param dict params: Request URL parameters.
        """
        request = self._request(url, params)
        request.method = 'HEAD'
        return request

    def patch(self, url=None, params={}):
        """Create a PATCH request object.

        :param str url: The request URL.
        :param dict params: Request URL parameters.
        """
        request = self._request(url, params)
        request.method = 'PATCH'
        return request

    def delete(self, url=None, params={}):
        """Create a DELETE request object.

        :param str url: The request URL.
        :param dict params: Request URL parameters.
        """
        request = self._request(url, params)
        request.method = 'DELETE'
        return request

    def merge(self, url=None, params={}):
        """Create a MERGE request object.

        :param str url: The request URL.
        :param dict params: Request URL parameters.
        """
        request = self._request(url, params)
        request.method = 'MERGE'
        return request


text:
//Diogo L.C. Felipe
//diogomem@outlook.com

/*
	O Selection Sort, ou algoritomo de ordenação por seleção ordena uma serie de dados
	da seguinte maneira:
		1. Acha o menor valor no vetor a partir da posição 'i';
		2. Troca esse valor com o valor que está na posição 'i';
		3. Soma 1 na posição de inicio (i = i + 1);
		4. Repete o algorítimo até a penultima posição do verto.
*/

function selectionSort(vetorDesordenado, inicio, fim) {

	for (let i = inicio; i < fim - 1; i++) {
		let menorPosicao = buscaPosicaoMenor(vetorDesordenado, i, fim);
		[vetorDesordenado[menorPosicao], vetorDesordenado[i]] = [vetorDesordenado[i], vetorDesordenado[menorPosicao]];
	}

	return vetorDesordenado;
}

function buscaPosicaoMenor(vetorDesordenado, inicio, termino){
	let posicaoMenor = inicio;
	let menor = vetorDesordenado[inicio]

	for (let i = inicio; i < termino; i++) {
		if(vetorDesordenado[i] < menor){
			menor = vetorDesordenado[i];
			posicaoMenor = i;
		}
	}
	return posicaoMenor;
}

var vetorDesordenado  = [54,42,11,33,24,99,77,80];
let vetorOrdenadoViaSelectionSort = selectionSort(vetorDesordenado, 0, vetorDesordenado.length);

console.log(vetorOrdenadoViaSelectionSort);


text:
"""
Created on Sun Apr 19 18:05:23 2015

@author: Paco
"""

import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import GradientBoostingClassifier,RandomForestClassifier,AdaBoostClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.lda import LDA
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC

'''
-----------------------
-- Models
-----------------------
'''
def listModels():
    models = list()
    models.append(KNeighborsClassifier(n_neighbors=20))
    models.append(LogisticRegression(penalty='l1'))
    models.append(AdaBoostClassifier())
    models.append(GradientBoostingClassifier())
    models.append(RandomForestClassifier())
    models.append(LDA())
    models.append(DecisionTreeClassifier())
    models.append(SVC(kernel='linear'))
    return models

'''
-----------------------
-- Useful
-----------------------
'''
def savePredictions(pred_res,filename='y_pred.txt'):
    np.savetxt(filename, pred_res, fmt='%s')

def createNormalizedDataframe(dic):
    df = pd.DataFrame(data=dic)
    df_norm = (df - df.mean()) / df.std()
    return np.array(df_norm)


text:
[![npm](https://img.shields.io/npm/v/flatelect.svg) ![npm](https://img.shields.io/npm/dm/flatelect.svg)](https://www.npmjs.com/package/flatelect)
[![vue2](https://img.shields.io/badge/vue-2.x-brightgreen.svg)](https://vuejs.org/)

Select plugin for VueJS

## Table of contents

- [Demo](http://flatelect.garazha.xyz)
- [Installation](#installation)
- [Usage](#usage)
- [Example](#example)

# Installation

```
npm install --save flatelect
```

## Default import

Install all the components:

```javascript
import Vue from 'vue'
import Flatelect from 'flatelect'

Vue.use(Flatelect)
```

Use specific components:

```javascript
import Vue from 'vue'
import { Test } from 'flatelect'

Vue.component('test', Test)
```

**⚠ A css file is included when importing the package. You may have to setup your bundler to embed the css in your page.**

## Distribution import

Install all the components:

```javascript
import 'flatelect/dist/flatelect.css'
import Flatelect from 'flatelect/dist/flatelect.common'

Vue.use(Flatelect)
```

Use specific components:

```javascript
import 'flatelect/dist/flatelect.css'
import { Test } from 'flatelect/dist/flatelect.common'

Vue.component('test', Test)
```

**⚠ You may have to setup your bundler to embed the css file in your page.**

## Browser

```html
<link rel="stylesheet" href="flatelect/dist/flatelect.css"/>

<script src="vue.js"></script>
<script src="flatelect/dist/flatelect.browser.js"></script>
```

The plugin should be auto-installed. If not, you can install it manually with the instructions below.

Install all the components:

```javascript
Vue.use(Flatelect)
```

Use specific components:

```javascript
Vue.component('test', Flatelect.Test)
```

## Source import

Install all the components:

```javascript
import Vue from 'vue'
import Flatelect from 'flatelect/src'

Vue.use(Flatelect)
```

Use specific components:

```javascript
import Vue from 'vue'
import { Test } from 'flatelect/src'

Vue.component('test', Test)
```

# Usage

  <flatelect
    :options="options" //options to display
    :size="compact" //or full
    :fancy="true" //transulcent & soft shadow dropdown.
    :required="false" //validation purposes
    :objKey="name" //if options consist of objects, provide here the key which will be used to display the option.
    :custom="false" //if you want to render something else instead of option name, then use slot tag and write your own markup!
    v-on:selected="handleSelection" //callback method when user has made the selection.
    >
  </flatelect>

## License

[MIT](http://opensource.org/licenses/MIT)


text:
package edu.depauw.scales

/*
 * @author Christopher Monsanto (chris@monsan.to)
 */

import javax.swing._
import java.awt._
import java.awt.{Color => JColor}
import java.awt.image._
import java.awt.geom._
import javax.imageio._
import java.io._

/*
 * Graphic
 */

abstract class Graphic extends Displayable with Reactable { me =>
  val _size = new Value((0, 0))
  def size = _size.get

  protected def onRedraw
  def draw(g : Graphics2D)
  def deriveGraphic(newDefs : => (
    () => Unit,
    Value[(Int, Int)],
    (Graphics2D, Graphics2D => Unit) => Unit)): MyType

  def makeComponent : JComponent = new JPanel with Reactable {
    setOpaque(false)

    listen({
      val (width, height) = me.size
      setPreferredSize(new Dimension(width, height))
      setSize(width, height)
    })
    listen(onRedraw, repaint())

    override def paintComponent(graphics : Graphics) {
      super.paintComponent(graphics)

      val g2d = graphics.asInstanceOf[Graphics2D]
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON)
      draw(g2d)
    }
  }

  /*
   *
   */

  def transform(t : => AffineTransform) = {
    deriveGraphic({
      def onRedraw() { t }

      val size = new Value((0, 0)) {
        override def set(sender: AnyRef, value: (Int, Int)) {
          val (width, height) = value

          val points = Array[Point2D](
            new Point2D.Float(0, 0),
            new Point2D.Float(width, 0),
            new Point2D.Float(0, height),
            new Point2D.Float(width, height))

          val newCoords = {
            val coords = new Array[Point2D](4)
            t.transform(points, 0, coords, 0, 4)
            coords
          }

          def max(p1 : Point2D, p2 : Point2D) = {
            val x = if (p1.getX() > p2.getX()) p1.getX() else p2.getX()
            val y = if (p1.getY() > p2.getY()) p1.getY() else p2.getY()
            new Point2D.Double(x, y)
          }

          def min(p1 : Point2D, p2 : Point2D) = {
            val x = if (p1.getX() < p2.getX()) p1.getX() else p2.getX()
            val y = if (p1.getY() < p2.getY()) p1.getY() else p2.getY()
            new Point2D.Double(x, y)
          }

          val maxCoord = newCoords.reduceLeft(
            (a, b) => new Point2D.Double(scala.math.max(a.getX(), a.getY()),
              scala.math.max(b.getX(), b.getY())))
          val minCoord =  newCoords.reduceLeft(
            (a, b) => new Point2D.Double(scala.math.min(a.getX(), a.getY()),
              scala.math.min(b.getX(), b.getY())))

          val newWidth = maxCoord.getX().toInt - minCoord.getX().toInt
          val newHeight = maxCoord.getY().toInt - minCoord.getY().toInt

          super.set(sender, (newWidth, newHeight))
        }
      }

      def newDraw(g: Graphics2D, draw: Graphics2D => Unit) {
        val orig = g.getTransform()
        g.transform(t)
        draw(g)
        g.setTransform(orig)
      }

      (onRedraw, size, newDraw(_, _))
    })
  }

  def rotate(theta: => Double, pos: => (Int, Int)):MyType = transform(
    AffineTransform.getRotateInstance(theta, pos._1.toInt, pos._2.toInt))
  def rotateDeg(degrees: => Double, pos: => (Int, Int)):MyType =
    rotate(scala.math.Pi/180 * degrees, pos)
  def rotate(theta: => Double):MyType =
    rotate(theta, {
      val (width, height) = size
      (width/2, height/2)
    })
  def rotateDeg(degrees: => Double):MyType =
    rotateDeg(degrees, {
      val (width, height) = size
      (width/2, height/2)
    })
  def shear(shx: => Double, shy: => Double) = transform(
    AffineTransform.getShearInstance(shx, shy))
  def scale(sx: => Double, sy: => Double) = transform(
    AffineTransform.getScaleInstance(sx, sy))
}

/*
 * Shapes
 */

class Shape(rShape: => java.awt.Shape,
            rOutlinedShape: => java.awt.Shape,
            rFillPaint: => Paint,
            rOutlinePaint: => Paint) extends Graphic {
  var shape: java.awt.Shape = null
  var outlinedShape: java.awt.Shape = null
  var fillPaint: Paint = null
  var outlinePaint: Paint = null

  listen({shape = rShape})
  listen({
    outlinedShape = rOutlinedShape
    val bounds = rOutlinedShape.getBounds2D()
    _size.set(this,
      (bounds.getWidth().toInt + bounds.getX().toInt,
      bounds.getHeight().toInt + bounds.getY().toInt))
  })
  listen({fillPaint = rFillPaint})
  listen({outlinePaint = rOutlinePaint})

  def onRedraw { rShape; rOutlinedShape; rFillPaint; rOutlinePaint }

  def draw(g: Graphics2D) {
    g.setPaint(fillPaint)
    g.fill(shape)
    g.setPaint(outlinePaint)
    g.fill(outlinedShape)
  }

  def fill(fillPaint: => Paint, opacity: => Double):Shape =
    new Shape(rShape, rOutlinedShape, fillPaint, rOutlinePaint)
  def fill(fillPaint: => Paint):Shape = fill(fillPaint, 1)

  def outline(outlinePaint: => Paint, size: => Int, opacity: => Double):Shape =
    new Shape(rShape,
              (new BasicStroke(size.toFloat)).createStrokedShape(rShape),
              rFillPaint, outlinePaint)
  def outline(outlinePaint: => Paint):Shape = outline(outlinePaint, 1, 1)
  def outline(outlinePaint: => Paint, size: => Int):Shape =
    outline(outlinePaint, size, 1)

  /*
   *
   */

  def this(shape: => java.awt.Shape) =
    this(shape, (new BasicStroke(1f)).createStrokedShape(shape),
         Color.white, Color.black)

  type MyType = Shape

  def derive(newMakeComponent: (=> JComponent) => JComponent) =
    new Shape(rShape, rOutlinedShape, rFillPaint, rOutlinePaint) {
      override def makeComponent = newMakeComponent(super.makeComponent)
    }

  def deriveGraphic(newDefs: => (() => Unit,
                                 Value[(Int, Int)],
                                 (Graphics2D, Graphics2D => Unit) => Unit)) = {
    val (newRedraw, newSize, newDraw) = newDefs
    new Shape(rShape, rOutlinedShape, rFillPaint, rOutlinePaint) {
      override def onRedraw { super.onRedraw ; newRedraw }
      override val _size = newSize
      override def draw(g: Graphics2D) {
        newDraw(g, super.draw(_))
      }
    }
  }
}

object Circle {
  def apply(diameter: => Double) =
    Ellipse(diameter, diameter)
}

object Ellipse {
  def apply(xDiam: => Double, yDiam : => Double) =
    new Shape(new Ellipse2D.Double(0, 0, xDiam, yDiam))
}

object Rectangle {
  def apply(width: => Double, height: => Double) =
    new Shape(new Rectangle2D.Double(0, 0, width, height))
}

object RoundRectangle {
  def apply(width: => Double, height: => Double,
            arcw: => Double, arch: => Double) = {
    new Shape(new RoundRectangle2D.Double(0,0,width,height,arcw,arch))
  }
}

object Square {
  def apply(width: => Double) = Rectangle(width, width)
}

object Line {
  def fromCoords(p1: => (Int,Int), p2: => (Int,Int)) =
    new Shape(new Line2D.Double(p1._1, p1._2, p2._1, p2._2))
}

object Canvas {
  def apply(width: => Double, height: => Double)(path: Turtle => Turtle) =
    new Shape(path(new Turtle(width, height)).shape)
}

/*
 * Turtle graphics
 *
 * Turtle starts at center (0,0) of a rectangle width x height, heading to the right
 * (positive x); angles are in degrees, increasing counter-clockwise.
 */
class Turtle(val width : Double, val height : Double) {
  // Warning: this GeneralPath is mutable, so Turtles are also mutable (hence not copyable)
  val shape : GeneralPath = new GeneralPath(new Rectangle2D.Double(0, 0, width, height))

  private var heading : Double = 0
  private var pen : Boolean = true

  def forward(distance : Double) : Turtle = {
    val current = shape.getCurrentPoint
    val newX = current.getX + distance * scala.math.cos(heading)
    val newY = current.getY - distance * scala.math.sin(heading)

    if (pen)
      shape.lineTo(newX.toFloat, newY.toFloat)
    else
      shape.moveTo(newX.toFloat, newY.toFloat)

    this
  }

  def left(angle : Double) : Turtle = {
    heading += angle * scala.math.Pi / 180

    this
  }

  def right(angle : Double) : Turtle = left(-angle)

  def penUp : Turtle = {
    pen = false

    this
  }

  def penDown : Turtle = {
    pen = true

    this
  }

  def moveTo(x : Double, y : Double) : Turtle = {
    val newX = x + width / 2
    val newY = -y + height / 2

    if (pen)
      shape.lineTo(newX.toFloat, newY.toFloat)
    else
      shape.moveTo(newX.toFloat, newY.toFloat)

    this
  }

  def turnTo(angle : Double) : Turtle = {
    heading = angle * scala.math.Pi / 180

    this
  }

  // TODO push (current point and heading) and pop for L-Systems?

  shape.moveTo(width.toFloat / 2, height.toFloat / 2)
}

// import path._ for "point free" turtle paths
object path {
  type Path = Turtle => Turtle

  def forward(distance : Double) : Path = { turtle => turtle forward distance }

  def left(angle : Double) : Path = { turtle => turtle left angle }

  def right(angle : Double) : Path = { turtle => turtle right angle }

  def penUp : Path = { turtle => turtle penUp }

  def penDown : Path = { turtle => turtle penDown }

  def moveTo(x : Double, y : Double) : Path = { turtle => turtle moveTo (x, y) }

  def turnTo(angle : Double) : Path = { turtle => turtle turnTo angle }
}

/*
 * Images
 */

class Image(rImage: => BufferedImage) extends Graphic {
  var image: BufferedImage = null

  listen({
    image = rImage
    _size.set(this, (image.getWidth(null), image.getHeight(null)))
  })

  def onRedraw { rImage }

  def draw(g: Graphics2D) {
    g.drawImage(image, 0, 0, null)
  }

  /*
   *
   */

  type MyType = Image

  def derive(newMakeComponent: (=> JComponent) => JComponent) =
    new Image(rImage) {
      override def makeComponent = newMakeComponent(super.makeComponent)
    }

  def deriveGraphic(newDefs: => (
() => Unit,
Value[(Int, Int)],
(Graphics2D, Graphics2D => Unit) => Unit)) = {
      val (newRedraw, newSize, newDraw) = newDefs
      new Image(rImage) {
        override def onRedraw { super.onRedraw ; newRedraw }
        override val _size = newSize
        override def draw(g: Graphics2D) {
          newDraw(g, super.draw(_))
        }
      }
    }
}

object Image {
  def apply(fileName: String) = new Image(ImageIO.read(new File(fileName)))
}

/*
 * Utility
 */

object Color {
  val red = JColor.red
  val green = JColor.green
  val blue = JColor.blue
  val cyan = JColor.cyan
  val darkGray = JColor.darkGray
  val lightGray = JColor.lightGray
  val black = JColor.black
  val white = JColor.white
  val magenta = JColor.magenta
  val orange = JColor.orange
  val pink = JColor.pink
  val yellow = JColor.yellow

  def apply(r: Int, g: Int, b: Int) = new JColor(r, g, b)
  def apply(r: Int, g: Int, b: Int, a: Int) = new JColor(r, g, b, a)

  def gradient(t1:(Int,Int), c1:JColor, t2:(Int,Int), c2:JColor) =
    new GradientPaint(t1._1, t1._2, c1, t2._1, t2._2, c2)
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;

using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;

namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
    /// <summary>
    /// This module loads and saves OpenSimulator inventory archives
    /// </summary>
    public class InventoryArchiverModule : IRegionModule, IInventoryArchiverModule
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public string Name { get { return "Inventory Archiver Module"; } }

        public bool IsSharedModule { get { return true; } }

        /// <value>
        /// Enable or disable checking whether the iar user is actually logged in
        /// </value>
        public bool DisablePresenceChecks { get; set; }

        public event InventoryArchiveSaved OnInventoryArchiveSaved;

        /// <summary>
        /// The file to load and save inventory if no filename has been specified
        /// </summary>
        protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar";

        /// <value>
        /// Pending save completions initiated from the console
        /// </value>
        protected List<Guid> m_pendingConsoleSaves = new List<Guid>();

        /// <value>
        /// All scenes that this module knows about
        /// </value>
        private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
        private Scene m_aScene;

        public InventoryArchiverModule() {}

        public InventoryArchiverModule(bool disablePresenceChecks)
        {
            DisablePresenceChecks = disablePresenceChecks;
        }

        public void Initialise(Scene scene, IConfigSource source)
        {
            if (m_scenes.Count == 0)
            {
                scene.RegisterModuleInterface<IInventoryArchiverModule>(this);
                OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted;

                scene.AddCommand(
                    this, "load iar",
                    "load iar <first> <last> <inventory path> <password> [<IAR path>]",
                    "Load user inventory archive (IAR).",
                    "<first> is user's first name." + Environment.NewLine
                    + "<last> is user's last name." + Environment.NewLine
                    + "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine
                    + "<password> is the user's password." + Environment.NewLine
                    + "<IAR path> is the filesystem path or URI from which to load the IAR."
                    + string.Format("  If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME),
                    HandleLoadInvConsoleCommand);

                scene.AddCommand(
                    this, "save iar",
                    "save iar <first> <last> <inventory path> <password> [<IAR path>]",
                    "Save user inventory archive (IAR).",
                    "<first> is the user's first name." + Environment.NewLine
                    + "<last> is the user's last name." + Environment.NewLine
                    + "<inventory path> is the path inside the user's inventory for the folder/item to be saved." + Environment.NewLine
                    + "<IAR path> is the filesystem path at which to save the IAR."
                    + string.Format("  If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME),
                    HandleSaveInvConsoleCommand);

                m_aScene = scene;
            }

            m_scenes[scene.RegionInfo.RegionID] = scene;
        }

        public void PostInitialise() {}

        public void Close() {}

        /// <summary>
        /// Trigger the inventory archive saved event.
        /// </summary>
        protected internal void TriggerInventoryArchiveSaved(
            Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
            Exception reportedException)
        {
            InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved;
            if (handlerInventoryArchiveSaved != null)
                handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException);
        }

        public bool ArchiveInventory(Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream)
        {
            if (m_scenes.Count > 0)
            {
                UserAccount userInfo = GetUserInfo(firstName, lastName, pass);

                if (userInfo != null)
                {
                    if (CheckPresence(userInfo.PrincipalID))
                    {
                        try
                        {
                            new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute();
                        }
                        catch (EntryPointNotFoundException e)
                        {
                            m_log.ErrorFormat(
                                "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
                                    + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
                            m_log.Error(e);

                            return false;
                        }

                        return true;
                    }
                    else
                    {
                        m_log.ErrorFormat(
                            "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
                            userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
                    }
                }
            }

            return false;
        }

        public bool ArchiveInventory(Guid id, string firstName, string lastName, string invPath, string pass, string savePath)
        {
            if (m_scenes.Count > 0)
            {
                UserAccount userInfo = GetUserInfo(firstName, lastName, pass);

                if (userInfo != null)
                {
                    if (CheckPresence(userInfo.PrincipalID))
                    {
                        try
                        {
                            new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute();
                        }
                        catch (EntryPointNotFoundException e)
                        {
                            m_log.ErrorFormat(
                                "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
                                    + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
                            m_log.Error(e);

                            return false;
                        }

                        return true;
                    }
                    else
                    {
                        m_log.ErrorFormat(
                            "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
                            userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
                    }
                }
            }

            return false;
        }

        public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream)
        {
            if (m_scenes.Count > 0)
            {
                UserAccount userInfo = GetUserInfo(firstName, lastName, pass);

                if (userInfo != null)
                {
                    if (CheckPresence(userInfo.PrincipalID))
                    {
                        InventoryArchiveReadRequest request;

                        try
                        {
                            request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream);
                        }
                        catch (EntryPointNotFoundException e)
                        {
                            m_log.ErrorFormat(
                                "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
                                    + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
                            m_log.Error(e);

                            return false;
                        }

                        UpdateClientWithLoadedNodes(userInfo, request.Execute());

                        return true;
                    }
                    else
                    {
                        m_log.ErrorFormat(
                            "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
                            userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
                    }
                }
            }

            return false;
        }

        public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, string loadPath)
        {
            if (m_scenes.Count > 0)
            {
                UserAccount userInfo = GetUserInfo(firstName, lastName, pass);

                if (userInfo != null)
                {
                    if (CheckPresence(userInfo.PrincipalID))
                    {
                        InventoryArchiveReadRequest request;

                        try
                        {
                            request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath);
                        }
                        catch (EntryPointNotFoundException e)
                        {
                            m_log.ErrorFormat(
                                "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream."
                                    + "If you've manually installed Mono, have you appropriately updated zlib1g as well?");
                            m_log.Error(e);

                            return false;
                        }

                        UpdateClientWithLoadedNodes(userInfo, request.Execute());

                        return true;
                    }
                    else
                    {
                        m_log.ErrorFormat(
                            "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator",
                            userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID);
                    }
                }
            }

            return false;
        }

        /// <summary>
        /// Load inventory from an inventory file archive
        /// </summary>
        /// <param name="cmdparams"></param>
        protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams)
        {
            if (cmdparams.Length < 6)
            {
                m_log.Error(
                    "[INVENTORY ARCHIVER]: usage is load iar <first name> <last name> <inventory path> <user password> [<load file path>]");
                return;
            }

            m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL.  BUG REPORTS WELCOME.");

            string firstName = cmdparams[2];
            string lastName = cmdparams[3];
            string invPath = cmdparams[4];
            string pass = cmdparams[5];
            string loadPath = (cmdparams.Length > 6 ? cmdparams[6] : DEFAULT_INV_BACKUP_FILENAME);

            m_log.InfoFormat(
                "[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}",
                loadPath, invPath, firstName, lastName);

            if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath))
                m_log.InfoFormat(
                    "[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}",
                    loadPath, firstName, lastName);
        }

        /// <summary>
        /// Save inventory to a file archive
        /// </summary>
        /// <param name="cmdparams"></param>
        protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
        {
            if (cmdparams.Length < 6)
            {
                m_log.Error(
                    "[INVENTORY ARCHIVER]: usage is save iar <first name> <last name> <inventory path> <user password> [<save file path>]");
                return;
            }

            m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL.  BUG REPORTS WELCOME.");

            string firstName = cmdparams[2];
            string lastName = cmdparams[3];
            string invPath = cmdparams[4];
            string pass = cmdparams[5];
            string savePath = (cmdparams.Length > 6 ? cmdparams[6] : DEFAULT_INV_BACKUP_FILENAME);

            m_log.InfoFormat(
                "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}",
                savePath, invPath, firstName, lastName);

            Guid id = Guid.NewGuid();
            ArchiveInventory(id, firstName, lastName, invPath, pass, savePath);

            lock (m_pendingConsoleSaves)
                m_pendingConsoleSaves.Add(id);
        }

        private void SaveInvConsoleCommandCompleted(
            Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
            Exception reportedException)
        {
            lock (m_pendingConsoleSaves)
            {
                if (m_pendingConsoleSaves.Contains(id))
                    m_pendingConsoleSaves.Remove(id);
                else
                    return;
            }

            if (succeeded)
            {
                m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0} {1}", userInfo.FirstName, userInfo.LastName);
            }
            else
            {
                m_log.ErrorFormat(
                    "[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}",
                    userInfo.FirstName, userInfo.LastName, reportedException.Message);
            }
        }

        /// <summary>
        /// Get user information for the given name.
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="pass">User password</param>
        /// <returns></returns>
        protected UserAccount GetUserInfo(string firstName, string lastName, string pass)
        {
            UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName);
            if (null == account)
            {
                m_log.ErrorFormat(
                    "[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}",
                    firstName, lastName);
                return null;
            }

            try
            {
                string encpass = Util.Md5Hash(pass);
                if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty)
                {
                    return account;
                }
                else
                {
                    m_log.ErrorFormat(
                        "[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect.  Please try again.",
                        firstName, lastName);
                    return null;
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e.Message);
                return null;
            }
        }

        /// <summary>
        /// Notify the client of loaded nodes if they are logged in
        /// </summary>
        /// <param name="loadedNodes">Can be empty.  In which case, nothing happens</param>
        private void UpdateClientWithLoadedNodes(UserAccount userInfo, List<InventoryNodeBase> loadedNodes)
        {
            if (loadedNodes.Count == 0)
                return;

            foreach (Scene scene in m_scenes.Values)
            {
                ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID);

                if (user != null && !user.IsChildAgent)
                {
                    foreach (InventoryNodeBase node in loadedNodes)
                    {
//                        m_log.DebugFormat(
//                            "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}",
//                            user.Name, node.Name);

                        user.ControllingClient.SendBulkUpdateInventory(node);
                    }

                    break;
                }
            }
        }

        /// <summary>
        /// Check if the given user is present in any of the scenes.
        /// </summary>
        /// <param name="userId">The user to check</param>
        /// <returns>true if the user is in any of the scenes, false otherwise</returns>
        protected bool CheckPresence(UUID userId)
        {
            if (DisablePresenceChecks)
                return true;

            foreach (Scene scene in m_scenes.Values)
            {
                ScenePresence p;
                if ((p = scene.GetScenePresence(userId)) != null)
                {
                    p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false);
                    return true;
                }
            }

            return false;
        }
    }
}


text:
package it.cnr.isti.zigbee.eh.cluster.glue.general;

import it.cnr.isti.zigbee.ha.cluster.glue.Cluster;
import it.cnr.isti.zigbee.zcl.library.api.core.Attribute;

/**
 *
 * @author Giancarlo Riolo
 * @version $LastChangedRevision: 799 $ ($LastChangedDate: 2013-08-06 18:00:05 +0200 (mar, 06 ago 2013) $)
 *
 */
public interface MeterIdentification extends Cluster {

	public Attribute getZCLVersion();

}


text:
from sklearn.neighbors import NearestNeighbors

def get_distance(pt1, pt2):
    """ Finds the distance between two points. """
    x1 = pt1[0]
    y1 = pt1[1]
    x2 = pt2[0]
    y2 = pt2[1]
    return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** (1 / 2)

class Si():
    """ Contains the location of the Si atom, as well as each of the
        three rings surrounding it. Objects do not automatically calculate
        their locations if you do not tell them to. NOTE: The main
        functionality is done in nanometers.  Pixel locations are held on to so
        they can be easy to grab, but, if you start calling complex methods
        with pixel dimensions, you're going to have a bad time. """

    """ Public Methods """

    def __init__(self, x, y, z, unit):
        """ Constructor """
        if unit == "nm":
            self._nm_location = [x, y, z]
            self._pixel_location = [0, 0, 0]
        else:
            self._pixel_location = [x, y, z]
            self._nm_location = [0, 0, 0]
        self._rings = []
        self._hole_dist = 0  # dist 2 nearest hole, asnd later than constructed
        self._d1 = 0
        self._d2 = 0
        self._d3 = 0

    def _findClosestThree(self, ring_list, x_max, y_max, edge_buffer):
        if self.is_edge(x_max, y_max, edge_buffer):
            return

        ring_pos = []

        for ring in ring_list:
            ring_pos.append(ring.get_nm_location())

        nearest = NearestNeighbors(n_neighbors=3, algorithm='ball_tree').fit(ring_pos)
        dist, ind = nearest.kneighbors([self.get_nm_location()])
        for i in range(len(ind[0])):
            self._rings.append(ring_list[ind[0][i]])

    def find_rings(self, ring_list, x_max, y_max, edge_buffer):
        """ Finds the three rings bordering this Si atom, and stores
            them in self._rings.
        self._findFirst(ring_list, x_max, y_max, edge_buffer)
        print("1st ring found!")
        if (len(self.get_rings()) == 1):
            self._findSecond(ring_list, x_max, y_max, edge_buffer)
        if (len(self.get_rings()) == 2):
            self._findThird(ring_list, x_max, y_max, edge_buffer)
        print("size: ", len(self._rings))"""
        self._findClosestThree(ring_list, x_max, y_max, edge_buffer)

    def get_nm_location(self):
        """ Returns the location in (x, y, z) form. Units are nm. """
        return self._nm_location

    def get_pix_location(self):
        """ Returns the location in (x, y, z) form. Units are Pixels"""
        return self._location

    def find_nm_location(self, nm_dim, im_width, im_height):
        """ Finds the coordinates in nm when the pixel coordinates are
        known. """
        scale = (nm_dim[0] / im_width)
        for i in range(3):
            self._nm_location[i] = scale * self._pixels_location[i]

    def find_pix_location(self, nm_dim, im_width, im_height):
        """ Finds the coordinates in pixels when the nm coordinates are
        known. """
        scale = (im_width / nm_dim[0])
        for i in range(3):
            self._pixel_location[i] = scale * self._location[i]

    def get_rings(self):
        """ Returns the list of rings bordering the atom. """
        return self._rings

    def is_edge(self, max_x, max_y, edge_buffer):
        """ Determines if this Si atom is on the edge of the image
            returns true if so, false otherwise. """
        x = self.get_nm_location()[0]
        y = self.get_nm_location()[1]
        d = edge_buffer
        return x < d or x > max_x - d or y < d or y > max_y - d

    def assign_hole_dist(self, hole_dist):
        self._hole_dist = hole_dist

    def get_hole_dist(self):
        return self._hole_dist

    """ Private Methods """

    def _findFirst(self, ring_list, x_max, y_max, edge_buffer):
        """ Finds the closest ring center to the atom. If there are
            equidistant centers, puts all into self._rings. """
        # Excludes any Si atoms that are included as an edge case
        if self.is_edge(x_max, y_max, edge_buffer):
            return

        # Sets an arbitrary number as the first distance. This number
        # is used because it will be bigger than any distance
        # calculated.
        distance = 100000000000000000000
        answers = []
        for i in range(len(ring_list)):
            c1 = ring_list[i].get_nm_location()
            c2 = self.get_nm_location()

            # Checks if the calculate distance is less than the current
            # smallest distance. If so, resets the answer list and adds
            # the newest ring.
            if get_distance(c1, c2) < distance:
                answers = []
                answers.append(ring_list[i])
                distance = get_distance(c1, c2)
            if get_distance(c1, c2) == distance:
                answers.append(ring_list[i])
            for ring in answers:
                self._rings.append(ring)
                # print(len(self._rings))
                ring.set_atom(self)
            self._d1 = distance

    def _findSecond(self, ring_list, x_max, y_max, edge_buffer):
        """ Finds the second closest ring center to the atom. If there
            are equidistant centers, puts all into self._rings. """
        if self.is_edge(x_max, y_max, edge_buffer):
            return
        distance = 100000000000000000000
        answers = []
        for i in range(len(ring_list)):
            c1 = ring_list[i].get_nm_location()
            c2 = self.get_nm_location()
            dist_2 = get_distance(c1, c2)
            if dist_2 < distance and dist_2 > self._d1:
                answers = []
                answers.append(ring_list[i])
                distance = dist_2
            if dist_2 == distance and dist_2 > self._d1:
                answers.append(ring_list[i])
            for ring in answers:
                self._rings.append(ring)
                ring.set_atom(self)
            self._d2 = distance

    def _findThird(self, ring_list, x_max, y_max, edge_buffer):
        """ Finds the second closest ring center to the atom. """
        if self.is_edge(x_max, y_max, edge_buffer):
            return
        distance = 100000000000000000000
        answers = []
        for i in range(len(ring_list)):
            c1 = ring_list[i].get_nm_location()
            c2 = self.get_nm_location()
            dist_2 = get_distance(c1, c2)
            if dist_2 < distance and dist_2 > self._d2:
                answers = []
                answers.append(ring_list[i])
                distance = dist_2
            if dist_2 == distance and dist_2 > self._d2:
                answers.append(ring_list[i])
            for ring in answers:
                self._rings.append(ring)
                ring.set_atom(self)
            self._d3 = distance

class ring_center():
    """ Contains the location of the ring center, and the type of ring
        (number of members). Objects do not automatically calculate their
        locations if you do not tell them to. NOTE: The main functionality is
        done in nanometers.  Pixel locations are held on to so they can be easy
        to grab, but, if you start calling complex methods with pixel
        dimensions, you're going to have a bad time. """

    def __init__(self, ring_type, x, y, z, unit):
        """ Constructor. """
        self._ring_type = ring_type
        if unit == "nm":
            self._nm_location = [x, y, z]
            self._pixel_location = [0, 0, 0]
        else:
            self._nm_location = [0, 0, 0]
            self._pixel_location = [x, y, z]
        self._atoms = []

    def get_nm_location(self):
        """ Returns the location in (x, y, z) form. Units are nm. """
        return self._nm_location

    def get_pix_location(self):
        """ Returns the location in (x, y, z) form. Units are Pixels"""
        return self._location

    def find_nm_location(self, nm_dim, im_width, im_height):
        """ Finds the coordinates in nm when the pixel coordinates are
        known. """
        scale = (nm_dim[0] / im_width)
        for i in range(3):
            self._nm_location[i] = scale * self._pixels_location[i]

    def find_pix_location(self, nm_dim, im_width, im_height):
        """ Finds the coordinates in pixels when the nm coordinates are
        known. """
        scale = (im_width / nm_dim[0])
        for i in range(3):
            self._pixel_location[i] = scale * self._location[i]

    def change_location(self, x, y, z, unit, nm_dim, im_width, im_height):
        """ Changes the coordinates of the center, and finds the coordinates in
        the other unit. """
        if unit == "nm":
            self._nm_location = [x, y, z]
            self.find_pix_location(nm_dim, im_width, im_height)
        else:
            self._pixel_location = [x, y, z]
            self.find_nm_location(nm_dim, im_width, im_height)

    def get_type(self):
        """returns type of ring"""
        return self._ring_type

    def set_atom(self, atom):
        """ Puts an atom into self._atoms. """
        self._atoms.append(atom)

    def get_atoms(self):
        """ Returns the atom list """
        return self._atoms

    def remove(self, index):
        """ Removes an atom from the atom list BY INDEX """
        del self._atoms[index]

class STM():
    """ A class to describe the STM image. Includes information like filename,
    Image Dimensions (pixels), sample dimensions (nm), scale, number of holes,
    and coordinates of those holes."""

    def __init__(self, filename, im_dim, sample_dim, num_holes):
        """ Constructor. """
        self._filename = filename
        self._im_dim = im_dim  # [image width, image height] (pixels)
        self._sample_dim = sample_dim  # [sample width, sample height] (nm)
        self._scale = im_dim[0] / sample_dim[0]  # ratio pixels/nm
        self._num_holes = num_holes
        self._hole_coords = []

    def get_filename(self):
        return self._filename

    def get_im_dim(self):
        return self._im_dim

    def get_sample_dim(self):
        return self._sample_dim

    def get_scale(self):
        return self._scale

    def get_num_holes(self):
        return self._num_holes

    def get_hole_coords(self):
        return self._hole_coords

def main():
    return

main()


text:
package com.gitblit.wicket.pages;

import java.util.List;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.panel.Fragment;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;

import com.gitblit.models.UserModel;
import com.gitblit.servlet.RawServlet;
import com.gitblit.utils.BugtraqProcessor;
import com.gitblit.utils.JGitUtils;
import com.gitblit.utils.StringUtils;
import com.gitblit.wicket.CacheControl;
import com.gitblit.wicket.GitBlitWebSession;
import com.gitblit.wicket.CacheControl.LastModified;
import com.gitblit.wicket.MarkupProcessor;
import com.gitblit.wicket.MarkupProcessor.MarkupDocument;
import com.gitblit.wicket.MarkupProcessor.MarkupSyntax;
import com.gitblit.wicket.WicketUtils;

@CacheControl(LastModified.BOOT)
public class DocPage extends RepositoryPage {

	public DocPage(PageParameters params) {
		super(params);

		final String path = WicketUtils.getPath(params).replace("%2f", "/").replace("%2F", "/");
		MarkupProcessor processor = new MarkupProcessor(app().settings(), app().xssFilter());
		UserModel currentUser = (GitBlitWebSession.get().getUser() != null) ? GitBlitWebSession.get().getUser() : UserModel.ANONYMOUS;
		final boolean userCanEdit = currentUser.canEdit(getRepositoryModel());

		Repository r = getRepository();
		RevCommit commit = JGitUtils.getCommit(r, objectId);
		if (commit == null) {
			setResponsePage(NoDocsPage.class, params);
			return;
		}

		String [] encodings = getEncodings();

		// Read raw markup content and transform it to html
		String documentPath = path;
		String markupText = JGitUtils.getStringContent(r, commit.getTree(), path, encodings);

		// Hunt for document
		if (StringUtils.isEmpty(markupText)) {
			String name = StringUtils.stripFileExtension(path);

			List<String> docExtensions = processor.getAllExtensions();
			for (String ext : docExtensions) {
				String checkName = name + "." + ext;
				markupText = JGitUtils.getStringContent(r, commit.getTree(), checkName, encodings);
				if (!StringUtils.isEmpty(markupText)) {
					// found it
					documentPath = path;
					break;
				}
			}
		}

		if (markupText == null) {
			markupText = "";
		}

		BugtraqProcessor bugtraq = new BugtraqProcessor(app().settings());
		markupText = bugtraq.processText(getRepository(), repositoryName, markupText);

		Fragment fragment;
		MarkupDocument markupDoc = processor.parse(repositoryName, getBestCommitId(commit), documentPath, markupText);
		if (MarkupSyntax.PLAIN.equals(markupDoc.syntax)) {
			fragment = new Fragment("doc", "plainContent", this);
		} else {
			fragment = new Fragment("doc", "markupContent", this);
		}

		// document page links
		fragment.add(new BookmarkablePageLink<Void>("editLink", EditFilePage.class,
				WicketUtils.newPathParameter(repositoryName, objectId, documentPath))
				.setEnabled(userCanEdit));
		fragment.add(new BookmarkablePageLink<Void>("blameLink", BlamePage.class,
				WicketUtils.newPathParameter(repositoryName, objectId, documentPath)));
		fragment.add(new BookmarkablePageLink<Void>("historyLink", HistoryPage.class,
				WicketUtils.newPathParameter(repositoryName, objectId, documentPath)));
		String rawUrl = RawServlet.asLink(getContextUrl(), repositoryName, objectId, documentPath);
		fragment.add(new ExternalLink("rawLink", rawUrl));

		fragment.add(new Label("content", markupDoc.html).setEscapeModelStrings(false));
		add(fragment);
	}

	@Override
	protected String getPageName() {
		return getString("gb.docs");
	}

	@Override
	protected boolean isCommitPage() {
		return true;
	}

	@Override
	protected Class<? extends BasePage> getRepoNavPageClass() {
		return DocsPage.class;
	}
}


text:
#include <aws/customer-profiles/model/GetIntegrationResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::CustomerProfiles::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

GetIntegrationResult::GetIntegrationResult()
{
}

GetIntegrationResult::GetIntegrationResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

GetIntegrationResult& GetIntegrationResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("DomainName"))
  {
    m_domainName = jsonValue.GetString("DomainName");

  }

  if(jsonValue.ValueExists("Uri"))
  {
    m_uri = jsonValue.GetString("Uri");

  }

  if(jsonValue.ValueExists("ObjectTypeName"))
  {
    m_objectTypeName = jsonValue.GetString("ObjectTypeName");

  }

  if(jsonValue.ValueExists("CreatedAt"))
  {
    m_createdAt = jsonValue.GetDouble("CreatedAt");

  }

  if(jsonValue.ValueExists("LastUpdatedAt"))
  {
    m_lastUpdatedAt = jsonValue.GetDouble("LastUpdatedAt");

  }

  if(jsonValue.ValueExists("Tags"))
  {
    Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("Tags").GetAllObjects();
    for(auto& tagsItem : tagsJsonMap)
    {
      m_tags[tagsItem.first] = tagsItem.second.AsString();
    }
  }

  return *this;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
    <bean id="completePaymentActionAPI" class="org.dspace.workflow.actions.processingaction.CompletePaymentAction"/>
    <bean id="finalPaymentActionAPI" class="org.dspace.workflow.actions.processingaction.FinalPaymentAction"/>
    <bean id="dryadAcceptRejectEditActionAPI" class="org.dspace.workflow.actions.processingaction.EditMetadataAction" scope="prototype"/>
    <bean id="reviewActionAPI" class="org.dspace.workflow.actions.processingaction.DryadReviewAction"/>
    <bean id="pendingDeleteAPI" class="org.dspace.workflow.actions.processingaction.DryadPendingDeleteAction"/>
    <bean id="requiresReviewActionAPI" class="org.dspace.workflow.actions.processingaction.ReviewRequiredAction"/>
    <bean id="assignOriginalSubmitterActionAPI" class="org.dspace.workflow.actions.userassignment.AssignOriginalSubmitterAction" scope="prototype"/>
    <bean id="noUserSelectionActionAPI" class="org.dspace.workflow.actions.userassignment.NoUserSelectionAction" scope="prototype"/>
    <bean id="claimActionAPI" class="org.dspace.workflow.actions.userassignment.ClaimAction" scope="prototype"/>

    <bean id="registerPendingPublicationActionAPI" class="org.dspace.workflow.actions.processingaction.RegisterPendingPublicationAction" scope="prototype"/>
    <bean id="afterPublicationActionAPI" class="org.dspace.workflow.actions.processingaction.AfterPublicationAction" scope="prototype"/>

    <bean id="reAuthorizationPaymentActionAPI" class="org.dspace.workflow.actions.processingaction.ReAuthorizationPaymentAction" scope="prototype"/>

    <bean id="dryadAcceptEditRejectAction" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="dryadAcceptEditRejectAction"/>

        <property name="processingAction" ref="dryadAcceptRejectEditActionAPI"/>
        <property name="requiresUI" value="true"/>
    </bean>

    <bean id="reviewAction" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="reviewAction"/>

        <property name="processingAction" ref="reviewActionAPI"/>
        <property name="requiresUI" value="true"/>
    </bean>
    <bean id="finalPaymentAction" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="finalPaymentAction"/>

        <property name="processingAction" ref="finalPaymentActionAPI"/>
        <property name="requiresUI" value="false"/>
    </bean>

    <bean id="completePaymentAction" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="completePaymentAction"/>

        <property name="processingAction" ref="completePaymentActionAPI"/>
        <property name="requiresUI" value="false"/>
    </bean>

    <bean id="pendingdelete" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="pendingdelete"/>

        <property name="processingAction" ref="pendingDeleteAPI"/>
        <property name="requiresUI" value="false"/>
    </bean>

    <bean id="requiresReviewAction" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="requiresReviewAction"/>

        <property name="processingAction" ref="requiresReviewActionAPI"/>
        <property name="requiresUI" value="false"/>
    </bean>

    <bean id="registerPendingPublicationAction" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="registerPendingPublicationAction"/>

        <property name="processingAction" ref="registerPendingPublicationActionAPI"/>
        <property name="requiresUI" value="false"/>
    </bean>

    <bean id="afterPublicationAction" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="afterPublicationAction"/>

        <property name="processingAction" ref="afterPublicationActionAPI"/>
        <property name="requiresUI" value="true"/>
    </bean>

    <!--User selection actions-->
    <bean id="assignOriginalSubmitterAction" class="org.dspace.workflow.actions.UserSelectionActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="assignOriginalSubmitterAction"/>

        <property name="processingAction" ref="assignOriginalSubmitterActionAPI"/>
        <property name="requiresUI" value="false"/>
    </bean>

    <bean id="noUserSelectionAction" class="org.dspace.workflow.actions.UserSelectionActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="noUserSelectionAction"/>

        <property name="processingAction" ref="noUserSelectionActionAPI"/>
        <property name="requiresUI" value="false"/>
    </bean>

    <bean id="claimAction" class="org.dspace.workflow.actions.UserSelectionActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="claimAction"/>

        <property name="processingAction" ref="claimActionAPI"/>
        <property name="requiresUI" value="true"/>
    </bean>

    <bean id="reAuthorizationPaymentAction" class="org.dspace.workflow.actions.WorkflowActionConfig" scope="prototype">
        <constructor-arg type="java.lang.String" value="reAuthorizationPaymentAction"/>

        <property name="processingAction" ref="reAuthorizationPaymentActionAPI"/>
        <property name="requiresUI" value="true"/>
    </bean>

</beans>


text:
package ru.vyukov.bakapa.dump;

import ru.vyukov.bakapa.dto.backups.target.impl.DatabaseBackupOptionsDTO;
import ru.vyukov.bakapa.dto.backups.target.impl.DatabaseBackupTargetDTO;
import ru.vyukov.bakapa.dto.backups.target.impl.DatabaseLocationDTO;
import ru.vyukov.bakapa.dto.backups.target.impl.DatabaseUserCredentialsDTO;

/**
 * @author Oleg Vyukov
 */
public abstract class AbstractDatabaseDumpWrapperUtil {

    protected final DatabaseUserCredentialsDTO userCredentials;
    protected final DatabaseLocationDTO location;
    protected final DatabaseBackupOptionsDTO options;

    public AbstractDatabaseDumpWrapperUtil(DatabaseBackupTargetDTO databaseBackupTarget) {
        options = databaseBackupTarget.getOptions();
        location = databaseBackupTarget.getLocation();
        userCredentials = databaseBackupTarget.getUserCredentials();
    }
}


text:
layout: default
title: ICBES'17 - Results
meta: The search results of ICBES
keyword: biomedical engineering conference, biomedical conference, biosystems conference, biomaterials conference, biomechanics conference, biomechatronics conference, biosensors conference, telemedicine conference, robotics conference, biomedical engineering, biomedical, biosystems, biomaterials, biomechanics, biomechatronics, biosensors, telemedicine, robotics
---

Search Results

    <gcse:searchresults-only></gcse:searchresults-only>


text:
define(['altair/facades/declare',
        'altair/Lifecycle'], function (declare, Lifecycle) {

    return declare([Lifecycle], {

        foundry:    null,
        _cartridge: null,
        alias:      '', //we can give our database connections an alias so they are easy to lookup later
        constructor: function (cartridge, options) {

            this._cartridge = cartridge;
            this.options = options;
            this.foundry = (options && options.foundry) ? options.foundry : null;

        },

        startup: function (options) {

            var _options = options || this.options || {};

            //was this connection given an alias?
            this.alias    = _options.alias || '';

            if(!this.alias) {
                this.deferred = new this.Deferred();
                this.deferred.reject(new Error('please give your database adapter a nickname.'));

            }

            return this.inherited(arguments);
        }

    });

});


text:
'use strict';

function sanicUnshift(array, ...el) {
	if (!(array instanceof Array)) {
		throw new TypeError('array is not an Array');
	}

	let a = [];
	let i = array.length;

	a.length = array.length + el.length;

	for (; i > 0; i--) {
		a[i + el.length] = array[i];
	}

	i = el.length;

	for (; i > 0; i--) {
		a[i] = el[i];
	}

	array = [];

	return array.length;
}

module.exports = function(computeSuite, fileWriter, suiteOptions) {
	const little = new Array(10).fill(1);
	const medium = new Array(1000).fill(1);
	const big = new Array(1000000).fill(1);

	if (fileWriter) fileWriter.writeTableElement('Keep elements with values 0');
	little.unshift(1);
	console.log(little);
	little.shift();
	sanicUnshift(little, 1);
	console.log(little, little.length);
	little.shift();

	console.log(`\t10 elements`);
	computeSuite()
		.add('Array.prototype.unshift()', function() {
			little.unshift(1);
			little.shift();
		})
		.add('Sanic unshift()', function() {
			sanicUnshift(little, 1);
			little.shift();
		})
		.run(suiteOptions);

	console.log(`\t1k elements`);
	computeSuite()
		.add('Array.prototype.unshift()', function() {
			medium.unshift(1);
			medium.shift();
		})
		.add('Sanic unshift()', function() {
			sanicUnshift(medium, 1);
			medium.shift();
		})
		.run(suiteOptions);

	console.log(`\t1M elements`);
	computeSuite()
		.add('Array.prototype.unshift()', function() {
			big.unshift(1);
			big.shift();
		})
		.add('Sanic unshift()', function() {
			sanicUnshift(big, 1);
			big.shift();
		})
		.run(suiteOptions);
};


text:
from msrest.paging import Paged

class ExpressRouteCircuitPeeringPaged(Paged):
    """
    A paging container for iterating over a list of :class:`ExpressRouteCircuitPeering <azure.mgmt.network.v2017_08_01.models.ExpressRouteCircuitPeering>` object
    """

    _attribute_map = {
        'next_link': {'key': 'nextLink', 'type': 'str'},
        'current_page': {'key': 'value', 'type': '[ExpressRouteCircuitPeering]'}
    }

    def __init__(self, *args, **kwargs):

        super(ExpressRouteCircuitPeeringPaged, self).__init__(*args, **kwargs)