text:
//
//  ETEventMessage.h
//  JB4A-SDK-iOS
//
//  Copyright © 2016 Salesforce. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "PushConstants.h"
#import <CoreLocation/CoreLocation.h>

NS_ASSUME_NONNULL_BEGIN

/**
 ETEventMessage is the local representation of a Message from Salesforce. They are multipurpose, sometimes representing a message that should be scheduled because of the entrance or exit of a Geofence, the proximal arrival to an iBeacon, or a CloudPage message downloaded from ET. Because of their multipurpose nature, there are a lot of different attributes on them, many of which may be null at any give time depending on the type of message.
 */

@interface ETEventMessage : NSObject

/**
 Encoded ID from Salesforce. Will match the ID in MobilePush. This is the primary key.
 */
@property (nonatomic, readonly, copy, nullable) NSString *messageIdentifier;

/**
 This is the name which is set on SalesforceMarketingCloud, while setting the ETMessage
 */
@property (nonatomic, readonly, copy, nullable) NSString *messageName;

/**
 The type of ETMessage being represented.
 */
@property (nonatomic, readonly) MobilePushMessageType messageType;

/**
 Bitmask of features that this message has on it (CloudPage, Push only)
 */
@property (nonatomic, readonly) MobilePushContentType contentType;

/**
 The alert text of the message. This displays on the screen.
 */
@property (nonatomic, readonly, copy, nullable) NSString *alert;

/**
 The sound that should play, if any. Most of the time, either "default" or "custom.caf", conventions enforced in MobilePush.
 */
@property (nonatomic, readonly, copy, nullable) NSString *sound;

/**
 The badge modifier. This should be a NSString in the form of "+1" or nothing at all. It's saved as a string because of that.
 */
@property (nonatomic, readonly, copy, nullable) NSString *badge;

/**
 The category name for an interactive notification if it has one.
 */
@property (nonatomic, readonly, copy, nullable) NSString *category;

/**
 An array of Key Value Pairs, or Custom Keys in local parlance, for this message. This will contain NSDictionary objects.
 */
@property (nonatomic, readonly, copy, nullable) NSArray *keyValuePairs;

/**
 The message's start date. Messages shouldn't show before this time.
 */
@property (nonatomic, readonly, copy, nullable) NSDate *startDate;

/**
 The message's end date. Messages shouldn't show after this time.
 */
@property (nonatomic, readonly, copy, nullable) NSDate *endDate;

/**
 The Site URL for the CloudPage attached to this message.
 */
@property (nonatomic, readonly, copy, nullable) NSString *siteUrlAsString;

/**
 OpenDirect payload for this message, if there is one.
 */
@property (nonatomic, readonly, copy, nullable) NSString *openDirectPayload;

/**
 The total number of times, ever, that a message will show on a device.
 */
@property (nonatomic, readonly, copy, nullable) NSNumber *messageLimit;

/**
 The total number of times for a given number of time units that a message can be shown. In the statement "show 1 time per 2 hours", this is the "1" part.

 This defaults to 1 if it is not set in the received payload from Salesforce.
 */
@property (nonatomic, readonly, copy, nullable) NSNumber *messagesPerPeriod;

/**
 The number of time periods in which a message should be limited. In the statement "show 1 time per 2 hours", this is the "2" part.
 */
@property (nonatomic, readonly, copy, nullable) NSNumber *numberOfPeriods;

/**
 The time unit counted in numberOfPeriods. In the statement "show 1 time per 2 hours", this is the "hours" part.
 */
@property (nonatomic, readonly) MobilePushMessageFrequencyUnit periodType;

/**
 Whether or not the period is a rolling period. Defaults to YES through code.

 Consider a message being fired at 2:19PM, and it may only be shown once per hour. In a rolling period, the next time it may show is 3:19PM. In a non-rolling period, the next earliest showing time is 3:00PM, the start of the next hour.
 */
@property (nonatomic, readonly, getter = isRollingPeriod) BOOL rollingPeriod;

/**
 Use this for display in an inbox.
 */
@property (nonatomic, readonly, copy, nullable) NSString *subject;

/**
 A Cleansed Site URL as a proper NSURL. This is mostly for convenience.
 */
@property (nonatomic, readonly, copy, nullable) NSURL *siteURL;

@end
NS_ASSUME_NONNULL_END


text:
Available.toString
==================

Easily take your calendar and get text saying when you are available.

Why
===
Whenever you're trying to setup a meeting (think interviews), you'll be asked to provide your availibility in a certain date interval. I always have to go to my calendar and manually write down when I'm free. This task can and should be easily automated.

What
===
This is probably best as a Chrome extension but I don't want to use a hardcoded solution that's heavily dependant on the current Google Calendar HTML. If there's a way to use Google Calendar API's FreeBusy query with a chrome extension, that would be the best solution. Otherwise, it'll have to be a SPA.

Goals
===
Graphical calendar UI where the user highlights intervals and these intervals are translated to text
- User enters setup info like date interval, exclude-weekends and after-x and before-x times to limit the initial highlighted area
- User can then manually drag and reshape the highlighted area to fine-tune their availibility
- FreeBusy info taken from Google cal to automatically un-select times already blocked off.
- Press a button to intelligently convert the graphical representation to text that can be directly pasted in an email.

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE Arrows #-}
{-# OPTIONS_GHC -Wall #-}
-----------------------------------------------------------------------------
-- |
-- Copyright   :  (C) 2014 Edward Kmett and Gabríel Arthúr Pétursson
-- License     :  BSD-style (see the file LICENSE)
-- Maintainer  :  Edward Kmett <ekmett@gmail.com>
-- Stability   :  experimental
-- Portability :  portable
--
----------------------------------------------------------------------------
module Parser
  ( parseFile
  ) where

import Registry
import Text.XML.HXT.Core

#ifdef HLINT
{-# ANN module "HLint: ignore Reduce duplication" #-}
#endif

to :: ArrowXml a => String -> a XmlTree XmlTree
to name = hasName name <<< isElem <<< getChildren

perhaps :: ArrowIf a => a b c -> a b (Maybe c)
perhaps x = (arr Just <<< x) `orElse` constA Nothing

parseCommand :: ArrowXml a => a XmlTree Command
parseCommand = proc x -> do
  command <- to "command" -< x
  name <- getText <<< getChildren <<< to "name" <<< to "proto" -< command
  typ <- parseType <<< to "proto" -< command
  params <- listA parseParameter -< command
  veceq   <- perhaps (getAttrValue0 "name" <<< to "vecequiv") -< command
  alias   <- perhaps (getAttrValue0 "name" <<< to "alias") -< command
  returnA -< Command name typ params veceq alias

parseParameter :: ArrowXml a => a XmlTree Parameter
parseParameter = proc x -> do
  param <- to "param" -< x
  typ   <- parseType -< param
  name  <- getText <<< getChildren <<< to "name" -< param
  grp   <- perhaps (getAttrValue0 "group") -< param
  len   <- perhaps (getAttrValue0 "len") -< param
  returnA -< Parameter name typ grp len

parseEnum :: ArrowXml a => a XmlTree Enumeratee
parseEnum = proc x -> do
  enum <- to "enum" -< x
  name <- getAttrValue0 "name" -< enum
  value <- getAttrValue0 "value" -< enum
  returnA -< Enumeratee name value

parseExtension :: ArrowXml a => a XmlTree Extension
parseExtension = proc x -> do
  extension <- to "extension" -< x
  name <- getAttrValue0 "name" -< extension
  supported <- getAttrValue "supported" -< extension
  require <- listA $ parseRequire <<< to "require" -< extension
  returnA -< Extension name supported require

parseFeature :: ArrowXml a => a XmlTree Feature
parseFeature = proc x -> do
  name <- getAttrValue0 "name" -< x
  require <- listA $ parseRequire <<< to "require" -< x
  remove <- listA $ parseRemove <<< to "remove" -< x
  returnA -< Feature name require remove

parseGroup :: ArrowXml a => a XmlTree Group
parseGroup = proc x -> do
  group <- to "group" -< x
  name <- getAttrValue0 "name" -< group
  enum <- listA $ getAttrValue0 "name" <<< to "enum" -< group
  returnA -< Group name enum

parseRemove :: ArrowXml a => a XmlTree Remove
parseRemove = proc x -> do
  profile <- getAttrValue "profile" -< x
  comment <- getAttrValue "comment" -< x
  enums <- listA $ getAttrValue0 "name" <<< to "enum" -< x
  commands <- listA $ getAttrValue0 "name" <<< to "command" -< x
  returnA -< Remove profile comment enums commands

parseRequire :: ArrowXml a => a XmlTree Require
parseRequire = proc x -> do
  comment <- getAttrValue "comment" -< x
  enums <- listA $ getAttrValue0 "name" <<< to "enum" -< x
  commands <- listA $ getAttrValue0 "name" <<< to "command" -< x
  profile <- getAttrValue "profile" -< x
  returnA -< Require enums commands comment profile

parseType :: ArrowXml a => a XmlTree Type
parseType = proc x -> do
  ptype <- perhaps $ getText <<< getChildren <<< to "ptype" -< x
  pointer <- (getText <<< getChildren) >. length . filter (== '*') . concat -< x
  returnA -< Type
    { typeName = ptype
    , typePointer = pointer
    }

parse :: IOSLA (XIOState ()) XmlTree Registry
parse = proc x -> do
  registry <- to "registry" -< x
  groups <- listA $ parseGroup <<< to "groups" -< registry
  enums <- listA $ parseEnum <<< to "enums" -< registry
  extensions <- listA $ parseExtension <<< to "extensions" -< registry
  commands <- listA $ parseCommand <<< to "commands" -< registry
  features <- listA $ parseFeature <<< to "feature" -< registry
  returnA -< Registry
    { registryCommands = commands
    , registryEnums = enums
    , registryExtensions = extensions
    , registryFeatures = features
    , registryGroups = groups
    }

parseFile :: String -> IO Registry
parseFile file = return . head =<< runX (readDocument [withRemoveWS yes] file >>> parse)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GIO Reference Manual: GInputStream</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="index.html" title="GIO Reference Manual">
<link rel="up" href="streaming.html" title="Streaming I/O">
<link rel="prev" href="GSeekable.html" title="GSeekable">
<link rel="next" href="GOutputStream.html" title="GOutputStream">
<meta name="generator" content="GTK-Doc V1.21.1 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

Top  |
                  Description  |
                  Object Hierarchy  |
                  Known Derived Interfaces

GInputStream

GInputStream — Base class for implementing streaming input

Functions

<colgroup>
<col width="150px" class="functions_return">
<col class="functions_name">
</colgroup>

gssize

g_input_stream_read ()

gboolean

g_input_stream_read_all ()

gssize

g_input_stream_skip ()

gboolean

g_input_stream_close ()

void

g_input_stream_read_async ()

gssize

g_input_stream_read_finish ()

void

g_input_stream_skip_async ()

gssize

g_input_stream_skip_finish ()

void

g_input_stream_close_async ()

gboolean

g_input_stream_close_finish ()

gboolean

g_input_stream_is_closed ()

gboolean

g_input_stream_has_pending ()

gboolean

g_input_stream_set_pending ()

void

g_input_stream_clear_pending ()

GBytes *

g_input_stream_read_bytes ()

void

g_input_stream_read_bytes_async ()

GBytes *

g_input_stream_read_bytes_finish ()

Types and Values

<colgroup>
<col width="150px" class="name">
<col class="description">
</colgroup>

GInputStream

Object Hierarchy

    GObject
    ╰── GInputStream
        ├── GFilterInputStream
        ├── GFileInputStream
        ├── GMemoryInputStream
        ╰── GUnixInputStream

Known Derived Interfaces

GInputStream is required by
 GPollableInputStream.

Includes

#include <gio/gio.h>

Description

GInputStream has functions to read from a stream (g_input_stream_read()),
to close a stream (g_input_stream_close()) and to skip some content
(g_input_stream_skip()).

To copy the content of an input stream to an output stream without
manually handling the reads and writes, use g_output_stream_splice().

All of these functions have async variants too.

Functions

g_input_stream_read ()

gssize
g_input_stream_read (GInputStream *stream,
                     void *buffer,
                     gsize count,
                     GCancellable *cancellable,
                     GError **error);

Tries to read count
 bytes from the stream into the buffer starting at
buffer
. Will block during this read.

If count is zero returns zero and does nothing. A value of count

larger than G_MAXSSIZE will cause a G_IO_ERROR_INVALID_ARGUMENT error.

On success, the number of bytes read into the buffer is returned.
It is not an error if this is not the same as the requested size, as it
can happen e.g. near the end of a file. Zero is returned on end of file
(or if count
 is zero),  but never otherwise.

The returned buffer
 is not a nul-terminated string, it can contain nul bytes
at any position, and this function doesn't nul-terminate the buffer
.

If cancellable
 is not NULL, then the operation can be cancelled by
triggering the cancellable object from another thread. If the operation
was cancelled, the error G_IO_ERROR_CANCELLED will be returned. If an
operation was partially finished when the operation was cancelled the
partial result will be returned, without an error.

On error -1 is returned and error
 is set accordingly.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

a GInputStream.

buffer

 a buffer to
read data into (which should be at least count bytes long).

[<acronym title="Parameter points to an array of items.">array</acronym> length=count][<acronym title="Generics and defining elements of containers and arrays.">element-type</acronym> guint8]

count

the number of bytes that will be read from the stream

cancellable

 optional GCancellable object, NULL to ignore.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

error

location to store the error occurring, or NULL to ignore

Returns

 Number of bytes read, or -1 on error, or 0 on end of file.

g_input_stream_read_all ()

gboolean
g_input_stream_read_all (GInputStream *stream,
                         void *buffer,
                         gsize count,
                         gsize *bytes_read,
                         GCancellable *cancellable,
                         GError **error);

Tries to read count
 bytes from the stream into the buffer starting at
buffer
. Will block during this read.

This function is similar to g_input_stream_read(), except it tries to
read as many bytes as requested, only stopping on an error or end of stream.

On a successful read of count
 bytes, or if we reached the end of the
stream,  TRUE is returned, and bytes_read
 is set to the number of bytes
read into buffer
.

If there is an error during the operation FALSE is returned and error

is set to indicate the error status, bytes_read
 is updated to contain
the number of bytes read into buffer
 before the error occurred.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

a GInputStream.

buffer

 a buffer to
read data into (which should be at least count bytes long).

[<acronym title="Parameter points to an array of items.">array</acronym> length=count][<acronym title="Generics and defining elements of containers and arrays.">element-type</acronym> guint8]

count

the number of bytes that will be read from the stream

bytes_read

 location to store the number of bytes that was read from the stream.

[<acronym title="Parameter for returning results. Default is transfer full.">out</acronym>]

cancellable

 optional GCancellable object, NULL to ignore.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

error

location to store the error occurring, or NULL to ignore

Returns

 TRUE on success, FALSE if there was an error

g_input_stream_skip ()

gssize
g_input_stream_skip (GInputStream *stream,
                     gsize count,
                     GCancellable *cancellable,
                     GError **error);

Tries to skip count
 bytes from the stream. Will block during the operation.

This is identical to g_input_stream_read(), from a behaviour standpoint,
but the bytes that are skipped are not returned to the user. Some
streams have an implementation that is more efficient than reading the data.

This function is optional for inherited classes, as the default implementation
emulates it using read.

If cancellable
 is not NULL, then the operation can be cancelled by
triggering the cancellable object from another thread. If the operation
was cancelled, the error G_IO_ERROR_CANCELLED will be returned. If an
operation was partially finished when the operation was cancelled the
partial result will be returned, without an error.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

a GInputStream.

count

the number of bytes that will be skipped from the stream

cancellable

 optional GCancellable object, NULL to ignore.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

error

location to store the error occurring, or NULL to ignore

Returns

 Number of bytes skipped, or -1 on error

g_input_stream_close ()

gboolean
g_input_stream_close (GInputStream *stream,
                      GCancellable *cancellable,
                      GError **error);

Closes the stream, releasing resources related to it.

Once the stream is closed, all other operations will return G_IO_ERROR_CLOSED.
Closing a stream multiple times will not return an error.

Streams will be automatically closed when the last reference
is dropped, but you might want to call this function to make sure
resources are released as early as possible.

Some streams might keep the backing store of the stream (e.g. a file descriptor)
open after the stream is closed. See the documentation for the individual
stream for details.

On failure the first error that happened will be reported, but the close
operation will finish as much as possible. A stream that failed to
close will still return G_IO_ERROR_CLOSED for all operations. Still, it
is important to check and report the error to the user.

If cancellable
 is not NULL, then the operation can be cancelled by
triggering the cancellable object from another thread. If the operation
was cancelled, the error G_IO_ERROR_CANCELLED will be returned.
Cancelling a close will still leave the stream closed, but some streams
can use a faster close that doesn't block to e.g. check errors.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

A GInputStream.

cancellable

 optional GCancellable object, NULL to ignore.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

error

location to store the error occurring, or NULL to ignore

Returns

 TRUE on success, FALSE on failure

g_input_stream_read_async ()

void
g_input_stream_read_async (GInputStream *stream,
                           void *buffer,
                           gsize count,
                           int io_priority,
                           GCancellable *cancellable,
                           GAsyncReadyCallback callback,
                           gpointer user_data);

Request an asynchronous read of count
 bytes from the stream into the buffer
starting at buffer
. When the operation is finished callback
 will be called.
You can then call g_input_stream_read_finish() to get the result of the
operation.

During an async request no other sync and async calls are allowed on stream
, and will
result in G_IO_ERROR_PENDING errors.

A value of count
 larger than G_MAXSSIZE will cause a G_IO_ERROR_INVALID_ARGUMENT error.

On success, the number of bytes read into the buffer will be passed to the
callback. It is not an error if this is not the same as the requested size, as it
can happen e.g. near the end of a file, but generally we try to read
as many bytes as requested. Zero is returned on end of file
(or if count
 is zero),  but never otherwise.

Any outstanding i/o request with higher priority (lower numerical value) will
be executed before an outstanding request with lower priority. Default
priority is G_PRIORITY_DEFAULT.

The asyncronous methods have a default fallback that uses threads to implement
asynchronicity, so they are optional for inheriting classes. However, if you
override one you must override all.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

A GInputStream.

buffer

 a buffer to
read data into (which should be at least count bytes long).

[<acronym title="Parameter points to an array of items.">array</acronym> length=count][<acronym title="Generics and defining elements of containers and arrays.">element-type</acronym> guint8]

count

the number of bytes that will be read from the stream

io_priority

the I/O priority
of the request.

cancellable

 optional GCancellable object, NULL to ignore.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

callback

 callback to call when the request is satisfied.

[<acronym title="The callback is valid until first called.">scope async</acronym>]

user_data

 the data to pass to callback function.

[<acronym title="This parameter is a 'user_data', for callbacks; many bindings can pass NULL here.">closure</acronym>]

g_input_stream_read_finish ()

gssize
g_input_stream_read_finish (GInputStream *stream,
                            GAsyncResult *result,
                            GError **error);

Finishes an asynchronous stream read operation.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

a GInputStream.

result

a GAsyncResult.

error

a GError location to store the error occurring, or NULL to
ignore.

Returns

 number of bytes read in, or -1 on error, or 0 on end of file.

g_input_stream_skip_async ()

void
g_input_stream_skip_async (GInputStream *stream,
                           gsize count,
                           int io_priority,
                           GCancellable *cancellable,
                           GAsyncReadyCallback callback,
                           gpointer user_data);

Request an asynchronous skip of count
 bytes from the stream.
When the operation is finished callback
 will be called.
You can then call g_input_stream_skip_finish() to get the result
of the operation.

During an async request no other sync and async calls are allowed,
and will result in G_IO_ERROR_PENDING errors.

A value of count
 larger than G_MAXSSIZE will cause a G_IO_ERROR_INVALID_ARGUMENT error.

On success, the number of bytes skipped will be passed to the callback.
It is not an error if this is not the same as the requested size, as it
can happen e.g. near the end of a file, but generally we try to skip
as many bytes as requested. Zero is returned on end of file
(or if count
 is zero), but never otherwise.

Any outstanding i/o request with higher priority (lower numerical value)
will be executed before an outstanding request with lower priority.
Default priority is G_PRIORITY_DEFAULT.

The asynchronous methods have a default fallback that uses threads to
implement asynchronicity, so they are optional for inheriting classes.
However, if you override one, you must override all.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

A GInputStream.

count

the number of bytes that will be skipped from the stream

io_priority

the I/O priority of the request

cancellable

 optional GCancellable object, NULL to ignore.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

callback

 callback to call when the request is satisfied.

[<acronym title="The callback is valid until first called.">scope async</acronym>]

user_data

 the data to pass to callback function.

[<acronym title="This parameter is a 'user_data', for callbacks; many bindings can pass NULL here.">closure</acronym>]

g_input_stream_skip_finish ()

gssize
g_input_stream_skip_finish (GInputStream *stream,
                            GAsyncResult *result,
                            GError **error);

Finishes a stream skip operation.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

a GInputStream.

result

a GAsyncResult.

error

a GError location to store the error occurring, or NULL to
ignore.

Returns

 the size of the bytes skipped, or -1 on error.

g_input_stream_close_async ()

void
g_input_stream_close_async (GInputStream *stream,
                            int io_priority,
                            GCancellable *cancellable,
                            GAsyncReadyCallback callback,
                            gpointer user_data);

Requests an asynchronous closes of the stream, releasing resources related to it.
When the operation is finished callback
 will be called.
You can then call g_input_stream_close_finish() to get the result of the
operation.

For behaviour details see g_input_stream_close().

The asyncronous methods have a default fallback that uses threads to implement
asynchronicity, so they are optional for inheriting classes. However, if you
override one you must override all.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

A GInputStream.

io_priority

the I/O priority of the request

cancellable

 optional cancellable object.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

callback

 callback to call when the request is satisfied.

[<acronym title="The callback is valid until first called.">scope async</acronym>]

user_data

 the data to pass to callback function.

[<acronym title="This parameter is a 'user_data', for callbacks; many bindings can pass NULL here.">closure</acronym>]

g_input_stream_close_finish ()

gboolean
g_input_stream_close_finish (GInputStream *stream,
                             GAsyncResult *result,
                             GError **error);

Finishes closing a stream asynchronously, started from g_input_stream_close_async().

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

a GInputStream.

result

a GAsyncResult.

error

a GError location to store the error occurring, or NULL to
ignore.

Returns

 TRUE if the stream was closed successfully.

g_input_stream_is_closed ()

gboolean
g_input_stream_is_closed (GInputStream *stream);

Checks if an input stream is closed.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

input stream.

Returns

 TRUE if the stream is closed.

g_input_stream_has_pending ()

gboolean
g_input_stream_has_pending (GInputStream *stream);

Checks if an input stream has pending actions.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

input stream.

Returns

 TRUE if stream
has pending actions.

g_input_stream_set_pending ()

gboolean
g_input_stream_set_pending (GInputStream *stream,
                            GError **error);

Sets stream
 to have actions pending. If the pending flag is
already set or stream
 is closed, it will return FALSE and set
error
.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

input stream

error

a GError location to store the error occurring, or NULL to
ignore.

Returns

 TRUE if pending was previously unset and is now set.

g_input_stream_clear_pending ()

void
g_input_stream_clear_pending (GInputStream *stream);

Clears the pending flag on stream
.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

input stream

g_input_stream_read_bytes ()

GBytes *
g_input_stream_read_bytes (GInputStream *stream,
                           gsize count,
                           GCancellable *cancellable,
                           GError **error);

Like g_input_stream_read(), this tries to read count
 bytes from
the stream in a blocking fashion. However, rather than reading into
a user-supplied buffer, this will create a new GBytes containing
the data that was read. This may be easier to use from language
bindings.

If count is zero, returns a zero-length GBytes and does nothing. A
value of count
 larger than G_MAXSSIZE will cause a
G_IO_ERROR_INVALID_ARGUMENT error.

On success, a new GBytes is returned. It is not an error if the
size of this object is not the same as the requested size, as it
can happen e.g. near the end of a file. A zero-length GBytes is
returned on end of file (or if count
 is zero), but never
otherwise.

If cancellable
 is not NULL, then the operation can be cancelled by
triggering the cancellable object from another thread. If the operation
was cancelled, the error G_IO_ERROR_CANCELLED will be returned. If an
operation was partially finished when the operation was cancelled the
partial result will be returned, without an error.

On error NULL is returned and error
 is set accordingly.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

a GInputStream.

count

maximum number of bytes that will be read from the stream. Common
values include 4096 and 8192.

cancellable

 optional GCancellable object, NULL to ignore.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

error

location to store the error occurring, or NULL to ignore

Returns

 a new GBytes, or NULL on error

Since 2.34

g_input_stream_read_bytes_async ()

void
g_input_stream_read_bytes_async (GInputStream *stream,
                                 gsize count,
                                 int io_priority,
                                 GCancellable *cancellable,
                                 GAsyncReadyCallback callback,
                                 gpointer user_data);

Request an asynchronous read of count
 bytes from the stream into a
new GBytes. When the operation is finished callback
 will be
called. You can then call g_input_stream_read_bytes_finish() to get the
result of the operation.

During an async request no other sync and async calls are allowed
on stream
, and will result in G_IO_ERROR_PENDING errors.

A value of count
 larger than G_MAXSSIZE will cause a
G_IO_ERROR_INVALID_ARGUMENT error.

On success, the new GBytes will be passed to the callback. It is
not an error if this is smaller than the requested size, as it can
happen e.g. near the end of a file, but generally we try to read as
many bytes as requested. Zero is returned on end of file (or if
count
 is zero), but never otherwise.

Any outstanding I/O request with higher priority (lower numerical
value) will be executed before an outstanding request with lower
priority. Default priority is G_PRIORITY_DEFAULT.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

A GInputStream.

count

the number of bytes that will be read from the stream

io_priority

the I/O priority of the request

cancellable

 optional GCancellable object, NULL to ignore.

[<acronym title="NULL is OK, both for passing and for returning.">allow-none</acronym>]

callback

 callback to call when the request is satisfied.

[<acronym title="The callback is valid until first called.">scope async</acronym>]

user_data

 the data to pass to callback function.

[<acronym title="This parameter is a 'user_data', for callbacks; many bindings can pass NULL here.">closure</acronym>]

Since 2.34

g_input_stream_read_bytes_finish ()

GBytes *
g_input_stream_read_bytes_finish (GInputStream *stream,
                                  GAsyncResult *result,
                                  GError **error);

Finishes an asynchronous stream read-into-GBytes operation.

Parameters

<colgroup>
<col width="150px" class="parameters_name">
<col class="parameters_description">
<col width="200px" class="parameters_annotations">
</colgroup>

stream

a GInputStream.

result

a GAsyncResult.

error

a GError location to store the error occurring, or NULL to
ignore.

Returns

 the newly-allocated GBytes, or NULL on error

Since 2.34

Types and Values

GInputStream

typedef struct _GInputStream GInputStream;

Base class for streaming input operations.

          Generated by GTK-Doc V1.21.1


text:
package apple.foundation.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NUInt;

/**
 * [@enum] NSURLRequestAttribution
 *

 * The NSURLRequestAttribution enum is used to indicate whether the
 * user or developer specified the URL.
 *

 * [@constant] NSURLRequestAttributionDeveloper Indicates that the URL was specified
 * by the developer. This is the default value for an NSURLRequest when created.
 *

 * [@constant] NSURLRequestAttributionUser Indicates that the URL was specified by
 * the user.
 */
@Generated
public final class NSURLRequestAttribution {
    @Generated
    private NSURLRequestAttribution() {
    }

    @Generated @NUInt public static final long Developer = 0x0000000000000000L;
    @Generated @NUInt public static final long User = 0x0000000000000001L;
}


text:
import { IThing } from '../IThing';

export enum LINK_TYPE {
    boardgamecategory,
    boardgamefamily,
}

export interface IBggThing extends IThing {
    rank?: number;
}


text:
/*
scantree.cpp

Сканирование текущего каталога и, опционально, подкаталогов на
предмет имен файлов
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

// BUGBUG
#include "platform.headers.hpp"

// Self:
#include "scantree.hpp"

// Internal:
#include "config.hpp"
#include "pathmix.hpp"
#include "cvtname.hpp"
#include "global.hpp"
#include "log.hpp"

// Platform:
#include "platform.hpp"
#include "platform.fs.hpp"

// Common:
#include "common/algorithm.hpp"
#include "common/string_utils.hpp"

// External:

//----------------------------------------------------------------------------

enum tree_flags
{
	// TREE_RETUPDIR causes GetNextName() to return every directory twice:
	// 1. when scanning its parent directory
	// 2. after directory scan is finished
	TREE_RETUPDIR      = 0_bit, // = FRS_RETUPDIR
	TREE_RECUR         = 1_bit, // = FRS_RECUR
	TREE_SCANSYMLINK   = 2_bit, // = FRS_SCANSYMLINK
	TREE_FILESFIRST    = 3_bit, // Сканирование каталога за два прохода. Сначала файлы, затем каталоги
	TREE_SECONDDIRNAME = 4_bit, // set when FSCANTREE_RETUPDIR is enabled and directory scan is finished
};

enum tree_item_flags
{
	TREE_ITEM_SECONDPASS           = 0_bit, // то, что раньше было было SecondPass[]
	TREE_ITEM_INSIDE_REPARSE_POINT = 1_bit, // For Copy: we don't want to delete anything from any reparse points
};

class ScanTree::scantree_item
{
public:
	NONCOPYABLE(scantree_item);
	MOVE_CONSTRUCTIBLE(scantree_item);

	scantree_item() = default;

	BitFlags Flags;
	std::unique_ptr<os::fs::enum_files> Find;
	os::fs::enum_files::iterator Iterator;
	string RealPath;
	unordered_string_set ActiveDirectories;
};

ScanTree::ScanTree(bool RetUpDir, bool Recurse, int ScanJunction, bool FilesFirst)
{
	Flags.Change(TREE_RETUPDIR, RetUpDir);
	Flags.Change(TREE_RECUR, Recurse);
	Flags.Change(TREE_SCANSYMLINK, ScanJunction == -1? Global->Opt->ScanJunction.Get() : ScanJunction != 0);
	Flags.Change(TREE_FILESFIRST, FilesFirst);
}

ScanTree::~ScanTree() = default;

void ScanTree::SetFindPath(string_view const Path, string_view const Mask)
{
	ScanItems.clear();

	strFindMask = Mask;

	strFindPathOriginal = Path;
	AddEndSlash(strFindPathOriginal);

	const auto FullPath = NTPath(ConvertNameToFull(Path));

	strFindPath = NTPath(ConvertNameToReal(FullPath));

	scantree_item Item;
	Item.RealPath = strFindPath;
	Item.ActiveDirectories.emplace(strFindPath);

	path::append(strFindPath, strFindMask);

	if (os::fs::is_directory_reparse_point(os::fs::get_file_attributes(FullPath)))
	{
		Item.Flags.Set(TREE_ITEM_INSIDE_REPARSE_POINT);
	}

	ScanItems.emplace_back(std::move(Item));
}

bool ScanTree::GetNextName(os::fs::find_data& fdata,string &strFullName)
{
	if (ScanItems.empty())
		return false;

	bool Done=false;
	Flags.Clear(TREE_SECONDDIRNAME);

	{
		scantree_item& LastItem = ScanItems.back();
		for (;;)
		{
			if (!LastItem.Find)
			{
				LastItem.Find = std::make_unique<os::fs::enum_files>(strFindPath);
				LastItem.Iterator = LastItem.Find->end();
			}

			if (LastItem.Iterator == LastItem.Find->end())
			{
				LastItem.Iterator = LastItem.Find->begin();
			}
			else
			{
				++LastItem.Iterator;
			}

			Done = LastItem.Iterator == LastItem.Find->end();

			if (!Done)
			{
				fdata = *ScanItems.back().Iterator;
			}

			if (Flags.Check(TREE_FILESFIRST))
			{
				if (LastItem.Flags.Check(TREE_ITEM_SECONDPASS))
				{
					if (!Done && !(fdata.Attributes & FILE_ATTRIBUTE_DIRECTORY))
						continue;
				}
				else
				{
					if (!Done && (fdata.Attributes & FILE_ATTRIBUTE_DIRECTORY))
						continue;

					if (Done)
					{
						LastItem.Find.reset();
						LastItem.Flags.Set(TREE_ITEM_SECONDPASS);
						continue;
					}
				}
			}

			break;
		}
	}

	if (Done)
	{
		ScanItems.pop_back();

		if (ScanItems.empty())
			return false;
		else
		{
			CutToSlash(strFindPath,true);
			CutToSlash(strFindPathOriginal,true);

			if (Flags.Check(TREE_RETUPDIR))
			{
				strFullName = strFindPathOriginal;
				// BUGBUG check result
				if (!os::fs::get_find_data(strFindPath, fdata))
				{
					LOGWARNING(L"get_find_data({}): {}"sv, strFindPath, os::last_error());
				}

			}

			CutToSlash(strFindPath);
			strFindPath += strFindMask;

			if (Flags.Check(TREE_RETUPDIR))
			{
				Flags.Set(TREE_SECONDDIRNAME);
				return true;
			}

			return GetNextName(fdata,strFullName);
		}
	}
	else
	{
		const auto is_link = os::fs::is_directory_symbolic_link(fdata);
		if ((fdata.Attributes&FILE_ATTRIBUTE_DIRECTORY) && Flags.Check(TREE_RECUR) && (!is_link || Flags.Check(TREE_SCANSYMLINK)))
		{
			auto RealPath = path::join(ScanItems.back().RealPath, fdata.FileName);

			if (is_link)
				RealPath = NTPath(ConvertNameToReal(RealPath));

			//recursive symlinks guard
			if (!contains(ScanItems.back().ActiveDirectories, RealPath))
			{
				CutToSlash(strFindPath);
				path::append(strFindPath, fdata.FileName, strFindMask);

				CutToSlash(strFindPathOriginal);
				strFindPathOriginal += fdata.FileName;

				strFullName = strFindPathOriginal;
				AddEndSlash(strFindPathOriginal);

				scantree_item Data;
				Data.Flags = ScanItems.back().Flags; // наследуем флаг
				Data.Flags.Clear(TREE_ITEM_SECONDPASS);
				Data.RealPath = RealPath;
				Data.ActiveDirectories = ScanItems.back().ActiveDirectories;
				if (Flags.Check(TREE_SCANSYMLINK))
					Data.ActiveDirectories.emplace(RealPath);

				if (os::fs::is_directory_reparse_point(fdata.Attributes))
				{
					Data.Flags.Set(TREE_ITEM_INSIDE_REPARSE_POINT);
				}
				ScanItems.emplace_back(std::move(Data));

				return true;
			}
		}
	}

	strFullName = strFindPathOriginal;
	CutToSlash(strFullName);
	strFullName += fdata.FileName;

	return true;
}

void ScanTree::SkipDir()
{
	if (ScanItems.empty())
		return;

	{
		const auto& Current = ScanItems.back();
		if (!Flags.Check(TREE_SCANSYMLINK) &&
			Current.Find &&
			Current.Iterator != Current.Find->end() &&
			os::fs::is_directory_symbolic_link(*Current.Iterator)
			)
		{
			// The current item is a directory link but we don't treat it as a directory so it's nothing to skip
			// (perhaps it could have been better to add a special flag for this case rather than the quite complex condition above,
			// but these flags is already a mess).
			return;
		}
	}

	ScanItems.pop_back();

	if (ScanItems.empty())
		return;

	CutToSlash(strFindPath,true);
	CutToSlash(strFindPathOriginal,true);
	CutToSlash(strFindPath);
	CutToSlash(strFindPathOriginal);
	strFindPath += strFindMask;
}

bool ScanTree::IsDirSearchDone() const
{
	return Flags.Check(TREE_SECONDDIRNAME);
}

bool ScanTree::InsideReparsePoint() const
{
	return std::any_of(ALL_CONST_RANGE(ScanItems), [](scantree_item const& i)
	{
		return i.Flags.Check(TREE_ITEM_INSIDE_REPARSE_POINT);
	});
}


text:
'use strict';

function mongooseFS(schema, options){
  var mongoose          = options.mongoose || require('mongoose');
  var bucket            = options.bucket || 'fs';
  var Q                 = require('q');
  var linkPropertyName  = options.linkPropertyName || '_gfs';
  var gfsSchema         = {};
  var Grid              = mongoose.mongo.Grid;
  var GridStore         = mongoose.mongo.GridStore;
  var ObjectId          = mongoose.Schema.ObjectId;

  schema.set("strict", true);

  gfsSchema[linkPropertyName] = {};
  options.keys.forEach(function(key){
    gfsSchema[linkPropertyName][key] = ObjectId;
  });

  schema.add(gfsSchema);

  options.keys.forEach(function(key){
    schema.virtual(key).get(function(){
      var id      = this.get(linkPropertyName + '.' + key);
      var gridFS  = Grid(mongoose.connection.db, bucket);

      return Q.Promise(function(resolve, reject){
        if (id == null) return resolve(null);

        gridFS.get(id, function(err, buffer){
          if (err) resolve(null);
          else resolve(buffer);
        });
      });
    });
    schema.virtual(key).set(function(value){
      var self      = this;
      var gridFS    = Grid(mongoose.connection.db);
      var buffer    = new Buffer(value.buffer);
      var previous  = this.get(linkPropertyName + '.' + key);

      if (previous !== undefined)
        gridFS.delete(previous, function(err){
          if (err) throw err;
        });

      gridFS.put(buffer, {
        content_type: 'application/octet-stream',
        metadata: value.metadata
      }, function(err, info){
        if (err) throw err;
        self.set(linkPropertyName + '.' + key, info._id);
        self.save();
      });
    });
  });

  schema.methods.metadata = function (key){
    var id = this.get(linkPropertyName + '.' + key);
    if (id == null) return null;

    var gridFS = GridStore(mongoose.connection.db, id);

    return Q.promise(function(resolve, reject){
      gridFS.open(function(err, gridStore){
        resolve(gridStore.metadata);
        gridStore.close();
      });
    });
  }
}

exports = module.exports = mongooseFS;


text:
<f:be.container>

					<f:be.buttons.csh />
					<f:be.menus.actionMenu>
						<f:be.menus.actionMenuItem label="Overview" controller="" action="list" />
						<f:be.menus.actionMenuItem label="Create new Subscribe" action="new" controller="Subscribe" />
					</f:be.menus.actionMenu>

					<f:be.pagePath />
					<f:be.pageInfo />

					<f:be.buttons.shortcut />

				<f:flashMessages renderMode="div" />
				<f:render section="content" />

</f:be.container>


text:
<?php

namespace League\BooBoo\Handler;

use ErrorException;
use Exception;
use Raven_Client;

class RavenHandler implements HandlerInterface
{
    /**
     * @var \Raven_Client
     */
    protected $client;

    public function __construct(Raven_Client $client, $minimumLogLevel = E_ALL)
    {
        $this->client = $client;
        $this->minimumLogLevel = $minimumLogLevel;
    }

    public function handle($e)
    {
        if ($e instanceof ErrorException) {
            $level = $e->getSeverity();
        } else {
            $level = E_ERROR;
        }

        if ($this->minimumLogLevel & $level) {
            $this->client->captureException($e);
        }
    }
}


text:
require 'spec_helper'

shared_context 'with_load_path_helper' do

  def with_load_path(load_path)
    $LOAD_PATH.unshift load_path
    yield
  ensure
    $LOAD_PATH.shift
  end

end


text:
package org.squbs.unicomplex

import java.io.{File, FileInputStream, InputStreamReader, Reader}
import java.net.URL
import java.util.concurrent.TimeUnit
import java.util.jar.JarFile
import java.util.{Timer, TimerTask}

import akka.actor._
import akka.pattern.ask
import akka.routing.FromConfig
import akka.util.Timeout
import com.typesafe.config._
import com.typesafe.scalalogging.LazyLogging
import org.squbs.lifecycle.ExtensionLifecycle
import org.squbs.unicomplex.ConfigUtil._
import org.squbs.unicomplex.UnicomplexBoot.CubeInit

import scala.annotation.tailrec
import scala.collection.concurrent.TrieMap
import scala.collection.mutable
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.util.{Failure, Success, Try}

object UnicomplexBoot extends LazyLogging {

  final val extConfigDirKey = "squbs.external-config-dir"
  final val extConfigNameKey = "squbs.external-config-files"
  final val actorSystemNameKey = "squbs.actorsystem-name"

  val startupTimeout: Timeout =
    Try(System.getProperty("startup.timeout").toLong) map { millis =>
      akka.util.Timeout(millis, TimeUnit.MILLISECONDS)
    } getOrElse (1 minute)

  object StartupType extends Enumeration {
    type StartupType = Value
    val
    // Identifies extensions
    EXTENSIONS,

    // Identifies actors as startup type
    ACTORS,

    // Identifies service as startup type
    SERVICES = Value
  }

  case class CubeInit(info: Cube, components: Map[StartupType.Value, Seq[Config]])

  val actorSystems = TrieMap.empty[String, ActorSystem]

  def apply(addOnConfig: Config): UnicomplexBoot = {
    val startTime = Timestamp(System.nanoTime, System.currentTimeMillis)
    UnicomplexBoot(startTime, Option(addOnConfig), getFullConfig(Option(addOnConfig)))
  }

  def apply(actorSystemCreator : (String, Config) => ActorSystem): UnicomplexBoot = {
    val startTime = Timestamp(System.nanoTime, System.currentTimeMillis)
    UnicomplexBoot(startTime, None, getFullConfig(None), actorSystemCreator)
  }

  def getFullConfig(addOnConfig: Option[Config]): Config = {
    val baseConfig = ConfigFactory.load()
    // 1. See whether add-on config is there.
    addOnConfig match {
      case Some(config) =>
        ConfigFactory.load(config withFallback baseConfig)
      case None =>
        // Sorry, the configDir is used to read the file. So it cannot be read from this config file.
        val configDir = new File(baseConfig.getString(extConfigDirKey))
        import collection.JavaConversions._
        val configNames = baseConfig.getStringList(extConfigNameKey)
        configNames.add("application")
        val parseOptions = ConfigParseOptions.defaults().setAllowMissing(true)
        val addConfigs = configNames map {
        	name => ConfigFactory.parseFileAnySyntax(new File(configDir, name), parseOptions)
        }
        if (addConfigs.isEmpty) baseConfig
        else ConfigFactory.load((addConfigs :\ baseConfig) (_ withFallback _))
    }
  }

  private[unicomplex] def scan(jarNames: Seq[String])(boot: UnicomplexBoot): UnicomplexBoot = {
    val configEntries = jarNames map readConfigs
    val jarConfigs = jarNames zip configEntries collect { case (jar, Some(cfg)) => (jar, cfg) }
    resolveCubes(jarConfigs, boot.copy(jarNames = jarNames))
  }

  private[unicomplex] def scanResources(resources: Seq[URL])(boot: UnicomplexBoot): UnicomplexBoot = {
    val jarConfigs = resources map readConfigs collect { case Some(jarCfg) => jarCfg }
    resolveCubes(jarConfigs, boot)
  }

  private[unicomplex] def scanResources(boot: UnicomplexBoot): UnicomplexBoot = {
    val loader = getClass.getClassLoader
    import scala.collection.JavaConversions._
    val resources = Seq("conf", "json", "properties") flatMap { ext => loader.getResources(s"META-INF/squbs-meta.$ext") }
    scanResources(resources)(boot)
  }

  private[this] def resolveCubes(jarConfigs: Seq[(String, Config)], boot: UnicomplexBoot) = {

    val cubeList = resolveAliasConflicts(jarConfigs map { case (jar, config) => readCube(jar, config) } collect {
      case Some(cube) => cube
    })

    // Read listener and alias information.
    val (activeAliases, activeListeners, missingAliases) = findListeners(boot.config, cubeList)
    missingAliases foreach { name => logger.warn(s"Requested listener $name not found!") }
    boot.copy(cubes = cubeList, jarConfigs = jarConfigs, listeners = activeListeners, listenerAliases = activeAliases)
  }

  private[this] def readConfigs(jarName: String): Option[Config] = {

    // Make it extra lazy, so that we do not create the next File if the previous one succeeds.
    val configExtensions = Stream("conf", "json", "properties")

    val jarFile = new File(jarName)

    var fileName: String = "" // Contains the evaluated config file name, used for reporting errors.
    var configReader: Option[Reader] = None

    try {
      configReader =
        if (jarFile.isDirectory) {

          def getConfFile(ext: String) = {
            fileName = "META-INF/squbs-meta." + ext
            val confFile = new File(jarFile, fileName)
            if (confFile.isFile) Option(new InputStreamReader(new FileInputStream(confFile), "UTF-8"))
            else None
          }
          (configExtensions map getConfFile find { _ != None }).flatten

        } else if (jarFile.isFile) {

          val jar = new JarFile(jarFile)

          def getConfFile(ext: String) = {
            fileName = "META-INF/squbs-meta." + ext
            val confFile = jar.getEntry(fileName)
            if (confFile != null && !confFile.isDirectory)
              Option(new InputStreamReader(jar.getInputStream(confFile), "UTF-8"))
            else None
          }
          (configExtensions map getConfFile find { _ != None }).flatten
        } else None

      configReader map ConfigFactory.parseReader

    } catch {
      case e: Exception =>
        logger.info(s"${e.getClass.getName} reading configuration from $jarName : $fileName.\n ${e.getMessage}")
        None
    } finally {
      configReader match {
        case Some(reader) => reader.close()
        case None =>
      }
    }
  }

  private[this] def readConfigs(resource: URL): Option[(String, Config)] = {

    // Taking the best guess at the jar name or classpath entry. Should work most of the time.
    val jarName = resource.getProtocol match {
      case "jar" =>
        val jarURL = new URL(resource.getPath.split('!')(0))
        jarURL.getProtocol match {
          case "file" => jarURL.getPath
          case _ => jarURL.toString
        }
      case "file" => // We assume the classpath entry ends before the last /META-INF/
        val path = resource.getPath
        val endIdx = path.lastIndexOf("/META-INF/")
        if (endIdx > 0) path.substring(0, endIdx) else path
      case _ =>
        val path = resource.toString
        val endIdx = path.lastIndexOf("/META-INF/")
        if (endIdx > 0) path.substring(0, endIdx) else path
    }

    try {
      val config = ConfigFactory.parseURL(resource)
      Some((jarName, config))
    } catch {
      case e: Exception =>
        logger.info(s"${e.getClass.getName} reading configuration from $jarName.\n ${e.getMessage}")
        None
    }
  }

  private[this] def readCube(jarPath: String, config: Config): Option[CubeInit] = {
    val cubeName =
      try {
        config.getString("cube-name")
      } catch {
        case e: ConfigException => return None
      }

    val cubeVersion =
      try {
        config.getString("cube-version")
      } catch {
        case e: ConfigException => return None
      }

    val cubeAlias = cubeName.substring(cubeName.lastIndexOf('.') + 1)

    val c =
      Seq(config.getOptionalConfigList("squbs-actors") map ((StartupType.ACTORS, _)),
        config.getOptionalConfigList("squbs-services") map ((StartupType.SERVICES, _)),
        config.getOptionalConfigList("squbs-extensions") map ((StartupType.EXTENSIONS, _)))
      .collect { case Some((sType, configs)) => (sType, configs) } .toMap

    Some(CubeInit(Cube(cubeAlias, cubeName, cubeVersion, jarPath), c))
  }

  // Resolve cube alias conflict by making it longer on demand.
  @tailrec
  private[unicomplex] def resolveAliasConflicts(cubeList: Seq[CubeInit]): Seq[CubeInit] = {

    val aliasConflicts = cubeList map { cube =>
      (cube.info.name, cube.info.fullName)
    } groupBy (_._1) mapValues { seq =>
      (seq map (_._2)).toSet
    } filter { _._2.size > 1 }

    if (aliasConflicts.isEmpty) cubeList
    else {

      var updated = false

      val newAliases = (aliasConflicts map { case (alias, conflicts) =>
        conflicts.toSeq map { symName =>
          val idx = symName.lastIndexOf('.', symName.length - alias.length - 2)
          if (idx > 0) {
            updated = true
            (symName, symName.substring(idx + 1))
          }
          else (symName, symName)
        }
      }).flatten.toSeq

      if (updated) {
        val updatedList = cubeList map { cube =>
          newAliases find { case (symName, alias) => symName == cube.info.fullName } match {
            case Some((symName, alias)) => cube.copy(info = cube.info.copy(name = alias))
            case None => cube
          }
        }
        resolveAliasConflicts(updatedList)
      }
      else sys.error("Duplicate cube names: " + (aliasConflicts flatMap (_._2) mkString ", "))
    }
  }

  private [unicomplex] def startComponents(cube: CubeInit, aliases: Map[String, String])
                                          (implicit actorSystem: ActorSystem) = {
    import cube.components
    import cube.info.{fullName, jarPath, name, version}
    val cubeSupervisor = actorSystem.actorOf(Props[CubeSupervisor], name)
    Unicomplex(actorSystem).uniActor ! CubeRegistration(cube.info, cubeSupervisor)

    def startActor(actorConfig: Config): Option[(String, String, String, Class[_])] = {
      val className = actorConfig getString "class-name"
      val name = actorConfig getOptionalString "name" getOrElse (className substring (className.lastIndexOf('.') + 1))
      val withRouter = actorConfig getOptionalBoolean "with-router" getOrElse false
      val initRequired = actorConfig getOptionalBoolean "init-required" getOrElse false

      try {
        val clazz = Class.forName(className, true, getClass.getClassLoader)
        clazz asSubclass classOf[Actor]

        // Create and the props for this actor to be started, optionally enabling the router.
        val props = if (withRouter) Props(clazz) withRouter FromConfig() else Props(clazz)

        // Send the props to be started by the cube.
        cubeSupervisor ! StartCubeActor(props, name,initRequired)
        Some((fullName, name, version, clazz))
      } catch {
        case e: Exception =>
          val t = getRootCause(e)
          logger.warn(s"Can't load actor: $className.\n" +
            s"Cube: $fullName $version\n" +
            s"Path: $jarPath\n" +
            s"${t.getClass.getName}: ${t.getMessage}")
          t.printStackTrace()
          None
      }
    }

    def startServiceRoute(clazz: Class[_], proxyName : Option[String], webContext: String, listeners: Seq[String]) = {
      try {
        val routeClass = clazz asSubclass classOf[RouteDefinition]
        val props = Props(classOf[RouteActor], webContext, routeClass)
        val className = clazz.getSimpleName
        val actorName =
          if (webContext.length > 0) s"${webContext.replace('/', '_')}-$className-route"
          else s"root-$className-route"
        cubeSupervisor ! StartCubeService(webContext, listeners, props, actorName, proxyName, initRequired = true)
        Some((fullName, name, version, clazz))
      } catch {
        case e: ClassCastException => None
      }
    }

    // This same creator class is available in Akka's Props.scala but it is inaccessible to us.
    class TypedCreatorFunctionConsumer(clz: Class[_ <: Actor], creator: () => Actor) extends IndirectActorProducer {
      override def actorClass = clz
      override def produce() = creator()
    }

    def startServiceActor(clazz: Class[_], proxyName : Option[String], webContext: String, listeners: Seq[String],
                          initRequired: Boolean) = {
      try {
        val actorClass = clazz asSubclass classOf[Actor]
        def actorCreator: Actor = WebContext.createWithContext[Actor](webContext) { actorClass.newInstance() }
        val props = Props(classOf[TypedCreatorFunctionConsumer], clazz, actorCreator _)
        val className = clazz.getSimpleName
        val actorName =
          if (webContext.length > 0) s"${webContext.replace('/', '_')}-$className-handler"
          else s"root-$className-handler"
        cubeSupervisor ! StartCubeService(webContext, listeners, props, actorName, proxyName, initRequired)
        Some((fullName, name, version, actorClass))
      } catch {
        case e: ClassCastException => None
      }
    }

    def getProxyName(serviceConfig: Config): Option[String] = {
      Try {
        serviceConfig.getString("proxy-name").trim
      } match {
        case Success(proxyName) => Some(proxyName)
        case Failure(t) => None // not defined
      }
    }

    def startService(serviceConfig: Config): Option[(String, String, String, Class[_])] =
    try {
      val className = serviceConfig.getString("class-name")
      val clazz = Class.forName(className, true, getClass.getClassLoader)
      val proxyName = getProxyName(serviceConfig)
      val webContext = serviceConfig.getString("web-context")

      val listeners = serviceConfig.getOptionalStringList("listeners").fold(Seq("default-listener"))({ list =>

        val listenerMapping = list collect {
          case entry if entry != "*" => (entry, aliases get entry)
        }

        listenerMapping foreach {
          // Make sure we report any missing listeners
          case (entry, None) =>
            logger.warn(s"Listener $entry required by $fullName is not configured. Ignoring.")
          case _ =>
        }

        if (list contains "*") aliases.values.toSeq.distinct
        else listenerMapping collect { case (entry, Some(listener)) => listener }
      })

      val service = startServiceRoute(clazz, proxyName,webContext, listeners) orElse startServiceActor(
        clazz, proxyName, webContext, listeners, serviceConfig getOptionalBoolean "init-required" getOrElse false)

      if (service == None) throw new ClassCastException(s"Class $className is neither a RouteDefinition nor an Actor.")
      service

    } catch {
        case e: Exception =>
          val t = getRootCause(e)
          logger.warn(s"Can't load service definition $serviceConfig.\n" +
            s"Cube: $fullName $version\n" +
            s"Path: $jarPath\n" +
            s"${t.getClass.getName}: ${t.getMessage}")
          t.printStackTrace()
          None
      }

    val actorConfigs = components.getOrElse(StartupType.ACTORS, Seq.empty)
    val routeConfigs = components.getOrElse(StartupType.SERVICES, Seq.empty)

    val actorInfo = actorConfigs map startActor
    val routeInfo = routeConfigs map startService

    cubeSupervisor ! Started // Tell the cube all actors to be started are started.
    logger.info(s"Started cube $fullName $version")
    (actorInfo ++ routeInfo) collect { case Some(component) => component }
  }

  def configuredListeners(config: Config): Map[String, Config] = {
    import collection.JavaConversions._
    val listeners = config.root.toSeq collect {
      case (n, v: ConfigObject) if v.toConfig.getOptionalString("type") == Some("squbs.listener") => (n, v.toConfig)
    }
    // Check for duplicates
    val listenerMap = mutable.Map.empty[String, Config]
    listeners foreach { case (name, cfg) =>
        listenerMap.get(name) match {
          case Some(_) => logger.warn(s"Duplicate listener $name already declared. Ignoring.")
          case None => listenerMap += name -> cfg
        }
    }
    listenerMap.toMap
  }

  def findListenerAliases(listeners: Map[String, Config]): Map[String, String] = {
    val aliases =
    for ((name, config) <- listeners) yield {
      val aliasNames = config.getOptionalStringList("aliases") getOrElse Seq.empty[String]
      (name, name) +: (aliasNames map ((_, name)))
    }
    val aliasMap = mutable.Map.empty[String, String]

    // Check for duplicate aliases
    for {
      group <- aliases
      (alias, listener) <- group
    } {
      aliasMap.get(alias) match {
        case Some(l) =>
          logger.warn(s"Duplicate alias $alias for listener $listener already declared for listener $l. Ignoring.")
        case None => aliasMap += alias -> listener
      }
    }
    aliasMap.toMap
  }

  def findListeners(config: Config, cubes: Seq[CubeInit]) = {
    val demandedListeners =
    for {
      routes <- cubes.map { _.components.get(StartupType.SERVICES) } .collect { case Some(routes) => routes } .flatten
      routeListeners <- routes getOptionalStringList "listeners" getOrElse Seq("default-listener")
      if routeListeners != "*" // Filter out wildcard listener bindings, not starting those.
    } yield {
      routeListeners
    }
    val listeners = configuredListeners(config)
    val aliases = findListenerAliases(listeners)
    val activeAliases = aliases filter { case (n, _) => demandedListeners contains n }
    val missingAliases = demandedListeners filterNot { l => activeAliases exists { case (n, _) => n == l } }
    val activeListenerNames = activeAliases.values
    val activeListeners = listeners filter { case (n, c) => activeListenerNames exists (_ == n) }
    (activeAliases, activeListeners, missingAliases)
  }

  def startServiceInfra(boot: UnicomplexBoot)(implicit actorSystem: ActorSystem) {
    import actorSystem.dispatcher
    val startTime = System.nanoTime
    implicit val timeout = Timeout((boot.listeners.size * 5) seconds)
    val ackFutures =
      for ((listenerName, config) <- boot.listeners) yield {
        Unicomplex(actorSystem).uniActor ? StartListener(listenerName, config)
      }
    // Block for the web service to be started.
    Await.ready(Future.sequence(ackFutures), timeout.duration)

    val elapsed = (System.nanoTime - startTime) / 1000000
    logger.info(s"Web Service started in $elapsed milliseconds")
  }

  private[unicomplex] def getRootCause(e: Exception) = {
    var t : Throwable = e
    var cause = e.getCause
    while (cause != null) {
      t = cause
      cause = t.getCause
    }
    t
  }
}

case class UnicomplexBoot private[unicomplex] (startTime: Timestamp,
                          addOnConfig: Option[Config] = None,
                          config: Config,
                          actorSystemCreator: (String, Config) => ActorSystem =
                            {(name, config) => ActorSystem(name, config)},
                          cubes: Seq[CubeInit] = Seq.empty,
                          listeners: Map[String, Config] = Map.empty,
                          listenerAliases: Map[String, String] = Map.empty,
                          jarConfigs: Seq[(String, Config)] = Seq.empty,
                          jarNames: Seq[String] = Seq.empty,
                          actors: Seq[(String, String, String, Class[_])] = Seq.empty,
                          extensions: Seq[Extension] = Seq.empty,
                          started: Boolean = false,
                          stopJVM: Boolean = false) extends LazyLogging {

  import UnicomplexBoot._

  def actorSystemName = config.getString(actorSystemNameKey)

  def actorSystem = UnicomplexBoot.actorSystems(actorSystemName)

  def externalConfigDir = config.getString(extConfigDirKey)

  def createUsing(actorSystemCreator: (String, Config) => ActorSystem) = copy(actorSystemCreator = actorSystemCreator)

  def scanComponents(jarNames: Seq[String]): UnicomplexBoot = scan(jarNames)(this)

  def scanResources(resources: Seq[URL]): UnicomplexBoot = UnicomplexBoot.scanResources(resources)(this)

  def scanResources(): UnicomplexBoot = UnicomplexBoot.scanResources(this)

  def initExtensions: UnicomplexBoot = {

    val initSeq = cubes.flatMap { cube =>
      cube.components.getOrElse(StartupType.EXTENSIONS, Seq.empty) map { config =>
        val className = config getString "class-name"
        val seqNo = config getOptionalInt "sequence" getOrElse Int.MaxValue
        (seqNo, className, cube)
      }
    } .sortBy (_._1)

    // load extensions
    val extensions = initSeq map (loadExtension _).tupled

    // preInit extensions
    val preInitExtensions = extensions map extensionOp("preInit", _.preInit())

    // Init extensions
    val initExtensions = preInitExtensions map extensionOp("init", _.init())

    copy(extensions = initExtensions)
  }

  def stopJVMOnExit: UnicomplexBoot = copy(stopJVM = true)

  def start(): UnicomplexBoot = synchronized {

    if (started) throw new IllegalStateException("Unicomplex already started!")

    // Extensions may have changed the config. So we need to reload the config here.
    val newConfig = UnicomplexBoot.getFullConfig(addOnConfig)
    val newName = config.getString(UnicomplexBoot.actorSystemNameKey)

    implicit val actorSystem = {
      val system = actorSystemCreator(newName, newConfig)
      system.registerExtension(Unicomplex)
      Unicomplex(system).setScannedComponents(jarNames)
      system
    }

    UnicomplexBoot.actorSystems += actorSystem.name -> actorSystem
    actorSystem.registerOnTermination { UnicomplexBoot.actorSystems -= actorSystem.name }

    registerExtensionShutdown(actorSystem)

    val uniActor = Unicomplex(actorSystem).uniActor

    // Send start time to Unicomplex
    uniActor ! startTime

    // Register extensions in Unicomplex actor
    uniActor ! Extensions(extensions)

    val startServices = listeners.nonEmpty && cubes.exists(_.components.contains(StartupType.SERVICES))

    // Notify Unicomplex that services will be started.
    if (startServices) uniActor ! PreStartWebService(listeners)

    // Signal started to Unicomplex.
    uniActor ! Started

    // Start all actors
    val actors = cubes.map(startComponents(_, listenerAliases)).flatten

    // Start the service infrastructure if services are enabled and registered.
    if (startServices) startServiceInfra(this)

    val postInitExtensions = extensions map extensionOp("postInit", _.postInit())

    // Update the extension errors in Unicomplex actor, in case there are errors.
    uniActor ! Extensions(postInitExtensions)

    {
      // Tell Unicomplex we're done.
      implicit val timeout = startupTimeout
      val stateFuture = Unicomplex(actorSystem).uniActor ? Activate
      Try(Await.result(stateFuture, timeout.duration)) match {
        case Success(Active) => logger.info(s"[$actorSystemName] activated")
        case Success(Failed) => logger.info(s"[$actorSystemName] initialization failed.")
        case e => logger.warn(s"[$actorSystemName] awaiting confirmation, $e.")
      }
    }

    val boot = copy(config = actorSystem.settings.config, actors = actors, extensions = postInitExtensions, started = true)
    Unicomplex(actorSystem).boot send boot
    boot
  }

  def registerExtensionShutdown(actorSystem: ActorSystem) {
    if (extensions.nonEmpty) {
      actorSystem.registerOnTermination {
        // Run the shutdown in a different thread, not in the ActorSystem's onTermination thread.
        import scala.concurrent.Future

        // Kill the JVM if the shutdown takes longer than the timeout.
        if (stopJVM) {
          val shutdownTimer = new Timer(true)
          shutdownTimer.schedule(new TimerTask {
            def run() {
              System.exit(0)
            }
          }, 5000)
        }

        // Then run the shutdown in the global execution context.
        import scala.concurrent.ExecutionContext.Implicits.global
        Future {
          extensions.reverse foreach { e =>
            import e.info._
            e.extLifecycle foreach (_.shutdown())
            logger.info(s"Shutting down extension ${e.extLifecycle.getClass.getName} in $fullName $version")
          }
        } onComplete {
          case Success(result) =>
            logger.info(s"ActorSystem ${actorSystem.name} shutdown complete")
            if (stopJVM) System.exit(0)

          case Failure(e) =>
            logger.error(s"Error occurred during shutdown extensions: $e", e)
            if (stopJVM) System.exit(-1)
        }
      }
    }
  }

  def loadExtension(seqNo: Int, className: String, cube: CubeInit): Extension = {
      try {
        val clazz = Class.forName(className, true, getClass.getClassLoader)
        val extLifecycle = ExtensionLifecycle(this) { clazz.asSubclass(classOf[ExtensionLifecycle]).newInstance }
        Extension(cube.info, Some(extLifecycle), Seq.empty)
      } catch {
        case e: Exception =>
          import cube.info._
          val t = getRootCause(e)
          logger.warn(s"Can't load extension $className.\n" +
            s"Cube: $fullName $version\n" +
            s"Path: $jarPath\n" +
            s"${t.getClass.getName}: ${t.getMessage}")
          t.printStackTrace()
          Extension(cube.info, None, Seq("load" -> t))
      }
  }

  def extensionOp(opName: String, opFn: ExtensionLifecycle => Unit)
                 (extension: Extension): Extension = {
    import extension.info._

    extension.extLifecycle match {
      case None => extension
      case Some(l) =>
        try {
          opFn(l)
          logger.info(s"Success $opName extension ${l.getClass.getName} in $fullName $version")
          extension
        } catch {
          case e: Exception =>
            val t = getRootCause(e)
            logger.warn(s"Error on $opName extension ${l.getClass.getName}\n"  +
              s"Cube: $fullName $version\n" +
              s"${t.getClass.getName}: ${t.getMessage}")
            t.printStackTrace()
            extension.copy(exceptions = extension.exceptions :+ (opName -> t))
        }
    }
  }
}


text:
package org.finra.datagenerator.engine.scxml.tags.boundary;

    import org.finra.datagenerator.engine.scxml.tags.boundary.action.BoundaryActionDecimal;

    import java.util.List;
    import java.util.Map;

/**
* Implementation of dg:positiveBoundHiveDecimal tag
*/
public class PositiveBoundHiveDecimal extends BoundaryDecimal<PositiveBoundHiveDecimal.PositiveBoundHiveDecimalTag> {

    public Class<PositiveBoundHiveDecimalTag> getTagActionClass() {
        return PositiveBoundHiveDecimalTag.class;
    }

    public String getTagName() {
        return "positiveBoundHiveDecimal";
    }

    public String getTagNameSpace() {
        return "org.finra.datagenerator";
    }

    /**
     * @param action            an Action of the type handled by this class
     * @param possibleStateList a current list of possible states produced so far from
     *                          expanding a model state
     * @return a list with positive boundary conditions assigned
     * to the variable
     */
    public List<Map<String, String>> pipelinePossibleStates(PositiveBoundHiveDecimalTag action,
                                                            List<Map<String, String>> possibleStateList) {

        return returnStates(action, possibleStateList, setParameters(action, true));
    }

    /**
     * A custom Action for the 'dg:positiveBoundHiveDecimal' tag inside models
     */
    public static class PositiveBoundHiveDecimalTag extends BoundaryActionDecimal { }

}