text:
"""Generic Node base class for all workers that run on hosts."""

import inspect
import os
import random

from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_service import loopingcall
from oslo_service import service
from oslo_service import wsgi
from oslo_utils import importutils
osprofiler_initializer = importutils.try_import('osprofiler.initializer')
profiler = importutils.try_import('osprofiler.profiler')
profiler_opts = importutils.try_import('osprofiler.opts')

from cinder.backup import rpcapi as backup_rpcapi
from cinder.common import constants
from cinder import context
from cinder import coordination
from cinder import exception
from cinder.i18n import _, _LE, _LI, _LW
from cinder import objects
from cinder.objects import base as objects_base
from cinder.objects import fields
from cinder import rpc
from cinder.scheduler import rpcapi as scheduler_rpcapi
from cinder import version
from cinder.volume import rpcapi as volume_rpcapi
from cinder.volume import utils as vol_utils

LOG = logging.getLogger(__name__)

service_opts = [
    cfg.IntOpt('report_interval',
               default=10,
               help='Interval, in seconds, between nodes reporting state '
                    'to datastore'),
    cfg.IntOpt('periodic_interval',
               default=60,
               help='Interval, in seconds, between running periodic tasks'),
    cfg.IntOpt('periodic_fuzzy_delay',
               default=60,
               help='Range, in seconds, to randomly delay when starting the'
                    ' periodic task scheduler to reduce stampeding.'
                    ' (Disable by setting to 0)'),
    cfg.StrOpt('osapi_volume_listen',
               default="0.0.0.0",
               help='IP address on which OpenStack Volume API listens'),
    cfg.PortOpt('osapi_volume_listen_port',
                default=8776,
                help='Port on which OpenStack Volume API listens'),
    cfg.IntOpt('osapi_volume_workers',
               help='Number of workers for OpenStack Volume API service. '
                    'The default is equal to the number of CPUs available.'),
    cfg.BoolOpt('osapi_volume_use_ssl',
                default=False,
                help='Wraps the socket in a SSL context if True is set. '
                     'A certificate file and key file must be specified.'), ]

CONF = cfg.CONF
CONF.register_opts(service_opts)
if profiler_opts:
    profiler_opts.set_defaults(CONF)

def setup_profiler(binary, host):
    if (osprofiler_initializer is None or
            profiler is None or
            profiler_opts is None):
        LOG.debug('osprofiler is not present')
        return

    if CONF.profiler.enabled:
        osprofiler_initializer.init_from_conf(
            conf=CONF,
            context=context.get_admin_context().to_dict(),
            project="cinder",
            service=binary,
            host=host
        )
        LOG.warning(
            _LW("OSProfiler is enabled.\nIt means that person who knows "
                "any of hmac_keys that are specified in "
                "/etc/cinder/cinder.conf can trace his requests. \n"
                "In real life only operator can read this file so there "
                "is no security issue. Note that even if person can "
                "trigger profiler, only admin user can retrieve trace "
                "information.\n"
                "To disable OSProfiler set in cinder.conf:\n"
                "[profiler]\nenabled=false"))

class Service(service.Service):
    """Service object for binaries running on hosts.

    A service takes a manager and enables rpc by listening to queues based
    on topic. It also periodically runs tasks on the manager and reports
    it state to the database services table.
    """
    # Make service_id a class attribute so it can be used for clean up
    service_id = None

    def __init__(self, host, binary, topic, manager, report_interval=None,
                 periodic_interval=None, periodic_fuzzy_delay=None,
                 service_name=None, coordination=False, cluster=None, *args,
                 **kwargs):
        super(Service, self).__init__()

        if not rpc.initialized():
            rpc.init(CONF)

        self.cluster = cluster
        self.host = host
        self.binary = binary
        self.topic = topic
        self.manager_class_name = manager
        self.coordination = coordination
        manager_class = importutils.import_class(self.manager_class_name)
        if CONF.profiler.enabled:
            manager_class = profiler.trace_cls("rpc")(manager_class)

        self.service = None

        # NOTE(geguileo): We need to create the Service DB entry before we
        # create the manager, otherwise capped versions for serializer and rpc
        # client would use existing DB entries not including us, which could
        # result in us using None (if it's the first time the service is run)
        # or an old version (if this is a normal upgrade of a single service).
        ctxt = context.get_admin_context()
        self.is_upgrading_to_n = self.is_svc_upgrading_to_n(binary)
        try:
            service_ref = objects.Service.get_by_args(ctxt, host, binary)
            service_ref.rpc_current_version = manager_class.RPC_API_VERSION
            obj_version = objects_base.OBJ_VERSIONS.get_current()
            service_ref.object_current_version = obj_version
            # TODO(geguileo): In O we can remove the service upgrading part on
            # the next equation, because by then all our services will be
            # properly setting the cluster during volume migrations since
            # they'll have the new Volume ORM model.  But until then we can
            # only set the cluster in the DB and pass added_to_cluster to
            # init_host when we have completed the rolling upgrade from M to N.

            # added_to_cluster attribute marks when we consider that we have
            # just added a host to a cluster so we can include resources into
            # that cluster.  We consider that we have added the host when we
            # didn't have data in the cluster DB field and our current
            # configuration has a cluster value.  We don't want to do anything
            # automatic if the cluster is changed, in those cases we'll want
            # to use cinder manage command and to it manually.
            self.added_to_cluster = (not service_ref.cluster_name and cluster
                                     and not self.is_upgrading_to_n)

            # TODO(geguileo): In O - Remove self.is_upgrading_to_n part
            if (service_ref.cluster_name != cluster and
                    not self.is_upgrading_to_n):
                LOG.info(_LI('This service has been moved from cluster '
                             '%(cluster_svc)s to %(cluster_cfg)s. Resources '
                             'will %(opt_no)sbe moved to the new cluster'),
                         {'cluster_svc': service_ref.cluster_name,
                          'cluster_cfg': cluster,
                          'opt_no': '' if self.added_to_cluster else 'NO '})

            if self.added_to_cluster:
                # We pass copy service's disable status in the cluster if we
                # have to create it.
                self._ensure_cluster_exists(ctxt, service_ref)
                service_ref.cluster_name = cluster
            service_ref.save()
            Service.service_id = service_ref.id
        except exception.NotFound:
            # We don't want to include cluster information on the service or
            # create the cluster entry if we are upgrading.
            self._create_service_ref(ctxt, manager_class.RPC_API_VERSION)
            # TODO(geguileo): In O set added_to_cluster to True
            # We don't want to include resources in the cluster during the
            # start while we are still doing the rolling upgrade.
            self.added_to_cluster = not self.is_upgrading_to_n

        self.manager = manager_class(host=self.host,
                                     cluster=self.cluster,
                                     service_name=service_name,
                                     *args, **kwargs)
        self.report_interval = report_interval
        self.periodic_interval = periodic_interval
        self.periodic_fuzzy_delay = periodic_fuzzy_delay
        self.basic_config_check()
        self.saved_args, self.saved_kwargs = args, kwargs
        self.timers = []

        setup_profiler(binary, host)
        self.rpcserver = None
        self.backend_rpcserver = None
        self.cluster_rpcserver = None

    # TODO(geguileo): Remove method in O since it will no longer be used.
    @staticmethod
    def is_svc_upgrading_to_n(binary):
        """Given an RPC API class determine if the service is upgrading."""
        rpcapis = {'cinder-scheduler': scheduler_rpcapi.SchedulerAPI,
                   'cinder-volume': volume_rpcapi.VolumeAPI,
                   'cinder-backup': backup_rpcapi.BackupAPI}
        rpc_api = rpcapis[binary]
        # If we are pinned to 1.3, then we are upgrading from M to N
        return rpc_api.determine_obj_version_cap() == '1.3'

    def start(self):
        version_string = version.version_string()
        LOG.info(_LI('Starting %(topic)s node (version %(version_string)s)'),
                 {'topic': self.topic, 'version_string': version_string})
        self.model_disconnected = False

        if self.coordination:
            coordination.COORDINATOR.start()

        self.manager.init_host(added_to_cluster=self.added_to_cluster,
                               service_id=Service.service_id)

        LOG.debug("Creating RPC server for service %s", self.topic)

        ctxt = context.get_admin_context()
        endpoints = [self.manager]
        endpoints.extend(self.manager.additional_endpoints)
        obj_version_cap = objects.Service.get_minimum_obj_version(ctxt)
        LOG.debug("Pinning object versions for RPC server serializer to %s",
                  obj_version_cap)
        serializer = objects_base.CinderObjectSerializer(obj_version_cap)

        target = messaging.Target(topic=self.topic, server=self.host)
        self.rpcserver = rpc.get_server(target, endpoints, serializer)
        self.rpcserver.start()

        # NOTE(dulek): Kids, don't do that at home. We're relying here on
        # oslo.messaging implementation details to keep backward compatibility
        # with pre-Ocata services. This will not matter once we drop
        # compatibility with them.
        if self.topic == constants.VOLUME_TOPIC:
            target = messaging.Target(
                topic='%(topic)s.%(host)s' % {'topic': self.topic,
                                              'host': self.host},
                server=vol_utils.extract_host(self.host, 'host'))
            self.backend_rpcserver = rpc.get_server(target, endpoints,
                                                    serializer)
            self.backend_rpcserver.start()

        # TODO(geguileo): In O - Remove the is_svc_upgrading_to_n part
        if self.cluster and not self.is_svc_upgrading_to_n(self.binary):
            LOG.info(_LI('Starting %(topic)s cluster %(cluster)s (version '
                         '%(version)s)'),
                     {'topic': self.topic, 'version': version_string,
                      'cluster': self.cluster})
            target = messaging.Target(
                topic='%s.%s' % (self.topic, self.cluster),
                server=vol_utils.extract_host(self.cluster, 'host'))
            serializer = objects_base.CinderObjectSerializer(obj_version_cap)
            self.cluster_rpcserver = rpc.get_server(target, endpoints,
                                                    serializer)
            self.cluster_rpcserver.start()

        self.manager.init_host_with_rpc()

        if self.report_interval:
            pulse = loopingcall.FixedIntervalLoopingCall(
                self.report_state)
            pulse.start(interval=self.report_interval,
                        initial_delay=self.report_interval)
            self.timers.append(pulse)

        if self.periodic_interval:
            if self.periodic_fuzzy_delay:
                initial_delay = random.randint(0, self.periodic_fuzzy_delay)
            else:
                initial_delay = None

            periodic = loopingcall.FixedIntervalLoopingCall(
                self.periodic_tasks)
            periodic.start(interval=self.periodic_interval,
                           initial_delay=initial_delay)
            self.timers.append(periodic)

    def basic_config_check(self):
        """Perform basic config checks before starting service."""
        # Make sure report interval is less than service down time
        if self.report_interval:
            if CONF.service_down_time <= self.report_interval:
                new_down_time = int(self.report_interval * 2.5)
                LOG.warning(
                    _LW("Report interval must be less than service down "
                        "time. Current config service_down_time: "
                        "%(service_down_time)s, report_interval for this: "
                        "service is: %(report_interval)s. Setting global "
                        "service_down_time to: %(new_down_time)s"),
                    {'service_down_time': CONF.service_down_time,
                     'report_interval': self.report_interval,
                     'new_down_time': new_down_time})
                CONF.set_override('service_down_time', new_down_time)

    def _ensure_cluster_exists(self, context, service):
        if self.cluster:
            try:
                cluster = objects.Cluster.get_by_id(context, None,
                                                    name=self.cluster,
                                                    binary=self.binary)
                # If the cluster already exists, then the service replication
                # fields must match those of the cluster unless the service
                # is in error status.
                error_states = (fields.ReplicationStatus.ERROR,
                                fields.ReplicationStatus.FAILOVER_ERROR)
                if service.replication_status not in error_states:
                    for attr in ('replication_status', 'active_backend_id',
                                 'frozen'):
                        if getattr(service, attr) != getattr(cluster, attr):
                            setattr(service, attr, getattr(cluster, attr))

            except exception.ClusterNotFound:
                # Since the cluster didn't exist, we copy replication fields
                # from the service.
                cluster = objects.Cluster(
                    context=context,
                    name=self.cluster,
                    binary=self.binary,
                    disabled=service.disabled,
                    replication_status=service.replication_status,
                    active_backend_id=service.active_backend_id,
                    frozen=service.frozen)
                try:
                    cluster.create()

                # Race condition occurred and another service created the
                # cluster, so we can continue as it already exists.
                except exception.ClusterExists:
                    pass

    def _create_service_ref(self, context, rpc_version=None):
        zone = CONF.storage_availability_zone
        kwargs = {
            'host': self.host,
            'binary': self.binary,
            'topic': self.topic,
            'report_count': 0,
            'availability_zone': zone,
            'rpc_current_version': rpc_version or self.manager.RPC_API_VERSION,
            'object_current_version': objects_base.OBJ_VERSIONS.get_current(),
        }
        # TODO(geguileo): In O unconditionally set cluster_name like above
        # If we are upgrading we have to ignore the cluster value
        if not self.is_upgrading_to_n:
            kwargs['cluster_name'] = self.cluster
        service_ref = objects.Service(context=context, **kwargs)
        service_ref.create()
        Service.service_id = service_ref.id
        # TODO(geguileo): In O unconditionally ensure that the cluster exists
        if not self.is_upgrading_to_n:
            self._ensure_cluster_exists(context, service_ref)
            # If we have updated the service_ref with replication data from
            # the cluster it will be saved.
            service_ref.save()

    def __getattr__(self, key):
        manager = self.__dict__.get('manager', None)
        return getattr(manager, key)

    @classmethod
    def create(cls, host=None, binary=None, topic=None, manager=None,
               report_interval=None, periodic_interval=None,
               periodic_fuzzy_delay=None, service_name=None,
               coordination=False, cluster=None):
        """Instantiates class and passes back application object.

        :param host: defaults to CONF.host
        :param binary: defaults to basename of executable
        :param topic: defaults to bin_name - 'cinder-' part
        :param manager: defaults to CONF.<topic>_manager
        :param report_interval: defaults to CONF.report_interval
        :param periodic_interval: defaults to CONF.periodic_interval
        :param periodic_fuzzy_delay: defaults to CONF.periodic_fuzzy_delay
        :param cluster: Defaults to None, as only some services will have it

        """
        if not host:
            host = CONF.host
        if not binary:
            binary = os.path.basename(inspect.stack()[-1][1])
        if not topic:
            topic = binary
        if not manager:
            subtopic = topic.rpartition('cinder-')[2]
            manager = CONF.get('%s_manager' % subtopic, None)
        if report_interval is None:
            report_interval = CONF.report_interval
        if periodic_interval is None:
            periodic_interval = CONF.periodic_interval
        if periodic_fuzzy_delay is None:
            periodic_fuzzy_delay = CONF.periodic_fuzzy_delay
        service_obj = cls(host, binary, topic, manager,
                          report_interval=report_interval,
                          periodic_interval=periodic_interval,
                          periodic_fuzzy_delay=periodic_fuzzy_delay,
                          service_name=service_name,
                          coordination=coordination,
                          cluster=cluster)

        return service_obj

    def stop(self):
        # Try to shut the connection down, but if we get any sort of
        # errors, go ahead and ignore them.. as we're shutting down anyway
        try:
            self.rpcserver.stop()
            if self.backend_rpcserver:
                self.backend_rpcserver.stop()
            if self.cluster_rpcserver:
                self.cluster_rpcserver.stop()
        except Exception:
            pass

        self.timers_skip = []
        for x in self.timers:
            try:
                x.stop()
            except Exception:
                self.timers_skip.append(x)

        if self.coordination:
            try:
                coordination.COORDINATOR.stop()
            except Exception:
                pass
        super(Service, self).stop(graceful=True)

    def wait(self):
        skip = getattr(self, 'timers_skip', [])
        for x in self.timers:
            if x not in skip:
                try:
                    x.wait()
                except Exception:
                    pass
        if self.rpcserver:
            self.rpcserver.wait()
        if self.backend_rpcserver:
            self.backend_rpcserver.wait()
        if self.cluster_rpcserver:
            self.cluster_rpcserver.wait()
        super(Service, self).wait()

    def periodic_tasks(self, raise_on_error=False):
        """Tasks to be run at a periodic interval."""
        ctxt = context.get_admin_context()
        self.manager.periodic_tasks(ctxt, raise_on_error=raise_on_error)

    def report_state(self):
        """Update the state of this service in the datastore."""
        if not self.manager.is_working():
            # NOTE(dulek): If manager reports a problem we're not sending
            # heartbeats - to indicate that service is actually down.
            LOG.error(_LE('Manager for service %(binary)s %(host)s is '
                          'reporting problems, not sending heartbeat. '
                          'Service will appear "down".'),
                      {'binary': self.binary,
                       'host': self.host})
            return

        ctxt = context.get_admin_context()
        zone = CONF.storage_availability_zone
        try:
            try:
                service_ref = objects.Service.get_by_id(ctxt,
                                                        Service.service_id)
            except exception.NotFound:
                LOG.debug('The service database object disappeared, '
                          'recreating it.')
                self._create_service_ref(ctxt)
                service_ref = objects.Service.get_by_id(ctxt,
                                                        Service.service_id)

            service_ref.report_count += 1
            if zone != service_ref.availability_zone:
                service_ref.availability_zone = zone

            service_ref.save()

            # TODO(termie): make this pattern be more elegant.
            if getattr(self, 'model_disconnected', False):
                self.model_disconnected = False
                LOG.error(_LE('Recovered model server connection!'))

        except db_exc.DBConnectionError:
            if not getattr(self, 'model_disconnected', False):
                self.model_disconnected = True
                LOG.exception(_LE('model server went away'))

        # NOTE(jsbryant) Other DB errors can happen in HA configurations.
        # such errors shouldn't kill this thread, so we handle them here.
        except db_exc.DBError:
            if not getattr(self, 'model_disconnected', False):
                self.model_disconnected = True
                LOG.exception(_LE('DBError encountered: '))

        except Exception:
            if not getattr(self, 'model_disconnected', False):
                self.model_disconnected = True
                LOG.exception(_LE('Exception encountered: '))

    def reset(self):
        self.manager.reset()
        super(Service, self).reset()

class WSGIService(service.ServiceBase):
    """Provides ability to launch API from a 'paste' configuration."""

    def __init__(self, name, loader=None):
        """Initialize, but do not start the WSGI server.

        :param name: The name of the WSGI server given to the loader.
        :param loader: Loads the WSGI application using the given name.
        :returns: None

        """
        self.name = name
        self.manager = self._get_manager()
        self.loader = loader or wsgi.Loader(CONF)
        self.app = self.loader.load_app(name)
        self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0")
        self.port = getattr(CONF, '%s_listen_port' % name, 0)
        self.use_ssl = getattr(CONF, '%s_use_ssl' % name, False)
        self.workers = (getattr(CONF, '%s_workers' % name, None) or
                        processutils.get_worker_count())
        if self.workers and self.workers < 1:
            worker_name = '%s_workers' % name
            msg = (_("%(worker_name)s value of %(workers)d is invalid, "
                     "must be greater than 0.") %
                   {'worker_name': worker_name,
                    'workers': self.workers})
            raise exception.InvalidInput(msg)
        setup_profiler(name, self.host)

        self.server = wsgi.Server(CONF,
                                  name,
                                  self.app,
                                  host=self.host,
                                  port=self.port,
                                  use_ssl=self.use_ssl)

    def _get_manager(self):
        """Initialize a Manager object appropriate for this service.

        Use the service name to look up a Manager subclass from the
        configuration and initialize an instance. If no class name
        is configured, just return None.

        :returns: a Manager instance, or None.

        """
        fl = '%s_manager' % self.name
        if fl not in CONF:
            return None

        manager_class_name = CONF.get(fl, None)
        if not manager_class_name:
            return None

        manager_class = importutils.import_class(manager_class_name)
        return manager_class()

    def start(self):
        """Start serving this service using loaded configuration.

        Also, retrieve updated port number in case '0' was passed in, which
        indicates a random port should be used.

        :returns: None

        """
        if self.manager:
            self.manager.init_host()
        self.server.start()
        self.port = self.server.port

    def stop(self):
        """Stop serving this API.

        :returns: None

        """
        self.server.stop()

    def wait(self):
        """Wait for the service to stop serving this API.

        :returns: None

        """
        self.server.wait()

    def reset(self):
        """Reset server greenpool size to default.

        :returns: None

        """
        self.server.reset()

def process_launcher():
    return service.ProcessLauncher(CONF)

# NOTE(vish): the global launcher is to maintain the existing
#             functionality of calling service.serve +
#             service.wait
_launcher = None

def serve(server, workers=None):
    global _launcher
    if _launcher:
        raise RuntimeError(_('serve() can only be called once'))

    _launcher = service.launch(CONF, server, workers=workers)

def wait():
    LOG.debug('Full set of CONF:')
    for flag in CONF:
        flag_get = CONF.get(flag, None)
        # hide flag contents from log if contains a password
        # should use secret flag when switch over to openstack-common
        if ("_password" in flag or "_key" in flag or
                (flag == "sql_connection" and
                    ("mysql:" in flag_get or "postgresql:" in flag_get))):
            LOG.debug('%s : FLAG SET ', flag)
        else:
            LOG.debug('%(flag)s : %(flag_get)s',
                      {'flag': flag, 'flag_get': flag_get})
    try:
        _launcher.wait()
    except KeyboardInterrupt:
        _launcher.stop()
    rpc.cleanup()

class Launcher(object):
    def __init__(self):
        self.launch_service = serve
        self.wait = wait

def get_launcher():
    # Note(lpetrut): ProcessLauncher uses green pipes which fail on Windows
    # due to missing support of non-blocking I/O pipes. For this reason, the
    # service must be spawned differently on Windows, using the ServiceLauncher
    # class instead.
    if os.name == 'nt':
        return Launcher()
    else:
        return process_launcher()


text:
using System;
using Server.Network;
using Server.Items;

namespace Server.Items
{
	public class RaedsGlory : WarCleaver
	{
		public override int LabelNumber{ get{ return 1075036; } } // Raed's Glory

		public override int InitMinHits{ get{ return 255; } }
		public override int InitMaxHits{ get{ return 255; } }

		[Constructable]
		public RaedsGlory()
		{
			ItemID = 0x2D23;
			Hue = 0x1E6;

			Attributes.BonusMana = 8;
			Attributes.SpellChanneling = 1;
			Attributes.WeaponSpeed = 20;

			WeaponAttributes.HitLeechHits = 40;
		}

		public RaedsGlory( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.WriteEncodedInt( 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadEncodedInt();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="horizontal"
        >
        <ImageView
            android:layout_width="36dp"
            android:layout_height="36dp"
            android:id="@+id/tuijian_icon"
            android:src="@mipmap/bg"
            android:layout_gravity="center_vertical"/>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="36dp"
            android:orientation="vertical"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center_vertical">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tuijian_name"
                android:textColor="@color/black"
                android:textSize="@dimen/tuijian_list_size"
                android:text="@string/content"
                />
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                >
                <TextView
                    android:id="@+id/dingyue_count"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:textSize="@dimen/tuijian_count_size"
                    android:text="@string/content"/>
                <TextView
                    android:id="@+id/tiezi_count"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dp"
                    android:textSize="@dimen/tuijian_count_size"
                    android:textColor="@color/baisiColor"
                    android:text="1231231"/>
            </LinearLayout>
        </LinearLayout>
        <TextView
            android:id="@+id/follow_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:paddingBottom="5dp"
            android:paddingTop="5dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="+关注"
            android:textSize="@dimen/tuijian_list_size"
            android:textColor="@color/baisiColor"
            android:background="@drawable/focuse_bg"/>
    </LinearLayout>
</LinearLayout>


text:
"""
Equivalencies between different kinds of units

"""

# -----------------------------------------------------------------------------
# Copyright (c) 2018, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the LICENSE file, distributed with this software.
# -----------------------------------------------------------------------------

from collections import OrderedDict

import numpy as np

from unyt.dimensions import (
    density,
    dimensionless,
    energy,
    flux,
    length,
    mass,
    number_density,
    rate,
    spatial_frequency,
    temperature,
    velocity,
)
from unyt.exceptions import InvalidUnitEquivalence

equivalence_registry = OrderedDict()

class _RegisteredEquivalence(type):
    def __init__(cls, name, b, d):
        type.__init__(cls, name, b, d)
        if hasattr(cls, "type_name"):
            equivalence_registry[cls.type_name] = cls

class Equivalence(metaclass=_RegisteredEquivalence):
    def __init__(self, in_place=False):
        self.in_place = in_place

    def convert(self, x, new_dims, **kwargs):
        if x.units.dimensions in self._dims and new_dims in self._dims:
            return self._convert(x, new_dims, **kwargs)
        else:
            raise InvalidUnitEquivalence(self, x.units, new_dims)

    def _get_out(self, x):
        if self.in_place:
            return x
        return None

class NumberDensityEquivalence(Equivalence):
    """Equivalence between mass and number density, given a mean molecular
    weight.

    Given a number density :math:`n`, the mass density :math:`\\rho` is:

    .. math::

      \\rho = \\mu m_{\\rm H} n

    And similarly

    .. math::

      n = \\rho (\\mu m_{\\rm H})^{-1}

    Parameters
    ----------
    mu : float
      The mean molecular weight. Defaults to 0.6 whcih is valid for fully
      ionized gas with primordial composition.

    Example
    -------
    >>> print(NumberDensityEquivalence())
    number density: density <-> number density
    >>> from unyt import Msun, pc
    >>> rho = 3*Msun/pc**3
    >>> rho.to_equivalent('cm**-3', 'number_density', mu=1.4)
    unyt_quantity(86.64869896, 'cm**(-3)')
    """

    type_name = "number_density"
    _dims = (density, number_density)

    def _convert(self, x, new_dims, mu=0.6):
        from unyt import physical_constants as pc

        if new_dims == number_density:
            return np.true_divide(x, mu * pc.mh, out=self._get_out(x))
        elif new_dims == density:
            return np.multiply(x, mu * pc.mh, out=self._get_out(x))

    def __str__(self):
        return "number density: density <-> number density"

class ThermalEquivalence(Equivalence):
    """Equivalence between temperature and energy via the Boltzmann constant

    Given a temperature :math:`T` in an absolute scale (e.g. Kelvin or
    Rankine), the equivalent thermal energy :math:`E` for that temperature is
    given by:

    .. math::

      E = k_B T

    And

    .. math::

      T = E/k_B

    Where :math:`k_B` is Boltzmann's constant.

    Example
    -------
    >>> print(ThermalEquivalence())
    thermal: temperature <-> energy
    >>> from unyt import Kelvin
    >>> temp = 1e6*Kelvin
    >>> temp.to_equivalent('keV', 'thermal')
    unyt_quantity(0.08617332, 'keV')
    """

    type_name = "thermal"
    _dims = (temperature, energy)

    def _convert(self, x, new_dims):
        from unyt import physical_constants as pc

        if new_dims == energy:
            return np.multiply(x, pc.kboltz, out=self._get_out(x))
        elif new_dims == temperature:
            return np.true_divide(x, pc.kboltz, out=self._get_out(x))

    def __str__(self):
        return "thermal: temperature <-> energy"

class MassEnergyEquivalence(Equivalence):
    """Equivalence between mass and energy in special relativity

    Given a body with mass :math:`m`, the self-energy :math:`E` of that mass is
    given by

    .. math::

      E = m c^2

    where :math:`c` is the speed of light.

    Example
    -------
    >>> print(MassEnergyEquivalence())
    mass_energy: mass <-> energy
    >>> from unyt import g
    >>> (3.5*g).to_equivalent('J', 'mass_energy')
    unyt_quantity(3.14564313e+14, 'J')

    """

    type_name = "mass_energy"
    _dims = (mass, energy)

    def _convert(self, x, new_dims):
        from unyt import physical_constants as pc

        if new_dims == energy:
            return np.multiply(x, pc.clight * pc.clight, out=self._get_out(x))
        elif new_dims == mass:
            return np.true_divide(x, pc.clight * pc.clight, out=self._get_out(x))

    def __str__(self):
        return "mass_energy: mass <-> energy"

class SpectralEquivalence(Equivalence):
    """Equivalence between wavelength, frequency, and energy of a photon.

    Given a photon with wavelength :math:`\\lambda`, spatial frequency
    :math:`\\bar\\nu`, frequency :math:`\\nu` and Energy :math:`E`,
    these quantities are related by the following forumlae:

    .. math::

      E = h \\nu = h c / \\lambda = h c \\bar\\nu

    where :math:`h` is Planck's constant and :math:`c` is the speed of light.

    Example
    ------
    >>> print(SpectralEquivalence())
    spectral: length <-> spatial_frequency <-> frequency <-> energy
    >>> from unyt import angstrom, km
    >>> (3*angstrom).to_equivalent('keV', 'spectral')
    unyt_quantity(4.13280644, 'keV')
    >>> (1*km).to_equivalent('MHz', 'spectral')
    unyt_quantity(0.29979246, 'MHz')
    """

    type_name = "spectral"
    _dims = (length, rate, energy, spatial_frequency)

    def _convert(self, x, new_dims):
        from unyt import physical_constants as pc

        if new_dims == energy:
            if x.units.dimensions == length:
                return np.true_divide(pc.clight * pc.h_mks, x, out=self._get_out(x))
            elif x.units.dimensions == rate:
                return np.multiply(x, pc.h_mks, out=self._get_out(x))
            elif x.units.dimensions == spatial_frequency:
                return np.multiply(x, pc.h_mks * pc.clight, out=self._get_out(x))
        elif new_dims == length:
            if x.units.dimensions == rate:
                return np.true_divide(pc.clight, x, out=self._get_out(x))
            elif x.units.dimensions == energy:
                return np.true_divide(pc.h_mks * pc.clight, x, out=self._get_out(x))
            elif x.units.dimensions == spatial_frequency:
                return np.true_divide(1, x, out=self._get_out(x))
        elif new_dims == rate:
            if x.units.dimensions == length:
                return np.true_divide(pc.clight, x, out=self._get_out(x))
            elif x.units.dimensions == energy:
                return np.true_divide(x, pc.h_mks, out=self._get_out(x))
            elif x.units.dimensions == spatial_frequency:
                return np.multiply(x, pc.clight, out=self._get_out(x))
        elif new_dims == spatial_frequency:
            if x.units.dimensions == length:
                return np.true_divide(1, x, out=self._get_out(x))
            elif x.units.dimensions == energy:
                return np.true_divide(x, pc.clight * pc.h_mks, out=self._get_out(x))
            elif x.units.dimensions == rate:
                return np.true_divide(x, pc.clight, out=self._get_out(x))

    def __str__(self):
        return "spectral: length <-> spatial_frequency <-> frequency " + "<-> energy"

class SoundSpeedEquivalence(Equivalence):
    """Equivalence between the sound speed, temperature, and thermal energy of
    an ideal gas

    For an ideal gas with sound speed :math:`c_s`, temperature :math:`T`, and
    thermal energy :math:`E`, the following equalities will hold:

    .. math::

      c_s = \\sqrt{\\frac{\\gamma k_B T}{\\mu m_{\\rm H}}}

    and

    .. math::

      E = c_s^2 \\mu m_{\\rm H} / \\gamma = k_B T

    where :math:`k_B` is Boltzmann's constant, :math:`\\mu` is the mean
    molecular weight of the gas, and :math:`\\gamma` is the ratio of specific
    heats.

    Parameters
    ----------
    gamma : float
       The ratio of specific heats. Defaults to 5/3, which is correct for
       monatomic species.
    mu : float
       The mean molecular weight. Defaults to 0.6, which is valid for fully
       ionized gas with primordial composition.

    Example
    -------
    >>> print(SoundSpeedEquivalence())
    sound_speed (ideal gas): velocity <-> temperature <-> energy
    >>> from unyt import Kelvin, km, s
    >>> hot = 1e6*Kelvin
    >>> hot.to_equivalent('km/s', 'sound_speed')
    unyt_quantity(151.37249927, 'km/s')
    >>> hot.to_equivalent('keV', 'sound_speed')
    unyt_quantity(0.08617332, 'keV')
    >>> cs = 100*km/s
    >>> cs.to_equivalent('K', 'sound_speed')
    unyt_quantity(436421.39881617, 'K')
    >>> cs.to_equivalent('keV', 'sound_speed')
    unyt_quantity(0.03760788, 'keV')
    """

    type_name = "sound_speed"
    _dims = (velocity, temperature, energy)

    def _convert(self, x, new_dims, mu=0.6, gamma=5.0 / 3.0):
        from unyt import physical_constants as pc

        if new_dims == velocity:
            if x.units.dimensions == temperature:
                v2 = np.multiply(
                    pc.kboltz * gamma / (mu * pc.mh), x, out=self._get_out(x)
                )
            elif x.units.dimensions == energy:
                v2 = np.multiply(gamma / (mu * pc.mh), x, out=self._get_out(x))
            return np.sqrt(v2, out=self._get_out(x))
        elif new_dims == temperature:
            if x.units.dimensions == velocity:
                v2 = np.multiply(x, x, out=self._get_out(x))
                kT = np.multiply(v2, mu * pc.mh / gamma, out=self._get_out(x))
                return np.true_divide(kT, pc.kboltz, out=self._get_out(x))
            else:
                return np.true_divide(x, pc.kboltz, out=self._get_out(x))
        else:
            if x.units.dimensions == velocity:
                v2 = np.multiply(x, x, out=self._get_out(x))
                return np.multiply(mu * pc.mh / gamma, v2, out=self._get_out(x))
            else:
                return np.multiply(x, pc.kboltz, out=self._get_out(x))

    def __str__(self):
        return "sound_speed (ideal gas): velocity <-> temperature <-> energy"

class LorentzEquivalence(Equivalence):
    """Equivalence between velocity and the Lorentz gamma factor.

    For a body with velocity :math:`v`, the Lorentz gamma factor,
    :math:`\\gamma` is

    .. math::

      \\gamma = \\frac{1}{\\sqrt{1 - v^2/c^2}}

    ans similarly

    .. math::

      v = \\frac{c}{\\sqrt{1 - \\gamma^2}}

    where :math:`c` is the speed of light.

    Example
    -------
    >>> print(LorentzEquivalence())
    lorentz: velocity <-> dimensionless
    >>> from unyt import c, dimensionless
    >>> v = 0.99*c
    >>> print(v.to_equivalent('', 'lorentz'))
    7.088812050083393 dimensionless
    >>> fast = 99.9*dimensionless
    >>> fast.to_equivalent('c', 'lorentz')
    unyt_quantity(0.9999499, 'c')
    >>> fast.to_equivalent('km/s', 'lorentz')
    unyt_quantity(299777.43797656, 'km/s')
    """

    type_name = "lorentz"
    _dims = (dimensionless, velocity)

    def _convert(self, x, new_dims):
        from unyt import physical_constants as pc

        if new_dims == dimensionless:
            beta = np.true_divide(x, pc.clight, out=self._get_out(x))
            beta2 = np.multiply(beta, beta, out=self._get_out(x))
            inv_gamma_2 = np.subtract(1, beta2, out=self._get_out(x))
            inv_gamma = np.sqrt(inv_gamma_2, out=self._get_out(x))
            gamma = np.true_divide(1.0, inv_gamma, out=self._get_out(x))
            return gamma
        elif new_dims == velocity:
            gamma2 = np.multiply(x, x, out=self._get_out(x))
            inv_gamma_2 = np.true_divide(1, gamma2, out=self._get_out(x))
            beta2 = np.subtract(1, inv_gamma_2, out=self._get_out(x))
            beta = np.sqrt(beta2, out=self._get_out(x))
            return np.multiply(pc.clight, beta, out=self._get_out(x))

    def __str__(self):
        return "lorentz: velocity <-> dimensionless"

class SchwarzschildEquivalence(Equivalence):
    """Equivalence between the mass and radius of a Schwarzschild black hole

    A Schwarzschild black hole of mass :math:`M` has radius :math:`R`

    .. math::

      R = \\frac{2 G M}{c^2}

    and similarly

    .. math::

      M = \\frac{R c^2}{2 G}

    where :math:`G` is Newton's gravitational constant and :math:`c` is the
    speed of light.

    Example
    -------
    >>> print(SchwarzschildEquivalence())
    schwarzschild: mass <-> length
    >>> from unyt import Msun, AU
    >>> (10*Msun).to_equivalent('km', 'schwarzschild')
    unyt_quantity(29.53161626, 'km')
    >>> (1*AU).to_equivalent('Msun', 'schwarzschild')
    unyt_quantity(50656851.7815179, 'Msun')
    """

    type_name = "schwarzschild"
    _dims = (mass, length)

    def _convert(self, x, new_dims):
        from unyt import physical_constants as pc

        if new_dims == length:
            return np.multiply(
                2.0 * pc.G / (pc.clight * pc.clight), x, out=self._get_out(x)
            )
        elif new_dims == mass:
            return np.multiply(
                0.5 * pc.clight * pc.clight / pc.G, x, out=self._get_out(x)
            )

    def __str__(self):
        return "schwarzschild: mass <-> length"

class ComptonEquivalence(Equivalence):
    """Equivalence between the Compton wavelength
    of a particle and its mass.

    .. math::

      \\lambda_c = h/mc

    Example
    -------
    >>> print(ComptonEquivalence())
    compton: mass <-> length
    >>> from unyt import me, fm
    >>> me.to_equivalent('angstrom', 'compton')
    unyt_quantity(0.0242631, 'Å')
    >>> (10*fm).to_equivalent('me', 'compton')
    unyt_quantity(242.63102371, 'me')
    """

    type_name = "compton"
    _dims = (mass, length)

    def _convert(self, x, new_dims):
        from unyt import physical_constants as pc

        return np.true_divide(pc.h_mks / pc.clight, x, out=self._get_out(x))

    def __str__(self):
        return "compton: mass <-> length"

class EffectiveTemperatureEquivalence(Equivalence):
    """Equivalence between the emmitted flux accross all wavelengths and
    temperature of a blackbody

    For a blackbody emitter with Temperature :math:`T` emitting radiation with
    a flux :math:`F`, the following equality holds:

    .. math::

    F = \\sigma T^4

    where :math:`\\sigma` is the Stefan-Boltzmann constant.

    Example
    -------
    >>> print(EffectiveTemperatureEquivalence())
    effective_temperature: flux <-> temperature
    >>> from unyt import K, W, m
    >>> (5000.*K).to_equivalent('W/m**2', 'effective_temperature')
    unyt_quantity(35439831.25, 'W/m**2')
    >>> (100.*W/m**2).to_equivalent('K', 'effective_temperature')
    unyt_quantity(204.92601414, 'K')
    """

    type_name = "effective_temperature"
    _dims = (flux, temperature)

    def _convert(self, x, new_dims):
        from unyt import physical_constants as pc

        if new_dims == flux:
            x4 = np.power(x, 4, out=self._get_out(x))
            return np.multiply(
                pc.stefan_boltzmann_constant_mks, x4, out=self._get_out(x)
            )
        elif new_dims == temperature:
            T4 = np.true_divide(
                x, pc.stefan_boltzmann_constant_mks, out=self._get_out(x)
            )
            ret = np.power(T4, 0.25, out=self._get_out(x))
            return ret

    def __str__(self):
        return "effective_temperature: flux <-> temperature"


text:
<?php

namespace App\Http\Controllers\Authority\Modify;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Illuminate\Support\Facades\Auth;

class ExportSQLController extends Controller
{
    private $temporary_file_path;
    private $zip_file_path;
    private $sql_file_path;

    public function index()
    {
        $this->temporary_file_path = 'temporary/';
        $this->dumpFile();
        $this->zipFileToZIP();

        //if (!$process->isSuccessful()) {
        //    throw new ProcessFailedException($process);
        //}

        return response()->download($this->sql_file_path);
    }

    public function dumpFile()
    {
        $this->sql_file_path = $this->temporary_file_path.'user_id:'.Auth::user()->id.'_'.date('M-j_G:i:s').'.sql';
        $process = new Process('mysqldump -uhomestead -p'.env('DB_PASSWORD').' homestead > '.$this->sql_file_path);
        $process->run();
    }

    public function zipFileToZIP()
    {
        $this->zip_file_path = 'customBackup/backup_sql.zip';
        $password = env('DB_DUMP_PASSWORD');
        $process = new Process("zip -ruP $password $this->zip_file_path $this->sql_file_path");
        $process->run();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="colorError">#F3373A</color>
  <color name="colorInfo">#3F51B5</color>
  <color name="colorSuccess">#388E3C</color>
  <color name="colorWarning">#FFA900</color>
</resources>


text:
package com.github.xemiru.luamesh.test;

import com.github.xemiru.luamesh.test.objects.ObjectFields;
import org.junit.Before;
import org.junit.Test;
import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;

import static com.github.xemiru.luamesh.LuaObjectValue.of;
import static com.github.xemiru.luamesh.test.Utility.init;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.luaj.vm2.LuaValue.valueOf;

public class TestFields {

    private Globals g;

    @Before
    public void before() {
        g = init();
    }

    @Test
    public void fields() {
        ObjectFields jobj = new ObjectFields();
        LuaValue obj = of(jobj);
        g.set("obj", obj);
        obj = g.get("obj");

        assertEquals(false, obj.get("bool").checkboolean());
        obj.set("bool", valueOf(true));
        assertEquals(true, jobj.bool);

        assertEquals(0x00, obj.get("bytee").checkint());
        obj.set("bytee", 15);
        assertEquals(0x0F, jobj.bytee);

        assertEquals('1', obj.get("charr").checkint());
        obj.set("charr", 'a');
        assertEquals('a', jobj.charr);

        assertEquals(4, obj.get("shortt").checkint());
        obj.set("shortt", 12);
        assertEquals(12, jobj.shortt);

        assertEquals(12, obj.get("intt").checkint());
        obj.set("intt", 64);
        assertEquals(64, jobj.intt);

        assertEquals(69, obj.get("longg").checklong());
        obj.set("longg", 495);
        assertEquals(495, jobj.longg);

        assertEquals(12.4, obj.get("doublee").checkdouble(), 0F);
        obj.set("doublee", 44.9);
        assertEquals(44.9, jobj.doublee, 0F);

        assertEquals(12.6F, obj.get("floatt").checknumber().tofloat(), 0F);
        obj.set("floatt", 99.4);
        assertEquals(99.4F, jobj.floatt, 0F);

        Object objj = new Object();
        assertEquals(of(jobj.obj), obj.get("obj"));
        obj.set("obj", of(objj));
        assertEquals(objj, jobj.obj);

        assertTrue(obj.get("poopy").isfunction());
    }

}


text:
layout: "enterprise"
page_title: "Configurations - API - Terraform Enterprise"
sidebar_current: "docs-enterprise-api-configurations"
description: |-
  A configuration represents settings associated with a resource that runs
  Terraform with versions of Terraform configuration.
---

# Configuration API

A configuration version represents versions of Terraform configuration. Each set
of changes to Terraform HCL files or the scripts used in the files should have
an associated configuration version.

When creating versions via the API, the variables attribute can be sent to
include the necessary variables for the Terraform configuration. A configuration
represents settings associated with a resource that runs Terraform with versions
of Terraform configuration. Configurations have many configuration versions
which represent versions of Terraform configuration templates and other
associated configuration. Most operations take place on the configuration
version, not the configuration.

## Get Latest Configuration Version

This endpoint gets the latest configuration version.

| Method | Path           |
| :----- | :------------- |
| `GET`  | `/terraform/configurations/:username/:name/versions/latest` |

### Parameters

- `:username` `(string: <required>)` - Specifies the username or organization
  name under which to get the latest configuration version. This username must
  already exist in the system, and the user must have permission to create new
  configuration versions under this namespace. This is specified as part of the
  URL.

- `:name` `(string: <required>)` - Specifies the name of the configuration for
  which to get the latest configuration. This is specified as part of the URL.

### Sample Request

```text
$ curl \
    --header "X-Atlas-Token: ..." \
    https://atlas.hashicorp.com/api/v1/terraform/configurations/my-organization/my-configuration/versions/latest
```

### Sample Response

```json
{
  "version": {
    "version": 6,
    "metadata": {
      "foo": "bar"
    },
    "tf_vars": [],
    "variables": {}
  }
}
```

- `version` `(int)` - the unique version instance number.

- `metadata` `(map<string|string>)` - a map of arbitrary metadata for this
  version.

## Create Configuration Version

This endpoint creates a new configuration version.

| Method | Path           |
| :----- | :------------- |
| `POST` | `/terraform/configurations/:username/:name/versions` |

### Parameters

- `:username` `(string: <required>)` - Specifies the username or organization
  name under which to create this configuration version. This username must
  already exist in the system, and the user must have permission to create new
  configuration versions under this namespace. This is specified as part of the
  URL.

- `:name` `(string: <required>)` - Specifies the name of the configuration for
  which to create a new version. This is specified as part of the URL.

- `metadata` `(map<string|string>)` - Specifies an arbitrary hash of key-value
  metadata pairs. This is specified as the payload as JSON.

- `variables` `(map<string|string>)` - Specifies a hash of key-value pairs that
  will be made available as variables to this version.

### Sample Payload

```json
{
  "version": {
    "metadata": {
      "git_branch": "master",
      "remote_type": "atlas",
      "remote_slug": "hashicorp/atlas"
    },
    "variables": {
      "ami_id": "ami-123456",
      "target_region": "us-east-1",
      "consul_count": "5",
      "consul_ami": "ami-123456"
    }
  }
}
```

### Sample Request

```text
$ curl \
    --request POST \
    --header "X-Atlas-Token: ..." \
    --header "Content-Type: application/json" \
    --data @payload.json \
    https://atlas.hashicorp.com/api/v1/terraform/configurations/my-organization/my-configuration/versions
```

### Sample Response

```json
{
  "version": 6,
  "upload_path": "https://binstore.hashicorp.com/ddbd7db6-f96c-4633-beb6-22fe2d74eeed",
  "token": "ddbd7db6-f96c-4633-beb6-22fe2d74eeed"
}
```

- `version` `(int)` - the unique version instance number. This is
  auto-incrementing.

- `upload_path` `(string)` - the path where the archive should be uploaded via a
  `POST` request.

- `token` `(string)` - the token that should be used when uploading the archive
  to the `upload_path`.

## Check Upload Progress

This endpoint retrieves the progress for an upload of a configuration version.

| Method | Path           |
| :----- | :------------- |
| `GET` | `/terraform/configurations/:username/:name/versions/progress/:token` |

### Parameters

- `:username` `(string: <required>)` - Specifies the username or organization to
  read progress. This is specified as part of the URL.

- `:name` `(string: <required>)` - Specifies the name of the configuration for
  to read progress. This is specified as part of the URL.

- `:token` `(string: <required>)` - Specifies the token that was returned from
  the create option. **This is not an Atlas Token!** This is specified as part
  of the URL.

### Sample Request

```text
$ curl \
    --header "X-Atlas-Token: ..." \
    https://atlas.hashicorp.com/api/v1/terraform/configurations/my-organization/my-configuration/versions/progress/ddbd7db6-f96c-4633-beb6-22fe2d74eeed
```

### Sample Response


text:
<?php

namespace Attila;

use \Attila\Batch\Entity as Entity;
use \Attila\Batch\Operation as Operation;

include('../../../autoload.php');

if (isset($_SERVER['argv'])) { $aArguments = $_SERVER['argv']; }
else { $aArguments = $argv; }

$sBatchName = $aArguments[1];
array_shift($aArguments);

$aOptions = array();

while (count($aArguments) > 0) {

    if (preg_match('/^-[a-z]/', $aArguments[0])) {

        $sOptionName = str_replace('-', '', $aArguments[0]);

        if (isset($aArguments[1])) {
            $sOptionValue = $aArguments[1];
        } else {
            $sOptionValue = '';
        }

        if (isset(Entity::$aOptionsBatch[$sOptionName]) && Entity::$aOptionsBatch[$sOptionName] === false) {

            $aOptions[$sOptionName] = true;
            array_shift($aArguments);
        } else if (isset(Entity::$aOptionsBatch[$sOptionName]) && Entity::$aOptionsBatch[$sOptionName] === 'string') {

            $aOptions[$sOptionName] = $sOptionValue;
            array_shift($aArguments);
            array_shift($aArguments);
        } else {

            array_shift($aArguments);
        }
    } else {

        array_shift($aArguments);
    }
}

if ($sBatchName == 'scaffolding:run') {
    $oBatch = new Entity;
    $oBatch->runScaffolding($aOptions);
} else if ($sBatchName == 'db:init') {
    $oBatch = new Operation;
    $oBatch->createDb($aOptions);
} else {
    new \Exception("Error: batch doesn\\'t exist");
}


text:
class Listing
  attr_accessor :address, :price, :beds, :baths, :sqft, :acres, :status, :price_per_sqft, :days_on_market, :property_type, :year_built, :style, :description, :house_url
  @@all =[]

  def initialize(listing_hash)
    listing_hash.each {|key, value| self.send("#{key}=", value) if value != ""}
    @@all << self
  end

  def self.create_from_collection(listings_array)
    listings_array.each {|hash| Listing.new(hash)}
  end

  def add_listing_attributes(attributes_hash)
    attributes_hash.each do |key, value|
       self.send("#{key}=", value)
     end
    self
  end

  def self.all
    @@all
  end

  def self.reset_all
    @@all = []
  end

end


text:
package com.intellij.plugins.haxe.config;

import com.intellij.openapi.components.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jdom.Element;

import java.util.Arrays;
import java.util.Set;

/**
 * @author: Fedor.Korotkov
 */
@State(
  name = "HaxeProjectSettings",
  storages = {
    @Storage(file = StoragePathMacros.PROJECT_FILE),
    @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/haxe.xml", scheme = StorageScheme.DIRECTORY_BASED)
  }
)
public class HaxeProjectSettings implements PersistentStateComponent<Element> {
  public static final String HAXE_SETTINGS = "HaxeProjectSettings";
  public static final String DEFINES = "defines";
  private String userCompilerDefinitions = "";

  public Set<String> getUserCompilerDefinitionsAsSet() {
    return new THashSet<String>(Arrays.asList(getUserCompilerDefinitions()));
  }

  public static HaxeProjectSettings getInstance(Project project) {
    return ServiceManager.getService(project, HaxeProjectSettings.class);
  }

  public String[] getUserCompilerDefinitions() {
    return userCompilerDefinitions.split(",");
  }

  public void setUserCompilerDefinitions(String[] userCompilerDefinitions) {
    this.userCompilerDefinitions = StringUtil.join(ContainerUtil.filter(userCompilerDefinitions, new Condition<String>() {
      @Override
      public boolean value(String s) {
        return s != null && !s.isEmpty();
      }
    }), ",");
  }

  @Override
  public void loadState(Element state) {
    userCompilerDefinitions = state.getAttributeValue(DEFINES, "");
  }

  @Override
  public Element getState() {
    final Element element = new Element(HAXE_SETTINGS);
    element.setAttribute(DEFINES, userCompilerDefinitions);
    return element;
  }
}


text:
title: "Find K Closest Elements"
description: "Some description ..."
authors: ["lek-tin"]
tags: ["leetcode", "binary-search"]
categories: ["algorithm"]
date: 2019-03-14T16:00:58-08:00
draft: false
archive: false
---
Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

### Example 1
```
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
```
### Example 2
```
Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]
```
#### Note
- The value k is positive and will always be smaller than the length of the sorted array.
- Length of the given array is positive and will not exceed 104
- Absolute value of elements in the array and x will not exceed 104
### Solution:
Assume we are taking `arr[i] ~ arr[i + k -1]`. We can binary search `i`. We compare the distance between `x - arr[mid] and arr[mid - k] - x`. If `x - arr[mid] > arr[mid + k] - x`, it means `arr[mid + 1] ~ A[mid + k]` is better than `arr[mid] ~ arr[mid + k - 1]`, and we have `mid` smaller than the right `i`.
So assign left = mid + 1.
```java
// Time: O(log(N-K) + K)
class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        Integer low = 0, high = arr.length - k;
        List<Integer> res = new ArrayList<>();

        while (low < high) {
            int mid = (low + high) / 2;
            if (x - arr[mid] > arr[mid + k] - x) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }

        for (int i = low; i < low + k; i++) res.add(arr[i]);

        return res;
    }
}
```
```python
class Solution:
    def findClosestElements(self, arr, k, x):
        """
        :type arr: List[int]
        :type k: int
        :type x: int
        :rtype: List[int]
        """
        low = 0
        high = len(arr) - k

        while low < high:
            mid = (low + high) // 2
            if x > (arr[mid] + arr[mid + k]) / 2:
                low = mid + 1
            else:
                high = mid

        return arr[low:low + k]
```


text:
**Algorithm** is well defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values, as output. In other words: "*It'a sequece of computational steps that transform the input into the output.*"

                            Input ---> Finite, ordered list of steps ---> Outputs

## Algorithms Basics

- **Data Structure**
  - is a way to store and organize data in order to facilitate access and modifications.
  - is a complecity of implementations.
  - is a Stack, Queue, Tree, etc.

- **Analysing Algorithms**
  - memory, communication bandwidth, or computer hardware, computational time.
  - RAM model of implementational technology.
  - arithmetic, data movement, and control - constant time.
  - clgn bits for some constants c >= 1
  - behavior of an algorithm - formulas

## Algorithms Techniques

- Backtraking
  - Travelling Salesman
  - THe N Queens problem
  - Traversal Tree
  - Convex HULL(GRAHAM'S SCAN)
  - GEnerating Permutations
- Brute Force Algorithm

## Data Structures

**Data Structures** is a foundations for building algorithms

- **Binomal Heap**
- **B-Tree**
- **List**
  - Operations
    - Search(L, k)
    - Insert(L, x)
    - Delete(L, x)
    - Successor(L, x)
    - Predecessor(L, x)
    - Minimum(L)
    - Maximum(L)
  - Double linked list
  - Searching a linked list
- **Dictionary**
  - Operations
    - `Insert(x,d)` - Insert item x into dictionary d.
    - `Delete(x,d)` - Remove item x (or the item pointed to by x) from dictionary d.
    - `Search(k,d)` - Return an item with key k if one exists in dictionary d.
- **Hash Tables**
- **Maps**
- **Tires**
- **Queue**
- **Stack**
- **Tree**
- **Red Black Tree**


text:
namespace MQTTnet.Diagnostics.PacketInspection
{
    public enum MqttPacketFlowDirection
    {
        Inbound,

        Outbound
    }
}


text:
package gui.windows.device;

public class Web {

}


text:
package org.pm4j.core.sample.album;

import org.pm4j.core.pm.impl.PmConversationImpl;
import org.pm4j.core.sample.album.domain.AlbumService;

public class AlbumConversationPm extends PmConversationImpl {

  public AlbumConversationPm() {
    // The services may be provided by a container such as cdi or spring.
    // For this simple demo, the services are simply provided as named PM conversation
    // properties. - A simple option that may be fine for some small applications.
    setPmNamedObject("albumService", new AlbumService());
  }

}


text:
import * as React from "react";
import { connect } from "react-redux";
import { ApplicationState }  from "../store";
import * as AppStore from "../store/App";

export type AppPropsType = AppStore.AppState & typeof AppStore.actionCreators;

interface AppProps extends AppPropsType {}

export class App extends React.Component<AppProps, undefined>{

}

/*
connect(
    (state: ApplicationState) => state.app,
    AppStore.actionCreators
)(App);
*/


text:
"""
    ctp-trade相关处理
    1. ctp trade_command_queue的处理
    2. ctp SPI -> trade_callback_queue

    #TODO:###
    0. 须处理8:59-9:00以及节间休息下单不成功的事项
        注意下 FTD(期货交易数据交换协议)
        根据文档, OnRtnInstrumentStatus是广播模式下订阅, 问题是TraderSpi的广播模式如何开启?

"""

import threading
import queue
import time
import logging

from . import trade_command
from ..common.macro_command_queue import DeferTradeCommand
from ..common.base import (XCLOSE,
                           XCLOSE_TODAY,
                           BaseObject,
)
from ..trader.position import ORDER_STATUS

class BaseTradeCommandQueue(object):
    """
        线程内模式. put_command后,由run驱动, 调用run之前命令均在队列中
        接收命令
        翻译成CTP所需的模式
        执行命令
        设置命令状态
    """
    #TODO: 须处理8:59-9:00以及节间休息下单不成功的事项, 错误信息返回值中有明确标示么?
    #       应已经处理(失败后再次发单),须确认 2014-11-23

    logger = logging.getLogger('ctp_trade.BaseTradeCommandQueue')

    def __init__(self, env, account):
        self._env = env
        self._account = account
        self._spi = account.spi
        self._queue = queue.PriorityQueue()
        self._last_query_time = 0
        self.init_command_map()
        self._tcq_initialized = False    #未正常初始化,在结算单确认后OK
        self._ref2command = {}      #用于部分需要用refid来获取原来command(中信息)的command缓存

    @property
    def account(self):
        return self._account

    def run(self):
        while not self._queue.empty():
            command = self._queue.get()[1]
            self._exec(command)

    def put_command(self, command):
        #print(command.priority,str(command))
        self._queue.put((command.priority, command))

    def _exec(self, command):
        """
            不去主动流控
        """
        command_type = type(command)
        self.command_map[command_type](command)

    def init_command_map(self):
        self.command_map = {
            #SYSTEM
            trade_command.LoginCommand: self.login,
            trade_command.SettlementQueryCommand: self.query_settlement_info,
            trade_command.SettlementConfirmCommand: self.confirm_settlement_info,
            #QUERY
            trade_command.QueryAccountCommand: self.query_account,
            trade_command.QueryInstrumentCommand: self.query_instrument,
            trade_command.QueryInstrumentMarginRateCommand: self.query_instrument_marginrate,  # 直接使用query_instrument, 不需要
            trade_command.QueryDepthMarketDataCommand: self.query_depth_market_data,  # 接使用query_instrument, 不需要
            trade_command.QueryPositionCommand: self.query_position,
            trade_command.QueryPositionDetailCommand: self.query_position_detail,
            trade_command.OpenInstruction:  self.t_open,
            trade_command.CloseInstruction: self.t_close,
            trade_command.CancelInstruction: self.t_cancel,
        }

    #登录与结算单
    def login(self, command):
        #print("login......")
        return self._spi.user_login()

    def on_login_success(self,trading_day):
        self._env.put_macro_command(DeferTradeCommand(self,trade_command.SETTLEMENT_QUERY_COMMAND,1))      #1s后执行查询,以避免流控
        self._env.trading_day = trading_day
        self._account.on_login()

    def query_settlement_info(self, command):
        return self._spi.query_settlement_info()

    def confirm_settlement_info(self, command):
        return self._spi.confirm_settlement_info()

    #回调函数
    def on_settlement_info_confirmed(self):
        self._tcq_initialized = True
        self.put_command(trade_command.QueryAccountCommand(self.account.stamp))

    #获取帐户信息
    def query_account(self, command):
        """获取帐户信息
           市值, 可用余额, 保证金等
        """
        ret,ref_id = self._spi.fetch_trading_account()
        self._ref2command[ref_id] = command
        #print("query_account ref_id:",ref_id)
        return ret

    def on_query_trading_account(self, ref_id, balance, available, margin, locked):
        #print("on_query_account ref_id:",ref_id)
        #print(ref_id,balance,available)
        command = self._ref2command[ref_id] #用于找到时间戳
        self._env.update_account(self.account, command.stamp, balance, available, margin, locked)

    #查询合约
    def query_instrument(self, command):
        return self._spi.fetch_instrument(command.instrument_id)

    def on_query_instrument(self, instrument_id, exchange_id, price_tick, multiple, long_rate, short_rate):
        self._env.update_instrument(instrument_id, exchange_id, price_tick, multiple, long_rate, short_rate)

    def on_instrument_status(self,instrument_id,enter_time,trading_status):
        self._env.update_instrument_status(instrument_id,trading_status)

    #查询保证金
    def query_instrument_marginrate(self, command):
        return self._spi.fetch_instrument_marginrate(command.instrument_id)

    def on_query_instrument_marginrate(self, instrument_id, long_rate, short_rate):
        self._env.update_instrument_marginrate(instrument_id, long_rate, short_rate)

    #查询涨跌停价格
    def query_depth_market_data(self, command):
        return self._spi.fetch_depth_market_data(command.instrument_id)

    def on_query_market_data(self, instrument_id, trading_day, upperlimit_price, lowerlimit_price):
        self._env.update_limit_price(instrument_id, trading_day, upperlimit_price, lowerlimit_price)

    #查询头寸
    def query_position(self, command):
        return self._spi.investor_position(command.instrument_id)

    def query_position_detail(self, command):
        return self._spi.investor_position_detail(command.instrument_id)

    #交易处理

    def t_open(self, instruction):
        corder = instruction.order
        #print("t_open:",corder.contract.name,self._spi)
        #instrument_id = corder.get_contract_name()
        instrument_id = instruction.contract_name
        #print("topen:direction:",corder.direction)
        return self._spi.xopen(instrument_id,
                              corder.direction,
                              corder.approved - corder.accomplished2, #将已完成的剪掉
                              corder.target_price,
                              #self.env.calc_target_price(instrument_id,
                              #                           instruction.direction,
                              #                           instruction.base_price,
                              #                           instruction.extra_hops,
                              #                          ),
                            )

    def t_close(self, instruction):
        corder = instruction.order
        #instrument_id = corder.get_contract_name()
        instrument_id = instruction.contract_name
        close_type = instruction.order.atype

        # 也可由CTP自行搞定 其它交易所的平今/平仓转换
        if close_type == XCLOSE_TODAY and not self._env.is_contract_CLOSETODAY(instrument_id):
            #只有必须用CLOSE_TODAY时,才用
            close_type = XCLOSE

        return self._spi.xclose(instrument_id,
                              close_type,  #XCLOSE,XCLOSE_TODAY
                              corder.direction,
                              corder.approved,
                              corder.target_price,
                              #self.env.calc_target_price(instrument_id,corder.direction,corder.base_price,corder.extra_hops),
                            )

    def t_cancel(self, instruction):
        instrument_id = instruction.instrument_id
        trade_info = instruction.order.trade_info
        self._spi.xcancel(instrument_id,
                         trade_info.exchange_id,
                         trade_info.order_sys_id,
                         trade_info.front_id,
                         trade_info.session_id,
                         trade_info.order_ref,
            )

    def on_accept(self,instrument_id,direction,volume,price,uid,trade_info):
        self._env.matcher.on_accept(uid,instrument_id,direction,volume,price,trade_info)

    def on_reject(self,instrument_id,direction,volume,price,error_id):
        #print("TCQ:reject")
        self._env.matcher.on_reject(instrument_id,direction,volume,price,error_id)

    def on_rtn_order(self,uid,order_status,volume_traded=0):
        """委托回报
           反映执行状态
        """
        #print("tcq:on_rtn_order:uid=",uid)
        if order_status == ORDER_STATUS.CANCELLED or order_status == ORDER_STATUS.PART_SUCCESSED or order_status == ORDER_STATUS.SUCCESSED:
            #self.env.get_matcher().on_cancelled(uid,volume_traded)
            self._env.matcher.on_done(uid,volume_traded,order_status)
        #elif order_status == ORDER_STATUS.PART_TRADED:
        #    self.env.get_matcher().on_done(uid,volume_traded,order_status)
        #elif order_status == ORDER_STATUS.ALL_TRADED:
        #    self.env.get_matcher().on_done(uid,volume_traded,order_status)
        elif order_status == ORDER_STATUS.LOCAL_REJECT or order_status == ORDER_STATUS.EXCHANGE_REJECT: #不可能出现,已经走on_reject了
            #self.env.get_matcher().on_error(uid)
            pass
        else:   #等
            print("异常情况 %s:%d" % (uid,volume_traded))

    def on_trade(self,uid,trade_date,trade_time,volume,price):
        """
            volume为当次成交数,而非累积数
            在on_rtn_order中, 成交数为累积数
            只能使用OnTrade中的数据,因为RtnOrder中没有成交价格信息
        """
        self._env.matcher.on_progress(uid,volume,price,trade_date,trade_time)

    #错误处理#
    def on_error(self, ref_id, instrument_id, error_id, error_msg):
        logging.info('instrument %s: request_id %s:error_id %s:error_msg %s' % (ref_id, instrument_id, error_id, error_msg))

    #开始运行之前的委托回报,成交回报
    def on_pre_rtn_order(self,front_id,session_id,ref_id,instrument_id,insert_time,volume_total,volume_traded):
        #1. 是否需要都撤单? 对于单帐户多路值守, 撤单是不正确的
        #2. 对前次登陆时的挂单撤单时,会收到以前次登陆的front_id+session_id为关键字的on_rtn_order
        print('收到之前委托回报,front_id=%s,session_id=%s,ref_id=%s' % (front_id,session_id,ref_id))
        pass

    def on_pre_trade(self,exchange_id,order_sys_id,trade_time,instrument_id,volume,price):
        pass

    def on_other_rtn_order(self,front_id,session_id,ref_id,instrument_id,insert_time,volume_total,volume_traded):
        """
            这个现在已经不再用了
        """
        pass

    def on_other_trade(self,exchange_id,order_sys_id,trade_time,instrument_id,volume,price):
        """
            这个现在已经不再用了
        """
        pass

class TradeCommandQueue(threading.Thread,BaseTradeCommandQueue):
    """
        独立线程模式
        接收命令
        翻译成CTP所需的模式
        执行命令
        设置命令状态
    """

    logger = logging.getLogger('ctp_trade.CTPTradeCommandQueue')

    def __init__(self, env, account):
        threading.Thread.__init__(self)
        BaseTradeCommandQueue.__init__(self,env,account)

    def run(self):
        while 1:
            command = self._queue.get()[1]
            self._exec(command)

class TradeCommandQueueStub(BaseTradeCommandQueue):
    """
        Stub模式
        把队列绕过了,而直接在putcommand中搞定
        步子迈得有点大. 会导致在集成中测试不到队列相关语句. 和BaseTradeCommandQueue相比,优点是不需要额外调用run
            确定在策略通路测试/集成模拟/时使用Stub
        建议在 实盘行情模拟 时使用BaseTradeCommandQueue,用put_command/run组合来解决问题
    """

    logger = logging.getLogger('ctp_trade.CTPTradeCommandQueueStub')

    def __init__(self, env, account):
        BaseTradeCommandQueue.__init__(self,env,account)
        self.lock = threading.Lock()

    def start(self):    #提供一致性接口
        pass

    def run(self):      #提供一致性接口
        pass

    def put_command(self, command):
        #print("TCQStub:",command.priority,str(command))
        self._exec(command)

    #获取帐户信息
    def query_account(self, command):
        """获取帐户信息
           市值, 可用余额, 保证金等
            #所有需要设定 _ref2command[ref_id]的方法, 即返回值与时间有关的,如查询头寸等,均须先peek设定ref_id之后再调用
            #其实在实盘交易中,这么做也没啥错.就是复杂化了,所以把测试和实盘分开
        """
        #因为直通调用的关系,导致在on_query_account时,_ref2command[ref_id]还没有设定,即在测试中onXXXX是在fetch_trading_account中调用
        #如果需要用到ref_id,就会出现 Key Error
        #因此,在调用fetch_trading_account()之前必须先得到ref_id. 对于测试环境而言此为应有之义
        with self.lock:     #加锁是为了避免在 实盘行情模拟交易时  引发潜在的竞争条件
            ref_id = self._spi.peep_next_request_id()
            self._ref2command[ref_id] = command
            ret,ref_id2 = self._spi.fetch_trading_account()
        assert ref_id,ref_id2
        #print("query_account ref_id:",ref_id)
        return ret


text:
package it.trilogis.worldwind.tilecreation.swing;

import it.trilogis.worldwind.tilecreation.utils.FileUtils;
import java.io.File;
import javax.swing.SwingWorker;

/**
 * @author nmeneghini
 * @version $Id: ZipDirectorySwingWorker.java 1 2014-05-01 15:22:47Z nmeneghini $
 */
public class ZipDirectorySwingWorker extends SwingWorker<Boolean, Integer> {

    private String zipFileName;
    private File cacheDirectory;

    public ZipDirectorySwingWorker(File cacheDir, String zipFile) {
        this.cacheDirectory = cacheDir;
        this.zipFileName = zipFile;
    }

    /*
     * (non-Javadoc)
     * @see javax.swing.SwingWorker#doInBackground()
     */
    @Override
    protected Boolean doInBackground() throws Exception {
        // if you have both landsat and custom, create package
        setProgress(20);
        boolean success = FileUtils.createZipFile(cacheDirectory, zipFileName);
        setProgress(100);
        return success;
    }

}


text:
class RemoveApplicationRequirementFromInterviews < ActiveRecord::Migration[5.1]
  def change
    change_column_null :interviews, :my_application_id, true
  end
end


text:
package i2p.bote.packet.dht;

import i2p.bote.packet.CommunicationPacket;
import i2p.bote.packet.I2PBotePacket;

import java.util.Collection;

import net.i2p.data.Hash;

/**
 * Superclass for delete requests. A delete request contains zero or more entries,
 * each consisting of a DHT key (of the DHT item that is to be deleted) and
 * authentication data (which is defined in subclasses).
 */
public abstract class DeleteRequest extends CommunicationPacket {

    protected DeleteRequest() {
    }

    protected DeleteRequest(byte[] data) {
        super(data);
    }

    public abstract Class<? extends I2PBotePacket> getDataType();

    /** Returns all DHT keys in the DeleteRequest. */
    public abstract Collection<Hash> getDhtKeys();

    /**
     * Creates a new DeleteRequest containing only one of the entries in this DeleteRequest.
     * @param dhtKey The DHT key of the entry to use
     * @return A new DeleteRequest, or null if the DHT key doesn't exist in the packet
     */
    public abstract DeleteRequest getIndividualRequest(Hash dhtKey);
}


text:
package org.example.heatmap;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import pyalot.heatmap.opengl.GLHeatmap;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;

/**
 * Provides drawing instructions for a GLSurfaceView object.
 */
public class MyGLRenderer implements GLSurfaceView.Renderer {

	private static final String LOG = "MyGLRenderer";
	private GLHeatmap mHeatmap;

	// mMVPMatrix is an abbreviation for "Model View Projection Matrix"
	private final float[] mMVPMatrix = new float[16];
	private final float[] mProjectionMatrix = new float[16];
	private final float[] mViewMatrix = new float[16];

	@Override
	public void onSurfaceCreated(GL10 unused, EGLConfig config) {

		// Set the background frame color
		GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    }

	@Override
	public void onDrawFrame(GL10 unused) {

		// Draw background color
		GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

		// Position the eye behind the origin.
		final float eyeX = 0.0f;
		final float eyeY = 0.0f;
		final float eyeZ = -3.0f;

		// We are looking toward the distance
		final float lookX = 0.0f;
		final float lookY = 0.0f;
		final float lookZ = -5.0f;

		// Set our up vector. This is where our head would be pointing were we holding the camera.
		final float upX = 0.0f;
		final float upY = 1.0f;
		final float upZ = 0.0f;

		// Set the camera position (View matrix)
		Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);

		// Calculate the projection and view transformation
		Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);

		mHeatmap.update();
		mHeatmap.display();
	}

	@Override
	public void onSurfaceChanged(GL10 unused, int width, int height) {
Log.i(LOG, "width=" + width + ", height=" + height);

		try {
			if (mHeatmap == null) {
				mHeatmap = new GLHeatmap(width, height, null, null, null);
				mHeatmap.addPoint(200, 100, 100, 0.8f);
				mHeatmap.addPoint(200, 160, 100, 0.7f);
				mHeatmap.addPoint(300, 310, 100, 0.5f);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Adjust the viewport based on geometry changes,
		// such as screen rotation
		GLES20.glViewport(0, 0, width, height);

		// Create a new perspective projection matrix. The height will stay the same
		// while the width will vary as per aspect ratio.
		final float ratio = (float) width / height;
		final float left = -ratio;
		final float right = ratio;
		final float bottom = -1.0f;
		final float top = 1.0f;
		final float near = 3.0f;
		final float far = 7.0f;

		// this projection matrix is applied to object coordinates
		// in the onDrawFrame() method
		Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);

	}

	/**
	 * Utility method for debugging OpenGL calls. Provide the name of the call
	 * just after making it:
	 *
	 *

	 * mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
	 * MyGLRenderer.checkGlError("glGetUniformLocation");

	 *
	 * If the operation is not successful, the check throws an error.
	 *
	 * @param glOperation - Name of the OpenGL call to check.
	 */
	public static void checkGlError(String glOperation) {
		int error;
		while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
			Log.e(LOG, glOperation + ": glError " + error);
			throw new RuntimeException(glOperation + ": glError " + error);
		}
	}

	public void onTouchEvent(float x, float y) {
		float i = (float) Math.random();
		if (i < 0.4) i = 0.4f;
		Log.i(LOG, "intensity=" + i);
		mHeatmap.addPoint(x, y, 150, i);
	}
}


text:
require 'rails_helper'

feature 'Update accreditations' do
  background do
    @organization = create(:organization)
    login_super_admin
    visit '/admin/organizations/parent-agency'
  end

  scenario 'when no accreditations exist', :js do
    within '#s2id_organization_accreditations' do
      expect(page).to have_no_css('.select2-search-choice-close')
    end
  end

  scenario 'with one accreditation', :js do
    select2('Knight Foundation Grant', 'organization_accreditations', multiple: true, tag: true)
    click_button 'Save changes'
    expect(@organization.reload.accreditations).to eq ['Knight Foundation Grant']
  end

  scenario 'with two accreditations', :js do
    select2('first', 'organization_accreditations', multiple: true, tag: true)
    select2('second', 'organization_accreditations', multiple: true, tag: true)
    click_button 'Save changes'
    expect(@organization.reload.accreditations).to eq %w(first second)
  end

  scenario 'removing an accreditation', :js do
    @organization.update!(accreditations: %w(County Donations))
    visit '/admin/organizations/parent-agency'
    within '#s2id_organization_accreditations' do
      first('.select2-search-choice-close').click
    end
    click_button 'Save changes'
    expect(@organization.reload.accreditations).to eq ['Donations']
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gymnopilus fibrillosipes Murrill

### Remarks
null


text:
/**
 *
 */
package me.learn.personal.month5;

/**
 * Title 199 :
 *
 * Date : Dec 7, 2020
 *
 * @author bramanarayan
 *
 */
public class BinaryTreeRightSideView {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


text:
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74.123456789 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'

print "Let's talk about %s." % my_name
print "He's %f inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth

#this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)

#No idea what this does
print "%r" % my_height

#To round a float
print round(1.7333)

#To convert inches into centimeters

#To convert pounds into kilograms


text:
package be.g00glen00b.repository;

import be.g00glen00b.entity.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface TaskRepository extends JpaRepository<Task, Long> {
}


text:
module Jekyll
  class YouTubeTag < Liquid::Tag
    @videoid = nil
    @width = ""
    @height = ""

    def initialize(tag_name, markup, tokens)
      if markup =~ /(?:(?:https?:\/\/)?(?:www.youtube.com\/(?:embed\/|watch\?v=)|youtu.be\/)?(\S+)(?:\?rel=\d)?)(?:\s+(\d+)\s(\d+))?/i
        @videoid = $1
        @width = $2 || "480"
        @height = $3 || "360"
      end
      super
    end

    def render(context)
      ouptut = super
      if @videoid
        video = %Q{

}
      else
        "Error processing input, expected syntax: {% youtube video_id [width height] %}"
      end
    end
  end
end

Liquid::Template.register_tag("youtube", Jekyll::YouTubeTag)


text:
package main

import (
	"flag"
	"os"
	"os/signal"
	"syscall"

	"go-common/app/job/main/history/conf"
	"go-common/app/job/main/history/http"
	"go-common/app/job/main/history/service"
	"go-common/library/log"
	"go-common/library/net/trace"
)

func main() {
	flag.Parse()
	if err := conf.Init(); err != nil {
		log.Error("conf.Init() error(%v)", err)
		panic(err)
	}
	log.Init(conf.Conf.Log)
	trace.Init(conf.Conf.Tracer)
	defer trace.Close()
	defer log.Close()
	log.Info("history-job start")
	// init
	svr := service.New(conf.Conf)
	http.Init(conf.Conf, svr)
	// init signal
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	for {
		s := <-c
		log.Info("history get a signal %s", s.String())
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			svr.Close()
			log.Info("history exit")
			return
		case syscall.SIGHUP:
		// TODO reload
		default:
			return
		}
	}
}


text:
#ifndef __G729A_INTERFACE_H__
#define __G729A_INTERFACE_H__

#include "g729a_typedef.h"
#include "g729a_errors.h"

typedef void * G729A_Enc_state;
typedef void * G729A_Dec_state;

#ifdef __cplusplus
extern "C" {
#endif

/*---------------------------------------------*
 * Encoder functions                           *
 *---------------------------------------------*/

/**
 *  @brief  Get size in bytes of the g729a encoder state.
 *
 *  @return  Number of bytes in g729a encoder state.
 */
G729_UWord32 G729A_Encoder_Get_Size();

/**
 *  @brief  Init or reset encoder.
 *
 *  @param encState,  Encoder state.
 *
 *  @return   0, succeeded
 *           -1, if an error occurs
 */
G729_Word32 G729A_Encoder_Init(G729A_Enc_state encState);

/**
 *  @brief  Encode a frame of 16-bit linear PCM data with g729a.
 *
 *  @param encState,  Encoder state.
 *  @param speechIn,  Speech sample input vector (80 samples).
 *  @param outData,   Encoded output vector (10 Bytes).
 *
 *  @return   0, succeeded
 *           -1, if an error occurs,
 *               and you can use G729A_Encoder_Get_Error to get the last error code.
 */
G729_Word32 G729A_Encoder_Process(G729A_Enc_state encState, G729_Word16 * speechIn, G729_UWord8 * outData);

/**
 *  @brief  Get last error code of encoder.
 *
 *  @param encState,  encoder state.
 *
 *  @return  -1, if getting last error code failed
 *           otherwise, return the last error code of decoder
 */
G729_Word32 G729A_Encoder_Get_Error(G729A_Enc_state encState);

/*---------------------------------------------*
 * Decoder functions                           *
 *---------------------------------------------*/

/**
 *  @brief  Get size in bytes of the g729a decoder state.
 *
 *  @return  Number of bytes in g729a decoder state.
 */
G729_UWord32 G729A_Decoder_Get_Size();

/**
 *  @brief  Init or reset decoder.
 *
 *  @param decState,  decoder state.
 *
 *  @return   0, succeeded
 *           -1, if an error occurs
 */
G729_Word32 G729A_Decoder_Init(G729A_Dec_state decState);

/**
 *  @brief  Decode a frame of g729a encoded bitstream data.
 *
 *  @param decState,   Decoder state.
 *  @param inData,     Encoded input vector (10 Bytes).
 *  @param speechOut,  Decoded output speech vector (80 samples).
 *
 *  @return   0, succeeded
 *           -1, if an error occurs,
 *               and you can use G729A_Decoder_Get_Error to get the last error code.
 */
G729_Word32 G729A_Decoder_Process(G729A_Dec_state decState, G729_UWord8 * inData, G729_Word16 * speechOut);

/**
 *  @brief  Get last error code of decoder.
 *
 *  @param decState,  Decoder state.
 *
 *  @return  -1, if getting last error code failed
 *           otherwise, return the last error code of decoder
 */
G729_Word32 G729A_Decoder_Get_Error(G729A_Dec_state decState);

/*---------------------------------------------*
 * Generic functions                           *
 *---------------------------------------------*/

/**
 *  @brief  Get the version number.
 *
 *  @return  A pointer to string specifying the version.
 */
const char * G729A_Get_Version();

/*---------------------------------------------*
 * Testing functions                           *
 * Derived from ITU official testing code      *
 *---------------------------------------------*/

/**
 *  @param encState,  Encoder state.
 *  @param speechIn,  Speech sample input vector (80 samples).
 *  @param outData,   Encoded output vector (164 Bytes).
 */
G729_Word32 G729A_Encoder_Process_Testing(G729A_Enc_state encState, G729_Word16 * speechIn, G729_Word16 * outData);

/**
 *  @param decState,   Decoder state.
 *  @param inData,     Encoded input vector (164 Bytes).
 *  @param speechOut,  Decoded output speech vector (80 samples).
 */
G729_Word32 G729A_Decoder_Process_Testing(G729A_Dec_state decState, G729_Word16 * inData, G729_Word16 * speechOut);

#ifdef __cplusplus
}
#endif

#endif  /* __G729A_INTERFACE_H__ */
/* end of file */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Br. Mus. nat. Hist. , Bot. 14(2): 171 (1985)

#### Original name
Microthelia uniserialis Zahlbr.

### Remarks
null


text:
package io.gravitee.repository.management.model;

import java.util.Date;
import java.util.Objects;

/**
 * @author Azize ELAMRANI (azize.elamrani at graviteesource.com)
 * @author GraviteeSource Team
 */
public class Rating {
    public enum RatingEvent implements Audit.ApiAuditEvent {
        RATING_CREATED, RATING_UPDATED, RATING_DELETED
    }
    private String id;
    private String referenceId;
    private RatingReferenceType referenceType;
    private String user;
    private byte rate;
    private String title;
    private String comment;
    private Date createdAt;
    private Date updatedAt;

    public Rating() {
    }

    public Rating(Rating cloned) {
        this.id = cloned.id;
        this.user = cloned.user;
        this.rate = cloned.rate;
        this.title = cloned.title;
        this.comment = cloned.comment;
        this.createdAt = cloned.createdAt;
        this.updatedAt = cloned.updatedAt;
        this.referenceId = cloned.referenceId;
        this.referenceType = cloned.referenceType;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public byte getRate() {
        return rate;
    }

    public void setRate(byte rate) {
        this.rate = rate;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public String getReferenceId() {
        return referenceId;
    }

    public void setReferenceId(String referenceId) {
        this.referenceId = referenceId;
    }

    public RatingReferenceType getReferenceType() {
        return referenceType;
    }

    public void setReferenceType(RatingReferenceType referenceType) {
        this.referenceType = referenceType;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Rating)) return false;
        Rating rating = (Rating) o;
        return Objects.equals(id, rating.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, referenceId, referenceType);
    }

    @Override
    public String toString() {
        return "Rating{" +
                "id='" + id + '\'' +
                ", referenceId='" + referenceId + '\'' +
                ", referenceType=" + referenceType +
                ", user='" + user + '\'' +
                ", rate=" + rate +
                ", title='" + title + '\'' +
                ", comment='" + comment + '\'' +
                ", createdAt=" + createdAt +
                ", updatedAt=" + updatedAt +
                '}';
    }
}


text:
alter table indicator_location_values

rename column time_period to observation_timestamp;

alter table indicator_location_values

drop constraint indicator_location_values_time_period_fkey,

alter column observation_timestamp type timestamptz
USING to_date(observation_timestamp, 'YYYY'),

add column observation_range tstzrange,

add constraint only_one check (
    observation_range is null
    or observation_timestamp is null);


text:
require 'spec_helper'

describe Morito::Client do
  let(:client) { described_class.new(user_agent) }

  describe '#allowed?' do
    subject { client.allowed?(requesting_url, cache: cache) }

    let(:cache) { true }

    context 'with response' do
      let(:body) do
        <<-EOS
User-agent: *
Disallow: /private
Disallow: /*?$
Allow: /private/photo

# Comment
User-agent: restricted agent # Comment
Disallow: /

User-agent: allowed agent
Disallow: /super_private
EOS
      end

      before do
        stub_request(:any, //).to_return(body: body)
      end

      context 'with public path' do
        let(:requesting_url) { 'http://example.com/public/path' }

        context 'with some agent' do
          let(:user_agent) { 'some agent' }
          it { should == true }
        end

        context 'with restricted agent' do
          let(:user_agent) { 'restricted agent' }
          it { should == false }
        end

        context 'without cache' do
          let(:user_agent) { 'some agent' }
          let(:cache) { false }
          it { should == true }
        end
      end

      context 'with private path' do
        let(:requesting_url) { 'http://example.com/private/path' }

        context 'with some agent' do
          let(:user_agent) { 'some agent' }
          it { should == false }
        end

        context 'with restricted agent' do
          let(:user_agent) { 'restricted agent' }
          it { should == false }
        end

        context 'with allowed agent' do
          let(:user_agent) { 'allowed agent' }
          it { should == true }
        end
      end

      context 'with private but allowed path' do
        let(:requesting_url) { 'http://example.com/private/photo/1' }

        context 'with some agent' do
          let(:user_agent) { 'some agent' }
          it { should == true }
        end
      end

      context 'with patternized path' do
        let(:user_agent) { 'some agent' }

        context 'for eol' do
          let(:requesting_url) { 'http://example.com/some/path?' }
          it { should == false }
        end

        context 'for no eol' do
          let(:requesting_url) { 'http://example.com/some/path?param=1' }
          it { should == true }
        end
      end
    end

    context 'with 404' do
      let(:requesting_url) { 'http://example.com/public/path' }
      let(:user_agent) { 'restricted agent' }

      before do
        stub_request(:any, //).to_return(body: '', status: 404)
      end

      it { should == true }
    end
  end
end


text:
package org.apache.drill.exec.rpc;

import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;

import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;

import static com.google.common.base.Preconditions.checkState;

public abstract class AbstractClientConnection extends AbstractRemoteConnection implements ClientConnection {
//  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AbstractClientConnection.class);

  private SaslClient saslClient;

  public AbstractClientConnection(SocketChannel channel, String name,
                                  EncryptionContext encryptContext) {
    super(channel, name, encryptContext);
  }

  public AbstractClientConnection(SocketChannel channel, String name) {
    this(channel, name, new EncryptionContextImpl());
  }

  protected abstract Logger getLogger();

  @Override
  public void setSaslClient(final SaslClient saslClient) {
    checkState(this.saslClient == null);
    this.saslClient = saslClient;

    // If encryption is enabled set the backend wrapper instance corresponding to this SaslClient in the connection
    // object. This is later used to do wrap/unwrap in handlers.
    if (isEncryptionEnabled()) {
      saslCodec = new SaslCodec() {

        @Override
        public byte[] wrap(byte[] data, int offset, int len) throws SaslException {
          checkState(saslClient != null);
          return saslClient.wrap(data, offset, len);
        }

        @Override
        public byte[] unwrap(byte[] data, int offset, int len) throws SaslException {
          checkState(saslClient != null);
          return saslClient.unwrap(data, offset, len);
        }
      };
    }
  }

  @Override
  public SaslClient getSaslClient() {
    checkState(this.saslClient != null);
    return saslClient;
  }

  @Override
  public void disposeSaslClient() {
    try {
      if (saslClient != null) {
        saslClient.dispose();
        saslClient = null;
      }
    } catch (final SaslException e) {
      getLogger().warn("Unclean disposal", e);
    }
  }

  @Override
  public void channelClosed(RpcException ex) {
    // This will be triggered from Netty when a channel is closed. We should cleanup here
    // as this will handle case for both client closing the connection or server closing the
    // connection.
    disposeSaslClient();

    // Decrease the connection counter here since the close handler will be triggered
    // for all the types of connection
    decConnectionCounter();
    super.channelClosed(ex);
  }
}