text:
"""
Hiveary
https://hiveary.com

Licensed under Simplified BSD License (see LICENSE)
(C) Hiveary, Inc. 2013-2014 all rights reserved
"""

import datetime
import json
import kombu
import kombu.common
import kombu.utils.debug
import logging
import oauth2
import os
import platform
import random
import socket
from ssl import CERT_REQUIRED, CERT_NONE
import subprocess
import sys
import time
import traceback
import urllib2

# Windows specific imports
if subprocess.mswindows:
  import pythoncom
  import wincom

# Local imports
from . import oauth_client
from . import paths
import hiveary.info.system

class NetworkController(object):
  """Class used to handle network functions, such as the AMQP connection."""

  PING_TIMER = 120  # How often to ping the server, in seconds
  MAX_BACKOFF_MULTIPLE = 10

  def __init__(self, reactor=None, logger=None):
    """Initialze the controller.

    Args:
      reactor: A reference to the twisted reactor controlling the agent.
      logger: A logging object to use.
    """

    self.logger = logger or logging.getLogger('hiveary_agent.network')

    # Configuration values - most of these will be modified by the host's
    # configuration file
    self.running = True
    self.owner = ''
    self.hostname = ''
    self.access_token = 'hunter5'
    self.debug_mode = False
    self.disable_ssl_verification = False
    self.obj_id = None
    self.remote_host = ''
    self.amqp_server = ''
    self.ca_bundle = None
    self.current_system = platform.system()

    # AMQP connection values
    self.user_id = None
    self.amqp_password = None
    self.amqp = None

    # Thread and deferred management
    self.reactor = reactor

    self.monitors = {}

  def ensure_internet_connection(self, test_url='http://google.com'):
    """Blocks until there is an active connection to the public internet.
    Uses an IP address by default, since DNS lookups can cause urllib2 to
    block for a while and eat up system resources while doing so."""

    self.logger.debug('Checking for an active internet connection...')

    while True:
      try:
        urllib2.urlopen(test_url, timeout=1)
        break
      except urllib2.URLError:
        self.logger.debug('Test connection failed:\n', exc_info=True)
        time.sleep(5)

    self.logger.debug('Active connection found!')

  def initialize_amqp(self):
    """Method to establish an AMQP connection and consumers."""

    # Find out the credentials used for AMQP
    url = 'https://{host}/amqp/account?hostname={hostname}'.format(
        host=self.remote_host, hostname=self.hostname)
    resp, content = self.request_with_backoff(url, method='GET')

    if resp.status == 200:
      self.logger.info('Retrieved AMQP credentials')
      content_json = json.loads(content)
      self.amqp_password = content_json.get('amqp_password')
      self.user_id = content_json.get('user_id')
      self.obj_id = content_json.get('host_id')
    elif resp.status == 409:
      self.logger.error('Unable to connect this host to the server, '
                        'you\'ve already used all of your licenses. '
                        'Please vist https://%s/upgrade to upgrade your plan.',
                        self.remote_host)
      sys.exit(409)
    else:
      self.logger.error('Failed to retrieve AMQP credentials. Status: %s',
                        resp.status)
      sys.exit(resp.status)

    if self.obj_id is None or self.amqp_password is None or self.user_id is None:
      self.logger.error('Missing required parameters to establish an AMQP connection')
      sys.exit(1)

    if self.debug_mode:
      kombu.utils.debug.setup_logging()

    # Create the connection
    ca_certs = os.path.join(paths.get_program_path(), 'ca-bundle.pem')
    self.logger.debug('Using SSL cert bundle at "%s"', ca_certs)

    ssl_options = {
        'ca_certs': ca_certs,
        'cert_reqs': CERT_REQUIRED,
      }
    # Disable certificate validation when debugging a non-frozen app or when
    # specifically told to as a startup arg
    if self.disable_ssl_verification:
      ssl_options['cert_reqs'] = CERT_NONE

    self.logger.debug('Connecting to %s as user %s', self.amqp_server, self.user_id)
    self.amqp = kombu.Connection(self.amqp_server, self.user_id, self.amqp_password,
                                 port=5671, ssl=ssl_options, insist=True,
                                 transport='amqplib',
                                 transport_options={'confirm_publish': True})

    self.amqp.ensure_connection(errback=self.amqp_errback, interval_max=60)
    self.logger.info('SSL-AMQP connection established')
    self.reactor.callInThread(self.drain_events)

  def stop_amqp(self):
    """Stops listening for AMQP messages and releases the connection."""

    self.running = False
    if self.amqp:
      try:
        self.amqp.release()
      except:
        pass

  def amqp_reconnect(self):
    """Handles re-establishing an AMQP connection after an error occurred.
    In some error cases, the connection will be marked as connected despite
    the error, so ensure_connection will not be enoguh to reconnnect.
    Forcing a release first resolves this."""

    self.logger.info('Reconnecting to AMQP...')
    self.amqp.release()
    self.amqp.ensure_connection(errback=self.amqp_errback,
                                interval_start=5,
                                interval_step=5,
                                interval_max=60)

  def drain_events(self):
    """Attempts to receive a message from the AMQP server and times out after
    a short wait. Loops until the agent is marked as stopping. This allows us
    to gracefully close the connection when waiting for messages."""

    # Setup the consumers
    task_queue = kombu.Queue('agent.{user}.tasks.{host}'.format(
                             user=self.user_id, host=self.obj_id))
    try:
      task_consumer = self.amqp.Consumer(task_queue, auto_declare=False,
                                         callbacks=[self.task_callback])
      task_consumer.consume()
    except:
      if self.running:
        raise

    self.logger.info('Draining events from the server')

    while self.running:
      try:
        self.amqp.drain_events(timeout=1)
      except (socket.timeout, socket.error):
        pass
      except Exception, err:
        # Errors generated while the agent is stopping can be ignored
        if self.running:
          self.logger.error('AMQP error while draining events: %s', err,
                            exc_info=self.debug_mode)
          self.amqp_reconnect()
          break
    else:
      self.logger.debug('No longer running, stopping the amqp drain')
      return

    # If the loop broke while the agent is still running, try starting over
    self.drain_events()

  def create_oauth_client(self):
    """Generates an OAuth client that handles the OAuth signature and header.

    Returns:
      The configured OAuth client, an instance of oauth2.Consumer.
    """

    consumer = oauth2.Consumer(key=self.owner, secret=self.access_token)
    try:
      client = oauth_client.OAuthClient(consumer, debug=self.debug_mode,
                                        disable_ssl_verification=self.disable_ssl_verification,
                                        ca_bundle=self.ca_bundle)
    except IOError:
      sys.exit(1)

    return client

  def request_with_backoff(self, url, attempt=0, **kwargs):
    """Makes an OAuth authenticated HTTPS request. If the request fails, it
    will be retried using an exponential backoff.

    Args:
      url: The absolute url of the server.
      attempt: The current attempt. Anything higher than 0 indicates that a
               previous attempt failed and the request is being retried. This
               is used as a multiple to determine how long to backoff.
      kwargs: Any extra arguments to pass to the client.
    Returns:
      A tuple of (response, content), the first being an instance of the
      'httplib2.Http.Response' class, the second being a string that
      contains the response entity body.

    Raises:
      RuntimeError: Occurs when the program is exiting but we are stuck in this loop.
    """

    # Check to see if we tried to kill the process, if so, bail.
    if not self.running:
      raise RuntimeError

    client = self.create_oauth_client()

    try:
      response = client.request(url, **kwargs)

      # Response is a 2-item tuple of headers, content
      self.logger.debug('Got back a response of %s', response[0].status)

      return response
    except socket.error:
      # Parse out extremely verbose/sensitive data
      logged_kwargs = kwargs.copy()
      if 'body' in logged_kwargs:
        del(logged_kwargs.body)

      self.logger.error('Socket error when attempting to send to %s with params %s:',
                        url, logged_kwargs, exc_info=traceback.format_exc())
      self.logger.debug('Verbose parameter information for errored request:\n%s',
                        kwargs)

      timer = (2 ** attempt) + (random.randint(0, 1000) / 1000.0)
      self.logger.error('Retrying in %.3f', timer)

      # Try again after the backoff and increment the attempts made
      time.sleep(timer)

      # Limit the upper end of the backoff timer
      if attempt < self.MAX_BACKOFF_MULTIPLE:
        attempt += 1

      self.ensure_internet_connection()

      return self.request_with_backoff(url, attempt, **kwargs)

  def publish_alert_message(self, alert=None):
    """Publishes an AMQP message to the alert queue, with some extra data.

    Args:
      alert: The alert to publish. This should be an instance of alerts.BaseAlert
          and will be JSONified before being sent.
    """

    self.publish_info_message('alert', alert)

  def publish_info_message(self, routing_key, message='', retry=True,
                           exchange_name=None):
    """Method to publish an AMQP message.

    Args:
      routing_key: The AMQP routing key.
      message: The message to publish, as a string or dict.
      retry: A boolean of whether a failed publish should be re-attempted.
      exchange_name: An optional AMQP exchange name to use.
    """

    self.logger.debug('Sending "%s" AMQP message', routing_key)

    if not exchange_name:
      exchange_name = 'agent.{user}'.format(user=self.user_id)

    # Check the message format and add the host ID
    if type(message) == dict:
      message['host_id'] = self.obj_id
      message['timestamp'] = time.time()
      message = json.dumps(message)

    exchange = kombu.Exchange(exchange_name)
    with self.amqp.Producer(exchange=exchange, routing_key=routing_key,
                            auto_declare=False) as producer:
      try:
        producer.publish(message, user_id=self.user_id,
                         timestamp=datetime.datetime.utcnow())
      except Exception, err:
        self.logger.error('Error while publishing to AMQP: %s', err,
                          exc_info=self.debug_mode)
        self.amqp_reconnect()

        # Retry publishing the message if requested
        if retry:
          self.publish_info_message(routing_key, message, retry, exchange_name)

  def amqp_errback(self, exc, interval):
    """Error callback fired when there is a problem with the connection or channel.

    Args:
      exc: The exception that occurred.
      interval: Amount of time before the message is attempted again.
    """

    self.logger.error('AMQP connection error: %r. Retrying in %ds', exc, interval)
    self.ensure_internet_connection()

  def ping_pong(self):
    """Function to alert the server that we're still alive and doing science."""

    # Send the ping
    self.logger.debug('Sending ping to server')
    self.publish_info_message('ping', {}, retry=False)

  def task_callback(self, body, message):
    """Callback for when a message is received from the tasks queue.

    Args:
      body: A string of the response sent back from the broker.
      message: The AMQP object containing metadata about the response.
    """

    self.logger.debug('Received the following task message: %s', body)
    message.ack()

    try:
      data = json.loads(body)
    except ValueError:
      self.logger.error('Unable to process task:', exc_info=True)
    else:
      self.run_task(data)

  def run_task(self, client_task):
    """Run a task as commanded by the control server.

    Args:
      client_task: A dictionary of the task to attempt.
    """

    # Start creating the response to send back to the server
    data = {'id': client_task.get('id')}
    task_name = client_task['command']['name']
    routing_key = 'task_complete'

    if task_name == 'refresh':
      # Re-poll available system data
      item = client_task['command'].get('item', 'all')
      self.logger.debug('Retrieving %s information', item)
      info_method = getattr(hiveary.info.system, 'pull_{item}'.format(item=item))

      routing_key = '{user}.{host}.{item}'.format(user=self.user_id,
                                                  host=self.obj_id, item=item)

      data['info'] = info_method()
      data['status'] = 'SUCCESS'
    elif task_name == 'com':
      # Run a command using the Windows COM interface
      if self.current_system == 'Windows':
        interface = client_task['command']['interface']
        item = client_task['command']['item']

        try:
          com_client = wincom.WindowsCOMClient(interface)

          # Check if are retrieving or setting information
          if client_task['command']['action'] == 'set':
            value = client_task['command']['value']
            com_client.set_item(value, item)
          elif client_task['command']['action'] == 'get':
            value = com_client.get_item(item)
            data['info'] = {'item': item, 'value': value}
          else:
            self.logger.error('Unable to perform requested COM action')
            data['status'] = 'NOT_IMPLEMENTED'
        except pythoncom.com_error, error:
          # A com_error likely indicates a bad interface name or item name, so we
          # should mark the task as incompleteable
          data['status'] = 'FAILURE'
          data['info'] = error.strerror
      else:
        self.logger.error('COM interface is only accessible on Windows systems')
        data['status'] = 'FAILURE'
    elif task_name == 'expected_update':
      expected_values = client_task['command']['expected']
      monitor_id = client_task['command']['monitor']
      self.logger.info('Received new %s expected values: %s',
                       monitor_id, expected_values)

      if monitor_id in self.monitors:
        self.monitors[monitor_id].expected_values.update(expected_values)
      else:
        self.logger.warn('Monitor "%s" is not enabled!', monitor_id)
    elif task_name == 'live_data':
      # Tell the relevant monitor to start sending a copy of all data to a special
      # real-time AMQP queue
      monitor_id = client_task['command']['monitor']
      action = client_task['command']['action']
      stream_routing_key = client_task['command']['routing_key']
      self.logger.info('Received request to %s sending real-time data for %s',
                       action, monitor_id)

      if monitor_id in self.monitors:
        if action == 'start':
          # Add a new livestream callback
          exchange_name = 'agent.{user}.reports'.format(user=self.user_id)
          live_publish = lambda data: self.publish_info_message(stream_routing_key,
                                                                data,
                                                                exchange_name=exchange_name)

          # Send a copy of any data that has been aggregated so far
          data = self.monitors[monitor_id].merge_data()
          data.pop('timestamp', None)
          data_container = {
              'data': data,
              'monitor_id': monitor_id,
              'interval': self.monitors[monitor_id].MONITOR_TIMER,
          }
          self.logger.debug('Sending inititial data: %s', data_container)
          live_publish(data_container)

          # Store the lambda on the monitor so all future data will get published
          self.monitors[monitor_id].livestreams[stream_routing_key] = live_publish
        elif action == 'stop':
          # Delete the previously setup stream
          self.logger.info('Stopping livestream for %s...', monitor_id)
          if monitor_id not in self.monitors:
            self.logger.warn('Monitor %s has not been started', monitor_id)
          elif stream_routing_key not in self.monitors[monitor_id].livestreams:
            self.logger.info('Livestream for monitor %s was not enabled, skipping',
                             monitor_id)
          else:
            del(self.monitors[monitor_id].livestreams[stream_routing_key])
            self.logger.info('Livestream stopped')
      else:
        self.logger.warn('Monitor "%s" is not enabled!', monitor_id)
    elif task_name == 'update':
      # An update for the agent is available
      version = client_task['command']['version']

      try:
        self.agent_update(self.reactor, version=version)
      except (NotImplementedError, NameError):
        self.logger.warn('Could not complete update task:', exc_info=True)
        data['status'] = 'NOT_IMPLEMENTED'
    else:
      self.logger.error('Unable to perform requested task')
      data['status'] = 'NOT_IMPLEMENTED'

    if data['id'] is not None or routing_key != 'task_complete':
      self.publish_info_message(routing_key, json.dumps(data))
      self.logger.info('Sent task completion to server')


text:
package bluge

import (
	"io/ioutil"
	"log"

	"github.com/blugelabs/bluge/index"

	"github.com/blugelabs/bluge/search"
	"github.com/blugelabs/bluge/search/similarity"

	"github.com/blugelabs/bluge/analysis"
	"github.com/blugelabs/bluge/analysis/analyzer"
)

type Config struct {
	indexConfig index.Config
	Logger      *log.Logger

	DefaultSearchField    string
	DefaultSearchAnalyzer *analysis.Analyzer
	DefaultSimilarity     search.Similarity
	PerFieldSimilarity    map[string]search.Similarity

	SearchStartFunc func(size uint64) error
	SearchEndFunc   func(size uint64)
}

// WithVirtualField allows you to describe a field that
// the index will behave as if all documents in this index were
// indexed with these field/terms, even though nothing is
// physically persisted about them in the index.
func (config Config) WithVirtualField(field Field) Config {
	_ = field.Analyze(0)
	config.indexConfig = config.indexConfig.WithVirtualField(field)
	return config
}

func (config Config) WithSegmentType(typ string) Config {
	config.indexConfig = config.indexConfig.WithSegmentType(typ)
	return config
}

func (config Config) WithSegmentVersion(ver uint32) Config {
	config.indexConfig = config.indexConfig.WithSegmentVersion(ver)
	return config
}

func (config Config) DisableOptimizeConjunction() Config {
	config.indexConfig = config.indexConfig.DisableOptimizeConjunction()
	return config
}

func (config Config) DisableOptimizeConjunctionUnadorned() Config {
	config.indexConfig = config.indexConfig.DisableOptimizeConjunctionUnadorned()
	return config
}

func (config Config) DisableOptimizeDisjunctionUnadorned() Config {
	config.indexConfig = config.indexConfig.DisableOptimizeDisjunctionUnadorned()
	return config
}

func (config Config) WithSearchStartFunc(f func(size uint64) error) Config {
	config.SearchStartFunc = f
	return config
}

func DefaultConfig(path string) Config {
	indexConfig := index.DefaultConfig(path)
	return defaultConfig(indexConfig)
}

func InMemoryOnlyConfig() Config {
	indexConfig := index.InMemoryOnlyConfig()
	return defaultConfig(indexConfig)
}
func DefaultConfigWithDirectory(df func() index.Directory) Config {
	indexConfig := index.DefaultConfigWithDirectory(df)
	return defaultConfig(indexConfig)
}

func defaultConfig(indexConfig index.Config) Config {
	rv := Config{
		Logger:                log.New(ioutil.Discard, "bluge", log.LstdFlags),
		DefaultSearchField:    "_all",
		DefaultSearchAnalyzer: analyzer.NewStandardAnalyzer(),
		DefaultSimilarity:     similarity.NewBM25Similarity(),
		PerFieldSimilarity:    map[string]search.Similarity{},
	}

	allDocsFields := NewKeywordField("", "")
	_ = allDocsFields.Analyze(0)
	indexConfig = indexConfig.WithVirtualField(allDocsFields)
	indexConfig = indexConfig.WithNormCalc(func(field string, length int) float32 {
		if pfs, ok := rv.PerFieldSimilarity[field]; ok {
			return pfs.ComputeNorm(length)
		}
		return rv.DefaultSimilarity.ComputeNorm(length)
	})
	rv.indexConfig = indexConfig

	return rv
}

redpajama_set_name: RedPajamaGithub


text:
PatanHospital
=============

This is a project developed by students of Loyola University Chicago for Open Source Computing(COMP 412). We gratefully acknowledge professor Matthew Butcher(github technosophos) for his support to build this project.

This is an application developed primarily to make interaction in the hospital environment easier. There are primarily 3 end users Administrator, Doctor and a patient. It creates a bridge among all the end users making interaction among each other easier. PatanHospital works as a basic structure that can be applied to any hospital environment and can be easily customized to meet specific requirement.

The project is developed in Microsoft Visual Studio Professional 2012. The backend server used is MS Server 2008. The server is hosted on sql.cs.luc.edu.

The latest versionof the project has the following features: Administrator can register,edit and delete patient/doctor information, reserve appointments for patients over the phone, edit the reservations.Patients can register themselves and reserve appointment with a doctor, request reservation over the phone and edit their information. Doctors can view their profile and view the appointment scheduled for a specific day. An auto generated password is mailed to doctor and patient upon registration. An email is also sent to doctors and patients upon appointment reservation. Forgot password and update password feature is also available for the doctor and patient.

For Technical Assistance
=========================

A group forum/Email list has been created using Google groups.All release information as well as ideas will be discussed on the forum. Simply submit a request and you will added to the forum thereafter. the link to the forum:
https://groups.google.com/forum/#!forum/patenthospitalgroup

To report Issues
=================

https://github.com/richa615/PatanHospital/issues


text:
namespace RenderCore { namespace Techniques { class ParsingContext; } }
namespace SceneEngine { class IIntersectionTester; }

namespace EntityInterface { class RetainedEntities; }

namespace GUILayer
{
    class ObjectPlaceholders : public std::enable_shared_from_this<ObjectPlaceholders>
    {
    public:
        void Render(
            RenderCore::Metal::DeviceContext& threadContext,
            RenderCore::Techniques::ParsingContext& parserContext,
            unsigned techniqueIndex);

        void AddAnnotation(EntityInterface::ObjectTypeId typeId, const std::string& geoType);

        std::shared_ptr<SceneEngine::IIntersectionTester> CreateIntersectionTester();

        ObjectPlaceholders(std::shared_ptr<EntityInterface::RetainedEntities> objects);
        ~ObjectPlaceholders();
    protected:
        std::shared_ptr<EntityInterface::RetainedEntities> _objects;

        class Annotation
        {
        public:
            EntityInterface::ObjectTypeId _typeId;
        };
        std::vector<Annotation> _cubeAnnotations;
		std::vector<Annotation> _directionalAnnotations;
        std::vector<Annotation> _triMeshAnnotations;
		std::vector<Annotation> _areaLightAnnotation;

        class IntersectionTester;
    };
}


text:
from __future__ import absolute_import
import time
import os
import atexit
import six
from six.moves import range

try:
    import multiprocessing as mp

except ImportError:
    mp = None

import numpy as nm

from sfepy.base.base import sfepy_config_dir, ordered_iteritems
from sfepy.base.base import output, get_default, set_defaults, Output, Struct
from sfepy.base.log_plotter import draw_data, LogPlotter

_msg_no_live = 'warning: log plot is disabled, install matplotlib and' \
    ' multiprocessing'

def get_logging_conf(conf, log_name='log'):
    """
    Check for a log configuration ('log' attribute by default) in
    `conf`. Supply default values if necessary.

    Parameters
    ----------
    conf : Struct
        The configuration object.
    log_name : str, optional
        The name of the log configuration attribute in `conf`.

    Returns
    -------
    log : dict
        The dictionary {'plot' : <figure_file>, 'text' : <text_log_file>}. One
        or both values can be None.
    """
    log = conf.get(log_name, None)

    default_log = {'text' : None, 'plot' : None}

    if log is None:
        log = default_log

    else:
        set_defaults(log, default_log)

    return log

def iter_names(data_names, igs=None):
    if igs is None:
        igs = nm.arange(len(data_names))

    ii = iseq = 0
    for ig, names in ordered_iteritems(data_names):
        for ip, name in enumerate(names):
            if ig in igs:
                yield ig, ip, ii, iseq, name
                iseq += 1
            ii += 1

def read_log(filename):
    """
    Read data saved by :class:`Log` into a text file.

    Parameters
    ----------
    filename : str
        The name of a text log file.

    Returns
    -------
    log : dict
        The log with data names as keys and ``(xs, ys, vlines)`` as values.
    info : dict
        The log plot configuration with subplot numbers as keys.
    """
    from sfepy.base.base import as_float_or_complex as afc

    log = {}
    info = {}
    name2key = {}

    fd = open(filename, 'r')

    for line in fd:
        if line[0] == '#':
            ls = line.split(':')
            if ls[0] == '# groups':
                n_gr = int(ls[1])
                offset = 0
                for ig in range(n_gr):
                    next(fd)
                    line_info = next(fd)
                    xlabel, ylabel, yscales = line_info.split(',')

                    line_names = next(fd)
                    names = line_names.split(':')[1]
                    names = [name.strip().strip('"')
                             for name in names.split(',')]
                    if len(names[0]) == 0:
                        names = []

                    line_plot_kwargs = next(fd)
                    aux = line_plot_kwargs[19:].strip().strip('"')
                    plot_kwargs = eval(aux + ',') if len(aux) else ({},)

                    info[ig] = (xlabel.split(':')[1].strip().strip('"'),
                                ylabel.split(':')[1].strip().strip('"'),
                                yscales.split(':')[1].strip().strip('"'),
                                names,
                                plot_kwargs)

                    name2key.update({name : ik + offset
                                     for ik, name in enumerate(info[ig][3])})
                    offset += len(info[ig][3])
            continue

        ls = line.split(':')

        try:
            key = int(ls[0])

        except ValueError:
            key = name2key[ls[0]] # Old style log.

        xs, ys, vlines = log.setdefault(key, ([], [], []))

        if (len(ls) == 2) and len(log[key][0]):
            vlines.append(log[key][0][-1])

        else:
            try:
                xval = afc(ls[1])
                yval = afc(ls[2])

            except ValueError:
                continue

            xs.append(xval)
            ys.append(yval)

    fd.close()

    for key, (xs, ys, vlines) in six.iteritems(log):
        log[key] = (nm.array(xs), nm.array(ys), nm.array(vlines))

    return log, info

def write_log(output, log, info):
    xlabels, ylabels, yscales, names, plot_kwargs = zip(*info.values())
    _write_header(output, xlabels, ylabels, yscales, names, plot_kwargs)

    offset = 0
    for ig, (xlabel, ylabel, yscale, names, plot_kwargs) \
        in ordered_iteritems(info):
        for ip, name in enumerate(names):
            xs, ys, vlines = log[ip + offset]

            for ir, x in enumerate(xs):
                output('{}: {}: {:.16e}'.format(ip + offset, x, ys[ir]))

                if x in vlines:
                    output('%d: -----' % (ip + offset))

        offset += len(names)

    output('# ended: %s' % time.asctime())

def _write_header(output, xlabels, ylabels, yscales, data_names, plot_kwargs):
    _fmt = lambda x: '%s' % x if x is not None else ''

    output('# started: %s' % time.asctime())
    output('# groups: %d' % len(data_names))
    for ig, names in enumerate(data_names):
        output('#   %d' % ig)
        output('#     xlabel: "%s", ylabel: "%s", yscales: "%s"'
                    % (_fmt(xlabels[ig]), _fmt(ylabels[ig]),
                       yscales[ig]))
        output('#     names: "%s"' % ', '.join(names))
        output('#     plot_kwargs: "%s"'
                    % ', '.join('%s' % ii
                                for ii in plot_kwargs[ig]))

def plot_log(axs, log, info, xticks=None, yticks=None, xnbins=None, ynbins=None,
             groups=None, show_legends=True, swap_axes=False):
    """
    Plot log data returned by :func:`read_log()` into a specified figure.

    Parameters
    ----------
    axs : sequence of matplotlib.axes.Axes
        The list of axes for the log data plots.
    log : dict
        The log with data names as keys and ``(xs, ys, vlines)`` as values.
    info : dict
        The log plot configuration with subplot numbers as keys.
    xticks : list of arrays, optional
        The list of x-axis ticks (array or None) for each subplot.
    yticks : list of arrays, optional
        The list of y-axis ticks (array or None) for each subplot.
    xnbins : list, optional
        The list of x-axis number of bins (int or None) for each subplot.
    ynbins : list, optional
        The list of y-axis number of bins (int or None) for each subplot.
    groups : list, optional
        The list of data groups subplots. If not given, all groups are plotted.
    show_legends : bool
        If True, show legends in plots.
    swap_axes : bool
        If True, swap the axes of the plots.
    """
    import matplotlib.pyplot as plt

    if axs is None:
        fig = plt.figure()

    else:
        fig = None

    if groups is None:
        n_gr = len(info)
        groups = nm.arange(n_gr)

    else:
        n_gr = len(groups)

    n_col = min(5.0, nm.fix(nm.sqrt(n_gr)))
    if int(n_col) == 0:
        n_row = 0

    else:
        n_row = int(nm.ceil(n_gr / n_col))
        n_col = int(n_col)

    if xticks is None:
        xticks = [None] * n_gr

    if yticks is None:
        yticks = [None] * n_gr

    if xnbins is None:
        xnbins = [None] * n_gr

    if ynbins is None:
        ynbins = [None] * n_gr

    isub = offset = 0
    for ig, (xlabel, ylabel, yscale, names, plot_kwargs) \
        in ordered_iteritems(info):
        if ig not in groups:
            offset += len(names)
            continue

        if axs is None:
            ax = fig.add_subplot(n_row, n_col, isub + 1)

        else:
            ax = axs[ig]

        if not swap_axes:
            xnb, ynb = xnbins[isub], ynbins[isub]
            xti, yti = xticks[isub], yticks[isub]
            ax.set_yscale(yscale)
            for ip, name in enumerate(names):
                xs, ys, vlines = log[ip + offset]
                draw_data(ax, xs, ys, name, plot_kwargs[ip])

                for x in vlines:
                    ax.axvline(x, color='k', alpha=0.3)

        else:
            xlabel, ylabel = ylabel, xlabel
            xti, yti = yticks[isub], xticks[isub]
            xnb, ynb = ynbins[isub], xnbins[isub]
            ax.set_xscale(yscale)

            for ip, name in enumerate(names):
                xs, ys, vlines = log[ip + offset]
                draw_data(ax, xs, ys, name, plot_kwargs[ip], swap_axes=True)

                for x in vlines:
                    ax.axhline(x, color='k', alpha=0.3)

        offset += len(names)

        if xti is not None:
            ax.set_xticks(xti)

        if yti is not None:
            ax.set_yticks(yti)

        if xnb is not None:
            ax.locator_params(tight=True, axis='x', nbins=xnb)

        if ynb is not None:
            ax.locator_params(tight=True, axis='y', nbins=ynb)

        if xlabel:
            ax.set_xlabel(xlabel)

        if ylabel:
            ax.set_ylabel(ylabel)

        if show_legends:
            ax.legend(loc='best')

        isub += 1

    plt.tight_layout(pad=0.5)

class Log(Struct):
    """
    Log data and (optionally) plot them in the second process via
    LogPlotter.
    """
    count = -1

    @staticmethod
    def from_conf(conf, data_names):
        """
        Parameters
        ----------
        data_names : list of lists of str
            The data names grouped by subplots: [[name1, name2, ...], [name3,
            name4, ...], ...], where name<n> are strings to display in
            (sub)plot legends.
        """
        obj = Log(data_names, **conf)

        return obj

    def __init__(self, data_names=None, plot_kwargs=None,
                 xlabels=None, ylabels=None, yscales=None,
                 show_legends=True, is_plot=True, aggregate=100, sleep=1.0,
                 log_filename=None, formats=None):
        """
        Parameters
        ----------
        data_names : list of lists of str
            The data names grouped by subplots: [[name1, name2, ...], [name3,
            name4, ...], ...], where name<n> are strings to display in
            (sub)plot legends.
        plot_kwargs : list of (lists of dicts) or dicts
            The keyword arguments dicts passed to plot(). For each group the
            item can be either a dict that is applied to all lines in the
            group, or a list of dicts for each line in the group.
        xlabels : list of str
            The x axis labels of subplots.
        ylabels : list of str
            The y axis labels of subplots.
        yscales : list of 'linear' or 'log'
            The y axis scales of subplots.
        show_legends : bool
            If True, show legends in plots.
        is_plot : bool
            If True, try to use LogPlotter for plotting.
        aggregate : int
            The number of plotting commands to process before a redraw.
        sleep : float
            The number of seconds to sleep between polling draw commands.
        log_filename : str, optional
            If given, save log data into a log file.
        formats : list of lists of number format strings
            The print formats of data to be used in a log file, group in the
            same way as subplots.
        """
        try:
            import matplotlib as mpl
        except:
            mpl = None

        Struct.__init__(self,
                        show_legends=show_legends, is_plot=is_plot,
                        aggregate=aggregate, sleep=sleep,
                        data_names={}, n_arg=0, n_gr=0,
                        data={}, x_values={}, n_calls=0, plot_kwargs={},
                        yscales={}, xlabels={}, ylabels={},
                        plot_pipe=None, formats={}, _format_styles={},
                        output=None)

        if data_names is not None:
            n_gr = len(data_names)
        else:
            n_gr = 0
            data_names = []

        plot_kwargs = get_default(plot_kwargs, [{}] * n_gr)
        yscales = get_default(yscales, ['linear'] * n_gr)
        xlabels = get_default(xlabels, ['iteration'] * n_gr)
        ylabels = get_default(ylabels, [''] * n_gr)

        if formats is None:
            formats = [None] * n_gr

        for ig, names in enumerate(data_names):
            self.add_group(names, plot_kwargs[ig],
                           yscales[ig], xlabels[ig], ylabels[ig],
                           formats[ig])

        self.can_plot = (mpl is not None) and (mp is not None)

        if log_filename is not None:
            self.output = Output('', filename=log_filename)
            _write_header(self.output, xlabels, ylabels, yscales, data_names,
                          self.plot_kwargs)

        if self.is_plot and (not self.can_plot):
            output(_msg_no_live)

    def add_group(self, names, plot_kwargs=None,
                  yscale=None, xlabel=None, ylabel=None, formats=None):
        """
        Add a new data group. Notify the plotting process if it is
        already running.
        """
        if plot_kwargs is None:
            plot_kwargs = {}

        ig = self.n_gr
        self.n_gr += 1

        self.x_values[ig] = []

        self.data_names[ig] = names
        self.yscales[ig] = yscale
        self.xlabels[ig] = xlabel
        self.ylabels[ig] = ylabel

        if isinstance(plot_kwargs, dict):
            self.plot_kwargs[ig] = [plot_kwargs] * len(names)

        else:
            self.plot_kwargs[ig] = plot_kwargs

        ii = self.n_arg
        for iseq, name in enumerate(names):
            self.data[ii] = []

            if formats is not None:
                self.formats[ii] = formats[iseq]
            else:
                self.formats[ii] = '{:.3e}'

            self._format_styles[ii] = 0 if '%' in self.formats[ii] else 1
            ii += 1

        self.n_arg = ii

        if self.plot_pipe is not None:
            send = self.plot_pipe.send
            send(['add_axis', ig, names, yscale, xlabel, ylabel,
                  self.plot_kwargs[ig]])

    def get_log_name(self):
        return os.path.join(sfepy_config_dir,
                            'plotter_%03d.log' % self.__class__.count)

    def __call__(self, *args, **kwargs):
        """
        Log the data passed via *args, and send them to the plotting
        process, if available.
        """
        finished = False
        save_figure = ''
        x_values = None
        igs = nm.arange(self.n_gr)
        full = True
        if kwargs:
            if 'finished' in kwargs:
                finished = kwargs['finished']
            if 'save_figure' in kwargs:
                save_figure = kwargs['save_figure']
            if 'x' in kwargs:
                x_values = kwargs['x']

            if 'igs' in kwargs:
                igs = nm.array(kwargs['igs'])
                full = False

        if save_figure and (self.plot_pipe is not None):
            self.plot_pipe.send(['save', save_figure])
            self.plot_pipe.recv()

        if finished:
            self.terminate()
            return

        if save_figure: return

        ls = len(args), self.n_arg
        if full and (ls[0] != ls[1]):
            msg = 'log called with wrong number of arguments! (%d == %d)' % ls
            raise IndexError(msg)

        for ig in igs:
            if (x_values is not None) and (x_values[ig] is not None):
                self.x_values[ig].append(x_values[ig])
            else:
                if len(self.x_values[ig]):
                    ii = self.x_values[ig][-1] + 1
                else:
                    ii = 0
                self.x_values[ig].append(ii)

        for ig, ip, ii, iseq, name in iter_names(self.data_names, igs):
            aux = args[iseq]
            if isinstance(aux, nm.ndarray):
                aux = nm.array(aux, ndmin = 1)
                if len(aux) == 1:
                    aux = aux[0]
                else:
                    raise ValueError('can log only scalars (%s)' % aux)
            self.data[ii].append(aux)

            if self.output:
                if self._format_styles[ii]:
                    self.output(('{}: {}: %s' % self.formats[ii])
                                .format(ii, self.x_values[ig][-1], aux))

                else:
                    self.output(('%%s: %%s: %s' % self.formats[ii])
                                % (ii, self.x_values[ig][-1], aux))

        if self.is_plot and self.can_plot:
            if self.n_calls == 0:
                atexit.register(self.terminate)

                self.__class__.count += 1

                ctx = mp.get_context('spawn')

                self.plot_pipe, plotter_pipe = ctx.Pipe()
                self.plotter = LogPlotter(self.aggregate, self.sleep)
                self.plot_process = ctx.Process(target=self.plotter,
                                                args=(plotter_pipe,
                                                      self.get_log_name(),
                                                      self.data_names,
                                                      self.yscales,
                                                      self.xlabels,
                                                      self.ylabels,
                                                      self.plot_kwargs))
                self.plot_process.daemon = True
                self.plot_process.start()

            self.plot_data(igs)

        self.n_calls += 1

    def terminate(self):
        if self.output is not None:
            self.output('# ended: %s' % time.asctime())
            self.output = None

        if self.is_plot and self.can_plot:
            self.plot_pipe.send(None)
            self.plot_process.join()
            self.n_calls = 0
            output('terminated')

        atexit.unregister(self.terminate)

    def plot_data(self, igs):
        send = self.plot_pipe.send

        for ig in igs:
            send(['clear', ig])

        for ig, ip, ii, iseq, name in iter_names(self.data_names, igs):
            try:
                send(['plot', ig, ip, self.x_values[ig][-1],
                      self.data[ii][-1]])
            except:
                msg = "send failed! (%s, %s, %s)!" % (ii, name, self.data[ii])
                raise IOError(msg)

        if self.show_legends:
            send(['legends'])

        send(['continue'])

    def plot_vlines(self, igs=None, **kwargs):
        """
        Plot vertical lines in axes given by igs at current x locations
        to mark some events.
        """
        if igs is None:
            igs = range(self.n_gr)

        if self.plot_pipe is not None:
            send = self.plot_pipe.send

            for ig in igs:
                x = self.x_values[ig]
                if len(x):
                    send(['vline', ig, x[-1], kwargs])

            send(['continue'])

        if self.output:
            for ig, ip, ii, iseq, name in iter_names(self.data_names, igs):
                self.output('%d: -----' % ii)


text:
/**
 * Terms:
 *
 * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
 * @fileOverview Image控件
 */
define([
    './util'
], function( Util ) {

    var api;

    api = {
        parsers: {
            0xffe1: []
        },

        maxMetaDataSize: 262144,

        parse: function( blob, cb ) {
            var me = this,
                fr = new FileReader();

            fr.onload = function() {
                cb( false, me._parse( this.result ) );
                fr = fr.onload = fr.onerror = null;
            };

            fr.onerror = function( e ) {
                cb( e.message );
                fr = fr.onload = fr.onerror = null;
            };

            blob = blob.slice( 0, me.maxMetaDataSize );
            fr.readAsArrayBuffer( blob.getSource() );
        },

        _parse: function( buffer, noParse ) {
            if ( buffer.byteLength < 6 ) {
                return;
            }

            var dataview = new DataView( buffer ),
                offset = 2,
                maxOffset = dataview.byteLength - 4,
                headLength = offset,
                ret = {},
                markerBytes, markerLength, parsers, i;

            if ( dataview.getUint16( 0 ) === 0xffd8 ) {

                while ( offset < maxOffset ) {
                    markerBytes = dataview.getUint16( offset );

                    if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
                            markerBytes === 0xfffe ) {

                        markerLength = dataview.getUint16( offset + 2 ) + 2;

                        if ( offset + markerLength > dataview.byteLength ) {
                            break;
                        }

                        parsers = api.parsers[ markerBytes ];

                        if ( !noParse && parsers ) {
                            for ( i = 0; i < parsers.length; i += 1 ) {
                                parsers[ i ].call( api, dataview, offset,
                                        markerLength, ret );
                            }
                        }

                        offset += markerLength;
                        headLength = offset;
                    } else {
                        break;
                    }
                }

                if ( headLength > 6 ) {
                    if ( buffer.slice ) {
                        ret.imageHead = buffer.slice( 2, headLength );
                    } else {
                        // Workaround for IE10, which does not yet
                        // support ArrayBuffer.slice:
                        ret.imageHead = new Uint8Array( buffer )
                                .subarray( 2, headLength );
                    }
                }
            }

            return ret;
        },

        updateImageHead: function( buffer, head ) {
            var data = this._parse( buffer, true ),
                buf1, buf2, bodyoffset;

            bodyoffset = 2;
            if ( data.imageHead ) {
                bodyoffset = 2 + data.imageHead.byteLength;
            }

            if ( buffer.slice ) {
                buf2 = buffer.slice( bodyoffset );
            } else {
                buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
            }

            buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );

            buf1[ 0 ] = 0xFF;
            buf1[ 1 ] = 0xD8;
            buf1.set( new Uint8Array( head ), 2 );
            buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );

            return buf1.buffer;
        }
    };

    return api;
});


text:
import * as React from 'react';
import styled, {css} from 'styled-components';

import Button from '/component/base/Button';
import Icon from '/component/base/Icon';
import AccountButton from '/component/partial/AccountButton';
import PaddedContent from '/component/base/PaddedContent';
import Animation from '/component/amp/Animation';
import handleAmpBindClassName from '/util/handleAmpBindClassName';

const SidebarHeader = styled((props) => {
  return
;
})`
  display: flex;
  align-items: center;
  flex-direction: row;
  justify-content: space-between;
  margin: 24px 0;
`;

const SidebarContainer = styled(({className, small: _small, ...rest}) => (
  <amp-sidebar class={className} {...rest} />
))`
  max-width: 100%;
  height: 100%;
  max-height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  ${({small}) => {
    if (small) {
      return css`
        width: 555px;
      `;
    }
    return css`
      width: 750px;
    `;
  }}
  box-shadow: -10px 0 0 rgba(255, 0, 86, 0.1);
  overflow: hidden;
  /* AMP HACK ALERT */
  > button ~ div:last-child {
    display: none;
  }
`;

const SidebarContent = styled.div`
  flex: auto;
  ${({noStickyFooter}) =>
    noStickyFooter
      ? ''
      : css`
          overflow: auto;
        `}
`;

const SidebarHeaderContainer = styled.div`
  position: relative;
  > *:last-child {
    margin-bottom: 32px;
  }
`;

const SidebarHeaderShadow = styled.div`
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  /*
  TODO: FIXME: Re-enable when AMP fixes scroll listeners in
  overflow elements..
  */
  /* -shadow: 0 2px 16px 0 rgba(0, 0, 0, 0.1); */
  pointer-events: none;
`;

class CloseButton extends React.Component {
  render() {
    const {id, prev} = this.props;
    return (
      <Button.FakeLink on={`tap:${id}.close${prev ? `,${prev}.open` : ''}`}>
        {prev ? <Icon name="arrow-back" /> : <Icon name="close" />}
      </Button.FakeLink>
    );
  }
}

class DefaultSidebarHeader extends React.Component {
  render() {
    const {id, prev} = this.props;
    return (
      <PaddedContent h={7}>
        <SidebarHeader>
          <CloseButton id={id} prev={prev} />

            <AccountButton on={`tap:${id}.close`} inverted label />

        </SidebarHeader>
      </PaddedContent>
    );
  }
}

class Sidebar extends React.PureComponent {
  static DefaultHeader = DefaultSidebarHeader;
  static CloseButton = CloseButton;
  render() {
    const {
      children,
      small,
      id,
      header = <DefaultSidebarHeader id={id} />,
      footer = null,
      side = 'right',
      noStickyFooter = false,
    } = this.props;
    return (
      <SidebarContainer small={small} id={id} layout="nodisplay" side={side}>
        <SidebarHeaderContainer>
          <Animation
            id={`amp-header-anim-${id}`}
            animation={{
              duration: '1',
              fill: 'both',
              animations: [
                {
                  selector: `#amp-header-shadow-${id}`,
                  keyframes: [
                    {opacity: 0.2, offset: 0},
                    {opacity: 0.7, offset: 1},
                  ],
                },
              ],
            }}
          />
          <SidebarHeaderShadow id={`amp-header-shadow-${id}`} />
          {header}
        </SidebarHeaderContainer>
        <SidebarContent noStickyFooter={noStickyFooter}>

            {children}

              <amp-position-observer layout="nodisplay" />

        </SidebarContent>
        {footer}
      </SidebarContainer>
    );
  }
}

export default Sidebar;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class XhtmlOnlyXmlUrlResolver
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class XhtmlOnlyXmlUrlResolver
   ">
    <meta name="generator" content="docfx 2.56.6.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class XhtmlOnlyXmlUrlResolver

A specialisation of System.Xml.XmlUrlResolver which resolves only
XHTML 1.0 and XHTML 1.1 entities.  This class does not permit the direct usage
of network requests, it makes use of a IGetsXhtmlDtds as its source
for the DTD/entity/module resources.

Inheritance

System.Object

System.Xml.XmlResolver

System.Xml.XmlUrlResolver

XhtmlOnlyXmlUrlResolver

Inherited Members

      System.Xml.XmlUrlResolver.GetEntityAsync(System.Uri, System.String, System.Type)

      System.Xml.XmlUrlResolver.CachePolicy

      System.Xml.XmlUrlResolver.Credentials

      System.Xml.XmlUrlResolver.Proxy

      System.Xml.XmlResolver.SupportsType(System.Uri, System.Type)

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.ToString()

Namespace: ZptSharp.Dom

Assembly: ZptSharp.Xml.dll

Syntax

public class XhtmlOnlyXmlUrlResolver : XmlUrlResolver

Constructors

    |
    Improve this Doc

    View Source

XhtmlOnlyXmlUrlResolver(IGetsXhtmlDtds)

Initializes a new instance of the XhtmlOnlyXmlUrlResolver class.

Declaration

public XhtmlOnlyXmlUrlResolver(IGetsXhtmlDtds xhtmlDtdProvider)

Parameters

        Type
        Name
        Description

        IGetsXhtmlDtds
        xhtmlDtdProvider

Xhtml dtd provider.

Fields

    |
    Improve this Doc

    View Source

DtdBaseUri

Gets a Uri for the root location where XHTML DTDs are found.

Declaration

public static readonly Uri DtdBaseUri

Field Value

        Type
        Description

        System.Uri

    |
    Improve this Doc

    View Source

ModuleBaseUri

Gets a Uri for the root location where XHTML modules are found.

Declaration

public static readonly Uri ModuleBaseUri

Field Value

        Type
        Description

        System.Uri

    |
    Improve this Doc

    View Source

W3BaseUri

Gets a Uri for the root of the w3.org's resolution namespace.

Declaration

public static readonly Uri W3BaseUri

Field Value

        Type
        Description

        System.Uri

Methods

    |
    Improve this Doc

    View Source

GetEntity(Uri, String, Type)

Gets the requested entity from a URI.

Declaration

public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)

Parameters

        Type
        Name
        Description

        System.Uri
        absoluteUri

Absolute URI.

        System.String
        role

Role.

        System.Type
        ofObjectToReturn

Of object to return.

Returns

        Type
        Description

        System.Object

The entity.

Overrides

System.Xml.XmlUrlResolver.GetEntity(System.Uri, System.String, System.Type)

    |
    Improve this Doc

    View Source

ResolveUri(Uri, String)

Resolves the URI from a base URI and a relative URI component.

Declaration

public override Uri ResolveUri(Uri baseUri, string relativeUri)

Parameters

        Type
        Name
        Description

        System.Uri
        baseUri

Base URI.

        System.String
        relativeUri

Relative URI.

Returns

        Type
        Description

        System.Uri

The resolved URI.

Overrides

System.Xml.XmlUrlResolver.ResolveUri(System.Uri, System.String)

                    Improve this Doc

                    View Source

In This Article

              Back to top

            Generated by DocFX


text:
namespace {

// Mark as volatile to defensively make sure usage is thread-safe.
// Note that at the time of this writing, access is only on the UI thread.
volatile bool g_non_browser_ui_displayed = false;

base::Time* MainEntryPointTimeInternal() {
  static base::Time main_start_time = base::Time::Now();
  return &main_start_time;
}

typedef base::hash_map<std::string,base::TimeDelta> SubsystemStartupTimeHash;

SubsystemStartupTimeHash* GetSubsystemStartupTimeHash() {
  static SubsystemStartupTimeHash* slow_startup_time_hash =
                                    new SubsystemStartupTimeHash;
  return slow_startup_time_hash;
}

base::Lock* GetSubsystemStartupTimeHashLock() {
  static base::Lock* slow_startup_time_hash_lock = new base::Lock;
  return slow_startup_time_hash_lock;
}

// Record time of main entry so it can be read from Telemetry performance
// tests.
// TODO(jeremy): Remove once crbug.com/317481 is fixed.
void RecordMainEntryTimeHistogram() {
  const int kLowWordMask = 0xFFFFFFFF;
  const int kLower31BitsMask = 0x7FFFFFFF;
  base::TimeDelta browser_main_entry_time_absolute =
      *MainEntryPointTimeInternal() - base::Time::UnixEpoch();

  uint64 browser_main_entry_time_raw_ms =
      browser_main_entry_time_absolute.InMilliseconds();

  base::TimeDelta browser_main_entry_time_raw_ms_high_word =
      base::TimeDelta::FromMilliseconds(
          (browser_main_entry_time_raw_ms >> 32) & kLowWordMask);
  // Shift by one because histograms only support non-negative values.
  base::TimeDelta browser_main_entry_time_raw_ms_low_word =
      base::TimeDelta::FromMilliseconds(
          (browser_main_entry_time_raw_ms >> 1) & kLower31BitsMask);

  // A timestamp is a 64 bit value, yet histograms can only store 32 bits.
  LOCAL_HISTOGRAM_TIMES("Startup.BrowserMainEntryTimeAbsoluteHighWord",
      browser_main_entry_time_raw_ms_high_word);
  LOCAL_HISTOGRAM_TIMES("Startup.BrowserMainEntryTimeAbsoluteLowWord",
      browser_main_entry_time_raw_ms_low_word);
}

bool g_main_entry_time_was_recorded = false;
bool g_startup_stats_collection_finished = false;
bool g_was_slow_startup = false;

// Environment variable that stores the timestamp when the executable's main()
// function was entered.
const char kChromeMainTimeEnvVar[] = "CHROME_MAIN_TIME";

}  // namespace

namespace startup_metric_utils {

bool WasNonBrowserUIDisplayed() {
  return g_non_browser_ui_displayed;
}

void SetNonBrowserUIDisplayed() {
  g_non_browser_ui_displayed = true;
}

void RecordMainEntryPointTime() {
  DCHECK(!g_main_entry_time_was_recorded);
  g_main_entry_time_was_recorded = true;
  MainEntryPointTimeInternal();
}

void RecordExeMainEntryTime() {
  std::string exe_load_time =
      base::Int64ToString(base::Time::Now().ToInternalValue());
  scoped_ptr<base::Environment> env(base::Environment::Create());
  env->SetVar(kChromeMainTimeEnvVar, exe_load_time);
}

#if defined(OS_ANDROID)
void RecordSavedMainEntryPointTime(const base::Time& entry_point_time) {
  DCHECK(!g_main_entry_time_was_recorded);
  g_main_entry_time_was_recorded = true;
  *MainEntryPointTimeInternal() = entry_point_time;
}
#endif // OS_ANDROID

// Return the time recorded by RecordMainEntryPointTime().
const base::Time MainEntryStartTime() {
  DCHECK(g_main_entry_time_was_recorded);
  return *MainEntryPointTimeInternal();
}

void OnBrowserStartupComplete(bool is_first_run) {
  RecordMainEntryTimeHistogram();

  // Bail if uptime < 7 minutes, to filter out cases where Chrome may have been
  // autostarted and the machine is under io pressure.
  const int64 kSevenMinutesInMilliseconds =
      base::TimeDelta::FromMinutes(7).InMilliseconds();
  if (base::SysInfo::Uptime() < kSevenMinutesInMilliseconds) {
    g_startup_stats_collection_finished = true;
    return;
  }

  // The Startup.BrowserMessageLoopStartTime histogram recorded in
  // chrome_browser_main.cc exhibits instability in the field which limits its
  // usefulness in all scenarios except when we have a very large sample size.
  // Attempt to mitigate this with a new metric:
  // * Measure time from main entry rather than the OS' notion of process start
  //   time.
  // * Only measure launches that occur 7 minutes after boot to try to avoid
  //   cases where Chrome is auto-started and IO is heavily loaded.
  base::TimeDelta startup_time_from_main_entry =
      base::Time::Now() - MainEntryStartTime();
  if (is_first_run) {
    UMA_HISTOGRAM_LONG_TIMES(
        "Startup.BrowserMessageLoopStartTimeFromMainEntry.FirstRun",
        startup_time_from_main_entry);
  } else {
    UMA_HISTOGRAM_LONG_TIMES(
        "Startup.BrowserMessageLoopStartTimeFromMainEntry",
        startup_time_from_main_entry);
  }

// CurrentProcessInfo::CreationTime() is currently only implemented on some
// platforms.
#if (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_WIN) || \
    defined(OS_LINUX)
  // Record timings between process creation, the main() in the executable being
  // reached and the main() in the shared library being reached.
  scoped_ptr<base::Environment> env(base::Environment::Create());
  std::string chrome_main_entry_time_string;
  if (env->GetVar(kChromeMainTimeEnvVar, &chrome_main_entry_time_string)) {
    // The time that the Chrome executable's main() function was entered.
    int64 chrome_main_entry_time_int = 0;
    if (base::StringToInt64(chrome_main_entry_time_string,
                            &chrome_main_entry_time_int)) {
      base::Time process_create_time = base::CurrentProcessInfo::CreationTime();
      base::Time exe_main_time =
          base::Time::FromInternalValue(chrome_main_entry_time_int);
      base::Time dll_main_time = MainEntryStartTime();

      // Process create to chrome.exe:main().
      UMA_HISTOGRAM_LONG_TIMES("Startup.LoadTime.ProcessCreateToExeMain",
                               exe_main_time - process_create_time);

      // chrome.exe:main() to chrome.dll:main().
      UMA_HISTOGRAM_LONG_TIMES("Startup.LoadTime.ExeMainToDllMain",
                               dll_main_time - exe_main_time);

      // Process create to chrome.dll:main().
      UMA_HISTOGRAM_LONG_TIMES("Startup.LoadTime.ProcessCreateToDllMain",
                               dll_main_time - process_create_time);
    }
  }
#endif

  // Record histograms for the subsystem times for startups > 10 seconds.
  const base::TimeDelta kTenSeconds = base::TimeDelta::FromSeconds(10);
  if (startup_time_from_main_entry < kTenSeconds) {
    g_startup_stats_collection_finished = true;
    return;
  }

  // If we got here this was what we consider to be a slow startup which we
  // want to record stats for.
  g_was_slow_startup = true;
}

void OnInitialPageLoadComplete() {
  if (!g_was_slow_startup)
    return;
  DCHECK(!g_startup_stats_collection_finished);

  const base::TimeDelta kStartupTimeMin(
      base::TimeDelta::FromMilliseconds(1));
  const base::TimeDelta kStartupTimeMax(base::TimeDelta::FromMinutes(5));
  static const size_t kStartupTimeBuckets = 100;

  // Set UMA flag for histograms outside chrome/ that can't use the
  // ScopedSlowStartupUMA class.
  base::HistogramBase* histogram =
      base::StatisticsRecorder::FindHistogram("Startup.SlowStartupNSSInit");
  if (histogram)
    histogram->SetFlags(base::HistogramBase::kUmaTargetedHistogramFlag);

  // Iterate over the stats recorded by ScopedSlowStartupUMA and create
  // histograms for them.
  base::AutoLock locker(*GetSubsystemStartupTimeHashLock());
  SubsystemStartupTimeHash* time_hash = GetSubsystemStartupTimeHash();
  for (SubsystemStartupTimeHash::iterator i = time_hash->begin();
      i != time_hash->end();
      ++i) {
    const std::string histogram_name = i->first;
    base::HistogramBase* counter = base::Histogram::FactoryTimeGet(
        histogram_name,
        kStartupTimeMin,
        kStartupTimeMax,
        kStartupTimeBuckets,
        base::Histogram::kUmaTargetedHistogramFlag);
    counter->AddTime(i->second);
  }

  g_startup_stats_collection_finished = true;
}

const base::Time* MainEntryPointTime() {
  if (!g_main_entry_time_was_recorded)
    return NULL;
  return MainEntryPointTimeInternal();
}

ScopedSlowStartupUMA::~ScopedSlowStartupUMA() {
  if (g_startup_stats_collection_finished)
    return;

  base::AutoLock locker(*GetSubsystemStartupTimeHashLock());
  SubsystemStartupTimeHash* hash = GetSubsystemStartupTimeHash();
  // Only record the initial sample for a given histogram.
  if (hash->find(histogram_name_) !=  hash->end())
    return;

  (*hash)[histogram_name_] =
      base::TimeTicks::Now() - start_time_;
}

}  // namespace startup_metric_utils


text:
package com.cronutils.model;

import com.cronutils.mapper.CronMapper;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.field.CronField;
import com.cronutils.model.field.CronFieldName;
import com.cronutils.utils.Preconditions;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class CompositeCron implements Cron {
    private Pattern split = Pattern.compile("\\|");
    private List<Cron> crons;
    private CronDefinition definition;

    public CompositeCron(List<Cron> crons){
        this.crons = Collections.unmodifiableList(crons);
        Preconditions.checkNotNullNorEmpty(crons, "List of Cron cannot be null or empty");
        this.definition = crons.get(0).getCronDefinition();
        Preconditions.checkArgument(crons.size()==crons.stream().filter(c->c.getCronDefinition().equals(definition)).count(), "All Cron objects must have same definition for CompositeCron");
    }

    public List<Cron> getCrons() {
        return crons;
    }

    @Override
    public CronField retrieve(CronFieldName name) {
        throw new UnsupportedOperationException("Currently not supported for CompositeCron");
    }

    @Override
    public Map<CronFieldName, CronField> retrieveFieldsAsMap() {
        throw new UnsupportedOperationException("Currently not supported for CompositeCron");
    }

    @Override
    public String asString() {
        StringBuilder builder = new StringBuilder();
        List<String> patterns = crons.stream().map(Cron::asString).collect(Collectors.toList());
        int fields = patterns.get(0).split(" ").length;
        for(int j=0;j<fields;j++){
            StringBuilder fieldbuilder = new StringBuilder();
            for(String pattern : patterns){
                fieldbuilder.append(String.format("%s ", pattern.split(" ")[j]));
            }
            String fieldstring = fieldbuilder.toString().trim().replaceAll(" ", "|");
            if(split.splitAsStream(fieldstring).distinct().limit(2).count() <= 1){
                fieldstring = split.split(fieldstring)[0];
            }
            builder.append(String.format("%s ", fieldstring));
        }
        return builder.toString().trim();
    }

    @Override
    public CronDefinition getCronDefinition() {
        return definition;
    }

    @Override
    public Cron validate() {
        for(Cron cron : crons){
            cron.validate();
        }
        return this;
    }

    @Override
    public boolean equivalent(CronMapper cronMapper, Cron cron) {
        throw new UnsupportedOperationException("Currently not supported for CompositeCron");
    }

    @Override
    public boolean equivalent(Cron cron) {
        return asString().equals(cron.asString());
    }
}


text:
<?php

namespace Tabloz\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Entity
 * @ORM\Table(name="print_type")
 * @ORM\HasLifecycleCallbacks()
 */
class PrintType
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    private $title;

    /**
     * @ORM\Column(type="string")
     */
    private $width;

    /**
     * @ORM\Column(type="string")
     */
    private $height;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $description;

    /**
     * @ORM\ManyToOne(targetEntity="FrameType", inversedBy="print_types")
     * @ORM\JoinColumn(name="frame_type_id", nullable=false, referencedColumnName="id")
     */
    protected $frame;

    /**
     * @ORM\Column(type="string")
     */
    private $unit_price;

    /**
     * @ORM\Column(type="boolean")
     */
    private $enable = true;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="create")
     */
    private $created_at;

    /**
     * @ORM\Column(type="datetime")
     * @Gedmo\Timestampable(on="update")
     */
    private $updated_at;

    public function __construct()
    {
        // your own logic
    }

    /**
     * {@inheritDoc}
     */
    public function __toString(){
    	return $this->getTitle();
    }

    /**
     * Returns the actual width of print according to the size given
     * @param int $width
     * @param int $height
     * @return int
     */
    public function getActualWidth($width, $height){
    	if ($this->width > $this->height){
    		if ($width > $height){
    			$w = $this->width;
    		} else {
    			$w = $this->width * ($height/$width);
    		}
    	} else {
    		if ($width > $height){
    			$w = $this->height;
    		} else {
    			$w = $this->height * ($width/$height);
    		}
    	}
    	return round($w);
    }

    /**
     * Returns the actual height of print according to the size given
     * @param int $width
     * @param int $height
     * @return int
     */
    public function getActualHeight($width, $height){
    	if ($this->width > $this->height){
    		if ($width > $height){
    			$h = $this->width * ($height/$width);
    		} else {
    			$h = $this->width;
    		}
    	} else {
    		if ($width > $height){
    			$h = $this->height * ($width/$height);
    		} else {
    			$h = $this->height;
    		}
    	}
    	return round($h);
    }

    /**
     * Renders the title width the appropriate size
     * @param int $width
     * @param int $height
     * @return string
     */
    public function getTitleBySize($width, $height){
    	$w = $this->getActualWidth($width, $height);
    	$h = $this->getActualHeight($width, $height);
    	return $this->getTitle().' ( '.$w.' × '.$h.' ) ';
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return PrintType
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set width
     *
     * @param string $width
     * @return PrintType
     */
    public function setWidth($width)
    {
        $this->width = $width;

        return $this;
    }

    /**
     * Get width
     *
     * @return string
     */
    public function getWidth()
    {
        return $this->width;
    }

    /**
     * Set height
     *
     * @param string $height
     * @return PrintType
     */
    public function setHeight($height)
    {
        $this->height = $height;

        return $this;
    }

    /**
     * Get height
     *
     * @return string
     */
    public function getHeight()
    {
        return $this->height;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return PrintType
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set unit_price
     *
     * @param string $unitPrice
     * @return PrintType
     */
    public function setUnitPrice($unitPrice)
    {
        $this->unit_price = $unitPrice;

        return $this;
    }

    /**
     * Get unit_price
     *
     * @return string
     */
    public function getUnitPrice()
    {
        return $this->unit_price;
    }

    /**
     * Set enable
     *
     * @param boolean $enable
     * @return PrintType
     */
    public function setEnable($enable)
    {
        $this->enable = $enable;

        return $this;
    }

    /**
     * Get enable
     *
     * @return boolean
     */
    public function getEnable()
    {
        return $this->enable;
    }

    /**
     * Set created_at
     *
     * @param \DateTime $createdAt
     * @return PrintType
     */
    public function setCreatedAt($createdAt)
    {
        $this->created_at = $createdAt;

        return $this;
    }

    /**
     * Get created_at
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->created_at;
    }

    /**
     * Set updated_at
     *
     * @param \DateTime $updatedAt
     * @return PrintType
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updated_at = $updatedAt;

        return $this;
    }

    /**
     * Get updated_at
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updated_at;
    }

    /**
     * Set frame
     *
     * @param \Tabloz\MainBundle\Entity\FrameType $frame
     * @return PrintType
     */
    public function setFrame(\Tabloz\MainBundle\Entity\FrameType $frame)
    {
        $this->frame = $frame;

        return $this;
    }

    /**
     * Get frame
     *
     * @return \Tabloz\MainBundle\Entity\FrameType
     */
    public function getFrame()
    {
        return $this->frame;
    }
}


text:
package at.ebinterface.validation.web.pages;

import java.io.IOException;
import java.io.InputStream;

import org.apache.wicket.Application;
import org.apache.wicket.feedback.ContainerFeedbackMessageFilter;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.helger.commons.io.stream.StreamHelper;
import com.helger.commons.string.StringHelper;

import at.austriapro.rendering.BaseRenderer;
import at.ebinterface.validation.validator.EbInterfaceValidator;
import at.ebinterface.validation.validator.ValidationResult;
import at.ebinterface.validation.web.Constants;
import net.sf.jasperreports.engine.JasperReport;

/**
 * The input form class
 *
 * @author pl
 */
final class ServiceForm extends Form <Object>
{
  private static final Logger LOG = LoggerFactory.getLogger (ServiceForm.class);

  /**
   * Panel for providing feedback in case of errorneous input
   */
  private final FeedbackPanel feedbackPanel;

  /**
   * Upload field for the ebInterface instance
   */
  private final FileUploadField fileUploadField;

  public ServiceForm (final String id)
  {
    super (id);

    // Set the form to multi part since we use file upload
    setMultiPart (true);

    // Add a feedback panel
    feedbackPanel = new FeedbackPanel ("feedback", new ContainerFeedbackMessageFilter (this));
    feedbackPanel.setVisible (false);
    add (feedbackPanel);

    // Add the file upload field
    fileUploadField = new FileUploadField ("fileInput");
    fileUploadField.setRequired (true);
    add (fileUploadField);

    // Add a button to visualize it as HTML
    add (new SubmitLink ("submitButtonVisualizeHTML")
    {
      @Override
      public void onSubmit ()
      {
        submit (EBasicEbiActionType.VISUALIZATION_HTML);
      }
      // latest requirements: only pdf visualization
    }.setVisibilityAllowed (false));

    // Add a button to visualize it as PDF
    add (new SubmitLink ("submitButtonVisualizePDF")
    {
      @Override
      public void onSubmit ()
      {
        submit (EBasicEbiActionType.VISUALIZATION_PDF);
      }
    });
  }

  /**
   * Process the input
   */
  protected void submit (final EBasicEbiActionType selectedAction)
  {

    // Hide the feedback panel first (will be shown in case of an error)
    feedbackPanel.setVisible (false);

    // Get the file input
    final FileUpload upload = fileUploadField.getFileUpload ();
    byte [] uploadedData = null;

    try
    {
      final InputStream inputStream = upload.getInputStream ();
      uploadedData = StreamHelper.getAllBytes (inputStream);
    }
    catch (final IOException e)
    {
      LOG.error ("Die hochgeladene Datei kann nicht verarbeitet werden.", e);
    }

    // Validate the XML instance - performed in any case
    final EbInterfaceValidator validator = Application.get ().getMetaData (Constants.METADATAKEY_EBINTERFACE_XMLSCHEMAVALIDATOR);
    final ValidationResult validationResult = validator.validateXMLInstanceAgainstSchema (uploadedData);

    if (validationResult.getDeterminedEbInterfaceVersion () == null)
    {
      error ("Das XML kann nicht verarbeitet werden, das es keiner ebInterface Version entspricht.");
      onError ();
      return;
    }

    switch (selectedAction)
    {
      case SCHEMA_VALIDATION:
        // Redirect to the ebInterface result page
        setResponsePage (new ServicePage (validationResult, null));
        break;
      case VISUALIZATION_HTML:
        // Visualization is only possible for valid instances
        if (StringHelper.hasText (validationResult.getSchemaValidationErrorMessage ()))
        {
          error ("Die gewählte ebInterface Instanz ist nicht valide. Es können nur valide Schemainstanzen in der Druckansicht angezeigt werden.");
          onError ();
        }
        else
        {
          // Get the transformed string
          final String s = validator.transformInput (uploadedData, validationResult.getDeterminedEbInterfaceVersion ().getVersion ());
          // Redirect to the printview page
          setResponsePage (new PrintViewPage (s));
        }
        break;
      case VISUALIZATION_PDF:
        final BaseRenderer renderer = new BaseRenderer ();

        try
        {
          LOG.debug ("Load ebInterface JasperReport template from application context.");
          final JasperReport jrReport = Application.get ().getMetaData (Constants.METADATAKEY_EBINTERFACE_JRTEMPLATE);
          LOG.debug ("Rendering PDF from ebInterface file.");
          final byte [] pdf = renderer.renderReport (jrReport, uploadedData, null);
          // Redirect to the ebInterface result page
          setResponsePage (new ServicePage (validationResult, pdf));
        }
        catch (final Exception ex)
        {
          LOG.error ("Error when generating PDF from ebInterface", ex);
          error ("Bei der ebInterface-PDF-Erstellung ist ein Fehler aufgetreten.");
          onError ();
        }
        break;
      default:
        throw new IllegalStateException ();
    }
  }

  /**
   * Process errors
   */
  @Override
  protected void onError ()
  {
    // Show the feedback panel in case on an error
    feedbackPanel.setVisible (true);
  }
}


text:
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost {

class bad_optional_access : public std::logic_error
{
public:
  bad_optional_access()
    : std::logic_error("Attempted to access the value of an uninitialized optional object.")
    {}
};

} // namespace mars_boost

#endif


text:
<?php
/**
 * @see KumbiaActiveRecord
 */
Load::coreLib('kumbia_active_record');

/**
 * ActiveRecord
 *
 * Esta clase es la clase padre de todos los modelos
 * de la aplicacion
 *
 * @category Kumbia
 * @package Db
 * @subpackage ActiveRecord
 */
class ActiveRecord extends KumbiaActiveRecord
{
	public function lastId(){
		$record = $this->find("limit: 1","order: id desc");
		return $record[0]->id;
	}
}