text:
"""A set of handlers to manage resources."""

import cgi
import httplib
import os
import urllib
from django.utils import simplejson as json
from google.appengine import runtime
from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import handlers.base
import model
import settings
import util

class ResourceHandler(blobstore_handlers.BlobstoreUploadHandler,
                      handlers.base.PageHandler):
  """A handler to upload and delete resources."""

  PERMISSION_REQUIRED = model.Permission.RESOURCES
  FORM_TEMPLATE = 'resource'
  ASSOCIATED_MODEL = model.Resource

  def ShowForm(self, layer):
    """Displays a resource upload and deletion form."""
    layer_id = layer.key().id()
    upload_url = blobstore.create_upload_url('/resource-create/%d' % layer_id)
    return {'upload_url': upload_url}

  def ShowRaw(self, layer):
    """Displays the result of Create(), as passed to it in the query string.

    The results are written in 5 lines:
      1. Status: BAD_REQUEST (400) if the "error" query argument is set.
         Otherwise OK (200).
      2. Result ID: The contents of the "result" query argument. This should be
         the ID(s) of the created resource(s) if any were created successfully.
         May be empty if creation failed.
      3. Error Message: The contents of the "error" query argument. May be empty
         if creation succeeded.
      4. Single Upload URL: A new upload URL that a user can use to upload
         another resource.
      5. Bulk Upload URL: A new upload URL that a user can use to bulk upload
         multiple resources.

    The status code is written out because on the client side, upload forms have
    to be submitted into an iframe and as a result the normal status code cannot
    be accessed through JS.

    GET Args:
      result: The ID of the created resource.
      error: An error message. Ignored if result is set.

    Args:
      layer: The layer to which the created resource belongs.
    """
    error = self.request.get('error')
    result = self.request.get('result')

    layer_id = layer.key().id()
    single_url = blobstore.create_upload_url('/resource-create/%d' % layer_id)
    bulk_url = blobstore.create_upload_url('/resource-bulk/%d' % layer_id)

    if error:
      status = httplib.BAD_REQUEST
    else:
      status = httplib.OK
    self.response.set_status(status)
    self.response.out.write(status)
    self.response.out.write('\n')
    self.response.out.write(cgi.escape(result or ''))
    self.response.out.write('\n')
    self.response.out.write(cgi.escape(error or ''))
    self.response.out.write('\n')
    self.response.out.write(cgi.escape(single_url))
    self.response.out.write('\n')
    self.response.out.write(cgi.escape(bulk_url))

  def ShowList(self, layer):
    """Lists all resources in the given layer of a specified type.

    Writes out a JSON list of resources, each item including the name and URL of
    the resource. If no type is specified, each item also has a type property
    with its type.

    GET Args:
      type: The type of resources to list. If specified, must be one of
          model.Resource.TYPES. If not specified, all resources are listed,
          along with their types.

    Args:
      layer: The layer whose resources are to be listed.
    """
    requested_type = self.request.get('type', None)
    if requested_type and requested_type not in model.Resource.TYPES:
      raise util.BadRequest('Invalid resource type.')
    resources_to_write = []
    for resource in layer.resource_set:
      if requested_type in (resource.type, None):
        info = {'id': resource.key().id(), 'url': resource.GetURL(),
                'name': resource.filename}
        if not requested_type: info['type'] = resource.type
        resources_to_write.append(info)
    self.response.out.write(json.dumps(resources_to_write))

  def Create(self, layer):
    """Handles resource creation, including blobstore uploads.

    Since blob upload handlers must use a redirect rather than write the
    response out, a redirect is issued to /resource-raw/{layer_id} with an error
    or result query argument. The result is the ID of the new resource.

    POST Args:
      type: The type of the resource. Must be one of model.Resource.TYPES. If
          "image", the upload is validated as an image. If it is "icon", the
          upload is validated as an icon. Icons larger than
          settings.MAX_ICON_SIZE pixels in either dimension are rejected.
      filename: A filename for the resource. If a file was uploaded, and type is
          not model_in_kmz, this can be left unspecified. In the case of
          model_in_kmz resources, the filename must be the name of the COLLADA
          model file inside the KMZ.
      url: The URL of an external resource. If this is specified, nothing should
          be uploaded.
      file: An uploaded data file.

    Args:
      layer: The layer to which the new resource will belong.
    """
    try:
      uploaded_file = self.get_uploads('file')
      if uploaded_file:
        uploaded_file = uploaded_file[0]
      else:
        uploaded_file = None
      resource_id = self._CreateResource(layer,
                                         self.request.get('type'),
                                         self.request.get('filename'),
                                         self.request.get('url'),
                                         uploaded_file)
    except util.BadRequest, e:
      self._DeleteBlobs(self.get_uploads())
      redirect_args = 'error=%s' % e
    else:
      redirect_args = 'result=%d' % resource_id
    self.redirect('/resource-raw/%d?%s' % (layer.key().id(), redirect_args))
    raise util.RequestDone(redirected=True)

  def BulkCreate(self, layer):
    """Handles bulk resource creation, including blobstore uploads.

    Makes sure either an external URL was specified or a valid file was uploaded
    for each entry and creates a new Resource instance for that blob or URL.

    Since blob upload handlers must use a redirect rather than write the
    response out, a redirect is issued to /resource-raw/{layer_id} with an error
    and result query argument. The result is an ordered comma-separated list of
    IDs of the new resources. The list may have fewer elements than the number
    of specified resources if an error was encountered during resource creation.

    POST Args:
      Receives any number of resource descriptions, where each resource is
      described by the same type/filename/url/file paramaters that are mentioned
      in Create(). Parameter names should have the number of the resource
      appended, with the numbering starting from 0. For example the first
      resource may be described by type0, filename0 and url0, the second by
      type1, filename1 and file1, etc.

    Args:
      layer: The layer to which the new resources will belong.
    """
    uploads = self.get_uploads()
    index = 0
    created_resource_ids = []
    error = None
    try:
      while True:
        resource_type = self.request.get('type%d' % index)
        name = self.request.get('filename%d' % index)
        url = self.request.get('url%d' % index)
        blob = self.get_uploads('file%d' % index)
        if blob: blob = blob[0]

        if not resource_type:
          # No more resources.
          break

        try:
          new_id = self._CreateResource(layer, resource_type, name, url, blob)
        except util.BadRequest, e:
          # A failed resource. Delete unprocessed ones.
          self._DeleteBlobs(uploads)
          error = 'Resource %d: %s' % (index, e)
          break
        created_resource_ids.append(new_id)

        if blob in uploads:
          uploads.remove(blob)

        index += 1
    except runtime.DeadlineExceededError:
      self._DeleteBlobs(uploads)
      error = 'Ran out of time.'
      # We still want to write out the resource IDs and issue a redirect.

    result = ','.join(str(i) for i in created_resource_ids)
    if error:
      self.redirect('/resource-raw/%s?result=%s&error=%s' %
                    (layer.key().id(), result, urllib.quote(error)))
    else:
      self.redirect('/resource-raw/%s?result=%s' % (layer.key().id(), result))
    raise util.RequestDone(redirected=True)

  def Delete(self, layer):
    """Deletes a resource.

    If anything in the datastore references this resource, returns an error.

    POST Args:
      resource_id: The ID of the resource to delete.

    Args:
      layer: The layer to which the resource to delete belongs.
    """
    resource_id = self.request.get('resource_id')
    resource = util.GetInstance(model.Resource, resource_id, layer)
    if _IsResourceReferenced(resource):
      raise util.BadRequest('A reference to this resource was found.')
    # NOTE: May leave an inaccessible orphan blob if delete fails.
    blob = resource.blob
    resource.delete()
    if blob: blob.delete()

  @staticmethod
  def _CreateResource(layer, resource_type, name, url, blob):
    """Creates a resource from the specified parameters.

    Args:
      layer: The layer to which the new resources will belong.
      resource_type: The type fo the resource, one of model.Resource.TYPES.
      name: The name of the new resource, optional for non-KMZ uploads.
      url: An external URL pointing to the resource's data. Either this or blob
          must be specified.
      blob: The BlobInfo of an uploaded file to assign to the new resource.

    Returns:
      The ID of the new resource.

    Raises:
      util.BadRequest: On invalid input.
    """

    if resource_type not in model.Resource.TYPES:
      raise util.BadRequest('Invalid resource type. Must be one of: %s.' %
                            model.Resource.TYPES)

    if url:
      if not name:
        raise util.BadRequest('No filename provided for an external resource.')
      resource = model.Resource(layer=layer, filename=name,
                                type=resource_type, external_url=url)
    elif blob:
      if resource_type in ('image', 'icon'):
        if not _IsImage(blob):
          raise util.BadRequest('The uploaded file is not a valid image.')

        if resource_type == 'icon':
          size = _TryGetImageSize(blob)
          if size is None or (size[0] > settings.MAX_ICON_SIZE or
                              size[1] > settings.MAX_ICON_SIZE):
            raise util.BadRequest('The uploaded image is too large to be an '
                                  'icon.')
      elif resource_type == 'model_in_kmz' and not name:
        raise util.BadRequest('A filename must be supplied when uploading a '
                              'model packed into a KMZ archive.')
      if not name:
        name = blob.filename
      resource = model.Resource(layer=layer, filename=name,
                                type=resource_type, blob=blob)
    else:
      raise util.BadRequest('Neither URL nor file specified.')
    resource.put()
    return resource.key().id()

  @staticmethod
  def _DeleteBlobs(blobs):
    """Safely deletes the specified blobs."""
    for blob in blobs:
      # pylint: disable-msg=W0702
      # Catching all exceptions here because on the dev server, the upload
      # blobs are sometimes locked, and may throw exceptions of uncertain type
      # (e.g. on Windows it's a WindowsError, on other systems it is likely to
      # be something else).
      try:
        blob.delete()
      except:
        if not os.environ['SERVER_SOFTWARE'].startswith('Development'):
          raise

def _IsImage(blob):
  """Checks if a blob contains image data."""
  try:
    image = images.Image(blob_key=str(blob.key()))
    # Force image to load.
    image.horizontal_flip()
    image.execute_transforms()
  except (images.BadImageError, images.NotImageError):
    return False
  except images.LargeImageError:
    pass
  return True

def _TryGetImageSize(blob):
  """Attempts to find the width and height of an image stored in blobstore.

  An image constructed from a blobstore blob does not fetch the data unless
  a transformation is applied to it and as a result does not provide the width
  and height attributes. Therefore we apply a no-op transformation to force
  the data to be fetched then return the newly-initialized width and height.
  However, images that are larger than 1MB in JPEG form cannot be returned by
  the transformer, and therefore this function may fail.

  Args:
    blob: The blob containing the image data.

  Returns:
    If the transformation succeeded, returns a 2-tuple of the image's width
    and height. Otherwise returns None.
  """
  image = images.Image(blob_key=str(blob.key()))
  try:
    image.crop(0.0, 0.0, 1.0, 1.0)
    data = image.execute_transforms(output_encoding=images.JPEG)
    transformed_image = images.Image(image_data=data)
    return transformed_image.width, transformed_image.height
  except (images.TransformationError, images.LargeImageError):
    return None

def _IsResourceReferenced(resource):
  """Checks whether the resource is referenced by any model in the database."""
  # All references create backreferences named *_set, except containers,
  # which have no backreference (due to circular dependency issues).
  for property_name in dir(resource):
    if (property_name.endswith('_set') and
        getattr(resource, property_name).get()):
      return True
  return bool(resource.layer.folder_set.filter('icon', resource).get() or
              resource.layer.link_set.filter('icon', resource).get() or
              resource.layer.icon == resource)


text:
//
//  PresenterTableViewController.h
//  IgniteTools
//
//  Created by Joseph Flasher on 6/5/11.
//  Copyright 2011 Ars Sollertia. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Event.h"
#import "AvatarDownload.h"

/**
 *	UITableViewController which shows all presenters or presenters for an event depending on if Event variable
 *	is set on load.
 */
@interface PresenterTableViewController : UITableViewController <NSFetchedResultsControllerDelegate, AvatarDownloadDelegate> {
	NSFetchedResultsController *fetchedResultsController;
	NSManagedObjectContext *managedObjectContext;
    NSMutableArray *avatars;
}

/**
 *	NSFetchedResultsController that contains all presenters.
 */
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;

/**
 *	Session NSManagedObjectContext.
 */
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

/**
 *  The array of avatars.
 */
@property (nonatomic, retain) NSMutableArray *avatars;

/**
 *  Create the avatars array
 */
- (void)createAvatarsArray;

@end

redpajama_set_name: RedPajamaGithub


text:
SELECT * FROM product WHERE type_id = (SELECT id FROM type WHERE name = 'СЫР');
-- продукты где в названии есть 'мороженое'
SELECT * FROM product WHERE name LIKE 'мороженое';
-- Написать запрос, который выводит все продукты, срок годности которых заканчивается в следующем месяце.
SELECT * FROM product WHERE expired_date >= (current_timestamp + INTERVAL '1 month')
                            AND expired_date <= (current_timestamp + INTERVAL '2 month');
-- Написать запрос, который выводит самый дорогой продукт.
SELECT * FROM product WHERE price = (SELECT max(price) FROM product);
-- Написать запрос, который выводит количество всех продуктов определенного типа
SELECT count, name FROM (SELECT type_id, count(type_id) FROM product GROUP BY type_id) AS c(type_id, count), type
WHERE c.type_id = type.id;
-- Написать запрос получение всех продуктов с типом "СЫР" и "МОЛОКО"
SELECT * FROM product WHERE type_id = (SELECT id FROM type WHERE name = 'СЫР')
                            OR type_id = (SELECT id FROM type WHERE name = 'МОЛОКО');
-- Написать запрос, который выводит тип продуктов, которых осталось меньше 10 штук.
SELECT count, name FROM (SELECT type_id, count(type_id) FROM product GROUP BY type_id) AS c(type_id, count), type
WHERE c.type_id = type.id AND c.count < 10;
-- Вывести все продукты и их тип.
SELECT product.id, product.name, product.expired_date, product.price, type.name
  FROM product, type
  WHERE product.type_id = type.id;


text:
mobileMenu
==========

jQuery Plugin for Make a HTML-Select Menu from an UL-Menu

## How to use
Simple use it this way:
```javascript
$('.menu').mobileMenu();
```

## Options
Option | Description | Default
------ | ----------- | -------
className: | The Classname the new generated Select gets. | mobileMenu
selectId: | The Id the new generated Select gets. | mobileMenu
depthSign | The sign for the current depth of the menuitem. | -
target | Where should the Select get rendered | $(this).parent()
minDepth | where to start the Menu | 0
maxDepth | where to stop the Menu | 10000

## License
Released under the MIT License. See the bundled LICENSE file for details.


text:
void usage()
{
    printf("multi-server %s (compilation date: %s)\n",
            MULTI_VERSION,
            __TIMESTAMP__);
    printf("  Configured port: %d \n", get_port());
    printf("  Maxium compilation unit at the same time: %ld\n\n",
           THREAD_COMPILE_MAX);

    printf("Copyright(C) 2013 by Baptiste COVOLATO\n\n");

    // FIXME : Add licence

    printf("Usage: multi OPTION\n");

    printf("Options:\n");
    printf("  --start : Start a new multi server if no server is running\n");
    printf("  --stop : Stop the running multi server\n");
    printf("  --restart : Restart running multi server or start a new one\n");
    printf("  --pid : Print the pid of the running multi server\n");
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin Page</title>

<link type="text/css" href="/css/blitzer/jquery-ui-1.8.17.custom.css"
	rel="stylesheet" />

		Create Ugly form for the following REST-APIs :
		http://archive.goldengekko.com/archive/user-security-mgmt/1.0.2/

		Admin Page

authenticateUserClientCredentialsType()

createUser()

getUserDetailInfo()

getUserWithPagination()

updateUserRole()

updateUserState()

LogIn Authorization /verify login with resource owner
			password

					POST
					/api/oauth2/token

					Login Name
					<input type="text" value="root@goldengekko.com" id="loginNameVerifyLogin" />

					Password
					<input type="password" value="tVeQxsuazfAhGNgrd1PWua29f" id="passwordVerifyLogin" />

					<button id="verifyLoginButton">Submit</button>

					Response Code

					Response

Create a new user type client credentials

					POST
					/api/admin/oauth2/v1/user

					clientId
					<input type="text" id="userNameCreateNewUser" />

					client Secret
					<input type="text" id="userSecretCreateNewUser" />

					Expire Policy
					 <select id="expirePolicy">
					           <option value="0"> After Login</option>
					           <option value="1"> Last Access</option>
					     </select>

                    Expire in Seconds
                     <input type="text" id="expireInSeconds" value="14400"/>

					<button id="createNewUserButton">Submit</button>

					Response
							Code

					Response

Get user detail info

					GET
					/api/admin/oauth2/v1/user/{userId}

					User Id
					<input type="text" id="userIdGetUserDetailInfo" />

					<button id="getUserDetailInfoButton">Submit</button>

					Response
							Code

					Response

Get user with pagination

					GET
					/api/admin/oauth2/v1/user

					User type( 1 type resource user_owner, 2
							client_credentials , 3 socialType )
					<input type="text" id="userTypeGetUserWithPagination" />

					Page Size
					<input type="text" id="pageSizeGetUserWithPagination" />

					Cursor key
					<input type="text" id="cursorKeyGetUserWithPagination" />

					<button id="getUserWithPaginationButton">Submit</button>

					Response
							Code

					Response

Update user role

					POST
					/api/admin/oauth2/v1/user/{userId}/roles

					User Id
					<input type="text" id="userIdUpdateUserRole" />

					User Roles
					<input type="text" id="rolesUpdateUserRole" />

					<button id="updateUserRoleButton">Submit</button>

					Response
							Code

					Response

Update user-state

					POST
					/api/admin/oauth2/v1/user/{userId}/state

					userId
					<input type="text" id="updateStateUserId" />

					State ( 1 acitve, -1 inactive)
					<input type="text" id="updateStateState" value="-1" />

					<button id="updateStateButton">Submit</button>

					Response Code

					Response


text:
<?php declare(strict_types = 1);

namespace ThibaudDauce\CompliantRegexps\Conciliators;

class Aggregator implements Conciliator
{
    /**
     * @var Conciliator[]
     */
    private $conciliators;

    public function __construct(array $conciliators)
    {
        $this->conciliators = $conciliators;
    }

    /**
     * Try to transform the string to match the regular expression.
     * Return all the possibilities for conciliating.
     *
     * @param string $regexp
     * @param string $string
     * @return string[]
     */
    public function conciliate(string $regexp, string $string): array
    {
        return $this->aggregate($regexp, [$string], $this->conciliators);
    }

    /**
     * @param string $regexp
     * @param string[] $possibilities
     * @param Conciliator[] $conciliators
     * @return string[]
     */
    private function aggregate(string $regexp, array $possibilities, array $conciliators)
    {
        $newResults = [$possibilities];
        $newConciliators = $conciliators;
        if (empty($conciliators)) {
            return $possibilities;
        }

        foreach ($conciliators as $key => $conciliator) {
            $newPossibilities = $possibilities;
            unset($newConciliators[$key]);
            foreach ($possibilities as $possibility) {
                foreach ($conciliator->conciliate($regexp, $possibility) as $newPossibilitiesFromConciliator) {
                    $newPossibilities[] = $newPossibilitiesFromConciliator;
                }
            }
            $newResults[] = $this->aggregate($regexp, array_unique($newPossibilities), $newConciliators);
            $newConciliators[$key] = $conciliator;
        }

        return array_values(array_unique(call_user_func_array('array_merge', $newResults)));
    }
}


text:
def input_films(quantity):
    films = []

    for x in range (quantity):
        print('\nFilm #{0}:'.format(x + 1))
        print('--------')

        films.append({
            'title': input('What is the film called? '),
            'category': input('What category does the film belong to? '),
            'director': input('Who directed the film? '),
            'rating': int(input('How would you rate the film out of 10? '))
        })

    display_films(films)

def display_films(films):
    print('\n\nHere are your films:\n')

    for film in films:
        for prop in film:
            print('{0}: {1}'.format(prop.title(), film[prop]))

if __name__ == '__main__':
    quantity = int(input('How many films do you want to enter? '))
    input_films(quantity)


text:
//
// Rebol 3 Language Interpreter and Run-time Environment
// "Ren-C" branch @ https://github.com/metaeducation/ren-c
//
//=////////////////////////////////////////////////////////////////////////=//
//
//  Summary: Debug Stack Reflection and Querying
//  File: %d-stack.h
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Copyright 2015-2017 Rebol Open Source Contributors
// REBOL is a trademark of REBOL Technologies
//
// See README.md and CREDITS.md for more information
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//=////////////////////////////////////////////////////////////////////////=//
//
// This file contains interactive debugging support for examining and
// interacting with the stack.
//
// !!! Interactive debugging is a work in progress, and comments are in the
// functions below.
//

#include "sys-core.h"

//
//  Collapsify_Array: C
//
// This will replace "long" nested blocks with collapsed versions with
// ellipses to show they have been cut off.  It does not change the arrays
// in question, but replaces them with copies.
//
void Collapsify_Array(REBARR *array, REBSPC *specifier, REBCNT limit)
{
    RELVAL *item = ARR_HEAD(array);
    for (; NOT_END(item); ++item) {
        if (ANY_ARRAY(item) and VAL_LEN_AT(item) > limit) {
            REBSPC *derived = Derive_Specifier(specifier, item);
            REBARR *copy = Copy_Array_At_Max_Shallow(
                VAL_ARRAY(item),
                VAL_INDEX(item),
                derived,
                limit + 1
            );

            Init_Word(ARR_AT(copy, limit), Canon(SYM_ELLIPSIS));

            Collapsify_Array(
                copy,
                SPECIFIED,
                limit
            );

            enum Reb_Kind kind = VAL_TYPE(item);
            Init_Any_Array_At(item, kind, copy, 0); // at 0 now
            assert(IS_SPECIFIC(item));
            assert(
                NOT_VAL_FLAG(item, VALUE_FLAG_NEWLINE_BEFORE) // gets cleared
            );
        }
    }
}

//
//  Init_Near_For_Frame: C
//
// Each call frame maintains the array it is executing in, the current index
// in that array, and the index of where the current expression started.
// This can be deduced into a segment of code to display in the debug views
// to indicate roughly "what's running" at that stack level.  The code is
// a shallow copy of the array content.
//
// The resulting WHERE information only includes the range of the array being
// executed up to the point of currently relevant evaluation.  It does not
// go all the way to the tail of the block (where future potential evaluation
// should be.
//
// !!! DO also offers a feature whereby values can be supplied at the start
// of an evaluation which are not resident in the array.  It also can run
// on an irreversible C va_list of REBVAL*, where these disappear as the
// evaluation proceeds.  A special debug setting would be needed to hang
// onto these values for the purposes of better error messages (at the cost
// of performance).
//
REBVAL *Init_Near_For_Frame(RELVAL *out, REBFRM *f)
{
    REBCNT dsp_start = DSP;

    if (FRM_IS_VALIST(f)) {
        //
        // Traversing a C va_arg, so reify into a (truncated) array.
        //
        const REBOOL truncated = TRUE;
        Reify_Va_To_Array_In_Frame(f, truncated);
    }

    // Get at most 6 values out of the array.  Ideally 3 before and after
    // the error point.  If truncating either the head or tail of the
    // values, put ellipses.

    // !!! We may be running a function where the value for the function was a
    // "head" value not in the array.  These cases could substitute the symbol
    // for the currently executing function.  Reconsider when such cases
    // appear and can be studied.
    /*
    if (...) {
        DS_PUSH_TRASH;
        Init_Word(DS_TOP, ...?)
    }
    */

    REBINT start = FRM_INDEX(f) - 3;
    if (start > 0) {
        DS_PUSH_TRASH;
        Init_Word(DS_TOP, Canon(SYM_ELLIPSIS));
    }
    else if (start < 0)
        start = 0;

    REBCNT count = 0;
    RELVAL *item = ARR_AT(FRM_ARRAY(f), start);
    for (; NOT_END(item) and count < 6; ++item, ++count) {
        DS_PUSH_TRASH;
        if (IS_VOID(item)) {
            //
            // If a va_list is used to do a non-evaluative call (something
            // like R3-Alpha's APPLY/ONLY) then void cells are currently
            // allowed.  Reify_Va_To_Array_In_Frame() may come along and
            // make a special block containing voids, which we don't want
            // to expose in a user-visible block.  Since this array is just
            // for display purposes and is "lossy" (as evidenced by the ...)
            // substitute a placeholder to avoid crashing the GC.
            //
            assert(GET_SER_FLAG(FRM_ARRAY(f), ARRAY_FLAG_VOIDS_LEGAL));
            Init_Word(DS_TOP, Canon(SYM___VOID__));
        }
        else
            Derelativize(DS_TOP, item, f->specifier);

        if (count == FRM_INDEX(f) - start - 1) {
            //
            // Leave a marker at the point of the error, currently `~~`.
            // (Formerly it was ?? but that is now being actually used).
            //
            // This is the marker for an execution point, so it can either
            // mean "error source is to the left" or just "frame is at a
            // breakpoint at that position".
            //
            DS_PUSH_TRASH;
            Init_Word(DS_TOP, Canon(SYM__T_T));
        }
    }

    if (NOT_END(item)) {
        DS_PUSH_TRASH;
        Init_Word(DS_TOP, Canon(SYM_ELLIPSIS));
    }

    // !!! This code can be called on an executing frame, such as when an
    // error happens in that frame.  Or it can be called on a pending frame
    // when examining a backtrace...where the function hasn't been called
    // yet.  This needs some way of differentiation, consider it.
    //
    /*
    if (Is_Action_Frame(f) and Is_Action_Frame_Fulfilling(f)) {
        ???
    }
    */

    REBARR *near = Pop_Stack_Values(dsp_start);

    // Simplify overly-deep blocks embedded in the where so they show (...)
    // instead of printing out fully.
    //
    Collapsify_Array(near, SPECIFIED, 3);

    if (ANY_ARRAY_KIND(f->eval_type))
        Init_Any_Array(out, f->eval_type, near);
    else
        Init_Block(out, near);

    return KNOWN(out);
}

//
//  near-of: native [
//
//  "Get execution point summary for a function call (if still on stack)"
//
//      frame [frame!]
//  ]
//
REBNATIVE(near_of)
{
    INCLUDE_PARAMS_OF_NEAR_OF;

    REBFRM *f = CTX_FRAME_MAY_FAIL(VAL_CONTEXT(ARG(frame)));

    Init_Near_For_Frame(D_OUT, f);
    return R_OUT;
}

//
//  label-of: native [
//
//  "Get word label used to invoke a function call (if still on stack)"
//
//      return: [word! blank!]
//      frame [frame!]
//  ]
//
REBNATIVE(label_of)
{
    INCLUDE_PARAMS_OF_LABEL_OF;

    REBFRM *f = CTX_FRAME_MAY_FAIL(VAL_CONTEXT(ARG(frame)));

    if (f->opt_label == NULL)
        return R_BLANK;

    Init_Word(D_OUT, f->opt_label);
    return R_OUT;
}

//
//  action-of: native [
//
//  {Get the action for a frame}
//
//      return: [action!]
//      frame [frame!]
//  ]
//
REBNATIVE(action_of)
{
    INCLUDE_PARAMS_OF_ACTION_OF;

    REBVAL *frame = ARG(frame);

    // The phase contains the paramlist of the actual function (the context is
    // the keylist of the *underlying* function).
    //
    // But to get the function REBVAL, the phase has to be combined with the
    // binding of the FRAME! value.  Otherwise you'd know (for instance) that
    // you had a RETURN, but you wouldn't know where to return *from*.
    //
    Move_Value(D_OUT, ACT_ARCHETYPE(frame->payload.any_context.phase));
    D_OUT->extra.binding = frame->extra.binding;

    return R_OUT;
}

//
//  parent-of: native [
//
//  "Get the parent of a FRAME!"
//
//      return: [blank! frame!]
//      frame [frame!]
//  ]
//
REBNATIVE(parent_of)
{
    INCLUDE_PARAMS_OF_PARENT_OF;

    REBVAL *frame = ARG(frame);

    // We only want to return frames that are actual function frames (though
    // `pending? = true` ones count).
    //
    REBFRM *f = CTX_FRAME_MAY_FAIL(VAL_CONTEXT(frame));
    while ((f = f->prior) != NULL) {
        if (Is_Action_Frame(f)) {
            Init_Any_Context(
                D_OUT, REB_FRAME, Context_For_Frame_May_Reify_Managed(f)
            );
            D_OUT->payload.any_context.phase = f->phase;
            return R_OUT;
        }
    }

    return R_BLANK;
}

//
//  Is_Context_Running_Or_Pending: C
//
REBOOL Is_Context_Running_Or_Pending(REBCTX *frame_ctx)
{
    REBFRM *f = CTX_FRAME_IF_ON_STACK(frame_ctx);
    if (f == NULL)
        return FALSE;

    if (Is_Action_Frame_Fulfilling(f))
        return FALSE;

    return TRUE;
}

//
//  running?: native [
//
//  "Returns TRUE if a FRAME! is on the stack and executing (arguments done)."
//
//      frame [frame!]
//  ]
//
REBNATIVE(running_q)
{
    INCLUDE_PARAMS_OF_RUNNING_Q;

    REBCTX *frame_ctx = VAL_CONTEXT(ARG(frame));

    REBFRM *f = CTX_FRAME_MAY_FAIL(frame_ctx);

    if (Is_Action_Frame_Fulfilling(f))
        return R_FALSE;

    return R_TRUE;
}

//
//  pending?: native [
//
//  "Returns TRUE if a FRAME! is on the stack, but is gathering arguments."
//
//      frame [frame!]
//  ]
//
REBNATIVE(pending_q)
{
    INCLUDE_PARAMS_OF_PENDING_Q;

    REBCTX *frame_ctx = VAL_CONTEXT(ARG(frame));

    REBFRM *f = CTX_FRAME_MAY_FAIL(frame_ctx);

    if (Is_Action_Frame_Fulfilling(f))
        return R_TRUE;

    return R_FALSE;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>SideCar: SideCar::Zeroconf::ACEMonitor Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="DoxygenStyleSheet.css" rel="stylesheet" type="text/css" />

SideCar

Main Page

Related Pages

Modules

Namespaces

Data Structures

Files

Data Structures

Class Hierarchy

Data Fields

SideCar

Zeroconf

ACEMonitor

Public Member Functions |
Static Public Member Functions

SideCar::Zeroconf::ACEMonitor Class Reference

Concrete implementation of the Monitor class that relies on the ACE infrastructure to determine when a Zeroconf object has data available for processing.
 More...

#include </Users/howes/src/sidecar/Zeroconf/ACEMonitor.h>

Inheritance diagram for SideCar::Zeroconf::ACEMonitor:

<map name="SideCar_1_1Zeroconf_1_1ACEMonitor_inherit__map" id="SideCar_1_1Zeroconf_1_1ACEMonitor_inherit__map">
<area shape="rect" id="node3" href="classSideCar_1_1Zeroconf_1_1Monitor.html" title="Abstract base class that monitors the running status of a Zerconf object such as Publisher or Browser..." alt="" coords="172,5,307,54"/>
</map>
[legend]

Public Member Functions

 	ACEMonitor ()

 	Constructor.  More...

 	~ACEMonitor ()

 	Destructor.

 Public Member Functions inherited from SideCar::Zeroconf::Monitor

virtual 	~Monitor ()

 	Destructor.  More...

Static Public Member Functions

static Logger::Log & 	Log ()

 	Obtain the log device for ACEMonitor objects.  More...

Additional Inherited Members

 Protected Member Functions inherited from SideCar::Zeroconf::Monitor

 	Monitor ()

 	Constructor.  More...

Transaction * 	getMonitored () const

 	Obtain the monitored object.  More...

Detailed Description

Concrete implementation of the Monitor class that relies on the ACE infrastructure to determine when a Zeroconf object has data available for processing.

When there is, it invokes Transaction::processConnection() to handle the incoming data.

The handle_input() method is the notification mechanism that ACE uses when there is data available from the file descriptor or socket managed by the ACEMonitor.

Definition at line 21 of file ACEMonitor.h.

Constructor & Destructor Documentation

          ACEMonitor::ACEMonitor
          (
          	)

Constructor.

Sets up the ACE_Event_Handler base class to use the global ACE_Reactor object.

Definition at line 17 of file ACEMonitor.cc.

References Log(), and LOGINFO.

Member Function Documentation

          Logger::Log & ACEMonitor::Log
          (
          	)

static

Obtain the log device for ACEMonitor objects.

Returns

log device

Definition at line 11 of file ACEMonitor.cc.

References Logger::Log::Find().

Referenced by ACEMonitor(), and ~ACEMonitor().

The documentation for this class was generated from the following files:

/Users/howes/src/sidecar/Zeroconf/ACEMonitor.h

/Users/howes/src/sidecar/Zeroconf/ACEMonitor.cc

<address class="footer">
Generated by

 1.8.11
</address>


text:
/* Base styles and content styles */

@import 'variables.css';

html {
    font-family: "Open Sans", sans-serif;
    color: var(--fg);
    background-color: var(--bg);
    text-size-adjust: none;
}

body {
    margin: 0;
    font-size: 1rem;
    overflow-x: hidden;
}

code {
    font-family: "Source Code Pro", Consolas, "Ubuntu Mono", Menlo, "DejaVu Sans Mono", monospace, monospace;
    font-size: 0.875em; /* please adjust the ace font size accordingly in editor.js */
}

.left { float: left; }
.right { float: right; }
.hidden { display: none; }
.play-button.hidden { display: none; }

h2, h3 { margin-top: 2.5em; }
h4, h5 { margin-top: 2em; }

.header + .header h3,
.header + .header h4,
.header + .header h5 {
    margin-top: 1em;
}

a.header:target h1:before,
a.header:target h2:before,
a.header:target h3:before,
a.header:target h4:before {
    display: inline-block;
    content: "»";
    margin-left: -30px;
    width: 30px;
}

.page {
    outline: 0;
    padding: 0 var(--page-padding);
}
.page-wrapper {
    box-sizing: border-box;
}
.js .page-wrapper {
    transition: margin-left 0.3s ease, transform 0.3s ease; /* Animation: slide away */
}

.content {
    overflow-y: auto;
    padding: 0 15px;
    padding-bottom: 50px;
}
.content main {
    margin-left: auto;
    margin-right: auto;
    max-width: var(--content-max-width);
}
.content a { text-decoration: none; }
.content a:hover { text-decoration: underline; }
.content img { max-width: 100%; }
.content .header:link,
.content .header:visited {
    color: var(--fg);
}
.content .header:link,
.content .header:visited:hover {
    text-decoration: none;
}

table {
    margin: 0 auto;
    border-collapse: collapse;
}
table td {
    padding: 3px 20px;
    border: 1px var(--table-border-color) solid;
}
table thead {
    background: var(--table-header-bg);
}
table thead td {
    font-weight: 700;
    border: none;
}
table thead tr {
    border: 1px var(--table-header-bg) solid;
}
/* Alternate background colors for rows */
table tbody tr:nth-child(2n) {
    background: var(--table-alternate-bg);
}

blockquote {
    margin: 20px 0;
    padding: 0 20px;
    color: var(--fg);
    background-color: var(--quote-bg);
    border-top: .1em solid var(--quote-border);
    border-bottom: .1em solid var(--quote-border);
}

:not(.footnote-definition) + .footnote-definition,
.footnote-definition + :not(.footnote-definition) {
    margin-top: 2em;
}
.footnote-definition {
    font-size: 0.9em;
    margin: 0.5em 0;
}
.footnote-definition p {
    display: inline;
}

.tooltiptext {
    position: absolute;
    visibility: hidden;
    color: #fff;
    background-color: #333;
    transform: translateX(-50%); /* Center by moving tooltip 50% of its width left */
    left: -8px; /* Half of the width of the icon */
    top: -35px;
    font-size: 0.8em;
    text-align: center;
    border-radius: 6px;
    padding: 5px 8px;
    margin: 5px;
    z-index: 1000;
}
.tooltipped .tooltiptext {
    visibility: visible;
}


text:
#import "EC2EbsBlockDevice.h"

/**
 * Block Device Mapping
 */

@interface EC2BlockDeviceMapping:NSObject

{
    NSString          *virtualName;
    NSString          *deviceName;
    EC2EbsBlockDevice *ebs;
    NSString          *noDevice;
}

/**
 * Default constructor for a new  object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * Specifies the virtual device name.
 */
@property (nonatomic, retain) NSString *virtualName;

/**
 * Specifies the device name (e.g., <code>/dev/sdh</code>).
 */
@property (nonatomic, retain) NSString *deviceName;

/**
 * Specifies parameters used to automatically setup Amazon EBS volumes
 * when the instance is launched.
 */
@property (nonatomic, retain) EC2EbsBlockDevice *ebs;

/**
 * Specifies the device name to suppress during instance launch.
 */
@property (nonatomic, retain) NSString *noDevice;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
package docker

import (
	"encoding/json"
	"hyper/lib/glog"
)

type TypeConfig struct {
	AttachStderr    bool                `json:"AttachStderr"`
	AttachStdin     bool                `json:"AttachStdin"`
	AttachStdout    bool                `json:"AttachStdout"`
	Cmd             []string            `json:"Cmd"`
	CpuShares       int64               `json:"CpuShares"`
	Cpuset          string              `json:"Cpuset"`
	Domainname      string              `json:"Domainname"`
	Entrypoint      []string            `json:"Entrypoint"`
	Env             []string            `json:"Env"`
	ExposedPorts    map[string]struct{} `json:"ExposedPorts"`
	Hostname        string              `json:"Hostname"`
	Image           string              `json:"Image"`
	MacAddress      string              `json:"MacAddress"`
	Memory          int64               `json:"Memory"`
	MemorySwap      int64               `json:"MemorySwap"`
	NetworkDisabled bool                `json:"NetworkDisabled"`
	OnBuild         []string            `json:"OnBuild"`
	OpenStdin       bool                `json:"OpenStdin"`
	PortSpecs       []string            `json:"PortSpecs"`
	StdinOnce       bool                `json:"StdinOnce"`
	Tty             bool                `json:"Tty"`
	User            string              `json:"User"`
	Volumes         map[string]struct{} `json:"Volumes"`
	WorkingDir      string              `json:"WorkingDir"`
}

type ConfigJSON struct {
	AppArmorProfile string     `json:"AppArmorProfile"`
	Args            []string   `json:"Args"`
	Config          TypeConfig `json:"Config"`
	Created         string     `json:"Created"`
	Driver          string     `json:"Driver"`
	ExecDriver      string     `json:"ExecDriver"`
	ExecIds         string     `json:"ExecIDs"`
	HostConfig      struct{}   `json:"HostConfig"`
	HostnamePath    string     `json:"HostnamePath"`
	HostsPath       string     `json:"HostsPath"`
	Id              string     `json:"Id"`
	Image           string     `json:"Image"`
	MountLabel      string     `json:"MountLabel"`
	Name            string     `json:"Name"`
	NetworkSettings struct{}   `json:"NetworkSettings"`
	Path            string     `json:"Path"`
	ProcessLabel    string     `json:"ProcessLabel"`
	ResolvConfPath  string     `json:"ResolvConfPath"`
	RestartCount    int        `json:"RestartCount"`
	State           struct{}   `json:"State"`
	Volumes         struct{}   `json:"Volumes"`
	VolumesRW       struct{}   `json:"VolumesRW"`
}

func (cli *DockerCli) GetContainerInfo(args ...string) (*ConfigJSON, error) {
	containerId := args[0]
	glog.V(1).Infof("ready to get the container(%s) info\n", containerId)
	body, _, err := readBody(cli.Call("GET", "/containers/"+containerId+"/json", nil, nil))
	if err != nil {
		return nil, err
	}
	var jsonResponse ConfigJSON
	if err := json.Unmarshal(body, &jsonResponse); err != nil {
		return nil, err
	}

	return &jsonResponse, nil
}


text:
@font-face {
    font-family: 'fundly-icons';
    src:    url('fonts/fundly-icons.eot?ci2d11');
    src:    url('fonts/fundly-icons.eot?ci2d11#iefix') format('embedded-opentype'),
        url('fonts/fundly-icons.ttf?ci2d11') format('truetype'),
        url('fonts/fundly-icons.woff?ci2d11') format('woff'),
        url('fonts/fundly-icons.svg?ci2d11#fundly-icons') format('svg');
	font-weight: normal;
	font-style: normal;
}

[class^="icon-"], [class*=" icon-"] {
    /* use !important to prevent issues with browser extensions that change fonts */
	font-family: 'fundly-icons' !important;
	speak: none;
	font-style: normal;
	font-weight: normal;
	font-variant: normal;
	text-transform: none;
	line-height: 1;

	/* Better Font Rendering =========== */
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.icon-lgbt:before {
    content: "\f0c0";
}
.icon-animal:before {
	content: "\e600";
}
.icon-arts:before {
	content: "\e601";
}
.icon-children:before {
	content: "\e602";
}
.icon-church:before {
	content: "\e603";
}
.icon-community:before {
	content: "\e604";
}
.icon-education:before {
	content: "\e605";
}
.icon-greek:before {
	content: "\e606";
}
.icon-health:before {
	content: "\e607";
}
.icon-location:before {
	content: "\e608";
}
.icon-logo-heart:before {
	content: "\e609";
}
.icon-logo-knockout:before {
	content: "\e60a";
}
.icon-memorial:before {
	content: "\e60b";
}
.icon-military:before {
	content: "\e60c";
}
.icon-non-profit:before {
	content: "\e60d";
}
.icon-other:before {
	content: "\e60e";
}
.icon-political:before {
	content: "\e60f";
}
.icon-run-walk-ride:before {
	content: "\e610";
}
.icon-sports:before {
	content: "\e611";
}
.icon-trips:before {
	content: "\e612";
}
.icon-whats-app:before {
	content: "\e613";
}


text:
package org.helyx.riatest.sql.util;

import static org.helyx.riatest.sql.util.LogUtil.printException;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class DbUtil {

	private static final String COLUMN_SEPARATOR = "|";
	private static final String ROW_SEPARATOR = ",";

	private DbUtil() {
		super();
	}

	public static String convertResultSetToString(ResultSet rs) throws SQLException {
		StringBuffer sb = new StringBuffer();
		boolean hasNext = rs.next();
		while (hasNext) {
			sb.append(convertCurrentRowToString(rs));
			hasNext = rs.next();
			if (hasNext) {
				sb.append(ROW_SEPARATOR);
			}
		}

		return sb.toString();
	}

	private static String convertCurrentRowToString(ResultSet rs) throws SQLException {
		StringBuffer sb = new StringBuffer();
	    ResultSetMetaData rsmd = rs.getMetaData();
	    int numColumns = rsmd.getColumnCount();
	    // Get the column names; column indices start from 1
	    for (int i = 1 ; i <= numColumns ; i++) {
	        String columnName = rsmd.getColumnName(i);
	        String columnValue = rs.getString(columnName);
			sb.append(columnValue);
			if (i < numColumns) {
				sb.append(COLUMN_SEPARATOR);
			}
		}

		return sb.toString();
	}

	public static void deregisterDriver(Driver driverClass) {
		try {
			if (driverClass != null) {
				DriverManager.deregisterDriver(driverClass);
			}
		}
		catch(Exception e) {
			printException(e);
		}
	}

	public static void close(Connection connection) {
		if (connection != null) {
			try {
				connection.close();
			}
			catch(Exception e) {
				printException(e);
			}
		}
	}

	public static void close(ResultSet resultSet) {
		if (resultSet != null) {
			try {
				resultSet.close();
			}
			catch(Exception e) {
				printException(e);
			}
		}
	}

	public static void close(Statement statement) {
		if (statement != null) {
			try {
				statement.close();
			}
			catch(Exception e) {
				printException(e);
			}
		}
	}

}


text:
<?php
declare(strict_types=1);
/**
 * This file is part of beotie/user_bundle
 *
 * As each files provides by the CSCFA, this file is licensed
 * under the MIT license.
 *
 * PHP version 7.1
 *
 * @category Model
 * @package  Beotie_Core_Bundle
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
namespace Beotie\CoreBundle\Model\Mediator;

/**
 * External data mediator interface
 *
 * This interface is used to define the methods of the external data mediator, used to describe a data
 * within another instance
 *
 * @category Model
 * @package  Beotie_Core_Bundle
 * @author   matthieu vallance <matthieu.vallance@cscfa.fr>
 * @license  MIT <https://opensource.org/licenses/MIT>
 * @link     http://cscfa.fr
 */
interface ExternalDataMediatorInterface extends DataMediatorInterface
{
    /**
     * Support
     *
     * This method return the support state of the ExternalDataMediator, according with the given data
     *
     * @param mixed $data The data which the mediator should support
     *
     * @return bool
     */
    public function support($data) : bool;
}


text:
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';

export default class ExpireAlert extends Component {
  constructor(props){
    super(props);
    this.state = {visible: false};
  }

  componentWillReceiveProps(nextProps) {
    // reset the timer if children are changed
    if (nextProps.set) {
      this.setTimer();
      this.setState({visible: true});
    }
  }
  componentDidMount() {
      this.setTimer();
  }
  setTimer() {
    // clear any existing timer
    this._timer != null ? clearTimeout(this._timer) : null;

    // hide after `delay` milliseconds
    this._timer = setTimeout(function(){
      this.setState({visible: false});
      this.props.reset();
      this._timer = null;
    }.bind(this), this.props.delay);
  }
  componentWillUnmount() {
    clearTimeout(this._timer);
  }
  render() {
    let alertStyling = this.props.status +' callout';
    return this.state.visible
           ?
{this.props.children}

           : ;
  }
};


text:
class ImageGroup < ActiveRecord::Base
  #attr_accessible :name, :product_id, :images_attributes

  validates :name,  :presence => true
  validates :product_id,  :presence => true

  belongs_to :product
  has_many :variants
  has_many :images, -> {order(:position)},
                    :as         => :imageable,
                    :dependent  => :destroy
  after_save :expire_cache

  accepts_nested_attributes_for :images, :reject_if => proc { |t| (t['photo'].nil? && t['photo_from_link'].blank?) }, :allow_destroy => true

  def image_urls(image_size = :small)
    Rails.cache.fetch("ImageGroup-image_urls-#{id}-#{image_size}", :expires_in => 3.hours) do
      images.empty? ? product.image_urls(image_size) : images.map{|i| i.photo.url(image_size)}
    end
  end

  private
    def expire_cache
      PAPERCLIP_STORAGE_OPTS[:styles].each_pair do |image_size, value|
        Rails.cache.delete("ImageGroup-image_urls-#{id}-#{image_size}")
      end
    end
end


text:
"Jason Rogers" <info@narfindustries.com>

### DARPA performer group
Narf Industries (NRFIN)

## Description

Too lazy to compute your own matrices? Let our workers do it for you. They'll process your messages in their super-speed pipeline, while you sit back and relax.

### Feature List

The first message you send provides the configuration of the pipeline. From there each subsequent message uses the same pipele, for super-speed operation. Since the pipeline only moves as fast as you submit messages, always make sure to clear the pipeline when you are done.

Message structure is the following
{Configuration, Array length, Array width, X Plotter, Y Plotter}

"Configuration" will be used to configure the pipeline
"Array length" and "Array width" configure the dimensions of the matrix.
"X Plotter" and "Y Plotter" drive the computation of the matrix.

## Vulnerability
This service has three vulnerabilties.

The first vulnerability will trigger if negative dimensions are submitted in a pipeline configuration where the modulus of the X plotter and Y plotter are configured before the dimensions are set to the absolute value. The modulus computation will result in negative plotter values. The first array assigment will use the negative values leading to an out-of-bounds write.

The second vulnerability will trigger if X Plotter or Y Plotter values are sumbitted. When the matrix is computed these values will be doubled as part of the modulus computation, resulting in an integer overlfow that causes a negative X Plotter or Y Plotter value. Similarily to the first vulnerability this will result in the same out-of-bounds write.

The third vulnerability will trigger if any of the message values for X_FIELD or Y_FIELD are equal to -32768. When the absoluteValueMap function is run, -32768 will remain -32768 due to the compiler using the 2's complete notation. When computeResult attempts to use assign '1' to the array using a negative offset it will result in an out-of-bounds write.

### Generic class of vulnerability
Out-of-bounds Write
Integer Overflow
Improper Validation of Array Index

### CWE classification
CWE-787: Out-of-bounds Write
CWE-190: Integer Overflow
CWE-129: Improper Validation of Array Index

## Challenge

1) Understand how the "Configuration" value provided by the client influences the permutation of message processing functions and the resulting output, in order to produce an exploitable configuration of the pipeline.

2) Determine how the modulus calculation is impacted by negative inputs. Both vulnerabilities require achieving a negative result from the modulus calculation.


text:
FROM python:2.7.9

MAINTAINER John Shen

RUN apt-get update && \
 apt-get install -y liblapack-dev \
 libblas-dev \
 gfortran \
 python-dev && \
 pip install tornado numpy requests

RUN pip install scipy scikit-learn && \
 git clone https://github.com/raphael-group/magi-stat-server.git src

EXPOSE 8888

CMD ["python", "/src/statserver.py", "--port", "8888"]


text:
// +build !ignore_autogenerated

// Code generated by conversion-gen. DO NOT EDIT.

package v1beta1

import (
	unsafe "unsafe"

	v1 "k8s.io/api/core/v1"
	v1beta1 "k8s.io/api/storage/v1beta1"
	conversion "k8s.io/apimachinery/pkg/conversion"
	runtime "k8s.io/apimachinery/pkg/runtime"
	core "k8s.io/kubernetes/pkg/apis/core"
	storage "k8s.io/kubernetes/pkg/apis/storage"
)

func init() {
	localSchemeBuilder.Register(RegisterConversions)
}

// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(scheme *runtime.Scheme) error {
	return scheme.AddGeneratedConversionFuncs(
		Convert_v1beta1_StorageClass_To_storage_StorageClass,
		Convert_storage_StorageClass_To_v1beta1_StorageClass,
		Convert_v1beta1_StorageClassList_To_storage_StorageClassList,
		Convert_storage_StorageClassList_To_v1beta1_StorageClassList,
		Convert_v1beta1_VolumeAttachment_To_storage_VolumeAttachment,
		Convert_storage_VolumeAttachment_To_v1beta1_VolumeAttachment,
		Convert_v1beta1_VolumeAttachmentList_To_storage_VolumeAttachmentList,
		Convert_storage_VolumeAttachmentList_To_v1beta1_VolumeAttachmentList,
		Convert_v1beta1_VolumeAttachmentSource_To_storage_VolumeAttachmentSource,
		Convert_storage_VolumeAttachmentSource_To_v1beta1_VolumeAttachmentSource,
		Convert_v1beta1_VolumeAttachmentSpec_To_storage_VolumeAttachmentSpec,
		Convert_storage_VolumeAttachmentSpec_To_v1beta1_VolumeAttachmentSpec,
		Convert_v1beta1_VolumeAttachmentStatus_To_storage_VolumeAttachmentStatus,
		Convert_storage_VolumeAttachmentStatus_To_v1beta1_VolumeAttachmentStatus,
		Convert_v1beta1_VolumeError_To_storage_VolumeError,
		Convert_storage_VolumeError_To_v1beta1_VolumeError,
	)
}

func autoConvert_v1beta1_StorageClass_To_storage_StorageClass(in *v1beta1.StorageClass, out *storage.StorageClass, s conversion.Scope) error {
	out.ObjectMeta = in.ObjectMeta
	out.Provisioner = in.Provisioner
	out.Parameters = *(*map[string]string)(unsafe.Pointer(&in.Parameters))
	out.ReclaimPolicy = (*core.PersistentVolumeReclaimPolicy)(unsafe.Pointer(in.ReclaimPolicy))
	out.MountOptions = *(*[]string)(unsafe.Pointer(&in.MountOptions))
	out.AllowVolumeExpansion = (*bool)(unsafe.Pointer(in.AllowVolumeExpansion))
	out.VolumeBindingMode = (*storage.VolumeBindingMode)(unsafe.Pointer(in.VolumeBindingMode))
	return nil
}

// Convert_v1beta1_StorageClass_To_storage_StorageClass is an autogenerated conversion function.
func Convert_v1beta1_StorageClass_To_storage_StorageClass(in *v1beta1.StorageClass, out *storage.StorageClass, s conversion.Scope) error {
	return autoConvert_v1beta1_StorageClass_To_storage_StorageClass(in, out, s)
}

func autoConvert_storage_StorageClass_To_v1beta1_StorageClass(in *storage.StorageClass, out *v1beta1.StorageClass, s conversion.Scope) error {
	out.ObjectMeta = in.ObjectMeta
	out.Provisioner = in.Provisioner
	out.Parameters = *(*map[string]string)(unsafe.Pointer(&in.Parameters))
	out.ReclaimPolicy = (*v1.PersistentVolumeReclaimPolicy)(unsafe.Pointer(in.ReclaimPolicy))
	out.MountOptions = *(*[]string)(unsafe.Pointer(&in.MountOptions))
	out.AllowVolumeExpansion = (*bool)(unsafe.Pointer(in.AllowVolumeExpansion))
	out.VolumeBindingMode = (*v1beta1.VolumeBindingMode)(unsafe.Pointer(in.VolumeBindingMode))
	return nil
}

// Convert_storage_StorageClass_To_v1beta1_StorageClass is an autogenerated conversion function.
func Convert_storage_StorageClass_To_v1beta1_StorageClass(in *storage.StorageClass, out *v1beta1.StorageClass, s conversion.Scope) error {
	return autoConvert_storage_StorageClass_To_v1beta1_StorageClass(in, out, s)
}

func autoConvert_v1beta1_StorageClassList_To_storage_StorageClassList(in *v1beta1.StorageClassList, out *storage.StorageClassList, s conversion.Scope) error {
	out.ListMeta = in.ListMeta
	out.Items = *(*[]storage.StorageClass)(unsafe.Pointer(&in.Items))
	return nil
}

// Convert_v1beta1_StorageClassList_To_storage_StorageClassList is an autogenerated conversion function.
func Convert_v1beta1_StorageClassList_To_storage_StorageClassList(in *v1beta1.StorageClassList, out *storage.StorageClassList, s conversion.Scope) error {
	return autoConvert_v1beta1_StorageClassList_To_storage_StorageClassList(in, out, s)
}

func autoConvert_storage_StorageClassList_To_v1beta1_StorageClassList(in *storage.StorageClassList, out *v1beta1.StorageClassList, s conversion.Scope) error {
	out.ListMeta = in.ListMeta
	out.Items = *(*[]v1beta1.StorageClass)(unsafe.Pointer(&in.Items))
	return nil
}

// Convert_storage_StorageClassList_To_v1beta1_StorageClassList is an autogenerated conversion function.
func Convert_storage_StorageClassList_To_v1beta1_StorageClassList(in *storage.StorageClassList, out *v1beta1.StorageClassList, s conversion.Scope) error {
	return autoConvert_storage_StorageClassList_To_v1beta1_StorageClassList(in, out, s)
}

func autoConvert_v1beta1_VolumeAttachment_To_storage_VolumeAttachment(in *v1beta1.VolumeAttachment, out *storage.VolumeAttachment, s conversion.Scope) error {
	out.ObjectMeta = in.ObjectMeta
	if err := Convert_v1beta1_VolumeAttachmentSpec_To_storage_VolumeAttachmentSpec(&in.Spec, &out.Spec, s); err != nil {
		return err
	}
	if err := Convert_v1beta1_VolumeAttachmentStatus_To_storage_VolumeAttachmentStatus(&in.Status, &out.Status, s); err != nil {
		return err
	}
	return nil
}

// Convert_v1beta1_VolumeAttachment_To_storage_VolumeAttachment is an autogenerated conversion function.
func Convert_v1beta1_VolumeAttachment_To_storage_VolumeAttachment(in *v1beta1.VolumeAttachment, out *storage.VolumeAttachment, s conversion.Scope) error {
	return autoConvert_v1beta1_VolumeAttachment_To_storage_VolumeAttachment(in, out, s)
}

func autoConvert_storage_VolumeAttachment_To_v1beta1_VolumeAttachment(in *storage.VolumeAttachment, out *v1beta1.VolumeAttachment, s conversion.Scope) error {
	out.ObjectMeta = in.ObjectMeta
	if err := Convert_storage_VolumeAttachmentSpec_To_v1beta1_VolumeAttachmentSpec(&in.Spec, &out.Spec, s); err != nil {
		return err
	}
	if err := Convert_storage_VolumeAttachmentStatus_To_v1beta1_VolumeAttachmentStatus(&in.Status, &out.Status, s); err != nil {
		return err
	}
	return nil
}

// Convert_storage_VolumeAttachment_To_v1beta1_VolumeAttachment is an autogenerated conversion function.
func Convert_storage_VolumeAttachment_To_v1beta1_VolumeAttachment(in *storage.VolumeAttachment, out *v1beta1.VolumeAttachment, s conversion.Scope) error {
	return autoConvert_storage_VolumeAttachment_To_v1beta1_VolumeAttachment(in, out, s)
}

func autoConvert_v1beta1_VolumeAttachmentList_To_storage_VolumeAttachmentList(in *v1beta1.VolumeAttachmentList, out *storage.VolumeAttachmentList, s conversion.Scope) error {
	out.ListMeta = in.ListMeta
	out.Items = *(*[]storage.VolumeAttachment)(unsafe.Pointer(&in.Items))
	return nil
}

// Convert_v1beta1_VolumeAttachmentList_To_storage_VolumeAttachmentList is an autogenerated conversion function.
func Convert_v1beta1_VolumeAttachmentList_To_storage_VolumeAttachmentList(in *v1beta1.VolumeAttachmentList, out *storage.VolumeAttachmentList, s conversion.Scope) error {
	return autoConvert_v1beta1_VolumeAttachmentList_To_storage_VolumeAttachmentList(in, out, s)
}

func autoConvert_storage_VolumeAttachmentList_To_v1beta1_VolumeAttachmentList(in *storage.VolumeAttachmentList, out *v1beta1.VolumeAttachmentList, s conversion.Scope) error {
	out.ListMeta = in.ListMeta
	out.Items = *(*[]v1beta1.VolumeAttachment)(unsafe.Pointer(&in.Items))
	return nil
}

// Convert_storage_VolumeAttachmentList_To_v1beta1_VolumeAttachmentList is an autogenerated conversion function.
func Convert_storage_VolumeAttachmentList_To_v1beta1_VolumeAttachmentList(in *storage.VolumeAttachmentList, out *v1beta1.VolumeAttachmentList, s conversion.Scope) error {
	return autoConvert_storage_VolumeAttachmentList_To_v1beta1_VolumeAttachmentList(in, out, s)
}

func autoConvert_v1beta1_VolumeAttachmentSource_To_storage_VolumeAttachmentSource(in *v1beta1.VolumeAttachmentSource, out *storage.VolumeAttachmentSource, s conversion.Scope) error {
	out.PersistentVolumeName = (*string)(unsafe.Pointer(in.PersistentVolumeName))
	return nil
}

// Convert_v1beta1_VolumeAttachmentSource_To_storage_VolumeAttachmentSource is an autogenerated conversion function.
func Convert_v1beta1_VolumeAttachmentSource_To_storage_VolumeAttachmentSource(in *v1beta1.VolumeAttachmentSource, out *storage.VolumeAttachmentSource, s conversion.Scope) error {
	return autoConvert_v1beta1_VolumeAttachmentSource_To_storage_VolumeAttachmentSource(in, out, s)
}

func autoConvert_storage_VolumeAttachmentSource_To_v1beta1_VolumeAttachmentSource(in *storage.VolumeAttachmentSource, out *v1beta1.VolumeAttachmentSource, s conversion.Scope) error {
	out.PersistentVolumeName = (*string)(unsafe.Pointer(in.PersistentVolumeName))
	return nil
}

// Convert_storage_VolumeAttachmentSource_To_v1beta1_VolumeAttachmentSource is an autogenerated conversion function.
func Convert_storage_VolumeAttachmentSource_To_v1beta1_VolumeAttachmentSource(in *storage.VolumeAttachmentSource, out *v1beta1.VolumeAttachmentSource, s conversion.Scope) error {
	return autoConvert_storage_VolumeAttachmentSource_To_v1beta1_VolumeAttachmentSource(in, out, s)
}

func autoConvert_v1beta1_VolumeAttachmentSpec_To_storage_VolumeAttachmentSpec(in *v1beta1.VolumeAttachmentSpec, out *storage.VolumeAttachmentSpec, s conversion.Scope) error {
	out.Attacher = in.Attacher
	if err := Convert_v1beta1_VolumeAttachmentSource_To_storage_VolumeAttachmentSource(&in.Source, &out.Source, s); err != nil {
		return err
	}
	out.NodeName = in.NodeName
	return nil
}

// Convert_v1beta1_VolumeAttachmentSpec_To_storage_VolumeAttachmentSpec is an autogenerated conversion function.
func Convert_v1beta1_VolumeAttachmentSpec_To_storage_VolumeAttachmentSpec(in *v1beta1.VolumeAttachmentSpec, out *storage.VolumeAttachmentSpec, s conversion.Scope) error {
	return autoConvert_v1beta1_VolumeAttachmentSpec_To_storage_VolumeAttachmentSpec(in, out, s)
}

func autoConvert_storage_VolumeAttachmentSpec_To_v1beta1_VolumeAttachmentSpec(in *storage.VolumeAttachmentSpec, out *v1beta1.VolumeAttachmentSpec, s conversion.Scope) error {
	out.Attacher = in.Attacher
	if err := Convert_storage_VolumeAttachmentSource_To_v1beta1_VolumeAttachmentSource(&in.Source, &out.Source, s); err != nil {
		return err
	}
	out.NodeName = in.NodeName
	return nil
}

// Convert_storage_VolumeAttachmentSpec_To_v1beta1_VolumeAttachmentSpec is an autogenerated conversion function.
func Convert_storage_VolumeAttachmentSpec_To_v1beta1_VolumeAttachmentSpec(in *storage.VolumeAttachmentSpec, out *v1beta1.VolumeAttachmentSpec, s conversion.Scope) error {
	return autoConvert_storage_VolumeAttachmentSpec_To_v1beta1_VolumeAttachmentSpec(in, out, s)
}

func autoConvert_v1beta1_VolumeAttachmentStatus_To_storage_VolumeAttachmentStatus(in *v1beta1.VolumeAttachmentStatus, out *storage.VolumeAttachmentStatus, s conversion.Scope) error {
	out.Attached = in.Attached
	out.AttachmentMetadata = *(*map[string]string)(unsafe.Pointer(&in.AttachmentMetadata))
	out.AttachError = (*storage.VolumeError)(unsafe.Pointer(in.AttachError))
	out.DetachError = (*storage.VolumeError)(unsafe.Pointer(in.DetachError))
	return nil
}

// Convert_v1beta1_VolumeAttachmentStatus_To_storage_VolumeAttachmentStatus is an autogenerated conversion function.
func Convert_v1beta1_VolumeAttachmentStatus_To_storage_VolumeAttachmentStatus(in *v1beta1.VolumeAttachmentStatus, out *storage.VolumeAttachmentStatus, s conversion.Scope) error {
	return autoConvert_v1beta1_VolumeAttachmentStatus_To_storage_VolumeAttachmentStatus(in, out, s)
}

func autoConvert_storage_VolumeAttachmentStatus_To_v1beta1_VolumeAttachmentStatus(in *storage.VolumeAttachmentStatus, out *v1beta1.VolumeAttachmentStatus, s conversion.Scope) error {
	out.Attached = in.Attached
	out.AttachmentMetadata = *(*map[string]string)(unsafe.Pointer(&in.AttachmentMetadata))
	out.AttachError = (*v1beta1.VolumeError)(unsafe.Pointer(in.AttachError))
	out.DetachError = (*v1beta1.VolumeError)(unsafe.Pointer(in.DetachError))
	return nil
}

// Convert_storage_VolumeAttachmentStatus_To_v1beta1_VolumeAttachmentStatus is an autogenerated conversion function.
func Convert_storage_VolumeAttachmentStatus_To_v1beta1_VolumeAttachmentStatus(in *storage.VolumeAttachmentStatus, out *v1beta1.VolumeAttachmentStatus, s conversion.Scope) error {
	return autoConvert_storage_VolumeAttachmentStatus_To_v1beta1_VolumeAttachmentStatus(in, out, s)
}

func autoConvert_v1beta1_VolumeError_To_storage_VolumeError(in *v1beta1.VolumeError, out *storage.VolumeError, s conversion.Scope) error {
	out.Time = in.Time
	out.Message = in.Message
	return nil
}

// Convert_v1beta1_VolumeError_To_storage_VolumeError is an autogenerated conversion function.
func Convert_v1beta1_VolumeError_To_storage_VolumeError(in *v1beta1.VolumeError, out *storage.VolumeError, s conversion.Scope) error {
	return autoConvert_v1beta1_VolumeError_To_storage_VolumeError(in, out, s)
}

func autoConvert_storage_VolumeError_To_v1beta1_VolumeError(in *storage.VolumeError, out *v1beta1.VolumeError, s conversion.Scope) error {
	out.Time = in.Time
	out.Message = in.Message
	return nil
}

// Convert_storage_VolumeError_To_v1beta1_VolumeError is an autogenerated conversion function.
func Convert_storage_VolumeError_To_v1beta1_VolumeError(in *storage.VolumeError, out *v1beta1.VolumeError, s conversion.Scope) error {
	return autoConvert_storage_VolumeError_To_v1beta1_VolumeError(in, out, s)
}


text:
usage="This script is intended to be used by other scripts in this directory."
usage=$"$usage\n Please refer to start-s2graph.sh and stop-s2graph.sh"
usage=$"$usage\n Usage: s2graph-daemon.sh (start|stop|restart|run|status)"
usage="$usage (s2rest_play|s2rest_netty|...) <args...>"

bin=$(cd "$(dirname "${BASH_SOURCE-$0}")">/dev/null; pwd)

# load environment variables
. $bin/s2graph-env.sh
. $bin/s2graph-common.sh

# show usage when executed without enough arguments
if [ $# -le 1 ]; then
  panic "$usage"
fi

# to enable the JVM application to use relative paths as well
cd "$S2GRAPH_HOME"

# arguments
action=$1
shift
service=$1
shift
this="$bin/$(basename ${BASH_SOURCE-$0})"
args="$@"

# locate java
if [ -z $JAVA_HOME ]; then
  JAVA=$(which java)
else
  JAVA=$JAVA_HOME/bin/java
fi

# require JVM 8
JAVA_VERSION=$($JAVA -version 2>&1 | sed 's/.*version "\(.*\)\.\(.*\)\..*"/\1\2/; 1q')
if [ $JAVA_VERSION -lt 18 ]; then
  panic "Java 8 or later is required"
fi

# construct the classpath
classpath="$S2GRAPH_CONF_DIR:$S2GRAPH_LIB_DIR/*"

# determine the main class
case $service in
s2rest_play)
  main="play.core.server.NettyServer"
  ;;
hbase)
  main="org.apache.hadoop.hbase.master.HMaster"
  ;;
*)
  panic "Unknown service: $service"
esac

# file that contains the service's pid
pidfile="$S2GRAPH_PID_DIR/$service.pid"

# file that contains the console output of the JVM
# this file should only contain abnormal logs, while
# the normal logs should go to the log files as configured separately,
# ideally with daily log-rotation.
log="$S2GRAPH_LOG_DIR/$service.log"

start() {
  if [ -f "$pidfile" ]; then
    if kill -0 $(cat "$pidfile") > /dev/null 2>&1; then
      panic "$service is already running as process $(cat "$pidfile")"
    fi
    rm -r "$pidfile"
  fi
  echo "Starting $service..." 1>&2

  "$this" run "$service" $args < /dev/null >> "$log" 2>&1 &
  disown -h -r

  # sleep enough, to check if there was any error during startup
  sleep 3
  if [ -f "$pidfile" ]; then
    echo "Service $service is running as process $(cat "$pidfile")"
  else
    echo "Service $service might have failed to start; see $log"
  fi
}

stop() {
  if [ -f "$pidfile" ]; then
    if kill -0 $(cat "$pidfile") > /dev/null 2>&1; then
      echo "Stopping $service" 1>&2
      terminate $(cat "$pidfile")
    else
      echo "Process $(cat "$pidfile") is not running" 1>&2
    fi
  else
    echo "PID file does not exist at $pidfile" 1>&2
  fi
  rm -f "$pidfile"
}

cleanup() {
  if [ -f "$pidfile" ]; then
    if kill -0 $(cat "$pidfile") > /dev/null 2>&1; then
      terminate $(cat "$pidfile")
    fi
    rm -f "$pidfile"
  fi
}

status() {
  if [ -f "$pidfile" ]; then
    if kill -0 $(cat "$pidfile") > /dev/null 2>&1; then
      echo "Service $service is running as process $(cat "$pidfile")" 1>&2
    else
      echo "PID file for service $service exists at $pidfile, " \
       "but process $(cat "$pidfile") is not running" 1>&2
    fi
  else
    echo "Service $service is not running" 1>&2
  fi
}

run() {
  trap cleanup SIGHUP SIGINT SIGTERM EXIT
  echo "$JAVA" -cp "$classpath" -Ds2graph.home="$S2GRAPH_HOME" $S2GRAPH_OPTS "$main" $args 2>&1 &
  "$JAVA" -cp "$classpath" -Ds2graph.home="$S2GRAPH_HOME" $S2GRAPH_OPTS "$main" $args 2>&1 &
  pid=$!
  echo "$pid" > "$pidfile"
  wait "$pid"
}

case $action in
start)
  start
  ;;
stop)
  stop
  ;;
restart)
  stop
  start
  ;;
status)
  status
  ;;
run)
  run
  ;;
*)
  panic "$usage"
esac


text:
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using ZMQ;

namespace MessageBus.Binding.ZeroMQ
{
    public abstract class ZMQReceivingChannelBase : ZMQChannelBase
    {
        private delegate bool TryReceiveHandler(TimeSpan timeout, out Message message);

        private readonly Func<TimeSpan, Message> _onReceiveHandler;
        private readonly TryReceiveHandler _onTryReceiveHandler;
        private readonly Func<TimeSpan, bool> _onWaitForMessageHandler;

        private readonly Context _context;

        protected ZMQReceivingChannelBase(ChannelManagerBase channelManager, BindingContext bindingContext, Context context, Socket socket, SocketMode socketMode)
            : base(channelManager, bindingContext, socket, socketMode)
        {
            _onReceiveHandler = Receive;
            _onTryReceiveHandler = TryReceive;
            _onWaitForMessageHandler = WaitForMessage;
            _context = context;
        }

        public abstract EndpointAddress LocalAddress { get; }

        #region Receive

        public Message Receive()
        {
            return Receive(TimeSpan.MaxValue);
        }

        public Message Receive(TimeSpan timeout)
        {
            byte[] bytes;
            int length;

            try
            {
#if VERBOSE
                DebugHelper.Start();
#endif
                byte[] lengthBytes = _socket.Recv();

                length = BitConverter.ToInt32(lengthBytes, 0);

                if (_bufferManager == null)
                {
                    bytes = _socket.Recv();
                }
                else
                {
                    bytes = _bufferManager.TakeBuffer(length);

                    _socket.Recv(bytes, out length);
                }
#if VERBOSE
                DebugHelper.Stop(" #### Message.Receive {{\n\tBytes={1}, \n\tTime={0}ms}}.", length);
#endif
            }
            catch
            {
                return null;
            }

            if (bytes == null) return null;

            Message message;
#if VERBOSE
            DebugHelper.Start();
#endif
            if (_bufferManager == null)
            {
                message = ConstructMessage(bytes);
            }
            else
            {
                message = ConstructMessage(new ArraySegment<byte>(bytes, 0, length), _bufferManager);
            }

            message.Headers.To = LocalAddress.Uri;

#if VERBOSE
            DebugHelper.Stop(
                " #### Message.DeSerialize {{\n\tAction={3}, \n\tBytes={2}, \n\tNow={1:HH-mm-ss:fff}ms, \n\tTime={0}ms}}.",
                DateTime.Now,
                length,
                message.Headers.Action);
#endif

            return message;
        }

        public bool TryReceive(TimeSpan timeout, out Message message)
        {
            message = Receive(timeout);

            return message != null;
        }

        public bool WaitForMessage(TimeSpan timeout)
        {
            return true;
        }

        #endregion

        protected override void OnClose(TimeSpan timeout)
        {
            _socket.Dispose();
            _context.Dispose();
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            string addr = LocalAddress.Uri.ToString().TrimEnd('/');

            _socket.Bind(addr);

            if (SocketMode == SocketMode.PubSub)
            {
                _socket.Subscribe(new byte[0]);
            }
        }

        #region Async Receive
        public IAsyncResult BeginReceive(AsyncCallback callback, object state)
        {
            return _onReceiveHandler.BeginInvoke(Context.Binding.ReceiveTimeout, callback, state);
        }

        public IAsyncResult BeginReceive(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return _onReceiveHandler.BeginInvoke(timeout, callback, state);
        }

        public Message EndReceive(IAsyncResult result)
        {
            return _onReceiveHandler.EndInvoke(result);
        }

        public IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback, object state)
        {
            Message message;
            return _onTryReceiveHandler.BeginInvoke(timeout, out message, callback, state);
        }

        public bool EndTryReceive(IAsyncResult result, out Message message)
        {
            return _onTryReceiveHandler.EndInvoke(out message, result);
        }

        public IAsyncResult BeginWaitForMessage(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return _onWaitForMessageHandler.BeginInvoke(timeout, callback, state);
        }

        public bool EndWaitForMessage(IAsyncResult result)
        {
            return _onWaitForMessageHandler.EndInvoke(result);
        }
        #endregion

    }
}


text:
/*
* WorkflowImpl.java
*
* User: Greg Schueler greg@dtosolutions.com
* Created: Mar 16, 2010 1:01:34 PM
* $Id$
*/
package com.dtolabs.rundeck.core.execution.workflow;

import com.dtolabs.rundeck.core.execution.StepExecutionItem;

import java.util.*;

/**
 * WorkflowImpl is ...
 *
 * @author Greg Schueler greg@dtosolutions.com
 * @version $Revision$
 */
public class WorkflowImpl implements IWorkflow {
    private List<StepExecutionItem> commands;
    private int threadcount;
    private boolean keepgoing;
    private String strategy;
    private Map<String, Object> pluginConfig;

    public WorkflowImpl(final List<StepExecutionItem> commands, final int threadcount, final boolean keepgoing,
                        final String strategy) {
        this.commands = commands;
        this.threadcount = threadcount;
        this.keepgoing= keepgoing;
        this.strategy = strategy;
    }

    public List<StepExecutionItem> getCommands() {
        return commands;
    }

    public void setCommands(final List<StepExecutionItem> commands) {
        this.commands = commands;
    }

    public int getThreadcount() {
        return threadcount;
    }

    public void setThreadcount(final int threadcount) {
        this.threadcount = threadcount;
    }

    public boolean isKeepgoing() {
        return keepgoing;
    }

    public void setKeepgoing(boolean keepgoing) {
        this.keepgoing = keepgoing;
    }

    @Override
    public String toString() {
        return "WorkflowImpl{" +
               "commands=" + commands +
               ", threadcount=" + threadcount +
               ", keepgoing=" + keepgoing +
               ", strategy=" + strategy +
               '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof WorkflowImpl)) {
            return false;
        }

        WorkflowImpl workflow = (WorkflowImpl) o;

        if (keepgoing != workflow.keepgoing) {
            return false;
        }
        if (threadcount != workflow.threadcount) {
            return false;
        }
        if (commands != null ? !commands.equals(workflow.commands) : workflow.commands != null) {
            return false;
        }
        if (strategy != null ? !strategy.equals(workflow.strategy) : workflow.strategy != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = commands != null ? commands.hashCode() : 0;
        result = 31 * result + threadcount;
        result = 31 * result + (keepgoing ? 1 : 0);
        result = 31 * result + (strategy != null ? strategy.hashCode() : 0);
        return result;
    }

    public String getStrategy() {
        return strategy;
    }

    public void setStrategy(String strategy) {
        this.strategy = strategy;
    }

    @Override
    public Map<String, Object> getPluginConfig() {
        return pluginConfig;
    }

    public void setPluginConfig(Map<String, Object> pluginConfig) {
        this.pluginConfig = pluginConfig;
    }
}


text:
export * from "./action_form";
export * from "./action_request";
export * from "./action_state";
export * from "./action_response";
export * from "./action";
export * from "./oauth_action";
export * from "./delegate_oauth_action";
export * from "./sources";
export * from "./utils";
import { LookmlModelExploreField as FieldBase } from "../api_types/lookml_model_explore_field";
import { LookmlModelExploreFieldset as ExploreFieldset } from "../api_types/lookml_model_explore_fieldset";
import { AESTransitCrypto as ActionCrypto } from "../crypto/aes_transit_crypto";
import * as JsonDetail from "./json_detail";
interface Field extends Partial<FieldBase> {
    name: string;
}
interface Fieldset extends ExploreFieldset {
    table_calculations: Field[] | null;
}
declare function allFields(fields: Fieldset): Field[];
export { ActionCrypto, JsonDetail, Field, Fieldset, allFields };


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/dataplex/v1/content.proto

namespace Google\Cloud\Dataplex\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Get content request.
 *
 * Generated from protobuf message google.cloud.dataplex.v1.GetContentRequest
 */
class GetContentRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The resource name of the content:
     * projects/{project_id}/locations/{location_id}/lakes/{lake_id}/content/{content_id}
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';
    /**
     * Optional. Specify content view to make a partial request.
     *
     * Generated from protobuf field .google.cloud.dataplex.v1.GetContentRequest.ContentView view = 2 [(.google.api.field_behavior) = OPTIONAL];
     */
    private $view = 0;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. The resource name of the content:
     *           projects/{project_id}/locations/{location_id}/lakes/{lake_id}/content/{content_id}
     *     @type int $view
     *           Optional. Specify content view to make a partial request.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Dataplex\V1\Content::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The resource name of the content:
     * projects/{project_id}/locations/{location_id}/lakes/{lake_id}/content/{content_id}
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. The resource name of the content:
     * projects/{project_id}/locations/{location_id}/lakes/{lake_id}/content/{content_id}
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

    /**
     * Optional. Specify content view to make a partial request.
     *
     * Generated from protobuf field .google.cloud.dataplex.v1.GetContentRequest.ContentView view = 2 [(.google.api.field_behavior) = OPTIONAL];
     * @return int
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * Optional. Specify content view to make a partial request.
     *
     * Generated from protobuf field .google.cloud.dataplex.v1.GetContentRequest.ContentView view = 2 [(.google.api.field_behavior) = OPTIONAL];
     * @param int $var
     * @return $this
     */
    public function setView($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Dataplex\V1\GetContentRequest\ContentView::class);
        $this->view = $var;

        return $this;
    }

}


text:
import { Component } from '@angular/core';
import { AuthenticationService } from '../service/authentication.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'metron-config-login',
  templateUrl: 'login.component.html',
  styleUrls: ['login.component.scss'],
})
export class LoginComponent {

  user: string;
  password: string;
  loginFailure: string = '';

  constructor(private authenticationService: AuthenticationService, private activatedRoute: ActivatedRoute) {
    this.activatedRoute.queryParams.subscribe(params => {
      if (params['sessionExpired'] === 'true') {
        this.loginFailure = 'Session has expired';
      }
    });
  }

  login(): void {
    this.authenticationService.login(this.user, this.password, error => {
      if (error.status === 401) {
        this.loginFailure = 'Login failed for ' + this.user;
      }
    });
  }

}


text:
run "ln -s #{destination_root} ~/.pow/#{app_name}"
say_wizard "App is available at http://#{app_name}.dev/"

__END__

name: Pow
description: "Automatically create a symlink for Pow."
author: mbleigh

category: other
tags: [dev]


text:
package com.redmintie.steelplate.device.java;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import com.redmintie.steelplate.input.Keyboard;
import com.redmintie.steelplate.input.event.KeyEvent;
import com.redmintie.steelplate.input.event.KeyListener;

public class JavaKeyboard extends Keyboard {
	private boolean[] keys = new boolean[65535];
	public JavaKeyboard(JFrame frame) {
		frame.addKeyListener(new java.awt.event.KeyListener() {
			private KeyEvent createEvent(java.awt.event.KeyEvent e) {
				return new KeyEvent(e.getKeyCode(), e.getKeyChar(),
						e.getID() == java.awt.event.KeyEvent.KEY_PRESSED,
						JavaUtil.getEventMods(e));
			}
			@Override
			public void keyPressed(java.awt.event.KeyEvent e) {
				if (!keys[e.getKeyCode()]) {
					keys[e.getKeyCode()] = true;
					KeyEvent event = createEvent(e);
					for (KeyListener listener : listeners) {
						listener.keyPressed(event);
					}
				}
			}
			@Override
			public void keyReleased(java.awt.event.KeyEvent e) {
				JavaKeyboard.this.keyReleased(createEvent(e));
			}
			@Override
			public void keyTyped(java.awt.event.KeyEvent e) {
				KeyEvent event = createEvent(e);
				for (KeyListener listener : listeners) {
					listener.keyTyped(event);
				}
			}
		});

		frame.addWindowFocusListener(new WindowAdapter() {
			@Override
			public void windowLostFocus(WindowEvent e) {
				for (int i = 0; i < keys.length; i++) {
					if (keys[i]) {
						keyReleased(new KeyEvent(i, KeyEvent.CHAR_UNDEFINED, false, 0));
					}
				}
			}
		});
	}
	private void keyReleased(KeyEvent event) {
		keys[event.getKey()] = false;
		for (KeyListener listener : listeners) {
			listener.keyReleased(event);
		}
	}
	@Override
	public boolean isKeyDown(int key) {
		return keys[key];
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Eic extends CI_Controller {

	public function index()
	{
        $this->load->view('eic/header');
        $this->load->view('eic/index');
        $this->load->view('eic/footer');
	}
}


text:
<?php
/**
 * Cart item data (when outputting non-flat)
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/cart/cart-item-data.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see 	    https://docs.woocommerce.com/document/template-structure/
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version 	2.4.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?>

	<?php foreach ( $item_data as $data ) : ?>
		<dt class="variation-<?php echo sanitize_html_class( $data['key'] ); ?>"><?php echo wp_kses_post( $data['key'] ); ?>:

		<dd class="variation-<?php echo sanitize_html_class( $data['key'] ); ?>"><?php echo wp_kses_post( wpautop( $data['display'] ) ); ?>

	<?php endforeach; ?>


text:
package io.skysail.server.app.ref.one2many.todo.resources;

import io.skysail.api.responses.SkysailResponse;
import io.skysail.server.restlet.resources.PutEntityServerResource;

import java.util.Date;
import org.restlet.resource.ResourceException;
import io.skysail.server.app.ref.one2many.*;
import io.skysail.server.app.ref.one2many.todo.*;

/**
 * generated from putResource.stg
 */
public class PutTodoResourceGen extends PutEntityServerResource<io.skysail.server.app.ref.one2many.todo.Todo> {

    protected String id;
    protected one2manyApplicationApplication app;

    @Override
    protected void doInit() throws ResourceException {
        id = getAttribute("id");
        app = (one2manyApplicationApplication)getApplication();
    }

    @Override
    public void updateEntity(Todo  entity) {
        io.skysail.server.app.ref.one2many.todo.Todo original = getEntity();
        copyProperties(original,entity);

        app.getRepository(io.skysail.server.app.ref.one2many.todo.Todo.class).update(original,app.getApplicationModel());
    }

    @Override
    public io.skysail.server.app.ref.one2many.todo.Todo getEntity() {
        return (io.skysail.server.app.ref.one2many.todo.Todo)app.getRepository(io.skysail.server.app.ref.one2many.todo.Todo.class).findOne(id);
    }

    @Override
    public String redirectTo() {
        return super.redirectTo(TodosResourceGen.class);
    }
}


text:
@interface TMYGeneralSearchModel : TMYBaseModel

- (void)requsetDataWithCategoryId:(NSString *)categoryId
                         regionId:(NSString *)regionId
                        searchKey:(NSString *)searchKey
                           buyNow:(BOOL)byNow
                           payNow:(BOOL)payNow
                           onSale:(BOOL)onSale
                  conditionMethod:(NSString *)conditionMethod
                   shippingMethod:(NSString *)shippingMethod
                  completionBlock:(RequestCompletion)completionBlock;

@end


text:
import type {Plugin} from "ajv"
import getDef from "../definitions/instanceof"

const instanceofPlugin: Plugin<undefined> = (ajv) => ajv.addKeyword(getDef())

export default instanceofPlugin
module.exports = instanceofPlugin


text:
import numpy as np
try:
    from pycocotools.coco import COCO
except ImportError:
    COCO = None

class COCOParser(object):
    def __init__(self, annotations_path, class_names='all'):
        self.coco = COCO(annotations_path)
        self.class_names = class_names
        self.data = dict()
        if self.class_names == 'all':
            class_data = self.coco.loadCats(self.coco.getCatIds())
            self.class_names = [class_['name'] for class_ in class_data]
            coco_ids = [class_['id'] for class_ in class_data]
            one_hot_ids = list(range(1, len(coco_ids) + 1))
            self.coco_id_to_class_arg = dict(zip(coco_ids, one_hot_ids))
            self.class_names = ['background'] + self.class_names
            self.num_classes = len(self.class_names)
            self.image_ids = self.coco.getImgIds()
        else:
            # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoDemo.ipynb
            catIds = self.coco.getCatIds(catNms=self.class_names)
            self.image_ids = self.coco.getImgIds(catIds=catIds)
            # imgIds = self.coco.getImgIds(imgIds=[324158])

    def load_data(self):
        # image_ids = self.coco.getImgIds()
        for image_id in self.image_ids:
            image_data = self.coco.loadImgs(image_id)[0]
            image_file_name = image_data['file_name']
            width = float(image_data['width'])
            height = float(image_data['height'])
            annotation_ids = self.coco.getAnnIds(imgIds=image_data['id'])
            annotations = self.coco.loadAnns(annotation_ids)
            num_objects_in_image = len(annotations)
            if num_objects_in_image == 0:
                continue
            image_ground_truth = []
            for object_arg in range(num_objects_in_image):
                coco_id = annotations[object_arg]['category_id']
                class_arg = self.coco_id_to_class_arg[coco_id]
                one_hot_class = self._to_one_hot(class_arg)
                coco_coordinates = annotations[object_arg]['bbox']

                x_min = coco_coordinates[0] / width
                y_min = coco_coordinates[1] / height
                x_max = x_min + coco_coordinates[2] / width
                y_max = y_min + coco_coordinates[3] / height

                ground_truth = [x_min, y_min, x_max, y_max] + one_hot_class
                image_ground_truth.append(ground_truth)
            image_ground_truth = np.asarray(image_ground_truth)
            if len(image_ground_truth.shape) == 1:
                image_ground_truth = np.expand_dims(image_ground_truth, 0)
            self.data[image_file_name] = image_ground_truth
        return self.data

    def _to_one_hot(self, class_arg):
        one_hot_vector = [0] * self.num_classes
        one_hot_vector[class_arg] = 1
        return one_hot_vector


text:
PACKAGE_NAME=drush
PACKAGE_URL=https://github.com/drush-ops/drush
#PACKAGE_VERSION is configurable can be passed as an argument.
PACKAGE_VERSION=${1:-10.x}

yum install -y git php php-json php-dom php-mbstring zip unzip gd gd-devel php-gd php-pdo php-mysqlnd
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && php composer-setup.php --install-dir=/bin --filename=composer
OS_NAME=`cat /etc/os-release | grep PRETTY_NAME | cut -d '=' -f2 | tr -d '"'`

if [ -d "$PACKAGE_NAME" ] ; then
  rm -rf $PACKAGE_NAME
  echo "$PACKAGE_NAME  | $PACKAGE_VERSION | $OS_NAME | GitHub | Removed existing package if any"
fi
HOME_DIR=`pwd`
if ! git clone $PACKAGE_URL $PACKAGE_NAME; then
        echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
        echo "$PACKAGE_URL $PACKAGE_NAME"
        echo "$PACKAGE_NAME  |  $PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails"
        exit 0
fi
cd $HOME_DIR/$PACKAGE_NAME
git checkout $PACKAGE_VERSION
if ! composer install --no-interaction; then
        echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
    echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_Fails"
    exit 1
fi
if ! vendor/bin/phpunit --colors=always --configuration tests --testsuite unit --debug; then
    echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
    echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_success_but_test_Fails"
    exit 1
else
    echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
     echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub  | Pass |  Both_Install_and_Test_Success"
    exit 0
fi

# To run integration and functional test need to install mysql database. Unit test case does not intract with database.
# Functional test case take around 18 mins to complete.
# Integration test case take around 1.07 minutes to complete.

  #vendor/bin/phpunit --colors=always --configuration tests --testsuite integration --debug
  #vendor/bin/phpunit --colors=always --configuration tests --testsuite functional --debug

# 1) sudo yum install mysql-server
# 2) systemctl start mysqld


text:
Hui's github web page.

# Build

Build page and start local web server

    jekyll serve

Build page into `_site` folder (It will also regenerate categories and tags)

    jekyll build


text:
from pyramid.security import NO_PERMISSION_REQUIRED
from pyramid.view import view_config
from sqlalchemy import select
from ns_portal.Models import DBSession, User

@view_config(
    route_name='core/user',
    permission=NO_PERMISSION_REQUIRED,
    renderer='json'
)
def users(request):
    """Return the list of all the users with their ids.
    """
    query = select([
        User.id.label('PK_id'),
        User.Login.label('fullname')
    ]).where(User.HasAccess == True).order_by(User.Lastname, User.Firstname)
    print(request)

    return [dict(row) for row in DBSession.execute(query).fetchall()]

@view_config(
    route_name='core/currentUser',
    renderer='json'
)
def current_user(request):
    """Return the list of all the users with their ids.
    """
    query = select([
        User.id.label('PK_id'),
        User.Login.label('fullname'),
        User.Firstname.label('firstname'),
        User.Lastname.label('lastname')
    ]).where(User.id == request.authenticated_userid)
    return dict(DBSession.execute(query).fetchone())