text:
require 'cartoset'
require 'rails'
require 'warden'
require 'rails_warden'

require 'cartoset/auth/omniauth_cartodb_authentication'
require 'cartoset/auth/warden_strategies'

module Cartoset
  class Engine < Rails::Engine

    initializer "static assets" do |app|
      app.middleware.use ::ActionDispatch::Static, "#{root}/public"
    end

    initializer "cartoset.add_middleware" do

      config.app_middleware.use RailsWarden::Manager do |manager|
        manager.default_strategies :cartodb_oauth
        manager.failure_app = SessionsController if defined?(SessionsController)
      end

      host = oauth_key = oauth_secret = nil
      if CartoDB.const_defined?('Settings')
        host = CartoDB::Settings['host']
        oauth_key = CartoDB::Settings['oauth_key']
        oauth_secret = CartoDB::Settings['oauth_secret']
      end
      config.app_middleware.use OmniAuth::Strategies::Cartodb, host, oauth_key, oauth_secret

    end

  end
end


text:
require "rails"
require "genericons-rails/version"

module Genericons
  module Rails
    if ::Rails.version < "3.1"
      require "genericons-rails/railtie"
    else
      require "genericons-rails/engine"
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

// error_reporting(E_ALL);

if (!is_file('config.php')) {
    die('Please create a config.php file');
}

include __DIR__.'/config.php';

if (!isset($_SERVER['PATH_INFO'])) {
    die('invalid package');
}

$data = build_parameters($_SERVER['PATH_INFO']);
$path = sprintf('caches/%s/%s', $data['vendor'], $data['name']);

if (!is_dir($path)) {
    mkdir($path, 0755, true);
}

$file = sprintf('%s/%s.bin', $path, hash('sha256', serialize($data)));

if (!is_file($file)) {
    rename(create_archive($data), $file);
}

if (!is_file($file)) {
    die('invalid package');
}

send_file(sprintf('%s-%s-%s.zip', $data['vendor'], $data['name'], $data['version']), $file);

/**
 * Create the archive and return the localtion path
 * The created filed is temporary, and will be deleted by
 * the calling function
 *
 * @return string
 */
function create_archive(array $parameters)
{
    $out = sprintf('/tmp/php-mirroring-%s', md5(serialize($parameters).uniqid()));

    $path = sprintf('%s/%s.git', get_repository_path(), $parameters['package']);

    if (!$path || substr($path, 0, strlen(get_repository_path())) !== get_repository_path()) {
        throw new Exception("Unable to parse the request");
    }

    if (!is_dir($path) || !is_file($path.'/config')) {
        throw new Exception("Unable to parse the request");
    }

    $cmd = sprintf('cd %s && /usr/bin/git archive %s --format=zip -o %s',
        escapeshellcmd($path),
        escapeshellcmd($parameters['version']),
        $out
     );

    system($cmd);

    if (!is_file($out)) {
        die('unable to create the file');
    }

    return $out;
}

function send_file($name, $file) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header(sprintf('Content-Disposition: attachment; filename=%s', $name));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

    readfile($file);
}


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

class Errors extends CI_Controller {

	public function page_missing()
	{
		$this->load->view('error_404');
	}
}


text:
#pragma once
#include <aws/chime-sdk-media-pipelines/ChimeSDKMediaPipelines_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace ChimeSDKMediaPipelines
{
namespace Model
{
  enum class LayoutOption
  {
    NOT_SET,
    GridView
  };

namespace LayoutOptionMapper
{
AWS_CHIMESDKMEDIAPIPELINES_API LayoutOption GetLayoutOptionForName(const Aws::String& name);

AWS_CHIMESDKMEDIAPIPELINES_API Aws::String GetNameForLayoutOption(LayoutOption value);
} // namespace LayoutOptionMapper
} // namespace Model
} // namespace ChimeSDKMediaPipelines
} // namespace Aws


text:
import numpy

class PID(object):
    """A generic PID loop controller which can be inherited and used in other control algorithms"""

    def __init__(self, startingError, p=1, i=0, d=0):
        """Return a instance of a un tuned PID controller"""
        self._p = p
        self._i = i
        self._d = d
        self._esum = 0              #Error sum for integral term
        self._le = startingError    #Last error value
        self._count = 0

    def calculate(self, error, dt):

        """Calculates the output of the PID controller"""
        self._esum += error*dt
        dError = (error - self._le)/dt
        u = self._p*error + self._i*self._esum + self._d *dError
        self._le = error
        return u

    def reset(self, startingError):
        """Resets the integral sum and the last error value"""
        self._esum = 0
        self._le = startingError

    def reset_esum(self):
        self._esum = 0

    @property
    def p(self):
        return self._p

    @p.setter
    def p(self, value):
        self._p = value

    @property
    def i(self):
        return self._i

    @i.setter
    def i(self, value):
        self._i = value

    @property
    def d(self):
        return self._d

    @d.setter
    def d(self, value):
        self._d = value


text:
from .base import BaseCommand

class SnapshotVerifyRepositoryCommand(BaseCommand):
    command_name = "elasticsearch:snapshot-verify-repository"

    def is_enabled(self):
        return True

    def run_request(self, repository=None):
        if not repository:
            self.show_repository_list_panel(self.run)
            return

        options = dict(
            repository=repository
        )

        return self.client.snapshot.verify_repository(**options)


text:
module Kirpich
  module Providers
    autoload 'Currency', 'kirpich/providers/currency'
    autoload 'GoogleImageCustomSearch', 'kirpich/providers/google_image_custom_search'
    autoload 'Lurk', 'kirpich/providers/lurk'
    autoload 'Text', 'kirpich/providers/text'
    autoload 'Youtube', 'kirpich/providers/youtube'
    autoload 'Image', 'kirpich/providers/image'
    autoload 'Fga', 'kirpich/providers/fga'
    autoload 'SlackUser', 'kirpich/providers/slack_user'
    autoload 'Ololo', 'kirpich/providers/ololo'

    autoload 'TextUtils', 'kirpich/providers/text_utils'
  end
end


text:
package basic.toolkit;

/**
 * Created with IntelliJ IDEA.
 * User: tian
 * Date: 27/1/14
 * Time: 10:44
 */
public class StringToolkit {

	/**
	 * a=1, b=2
	 */
	public static String list(String pointer, String separator, Object... list) {

		StringBuilder buffer = new StringBuilder();

		boolean title = true;
		boolean firtElement = true;
		for(Object aList : list) {

			if(!firtElement && title) {
				buffer.append(separator);
			} else {
				firtElement = false;
			}
			buffer.append(aList);
			if(title) {
				buffer.append(pointer);
			}
			title = !title;

		}

		return buffer.toString();
	}

	public static void main(String... args) {

		System.out.println(list("->", ", ", "a", 1, "b", 2));
	}
}


text:
<?php

namespace Canvas;

use Canvas\Models\User;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use RuntimeException;

class Canvas
{
    /**
     * Return the installed version.
     *
     * @return string
     */
    public static function installedVersion(): string
    {
        if (app()->runningUnitTests()) {
            return '';
        }

        $dependencies = json_decode(file_get_contents(base_path('composer.lock')), true)['packages'];

        return collect($dependencies)->firstWhere('name', 'austintoddj/canvas')['version'];
    }

    /**
     * Return a list of available language codes.
     *
     * @return array
     */
    public static function availableLanguageCodes(): array
    {
        $locales = preg_grep('/^([^.])/', scandir(dirname(__DIR__, 1).'/resources/lang'));

        return collect($locales)->each(function ($code) {
            return $code;
        })->toArray();
    }

    /**
     * Return an encoded string of app translations.
     *
     * @param $locale
     * @return string
     */
    public static function availableTranslations($locale): string
    {
        return collect(trans('canvas::app', [], $locale))->toJson();
    }

    /**
     * Return an array of available user roles.
     *
     * @return array
     */
    public static function availableRoles(): array
    {
        return [
            User::CONTRIBUTOR => 'Contributor',
            User::EDITOR => 'Editor',
            User::ADMIN => 'Admin',
        ];
    }

    /**
     * Return true if the publishable assets are up to date.
     *
     * @return bool
     */
    public static function assetsUpToDate(): bool
    {
        if (app()->runningUnitTests()) {
            return true;
        }

        $path = public_path('vendor/canvas/mix-manifest.json');

        $message = sprintf('%s%s.  %s',
            trans('canvas::app.assets_are_not_up_to_date'),
            trans('canvas::app.to_update_run'),
            'php artisan canvas:publish'
        );

        if (! File::exists($path)) {
            throw new RuntimeException($message);
        }

        return File::get($path) === File::get(__DIR__.'/../public/mix-manifest.json');
    }

    /**
     * Return the configured base path url.
     *
     * @return string
     */
    public static function basePath(): string
    {
        return sprintf('/%s', config('canvas.path'));
    }

    /**
     * Return the configured storage path url.
     *
     * @return string
     */
    public static function baseStoragePath(): string
    {
        return sprintf('%s/images', config('canvas.storage_path'));
    }

    /**
     * Return a valid host URL or null.
     *
     * @param string|null $url
     * @return string|null
     */
    public static function parseReferer(?string $url): ?string
    {
        if (filter_var($url, FILTER_VALIDATE_URL)) {
            return parse_url($url)['host'];
        }

        return null;
    }

    /**
     * Generate a Gravatar for a given email.
     *
     * @param string $email
     * @param int $size
     * @param string $default
     * @param string $rating
     * @return string
     */
    public static function gravatar(
        string $email,
        int $size = 200,
        string $default = 'retro',
        string $rating = 'g'
    ): string {
        $hash = md5(trim(Str::lower($email)));

        return "https://secure.gravatar.com/avatar/{$hash}?s={$size}&d={$default}&r={$rating}";
    }

    /**
     * Return true if dark mode is enabled.
     *
     * @param int|null $enabled
     * @return bool
     */
    public static function enabledDarkMode(?int $enabled): bool
    {
        return (bool) $enabled ?: false;
    }

    /**
     * Return true if the app is configured to use Arabic or Farsi.
     *
     * @param string|null $locale
     * @return bool
     */
    public static function usingRightToLeftLanguage(?string $locale): bool
    {
        return in_array($locale, ['ar', 'fa']);
    }
}


text:
@interface ErrorView ()

@property (nonatomic, strong) UILabel *label;

@end

@implementation ErrorView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    self.centerView.backgroundColor = [UIColor redColor];

    _label = [[UILabel alloc] init];
    _label.text = @"error...";
    [self.centerView addSubview:_label];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    [_label sizeToFit];
    _label.center = CGPointMake(CGRectGetMidX(self.centerView.bounds), CGRectGetMidY(self.centerView.bounds));
}

@end


text:
<?php

namespace Oro\Bundle\EmailBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;
use Oro\Bundle\EmailBundle\Entity\Email;

/**
* Doctrine repository for EmailThread entity
*/
class EmailThreadRepository extends EntityRepository
{
    /**
     * @return int
     */
    public function deleteOrphanThreads()
    {
        $em = $this->getEntityManager();

        $subQb = $em->createQueryBuilder();
        $subQb->select('e')
            ->from(Email::class, 'e')
            ->where(
                $subQb->expr()->eq('e.thread', 'et')
            );

        $qb = $em->createQueryBuilder();

        return $qb->delete($this->getEntityName(), 'et')
            ->where(
                $qb->expr()->not(
                    $qb->expr()->exists(
                        $subQb->getQuery()->getDQL()
                    )
                )
            )
            ->getQuery()
            ->execute();
    }
}


text:
layout: post
title: Mindscape NHibernate Designer Discount
---

Mindscape have a 60% discount on their NHibernate Designer.

<http://www.mindscapehq.com/blog/index.php/2011/01/20/60-off-nhibernate-designer-act-fast/>

> How to obtain this special
> When making your purchase please enter the following discount code:
> NHSPECIAL
> You should immediately see the price drop to $99, saving you $150 USD!

Great tool for anyone who hates writing XML or loves GUI's.


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class lbroute(base_resource) :
	""" Configuration for LB route resource. """
	def __init__(self) :
		self._network = ""
		self._netmask = ""
		self._gatewayname = ""
		self._td = 0
		self._flags = ""
		self.___count = 0

	@property
	def network(self) :
		"""The IP address of the network to which the route belongs.
		"""
		try :
			return self._network
		except Exception as e:
			raise e

	@network.setter
	def network(self, network) :
		"""The IP address of the network to which the route belongs.
		"""
		try :
			self._network = network
		except Exception as e:
			raise e

	@property
	def netmask(self) :
		"""The netmask to which the route belongs.
		"""
		try :
			return self._netmask
		except Exception as e:
			raise e

	@netmask.setter
	def netmask(self, netmask) :
		"""The netmask to which the route belongs.
		"""
		try :
			self._netmask = netmask
		except Exception as e:
			raise e

	@property
	def gatewayname(self) :
		"""The name of the route.
Minimum length =  1.
		"""
		try :
			return self._gatewayname
		except Exception as e:
			raise e

	@gatewayname.setter
	def gatewayname(self, gatewayname) :
		"""The name of the route.
Minimum length =  1
		"""
		try :
			self._gatewayname = gatewayname
		except Exception as e:
			raise e

	@property
	def td(self) :
		"""Integer value that uniquely identifies the traffic domain in which you want to configure the entity. If you do not specify an ID, the entity becomes part of the default traffic domain, which has an ID of 0.
Default value: 0
Maximum length =  4094.
		"""
		try :
			return self._td
		except Exception as e:
			raise e

	@td.setter
	def td(self, td) :
		"""Integer value that uniquely identifies the traffic domain in which you want to configure the entity. If you do not specify an ID, the entity becomes part of the default traffic domain, which has an ID of 0.
Default value: 0
Maximum length =  4094
		"""
		try :
			self._td = td
		except Exception as e:
			raise e

	@property
	def flags(self) :
		"""State of the configured gateway.
Possible values = UP, DOWN, UNKNOWN, BUSY, OUT OF SERVICE, GOING OUT OF SERVICE, DOWN WHEN GOING OUT OF SERVICE, NS_EMPTY_STR, Unknown, DISABLED.
		"""
		try :
			return self._flags
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(lbroute_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.lbroute
		except Exception as e :
			raise e

	def _get_object_name(self) :
		""" Returns the value of object identifier argument
		"""
		try :
			if (self.network) :
				return str(self.network)
			return None
		except Exception as e :
			raise e

	@classmethod
	def add(cls, client, resource) :
		""" Use this API to add lbroute.
		"""
		try :
			if type(resource) is not list :
				addresource = lbroute()
				addresource.network = resource.network
				addresource.netmask = resource.netmask
				addresource.gatewayname = resource.gatewayname
				addresource.td = resource.td
				return addresource.add_resource(client)
			else :
				if (resource and len(resource) > 0) :
					addresources = [ lbroute() for _ in range(len(resource))]
					for i in range(len(resource)) :
						addresources[i].network = resource[i].network
						addresources[i].netmask = resource[i].netmask
						addresources[i].gatewayname = resource[i].gatewayname
						addresources[i].td = resource[i].td
				result = cls.add_bulk_request(client, addresources)
			return result
		except Exception as e :
			raise e

	@classmethod
	def delete(cls, client, resource) :
		""" Use this API to delete lbroute.
		"""
		try :
			if type(resource) is not list :
				deleteresource = lbroute()
				if type(resource) !=  type(deleteresource):
					deleteresource.network = resource
				else :
					deleteresource.network = resource.network
					deleteresource.netmask = resource.netmask
					deleteresource.td = resource.td
				return deleteresource.delete_resource(client)
			else :
				if type(resource[0]) != cls :
					if (resource and len(resource) > 0) :
						deleteresources = [ lbroute() for _ in range(len(resource))]
						for i in range(len(resource)) :
							deleteresources[i].network = resource[i]
				else :
					if (resource and len(resource) > 0) :
						deleteresources = [ lbroute() for _ in range(len(resource))]
						for i in range(len(resource)) :
							deleteresources[i].network = resource[i].network
							deleteresources[i].netmask = resource[i].netmask
							deleteresources[i].td = resource[i].td
				result = cls.delete_bulk_request(client, deleteresources)
			return result
		except Exception as e :
			raise e

	@classmethod
	def get(cls, client, name="", option_="") :
		""" Use this API to fetch all the lbroute resources that are configured on netscaler.
		"""
		try :
			if not name :
				obj = lbroute()
				response = obj.get_resources(client, option_)
			else :
				if type(name) == cls :
					if type(name) is not list :
						option_ = options()
						option_.args = nitro_util.object_to_string_withoutquotes(name)
						response = name.get_resource(client, option_)
					else :
						if name and len(name) > 0 :
							response = [lbroute() for _ in range(len(name))]
							for i in range(len(name)) :
								option_ = options()
								option_.args = nitro_util.object_to_string_withoutquotes(name[i])
								response[i] = name[i].get_resource(client, option_)
			return response
		except Exception as e :
			raise e

	@classmethod
	def get_filtered(cls, client, filter_) :
		""" Use this API to fetch filtered set of lbroute resources.
		filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = lbroute()
			option_ = options()
			option_.filter = filter_
			response = obj.getfiltered(client, option_)
			return response
		except Exception as e :
			raise e

	@classmethod
	def count(cls, client) :
		""" Use this API to count the lbroute resources configured on NetScaler.
		"""
		try :
			obj = lbroute()
			option_ = options()
			option_.count = True
			response = obj.get_resources(client, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e :
			raise e

	@classmethod
	def count_filtered(cls, client, filter_) :
		""" Use this API to count filtered the set of lbroute resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = lbroute()
			option_ = options()
			option_.count = True
			option_.filter = filter_
			response = obj.getfiltered(client, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e :
			raise e

	class Flags:
		UP = "UP"
		DOWN = "DOWN"
		UNKNOWN = "UNKNOWN"
		BUSY = "BUSY"
		OUT_OF_SERVICE = "OUT OF SERVICE"
		GOING_OUT_OF_SERVICE = "GOING OUT OF SERVICE"
		DOWN_WHEN_GOING_OUT_OF_SERVICE = "DOWN WHEN GOING OUT OF SERVICE"
		NS_EMPTY_STR = "NS_EMPTY_STR"
		Unknown = "Unknown"
		DISABLED = "DISABLED"

class lbroute_response(base_response) :
	def __init__(self, length=1) :
		self.lbroute = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.lbroute = [lbroute() for _ in range(length)]


text:
//
// Copyright © 2012 Linaro Limited
//
// This file is part of the glmark2 OpenGL (ES) 2.0 benchmark.
//
// glmark2 is free software: you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// glmark2 is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// glmark2.  If not, see <http://www.gnu.org/licenses/>.
//
// Authors:
//  Jesse Barker
//
#include "gl-state-egl.h"
#include "log.h"
#include "options.h"
#include "gl-headers.h"
#include "limits.h"
#include "gl-headers.h"
#include <iomanip>
#include <sstream>
#include <cstring>

using std::vector;
using std::string;

GLADapiproc load_egl_func(void *userdata, const char *name)
{
    SharedLibrary *lib = reinterpret_cast<SharedLibrary *>(userdata);
    return reinterpret_cast<GLADapiproc>(lib->load(name));
}

/****************************
 * EGLConfig public methods *
 ****************************/

EglConfig::EglConfig(EGLDisplay dpy, EGLConfig config) :
    handle_(config),
    bufferSize_(0),
    redSize_(0),
    greenSize_(0),
    blueSize_(0),
    luminanceSize_(0),
    alphaSize_(0),
    alphaMaskSize_(0),
    bindTexRGB_(false),
    bindTexRGBA_(false),
    bufferType_(EGL_RGB_BUFFER),
    caveat_(0),
    configID_(0),
    conformant_(0),
    depthSize_(0),
    level_(0),
    pbufferWidth_(0),
    pbufferHeight_(0),
    pbufferPixels_(0),
    minSwapInterval_(0),
    maxSwapInterval_(0),
    nativeID_(0),
    nativeType_(0),
    nativeRenderable_(false),
    sampleBuffers_(0),
    samples_(0),
    stencilSize_(0),
    surfaceType_(0),
    xparentType_(0),
    xparentRedValue_(0),
    xparentGreenValue_(0),
    xparentBlueValue_(0)
{
    vector<string> badAttribVec;
    if (!eglGetConfigAttrib(dpy, handle_, EGL_CONFIG_ID, &configID_))
    {
        badAttribVec.push_back("EGL_CONFIG_ID");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_CONFIG_CAVEAT, &caveat_))
    {
        badAttribVec.push_back("EGL_CONFIG_CAVEAT");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_CONFORMANT, &conformant_))
    {
        badAttribVec.push_back("EGL_CONFORMANT");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_COLOR_BUFFER_TYPE, &bufferType_))
    {
        badAttribVec.push_back("EGL_COLOR_BUFFER_TYPE");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_BUFFER_SIZE, &bufferSize_))
    {
        badAttribVec.push_back("EGL_BUFFER_SIZE");
    }

    if (bufferType_ == EGL_RGB_BUFFER)
    {
        if (!eglGetConfigAttrib(dpy, handle_, EGL_RED_SIZE, &redSize_))
        {
            badAttribVec.push_back("EGL_RED_SIZE");
        }
        if (!eglGetConfigAttrib(dpy, handle_, EGL_GREEN_SIZE, &greenSize_))
        {
            badAttribVec.push_back("EGL_GREEN_SIZE");
        }
        if (!eglGetConfigAttrib(dpy, handle_, EGL_BLUE_SIZE, &blueSize_))
        {
            badAttribVec.push_back("EGL_BLUE_SIZE");
        }
    }
    else
    {
        if (!eglGetConfigAttrib(dpy, handle_, EGL_LUMINANCE_SIZE, &luminanceSize_))
        {
            badAttribVec.push_back("EGL_LUMINANCE_SIZE");
        }
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_ALPHA_SIZE, &alphaSize_))
    {
        badAttribVec.push_back("EGL_ALPHA_SIZE");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_ALPHA_MASK_SIZE, &alphaMaskSize_))
    {
        badAttribVec.push_back("EGL_ALPHA_MASK_SIZE");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_DEPTH_SIZE, &depthSize_))
    {
        badAttribVec.push_back("EGL_DEPTH_SIZE");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_STENCIL_SIZE, &stencilSize_))
    {
        badAttribVec.push_back("EGL_STENCIL_SIZE");
    }
    EGLint doBind(EGL_FALSE);
    if (!eglGetConfigAttrib(dpy, handle_, EGL_BIND_TO_TEXTURE_RGB, &doBind))
    {
        badAttribVec.push_back("EGL_BIND_TO_TEXTURE_RGB");
    }
    bindTexRGB_ = (doBind == EGL_TRUE);
    if (!eglGetConfigAttrib(dpy, handle_, EGL_BIND_TO_TEXTURE_RGBA, &doBind))
    {
        badAttribVec.push_back("EGL_BIND_TO_TEXTURE_RGBA");
    }
    bindTexRGBA_ = (doBind == EGL_TRUE);
    if (!eglGetConfigAttrib(dpy, handle_, EGL_LEVEL, &level_))
    {
        badAttribVec.push_back("EGL_LEVEL");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_MAX_PBUFFER_WIDTH, &pbufferWidth_))
    {
        badAttribVec.push_back("EGL_MAX_PBUFFER_WIDTH");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_MAX_PBUFFER_HEIGHT, &pbufferHeight_))
    {
        badAttribVec.push_back("EGL_MAX_PBUFFER_HEIGHT");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_MAX_PBUFFER_PIXELS, &pbufferPixels_))
    {
        badAttribVec.push_back("EGL_MAX_PBUFFER_PIXELS");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_MIN_SWAP_INTERVAL, &minSwapInterval_))
    {
        badAttribVec.push_back("EGL_MIN_SWAP_INTERVAL");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_MAX_SWAP_INTERVAL, &maxSwapInterval_))
    {
        badAttribVec.push_back("EGL_MAX_SWAP_INTERVAL");
    }
    EGLint doNative(EGL_FALSE);
    if (!eglGetConfigAttrib(dpy, handle_, EGL_NATIVE_RENDERABLE, &doNative))
    {
        badAttribVec.push_back("EGL_NATIVE_RENDERABLE");
    }
    nativeRenderable_ = (doNative == EGL_TRUE);
    if (!eglGetConfigAttrib(dpy, handle_, EGL_NATIVE_VISUAL_TYPE, &nativeType_))
    {
        badAttribVec.push_back("EGL_NATIVE_VISUAL_TYPE");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_NATIVE_VISUAL_ID, &nativeID_))
    {
        badAttribVec.push_back("EGL_NATIVE_VISUAL_ID");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_SURFACE_TYPE, &surfaceType_))
    {
        badAttribVec.push_back("EGL_SURFACE_TYPE");
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_SAMPLE_BUFFERS, &sampleBuffers_))
    {
        badAttribVec.push_back("EGL_SAMPLE_BUFFERS");
    }
    if (sampleBuffers_)
    {
        if (!eglGetConfigAttrib(dpy, handle_, EGL_SAMPLES, &samples_))
        {
            badAttribVec.push_back("EGL_SAMPLES");
        }
    }
    if (!eglGetConfigAttrib(dpy, handle_, EGL_TRANSPARENT_TYPE, &xparentType_))
    {
        badAttribVec.push_back("EGL_TRANSPARENT_TYPE");
    }
    //if (xparentType_ != EGL_NONE)
    {
        if (!eglGetConfigAttrib(dpy, handle_, EGL_TRANSPARENT_RED_VALUE, &xparentRedValue_))
        {
            badAttribVec.push_back("EGL_TRANSPARENT_RED_VALUE");
        }
        if (!eglGetConfigAttrib(dpy, handle_, EGL_TRANSPARENT_GREEN_VALUE, &xparentGreenValue_))
        {
            badAttribVec.push_back("EGL_TRANSPARENT_GREEN_VALUE");
        }
        if (!eglGetConfigAttrib(dpy, handle_, EGL_TRANSPARENT_BLUE_VALUE, &xparentBlueValue_))
        {
            badAttribVec.push_back("EGL_TRANSPARENT_BLUE_VALUE");
        }
    }

    if (!badAttribVec.empty())
    {
        Log::error("Failed to get the following config attributes for config 0x%x:\n",
                    config);
        for (vector<string>::const_iterator attribIt = badAttribVec.begin();
             attribIt != badAttribVec.end();
             attribIt++)
        {
            Log::error("%s\n", attribIt->c_str());
        }
    }
}

void
EglConfig::print_header()
{
    Log::debug("\n");
    Log::debug("    cfg buf  rgb  colorbuffer dp st config native support surface sample\n");
    Log::debug("     id  sz  lum  r  g  b  a  th cl caveat render  visid    type  buf ns\n");
    Log::debug("------------------------------------------------------------------------\n");
}

void
EglConfig::print() const
{
    std::ostringstream s;
    s.setf(std::ios::showbase);
    s.fill(' ');
    s << std::setw(7) << std::hex << configID_;
    s << std::setw(4) << std::dec << bufferSize_;
    if (bufferType_ == EGL_RGB_BUFFER)
    {
        s << std::setw(5) << "rgb";
        s << std::setw(3) << redSize_;
        s << std::setw(3) << greenSize_;
        s << std::setw(3) << blueSize_;
    }
    else
    {
        s << std::setw(5) << "lum";
        s << std::setw(3) << luminanceSize_;
        s << std::setw(3) << 0;
        s << std::setw(3) << 0;
    }
    s << std::setw(3) << alphaSize_;
    s << std::setw(4) << depthSize_;
    s << std::setw(3) << stencilSize_;
    string caveat("None");
    switch (caveat_)
    {
        case EGL_SLOW_CONFIG:
            caveat = string("Slow");
            break;
        case EGL_NON_CONFORMANT_CONFIG:
            caveat = string("Ncon");
            break;
        case EGL_NONE:
            // Initialized to none.
            break;
    }
    s << std::setw(7) << caveat;
    string doNative(nativeRenderable_ ? "true" : "false");
    s << std::setw(7) << doNative;
    s << std::setw(8) << std::hex << nativeID_;
    s << std::setw(8) << std::hex << surfaceType_;
    s << std::setw(4) << std::dec << sampleBuffers_;
    s << std::setw(3) << std::dec << samples_;
    Log::debug("%s\n", s.str().c_str());
}

/*****************************
 * GLStateEGL public methods *
 ****************************/

GLStateEGL::~GLStateEGL()
{
    if(egl_display_ != nullptr){
        if(!eglTerminate(egl_display_))
            Log::error("eglTerminate failed\n");
    }

    if(!eglReleaseThread())
       Log::error("eglReleaseThread failed\n");
}

bool
GLStateEGL::init_display(void* native_display, GLVisualConfig& visual_config)
{
#if defined(WIN32)
    if (!egl_lib_.open("libEGL.dll")) {
#else
    if (!egl_lib_.open_from_alternatives({"libEGL.so", "libEGL.so.1" })) {
#endif
        Log::error("Error loading EGL library\n");
        return false;
    }

    if (gladLoadEGLUserPtr(EGL_NO_DISPLAY, load_egl_func, &egl_lib_) == 0) {
        Log::error("Loading EGL entry points failed\n");
        return false;
    }

    native_display_ = reinterpret_cast<EGLNativeDisplayType>(native_display);
    requested_visual_config_ = visual_config;

    return gotValidDisplay();
}

bool
GLStateEGL::init_surface(void* native_window)
{
    native_window_ = reinterpret_cast<EGLNativeWindowType>(native_window);

    return gotValidSurface();
}

bool
GLStateEGL::init_gl_extensions()
{
#if GLMARK2_USE_GLESv2
    if (!gladLoadGLES2UserPtr(load_proc, this)) {
        Log::error("Loading GLESv2 entry points failed.");
        return false;
    }

    if (GLExtensions::support("GL_OES_mapbuffer")) {
        GLExtensions::MapBuffer = glMapBufferOES;
        GLExtensions::UnmapBuffer = glUnmapBufferOES;
    }
#elif GLMARK2_USE_GL
    if (!gladLoadGLUserPtr(load_proc, this)) {
        Log::error("Loading GL entry points failed.");
        return false;
    }
    GLExtensions::MapBuffer = glMapBuffer;
    GLExtensions::UnmapBuffer = glUnmapBuffer;
#endif
    return true;
}

bool
GLStateEGL::valid()
{
    if (!gotValidDisplay())
        return false;

    if (!gotValidConfig())
        return false;

    if (!gotValidSurface())
        return false;

    if (!gotValidContext())
        return false;

    if (egl_context_ == eglGetCurrentContext())
        return true;

    if (!eglMakeCurrent(egl_display_, egl_surface_, egl_surface_, egl_context_)) {
        Log::error("eglMakeCurrent failed with error: 0x%x\n", eglGetError());
        return false;
    }

    if (!eglSwapInterval(egl_display_, 0)) {
        Log::info("** Failed to set swap interval. Results may be bounded above by refresh rate.\n");
    }

    if (!init_gl_extensions()) {
        return false;
    }

    return true;
}

bool
GLStateEGL::reset()
{
    if (!gotValidDisplay()) {
        return false;
    }

    if (!egl_context_) {
        return true;
    }

    if (EGL_FALSE == eglDestroyContext(egl_display_, egl_context_)) {
        Log::debug("eglDestroyContext failed with error: 0x%x\n", eglGetError());
    }

    egl_context_ = 0;

    return true;
}

void
GLStateEGL::swap()
{
    eglSwapBuffers(egl_display_, egl_surface_);
}

bool
GLStateEGL::gotNativeConfig(intptr_t& vid)
{
    if (!gotValidConfig())
        return false;

    EGLint native_id;
    if (!eglGetConfigAttrib(egl_display_, egl_config_, EGL_NATIVE_VISUAL_ID,
        &native_id))
    {
        Log::debug("Failed to get native visual id for EGLConfig 0x%x\n", egl_config_);
        return false;
    }

    vid = native_id;
    return true;
}

void
GLStateEGL::getVisualConfig(GLVisualConfig& vc)
{
    if (!gotValidConfig())
        return;

    get_glvisualconfig(egl_config_, vc);
}

/******************************
 * GLStateEGL private methods *
 *****************************/

#ifdef GLMARK2_USE_X11
#define GLMARK2_NATIVE_EGL_DISPLAY_ENUM EGL_PLATFORM_X11_KHR
#elif  GLMARK2_USE_WAYLAND
#define GLMARK2_NATIVE_EGL_DISPLAY_ENUM EGL_PLATFORM_WAYLAND_KHR
#elif  GLMARK2_USE_DRM
#define GLMARK2_NATIVE_EGL_DISPLAY_ENUM EGL_PLATFORM_GBM_KHR
#elif  GLMARK2_USE_MIR
#define GLMARK2_NATIVE_EGL_DISPLAY_ENUM EGL_PLATFORM_MIR_KHR
#else
// Platforms not in the above platform enums fall back to eglGetDisplay.
#define GLMARK2_NATIVE_EGL_DISPLAY_ENUM 0
#endif

bool
GLStateEGL::gotValidDisplay()
{
    if (egl_display_)
        return true;

    char const * __restrict const supported_extensions =
        eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);

    if (GLMARK2_NATIVE_EGL_DISPLAY_ENUM != 0 && supported_extensions
        && strstr(supported_extensions, "EGL_EXT_platform_base"))
    {
        Log::debug("Using eglGetPlatformDisplayEXT()\n");
        PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display =
            reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(
                eglGetProcAddress("eglGetPlatformDisplayEXT"));

        if (get_platform_display != nullptr) {
            egl_display_ = get_platform_display(
                GLMARK2_NATIVE_EGL_DISPLAY_ENUM,
                reinterpret_cast<void*>(native_display_),
                nullptr);
        }

        if (!egl_display_) {
            Log::debug("eglGetPlatformDisplayEXT() failed with error: 0x%x\n",
                       eglGetError());
        }
    }
    else
    {
        Log::debug("eglGetPlatformDisplayEXT() seems unsupported\n");
    }

    /* Just in case get_platform_display failed... */
    if (!egl_display_) {
        Log::debug("Falling back to eglGetDisplay()\n");
        egl_display_ = eglGetDisplay(native_display_);
    }

    if (!egl_display_) {
        Log::error("eglGetDisplay() failed with error: 0x%x\n", eglGetError());
        return false;
    }

    int egl_major(-1);
    int egl_minor(-1);
    if (!eglInitialize(egl_display_, &egl_major, &egl_minor)) {
        Log::error("eglInitialize() failed with error: 0x%x\n", eglGetError());
        egl_display_ = 0;
        return false;
    }

    /* Reinitialize GLAD with a known display */
    if (gladLoadEGLUserPtr(egl_display_, load_egl_func, &egl_lib_) == 0) {
        Log::error("Loading EGL entry points failed\n");
        return false;
    }

#if GLMARK2_USE_GLESv2
    EGLenum apiType(EGL_OPENGL_ES_API);
#if defined(WIN32)
    std::initializer_list<const char *> libNames = { "libGLESv2.dll" };
#else
    std::initializer_list<const char *> libNames = { "libGLESv2.so", "libGLESv2.so.2" };
#endif
#elif GLMARK2_USE_GL
    EGLenum apiType(EGL_OPENGL_API);
    std::initializer_list<const char *> libNames = { "libGL.so", "libGL.so.1" };
#endif
    if (!eglBindAPI(apiType)) {
        Log::error("Failed to bind api EGL_OPENGL_ES_API\n");
        return false;
    }

    if (!gl_lib_.open_from_alternatives(libNames)) {
        Log::error("Error loading GL library\n");
        return false;
    }

    return true;
}

void
GLStateEGL::get_glvisualconfig(EGLConfig config, GLVisualConfig& visual_config)
{
    eglGetConfigAttrib(egl_display_, config, EGL_BUFFER_SIZE, &visual_config.buffer);
    eglGetConfigAttrib(egl_display_, config, EGL_RED_SIZE, &visual_config.red);
    eglGetConfigAttrib(egl_display_, config, EGL_GREEN_SIZE, &visual_config.green);
    eglGetConfigAttrib(egl_display_, config, EGL_BLUE_SIZE, &visual_config.blue);
    eglGetConfigAttrib(egl_display_, config, EGL_ALPHA_SIZE, &visual_config.alpha);
    eglGetConfigAttrib(egl_display_, config, EGL_DEPTH_SIZE, &visual_config.depth);
    eglGetConfigAttrib(egl_display_, config, EGL_STENCIL_SIZE, &visual_config.stencil);
}

EGLConfig
GLStateEGL::select_best_config(std::vector<EGLConfig>& configs)
{
    int best_score(INT_MIN);
    EGLConfig best_config(0);

    /*
     * Go through all the configs and choose the one with the best score,
     * i.e., the one better matching the requested config.
     */
    for (std::vector<EGLConfig>::const_iterator iter = configs.begin();
         iter != configs.end();
         iter++)
    {
        const EGLConfig config(*iter);
        GLVisualConfig vc;
        int score;

        get_glvisualconfig(config, vc);

        score = vc.match_score(requested_visual_config_);

        if (score > best_score) {
            best_score = score;
            best_config = config;
        }
    }

    return best_config;
}

bool
GLStateEGL::gotValidConfig()
{
    if (egl_config_)
        return true;

    if (!gotValidDisplay())
        return false;

    const EGLint config_attribs[] = {
        EGL_RED_SIZE, requested_visual_config_.red,
        EGL_GREEN_SIZE, requested_visual_config_.green,
        EGL_BLUE_SIZE, requested_visual_config_.blue,
        EGL_ALPHA_SIZE, requested_visual_config_.alpha,
        EGL_DEPTH_SIZE, requested_visual_config_.depth,
        EGL_STENCIL_SIZE, requested_visual_config_.stencil,
#if GLMARK2_USE_GLESv2
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
#elif GLMARK2_USE_GL
        EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
#endif
        EGL_NONE
    };

    // Find out how many configs match the attributes.
    EGLint num_configs(0);
    if (!eglChooseConfig(egl_display_, config_attribs, 0, 0, &num_configs)) {
        Log::error("eglChooseConfig() (count query) failed with error: %d\n",
                   eglGetError());
        return false;
    }

    if (num_configs == 0) {
        Log::error("eglChooseConfig() didn't return any configs\n");
        return false;
    }

    // Get all the matching configs
    vector<EGLConfig> configs(num_configs);
    if (!eglChooseConfig(egl_display_, config_attribs, &configs.front(),
                         num_configs, &num_configs))
    {
        Log::error("eglChooseConfig() failed with error: %d\n",
                     eglGetError());
        return false;
    }

    // Select the best matching config
    egl_config_ = select_best_config(configs);

    vector<EglConfig> configVec;
    for (vector<EGLConfig>::const_iterator configIt = configs.begin();
         configIt != configs.end();
         configIt++)
    {
        EglConfig cfg(egl_display_, *configIt);
        configVec.push_back(cfg);
        if (*configIt == egl_config_) {
            best_config_ = cfg;
        }
    }

    // Print out the config information, and let the user know the decision
    // about the "best" one with respect to the options.
    unsigned int lineNumber(0);
    Log::debug("Got %u suitable EGLConfigs:\n", num_configs);
    for (vector<EglConfig>::const_iterator configIt = configVec.begin();
         configIt != configVec.end();
         configIt++, lineNumber++)
    {
        if (!(lineNumber % 32))
        {
            configIt->print_header();
        }
        configIt->print();
    }
    Log::debug("\n");
    Log::debug("Best EGLConfig ID: 0x%x\n", best_config_.configID());

    return true;
}

bool
GLStateEGL::gotValidSurface()
{
    if (egl_surface_)
        return true;

    if (!gotValidDisplay())
        return false;

    if (!gotValidConfig())
        return false;

    egl_surface_ = eglCreateWindowSurface(egl_display_, egl_config_, native_window_, 0);
    if (!egl_surface_) {
        Log::error("eglCreateWindowSurface failed with error: 0x%x\n", eglGetError());
        return false;
    }

    return true;
}

bool
GLStateEGL::gotValidContext()
{
    if (egl_context_)
        return true;

    if (!gotValidDisplay())
        return false;

    if (!gotValidConfig())
        return false;

    static const EGLint context_attribs[] = {
#ifdef GLMARK2_USE_GLESv2
        EGL_CONTEXT_CLIENT_VERSION, 2,
#endif
        EGL_NONE
    };

    egl_context_ = eglCreateContext(egl_display_, egl_config_,
                                    EGL_NO_CONTEXT, context_attribs);
    if (!egl_context_) {
        Log::error("eglCreateContext() failed with error: 0x%x\n",
                   eglGetError());
        return false;
    }

    return true;
}

GLADapiproc
GLStateEGL::load_proc(void *userptr, const char* name)
{
    if (eglGetProcAddress) {
        GLADapiproc sym = reinterpret_cast<GLADapiproc>(eglGetProcAddress(name));
        if (sym) {
            return sym;
        }
    }

    GLStateEGL* state = reinterpret_cast<GLStateEGL*>(userptr);
    return reinterpret_cast<GLADapiproc>(state->gl_lib_.load(name));
}


text:
package org.apache.druid.segment.incremental;

import com.google.common.collect.Lists;
import org.apache.druid.data.input.MapBasedInputRow;
import org.apache.druid.query.aggregation.CountAggregatorFactory;
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 */
public class IncrementalIndexRowCompTest
{
  @Test
  public void testBasic()
  {
    IncrementalIndex<?> index = new IncrementalIndex.Builder()
        .setSimpleTestingIndexSchema(new CountAggregatorFactory("cnt"))
        .setMaxRowCount(1000)
        .buildOnheap();

    long time = System.currentTimeMillis();
    IncrementalIndexRow ir1 = index.toIncrementalIndexRow(toMapRow(time, "billy", "A", "joe", "B")).getIncrementalIndexRow();
    IncrementalIndexRow ir2 = index.toIncrementalIndexRow(toMapRow(time, "billy", "A", "joe", "A")).getIncrementalIndexRow();
    IncrementalIndexRow ir3 = index.toIncrementalIndexRow(toMapRow(time, "billy", "A")).getIncrementalIndexRow();

    IncrementalIndexRow ir4 = index.toIncrementalIndexRow(toMapRow(time + 1, "billy", "A", "joe", "B")).getIncrementalIndexRow();
    IncrementalIndexRow ir5 = index.toIncrementalIndexRow(toMapRow(time + 1, "billy", "A", "joe", Arrays.asList("A", "B"))).getIncrementalIndexRow();
    IncrementalIndexRow ir6 = index.toIncrementalIndexRow(toMapRow(time + 1)).getIncrementalIndexRow();

    Comparator<IncrementalIndexRow> comparator = index.dimsComparator();

    Assert.assertEquals(0, comparator.compare(ir1, ir1));
    Assert.assertEquals(0, comparator.compare(ir2, ir2));
    Assert.assertEquals(0, comparator.compare(ir3, ir3));

    Assert.assertTrue(comparator.compare(ir1, ir2) > 0);
    Assert.assertTrue(comparator.compare(ir2, ir1) < 0);
    Assert.assertTrue(comparator.compare(ir2, ir3) > 0);
    Assert.assertTrue(comparator.compare(ir3, ir2) < 0);
    Assert.assertTrue(comparator.compare(ir1, ir3) > 0);
    Assert.assertTrue(comparator.compare(ir3, ir1) < 0);

    Assert.assertTrue(comparator.compare(ir6, ir1) > 0);
    Assert.assertTrue(comparator.compare(ir6, ir2) > 0);
    Assert.assertTrue(comparator.compare(ir6, ir3) > 0);

    Assert.assertTrue(comparator.compare(ir4, ir6) > 0);
    Assert.assertTrue(comparator.compare(ir5, ir6) > 0);
    Assert.assertTrue(comparator.compare(ir4, ir5) < 0);
    Assert.assertTrue(comparator.compare(ir5, ir4) > 0);
  }

  private MapBasedInputRow toMapRow(long time, Object... dimAndVal)
  {
    Map<String, Object> data = new HashMap<>();
    for (int i = 0; i < dimAndVal.length; i += 2) {
      data.put((String) dimAndVal[i], dimAndVal[i + 1]);
    }
    return new MapBasedInputRow(time, Lists.newArrayList(data.keySet()), data);
  }
}


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

<title>Uses of Interface org.apache.poi.openxml4j.opc.internal.PartUnmarshaller (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Interface
org.apache.poi.openxml4j.opc.internal.PartUnmarshaller

Packages that use PartUnmarshaller

Package
Description

org.apache.poi.openxml4j.opc

org.apache.poi.openxml4j.opc.internal.unmarshallers

Uses of PartUnmarshaller in org.apache.poi.openxml4j.opc

Fields in org.apache.poi.openxml4j.opc with type parameters of type PartUnmarshaller

Modifier and Type
Field and Description

protected java.util.Map<ContentType,PartUnmarshaller>
OPCPackage.partUnmarshallers

Part unmarshallers by content type.

Methods in org.apache.poi.openxml4j.opc with parameters of type PartUnmarshaller

Modifier and Type
Method and Description

void
OPCPackage.addUnmarshaller(java.lang.String contentType,
               PartUnmarshaller unmarshaller)

Add an unmarshaller.

Uses of PartUnmarshaller in org.apache.poi.openxml4j.opc.internal.unmarshallers

Classes in org.apache.poi.openxml4j.opc.internal.unmarshallers that implement PartUnmarshaller

Modifier and Type
Class and Description

class
PackagePropertiesUnmarshaller

Package properties unmarshaller.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
{-# LANGUAGE FlexibleInstances #-}
module HETypes where
import           Control.Concurrent
import           Control.Concurrent.STM
import           Control.Exception
import           Control.Monad
import           Data.Hash.MD5
import           Data.Map
import           Network.Socket            hiding (recv, recvFrom, send, sendTo)
import           Network.Socket.ByteString (recv, send)
import           System.IO

import           DHT

dxhostname = "dd5xx.incq.com"
dxport = "4000"

type NodeId = Integer

type CallSign = String

data UsrMsg = Msg CallSign CallSign String
            | Trace String   -- DEBUG
            | DXCluster String   -- DEBUG
            deriving (Show,Read)

data Env = Env { _ngQueue     :: TQueue UsrMsg
               , _ngChan      :: TChan UsrMsg
               , _bbQueue     :: TQueue UsrMsg
               , _bbChan      :: TChan UsrMsg
               , _cm          :: Map NodeId Node
               , _bbm         :: Map NodeId Node
               , _usn         :: Maybe (NodeId,Node)
               , _usUpQueue   :: TQueue UsrMsg
               , _usDownQueue :: TQueue UsrMsg
               , _selfid      :: Maybe NodeId
               , _dhtinst     :: Maybe (Instance NodeId (DHTdata String))
               , _dhtport     :: Maybe PortNumber
               }
               deriving Show

data DHTdata i = Counter Integer
               | Value i
               | List [DHTdata i]
               deriving (Show,Read)

instance Show (Instance NodeId (DHTdata a)) where
  show _ = "DHTinst"

instance Show (TChan a) where
  show _ = "TChan"

instance Show (TQueue a) where
  show _ = "TQueue"

data Node = BackboneNode  { _nodeId   :: NodeId
                         , _toChan    :: TChan UsrMsg
                         , _fromQueue :: TQueue UsrMsg
                         , _handle    :: Handle
                         }
          | UpstreamNode { _nodeId    :: NodeId
                         , _upQueue   :: TQueue UsrMsg
                         , _downQueue :: TQueue UsrMsg
                         , _handle    :: Handle
                         }
          | ClientNode   { _nodeId   :: NodeId
                         , _callSign :: CallSign
                         , _privChan :: TChan UsrMsg
                         , _pubChan  :: TChan UsrMsg
                         , _msgQueue :: TQueue UsrMsg
                         , _handle   :: Handle
                         }
                         deriving Show


text:
package org.wso2.developerstudio.esb.form.editors.article.views;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.FormColors;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import org.eclipse.ui.part.ViewPart;
import org.wso2.developerstudio.esb.forgm.editors.article.FormArticlePlugin;

public class FormView extends ViewPart {
	private FormToolkit toolkit;
	private ScrolledForm form;
	/**
	 * The constructor.
	 */
	public FormView() {
	}
	/**
	 * This is a callback that will allow us to create the viewer and
	 * initialize it.
	 */
	public void createPartControl(Composite parent) {
		toolkit = new FormToolkit(parent.getDisplay());
		form = toolkit.createScrolledForm(parent);
		form.setText(Messages.getString("FormView.title")); //$NON-NLS-1$
		TableWrapLayout layout = new TableWrapLayout();
		//GridLayout layout = new GridLayout();
		form.getBody().setLayout(layout);
		Hyperlink link = toolkit.createHyperlink(form.getBody(), Messages.getString("FormView.link"), //$NON-NLS-1$
				SWT.WRAP);
		link.addHyperlinkListener(new HyperlinkAdapter() {
			public void linkActivated(HyperlinkEvent e) {
				System.out.println(Messages.getString("FormView.linkMessage")); //$NON-NLS-1$
			}
		});
		link.setText(Messages.getString("FormView.longLink")); //$NON-NLS-1$
		layout.numColumns = 2;
		TableWrapData td = new TableWrapData();
		td.colspan = 2;
		link.setLayoutData(td);
		//GridData gd = new GridData();
		//gd.horizontalSpan = 2;
		//link.setLayoutData(gd);
		toolkit.createLabel(form.getBody(), Messages.getString("FormView.textLabel")); //$NON-NLS-1$
		Text text = toolkit.createText(form.getBody(), ""); //$NON-NLS-1$
		td = new TableWrapData(TableWrapData.FILL_GRAB);
		text.setLayoutData(td);
		//text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		Button button = toolkit.createButton(form.getBody(),
				Messages.getString("FormView.checkbox"), SWT.CHECK); //$NON-NLS-1$
		td = new TableWrapData();
		td.colspan = 2;
		button.setLayoutData(td);

		//gd = new GridData();
		//gd.horizontalSpan = 2;
		//button.setLayoutData(gd);

		ExpandableComposite ec = toolkit.createExpandableComposite(form.getBody(), ExpandableComposite.TREE_NODE|ExpandableComposite.CLIENT_INDENT);
		ImageHyperlink eci = toolkit.createImageHyperlink(ec, SWT.NULL);
		//eci.setImage(FormArticlePlugin.getDefault().getImageRegistry().get(FormArticlePlugin.IMG_SAMPLE));
		ec.setTextClient(eci);
		ec.setText(Messages.getString("FormView.expandable")); //$NON-NLS-1$
		String ctext = Messages.getString("FormView.expandableText")+ //$NON-NLS-1$
		Messages.getString("FormView.expandablText2")+ //$NON-NLS-1$
		Messages.getString("FormView.expandableText3")+ //$NON-NLS-1$
		Messages.getString("FormView.expandableText4"); //$NON-NLS-1$
		Label client = toolkit.createLabel(ec, ctext, SWT.WRAP);
		ec.setClient(client);
		td = new TableWrapData();
		td.colspan = 2;
		ec.setLayoutData(td);
		ec.addExpansionListener(new ExpansionAdapter() {
			public void expansionStateChanged(ExpansionEvent e) {
				form.reflow(true);
			}
		});
		Section section = toolkit.createSection(form.getBody(), Section.DESCRIPTION|Section.TWISTIE|Section.TITLE_BAR|Section.EXPANDED);
		td = new TableWrapData(TableWrapData.FILL);
		td.colspan = 2;
		section.setLayoutData(td);
		section.addExpansionListener(new ExpansionAdapter() {
			public void expansionStateChanged(ExpansionEvent e) {
				form.reflow(true);
			}
		});
		section.setText(Messages.getString("FormView.stitle")); //$NON-NLS-1$
		section.setDescription(Messages.getString("FormView.sdesc")); //$NON-NLS-1$
		Composite sectionClient = toolkit.createComposite(section);
		sectionClient.setLayout(new GridLayout());
		button = toolkit.createButton(sectionClient, Messages.getString("FormView.radio1"), SWT.RADIO); //$NON-NLS-1$
		button = toolkit.createButton(sectionClient, Messages.getString("FormView.radio2"), SWT.RADIO); //$NON-NLS-1$
		section.setClient(sectionClient);

		StringBuffer buf = new StringBuffer();
		buf.append("<form>"); //$NON-NLS-1$
		buf.append("
"); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext1")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext2")); //$NON-NLS-1$
		buf.append("
"); //$NON-NLS-1$
		buf.append("
"); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext3")); //$NON-NLS-1$
		buf.append("
"); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext4")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext5")); //$NON-NLS-1$
		buf.append("
"); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext6")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext7")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext8")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext9")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext10")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext11")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext12")); //$NON-NLS-1$
		buf.append(Messages.getString("FormView.ftext13")); //$NON-NLS-1$
		buf.append("</form>"); //$NON-NLS-1$
		FormText rtext = toolkit.createFormText(form.getBody(), true);
		rtext.setWhitespaceNormalized(true);
		td = new TableWrapData(TableWrapData.FILL);
		td.colspan = 2;
		rtext.setLayoutData(td);
//		rtext.setImage("image", FormArticlePlugin.getDefault().getImageRegistry().get(FormArticlePlugin.IMG_SAMPLE)); //$NON-NLS-1$
		rtext.setColor("header", toolkit.getColors().getColor(FormColors.TITLE)); //$NON-NLS-1$
		rtext.setFont("header", JFaceResources.getHeaderFont()); //$NON-NLS-1$
		rtext.setFont("code", JFaceResources.getTextFont()); //$NON-NLS-1$
		rtext.setText(buf.toString(), true, false);
		rtext.addHyperlinkListener(new HyperlinkAdapter() {
			public void linkActivated(HyperlinkEvent e) {
				System.out.println(Messages.getString("FormView.lmessage")+e.getHref()); //$NON-NLS-1$
			}
		});
		/*
		layout.numColumns = 3;
		Label label;
		TableWrapData td;

		label = toolkit.createLabel(form.getBody(), "Some text to put in the first column", SWT.WRAP);
		label = toolkit.createLabel(form.getBody() ,"Some text to put in the second column and make it a bit longer so that we can see what happens with column distribution. This text must be the longest so that it can get more space allocated to the columns it belongs to.", SWT.WRAP);
		td = new TableWrapData();
		td.colspan = 2;
		label.setLayoutData(td);
		label = toolkit.createLabel(form.getBody(), "This text will span two rows and should not grow the column.", SWT.WRAP);
		td = new TableWrapData();
		td.rowspan = 2;
		label.setLayoutData(td);
		label = toolkit.createLabel(form.getBody(), "This text goes into column 2 and consumes only one cell", SWT.WRAP);
		label.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB));
		label = toolkit.createLabel(form.getBody(), "This text goes into column 3 and consumes only one cell too", SWT.WRAP);
		label.setLayoutData(new TableWrapData(TableWrapData.FILL));
		label = toolkit.createLabel(form.getBody(), "This text goes into column 2 and consumes only one cell", SWT.WRAP);
		label.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB));
		label = toolkit.createLabel(form.getBody(), "This text goes into column 3 and consumes only one cell too", SWT.WRAP);
		label.setLayoutData(new TableWrapData(TableWrapData.FILL));
		form.getBody().setBackground(form.getBody().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); */

		toolkit.paintBordersFor(form.getBody());
	}
	/**
	 * Passing the focus request to the form.
	 */
	public void setFocus() {
		form.setFocus();
	}
	/**
	 * Disposes the toolkit
	 */
	public void dispose() {
		toolkit.dispose();
		super.dispose();
	}
}


text:
.PHONY: all all_trampoline clean test test_trampoline examples examples_trampoline install

all:
	./env_trampoline all_trampoline

all_trampoline:
	$(MAKE) -C lib

test:
	./env_trampoline test_trampoline

test_trampoline: all
	$(MAKE) -C tests test

examples:
	./env_trampoline examples_trampoline

examples_trampoline: all
	$(MAKE) -C examples

install: all
	$(MAKE) -C lib install

clean:
	$(MAKE) -C lib clean
	$(MAKE) -C tests clean
	$(MAKE) -C examples clean


text:
//
//  LLLocalImageViewController.m
//  GetLocalPhoto01
//
//  Created by lyc on 15/3/31.
//  Copyright (c) 2015年 com. All rights reserved.
//

#import "LLLocalImageViewController.h"
#import "LLLocalImageCollectionViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>

#define CELL_NAME @"LLLocalImageCollectionViewCell"

@interface LLLocalImageViewController ()
{
    NSMutableArray *photoImages;
}

@end

@implementation LLLocalImageViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    endBtn.enabled = NO;
    endBtn.backgroundColor = [UIColor clearColor];
    endBtn.layer.cornerRadius = 5;
    countImageView.hidden = YES;
    countLabel.hidden = YES;

//    ALAssetsLibrary *_assetsLibrary = [[ALAssetsLibrary alloc] init];

    photoImages = [[NSMutableArray alloc] init];

    ///ALAssetsGroupLibrary
//    [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos|ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
//        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
//        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
//            if(result){
//                UIImage *img = [UIImage imageWithCGImage:result.thumbnail];
//                if(img)
//                {
//                    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//                    [dic setObject:img forKey:@"img"];
//                    [dic setObject:@"0" forKey:@"flag"];
//                    [photoImages addObject:dic];
//                }
//                if(index + 1 == group.numberOfAssets)
//                {
//                    ///最后一个刷新界面
//                    [self finish];
//                }
//            }
//        }];
//    } failureBlock:^(NSError *error) {
//        // error
//        NSLog(@"error ==> %@",error.localizedDescription);
//    }];
}
- (void)viewWillAppear:(BOOL)animated{

    [photoImages removeAllObjects];

    ALAssetsLibrary *_assetsLibrary = [[ALAssetsLibrary alloc] init];

    [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos|ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        [group setAssetsFilter:[ALAssetsFilter allPhotos]];
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            if(result){
                UIImage *img = [UIImage imageWithCGImage:result.thumbnail];
                if(img)
                {
                    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
                    [dic setObject:img forKey:@"img"];
                    [dic setObject:@"0" forKey:@"flag"];
                    [photoImages addObject:dic];
                }
                if(index + 1 == group.numberOfAssets)
                {
                    ///最后一个刷新界面
                    [self finish];
                }
            }
        }];
    } failureBlock:^(NSError *error) {
        // error
        NSLog(@"error ==> %@",error.localizedDescription);
    }];

}
- (void)backButtonClick:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}
- (void)finish
{
    mCollectionView.delegate = self;
    mCollectionView.dataSource = self;
}

#pragma mark UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [photoImages count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView registerNib:[UINib nibWithNibName:CELL_NAME bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:CELL_NAME];
    LLLocalImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_NAME forIndexPath:indexPath];
    cell.selectImageView.tag = indexPath.row;
    if (indexPath.row < [photoImages count])
    {
        id dic = [photoImages objectAtIndex:indexPath.row];
        [cell sendValue:dic];
    }
    return cell;
}

#pragma mark - ---UICollectionViewDelegateFlowLayout
// 设置每个View的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat itemWH = [UIScreen mainScreen].bounds.size.width / 4.0f - 16;
    return CGSizeMake(itemWH, itemWH);
}

// 设置每个图片的Margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

#pragma mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    LLLocalImageCollectionViewCell *cell = (LLLocalImageCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];

    id dic = [photoImages objectAtIndex:indexPath.row];
    BOOL flag = [[dic objectForKey:@"flag"] boolValue];
    if (!flag)
    {
        [dic setObject:@"1" forKey:@"flag"];
    } else {
        [dic setObject:@"0" forKey:@"flag"];
    }
    [cell setSelectFlag:!flag];

    NSInteger selectCount = [self getSelectImageCount];
    if (selectCount > 0)
    {
        endBtn.enabled = YES;
        endBtn.backgroundColor = [UIColor colorWithRed:134/255.0f green:208/255.0f blue:0/255.0f alpha:1];
        countImageView.hidden = NO;
        countLabel.hidden = NO;
        countLabel.text = [NSString stringWithFormat:@"%ld", selectCount];
    } else {
        endBtn.enabled = NO;
        endBtn.backgroundColor = [UIColor clearColor];
        countImageView.hidden = YES;
        countLabel.hidden = YES;
    }
}

/**
 *  获取列表中有多少Image被选中
 *
 *  @return 选中个数
 */
- (NSInteger)getSelectImageCount
{
    NSInteger count = 0;
    for (NSInteger i = 0; i < [photoImages count]; i++)
    {
        id dic = [photoImages objectAtIndex:i];
        BOOL flag = [[dic objectForKey:@"flag"] boolValue];
        if (flag)
        {
            count++;
        }
    }
    return count;
}

/**
 *  完成按钮点击
 */
- (IBAction)endBtnClick:(id)sender
{
    NSLog(@"完成按钮点击");
    if ([self.delegate respondsToSelector:@selector(getSelectImage:isFromCamer:)])
    {
        NSMutableArray *imageArr = [[NSMutableArray alloc] init];

        for (NSDictionary *dic in photoImages)
        {
            if ([[dic objectForKey:@"flag"] boolValue])
            {
                [imageArr addObject:[dic objectForKey:@"img"]];
            }
        }
        [self.delegate getSelectImage:imageArr isFromCamer:NO];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end


text:
<?php

namespace ERP\CRMBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * CrmDocumentoAdjuntoContacto
 *
 * @ORM\Table(name="crm_documento_adjunto_contacto", indexes={@ORM\Index(name="fk_documento_adjunto_contacto_contacto", columns={"contacto"}), @ORM\Index(name="fk_documento_adjunto_contacto_usuario", columns={"usuario"})})
 * @ORM\Entity
 */
class CrmDocumentoAdjuntoContacto
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="src", type="string", length=255, nullable=false)
     */
    private $src;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fecha_registro", type="datetime", nullable=false)
     */
    private $fechaRegistro;

    /**
     * @var integer
     *
     * @ORM\Column(name="estado", type="integer", nullable=false)
     */
    private $estado;

    /**
     * @var \CtlUsuario
     *
     * @ORM\ManyToOne(targetEntity="CtlUsuario")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="usuario", referencedColumnName="id")
     * })
     */
    private $usuario;

    /**
     * @var \CrmContacto
     *
     * @ORM\ManyToOne(targetEntity="CrmContacto")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="contacto", referencedColumnName="id")
     * })
     */
    private $contacto;

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

    /**
     * Set src
     *
     * @param string $src
     * @return CrmDocumentoAdjuntoActividad
     */
    public function setSrc($src)
    {
        $this->src = $src;

        return $this;
    }

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

    /**
     * Set fechaRegistro
     *
     * @param \DateTime $fechaRegistro
     * @return CrmDocumentoAdjuntoActividad
     */
    public function setFechaRegistro($fechaRegistro)
    {
        $this->fechaRegistro = $fechaRegistro;

        return $this;
    }

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

    /**
     * Set usuario
     *
     * @param \ERP\CRMBundle\Entity\CtlUsuario $usuario
     * @return CrmDocumentoAdjuntoActividad
     */
    public function setUsuario(\ERP\CRMBundle\Entity\CtlUsuario $usuario = null)
    {
        $this->usuario = $usuario;

        return $this;
    }

    /**
     * Get usuario
     *
     * @return \ERP\CRMBundle\Entity\CtlUsuario
     */
    public function getUsuario()
    {
        return $this->usuario;
    }

    /**
     * Set contacto
     *
     * @param \ERP\CRMBundle\Entity\CrmContacto $contacto
     * @return CrmDocumentoContacto
     */
    public function setContacto(\ERP\CRMBundle\Entity\CrmContacto $contacto= null)
    {
        $this->contacto= $contacto;

        return $this;
    }

    /**
     * Get contacto
     *
     * @return \ERP\CRMBundle\Entity\CrmContacto
     */
    public function getContacto()
    {
        return $this->contacto;
    }

    /**
     * Set estado
     *
     * @param integer $estado
     * @return CrmDocumentoAdjuntoCampania
     */
    public function setEstado($estado)
    {
        $this->estado = $estado;

        return $this;
    }

    /**
     * Get estado
     *
     * @return CrmDocumentoAdjuntoCampania
     */
    public function getEstado()
    {
        return $this->estado;
    }
}


text:
package com.lingke.xvp.demo.controller.response;

public class ExceptionResponse implements XvpResponse {
	private String code;
	private String message;
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Routing.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your quintessential app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your quintessential contact page.";

            return View();
        }
    }
}


text:
<title>UserGuide - Compiler directives (for different behavior on different OS)</title>

UserGuide - Compiler directives (for different behavior on different OS)

This will be our last visit to the File Properties program. There is one limitation
discussed previously to overcome and we've left it until now because it is a special case.

So far the Attributes column on the display has simply been an integer.
This is because the return values of the GetFileAttributes() and DirectoryEntryAttributes()
instructions have a different meaning on Windows systems compared with Mac and Linux systems.

We can't allow for this difference at run-time, however we can use
Compiler Directives to have the program behave
differently on the three different operating systems.

Add this new procedure declaration to that section.

  Declare.s AttributeString(Attributes.l)

Add this new procedure to the implementation section.

  Procedure.s AttributeString(Attributes.l)
    ; Converts an integer attributes value into a string description.
    ; Supports Linux, Mac and Windows system's attributes.

    Protected.s Result

    Result = ""

    CompilerIf #PB_Compiler_OS = #PB_OS_Windows
      ??
      ??; These are the attributes for Windows systems.
      ??; A logical-and of the attribute with each constant filters out that bit and can then be used for comparison.

      ??If Attributes & #PB_FileSystem_Archive
        ???Result + "A"
      ??Else
        ???Result + " "
      ??EndIf
      ??
      ??If Attributes & #PB_FileSystem_Compressed
        ???Result + "C"
      ??Else
        ???Result + " "
      ??EndIf
      ??
      ??If Attributes & #PB_FileSystem_Hidden
        ???Result + "H"
      ??Else
        ???Result + " "
      ??EndIf
      ??
      ??If Attributes & #PB_FileSystem_ReadOnly
        ???Result + "R"
      ??Else
        ???Result + " "
      ??EndIf
      ??
      ??If Attributes & #PB_FileSystem_System
        ???Result + "S"
      ??Else
        ???Result + " "
      ??EndIf
      ??
    CompilerElse

      ; These are the attributes for Mac and Linux systems.

      If Attributes & #PB_FileSystem_Link
        Result + "L "
      Else
        Result + "?"
      EndIf

      ; User attributes.
      If Attributes & #PB_FileSystem_ReadUser
        Result + "R"
      Else
        Result + " "
      EndIf

      If Attributes & #PB_FileSystem_WriteUser
        Result + "W"
      Else
        Result + " "
      EndIf

      If Attributes & #PB_FileSystem_ExecUser
        Result + "X "
      Else
        Result + "?"
      EndIf

      ; Group attributes.
      If Attributes & #PB_FileSystem_ReadGroup
        Result + "R"
      Else
        Result + " "
      EndIf

      If Attributes & #PB_FileSystem_WriteGroup
        Result + "W"
      Else
        Result + " "
      EndIf

      If Attributes & #PB_FileSystem_ExecGroup
        Result + "X "
      Else
        Result + "?"
      EndIf

      ; All attributes.
      If Attributes & #PB_FileSystem_ReadAll
        Result + "R"
      Else
        Result + " "
      EndIf

      If Attributes & #PB_FileSystem_WriteAll
        Result + "W"
      Else
        Result + " "
      EndIf

      If Attributes & #PB_FileSystem_ExecAll
        Result + "X"
      Else
        Result + " "
      EndIf

    CompilerEndIf

    ; Return the result.
    ProcedureReturn Result

  EndProcedure

Finally, replace these two lines in the ListLoad procedure

      ; Convert the attributes to a string, for now.
      Attrib = StrU(Files()\Attributes)

with these,

      ; Call AttributeString to convert the attributes to a string representation.
      Attrib = AttributeString(Files()\Attributes)

Now when the program is executed a string display will be shown instead of the integer values.
On a Windows system it would look something like this (assuming all attributes are set):

  ACHRS

and on the other two systems:

  L RWX RWX RWX

The CompilerIf instruction works much like an
If instruction - however it is the compiler that makes the
decision at compile-time, rather than the executable at run-time. This means that we can
include different code to handle the file attributes on the different operating systems.

The lines between:

  CompilerIf #PB_Compiler_OS = #PB_OS_Windows

and

  CompilerElse

will be compiled on Windows systems. The constant #PB_Compiler_OS is automatically defined
by PureBasic to allow this kind of program logic.

The other section will be used on Mac and Linux systems - which work the same way,
conveniently. If these operating systems had different attribute values too, then we could
use CompilerSelect and CompilerCase
to make a three-way determination.

  CompilerSelect #PB_Compiler_OS

    CompilerCase #PB_OS_Linux
      ; Code for Linux systems.

    CompilerCase #PB_OS_MacOS
      ; Code for Mac systems.

    CompilerCase #PB_OS_Windows
      ; Code for Windows systems.

  CompilerEndSelect

The last compiler directive that we're going to discuss here is:
EnableExplicit.

There is a good reason for using this directive. It requires that all variables
must be defined explicitly before usage, in some way, (using Define,
Dim, Global, Protected,
Static etc.) Doing so eliminates the possibility of logic errors due
to mistyped variable names being defined "on-the-fly". This type of subtle error will not affect
a program's compilation but could well present as an inconvenient bug at run-time. Using this
directive eliminates this kind of problem as a compiler error would occur.

For example:

  EnableExplicit

  Define.l Field, FieldMax

  ; ...

  If Field < FieldMax
    ; If EnableExplicit is omitted this section of code may not execute when intended because FieldMax will be zero.
  EndIf

UserGuide Navigation

< Previous: Structuring code in Procedures | Overview | Next: Reading and writing files >


text:
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace OrdersApi.Controllers
{
    public class HomeController : Controller
    {
        // GET: /<controller>/
        [HttpGet("/")]
        public IActionResult Index()
        {
            return View();
        }
    }
}


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset=UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Project AIM</title>
  <link rel="stylesheet" href="/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/font-awesome.min.css">
  <link rel="stylesheet" href="/css/style.css">
  <base href="/">
</head>
<body>

<app>
  Loading...
</app>

<script async src="/main.bundle.js"></script>
<script src="/js/ckeditor/ckeditor.js"></script>
<!-- Use this if the symbolic link is not working -->
<!-- <script src="https://cdn.ckeditor.com/4.5.11/full/ckeditor.js"></script> -->
</body>
</html>


text:
package org.apache.syncope.installer.files;

public final class ConsoleProperties {

    public static final String PLACEHOLDER = "scheme=http\n"
            + "host=localhost\n"
            + "port=8080";

    public static final String CONSOLE = "scheme=%s\n"
            + "host=%s\n"
            + "port=%s";

    private ConsoleProperties() {
        // private constructor for static utility class
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Runtime.InteropServices;
using Xunit;

namespace System.Runtime.InteropServices.RuntimeInformationTests
{
    public class CheckArchitectureTests
    {
        [Fact]
        public void VerifyArchitecture()
        {
            Architecture osArch = RuntimeInformation.OSArchitecture;
            Architecture processArch = RuntimeInformation.ProcessArchitecture;

            switch (osArch)
            {
                case Architecture.X64:
                    Assert.NotEqual(Architecture.Arm, processArch);
                    break;

                case Architecture.X86:
                    Assert.Equal(Architecture.X86, processArch);
                    break;

                case Architecture.Arm:
                    Assert.Equal(Architecture.Arm, processArch);
                    break;

                default:
                    Assert.False(true, "Unexpected Architecture.");
                    break;
            }
        }
    }
}


text:
// (C) Copyright 2015 Moodle Pty Ltd.
//
// 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.

import { Injectable } from '@angular/core';
import { CoreCourseProvider } from '@features/course/services/course';
import {
    CoreCourseAccess,
    CoreCourseOptionsHandler,
    CoreCourseOptionsHandlerData,
} from '@features/course/services/course-options-delegate';
import { CoreCourseUserAdminOrNavOptionIndexed } from '@features/courses/services/courses';
import { CoreEnrolledCourseDataWithExtraInfoAndOptions } from '@features/courses/services/courses-helper';
import { PARTICIPANTS_PAGE_NAME } from '@features/user/user.module';
import { makeSingleton } from '@singletons';
import { CoreUser } from '../user';

/**
 * Course nav handler.
 */
@Injectable({ providedIn: 'root' })
export class CoreUserCourseOptionHandlerService implements CoreCourseOptionsHandler {

    name = 'CoreUserParticipants';
    priority = 600;

    /**
     * Should invalidate the data to determine if the handler is enabled for a certain course.
     *
     * @param courseId The course ID.
     * @param navOptions Course navigation options for current user. See CoreCoursesProvider.getUserNavigationOptions.
     * @return Promise resolved when done.
     */
    invalidateEnabledForCourse(courseId: number, navOptions?: CoreCourseUserAdminOrNavOptionIndexed): Promise<void> {
        if (navOptions && navOptions.participants !== undefined) {
            // No need to invalidate anything.
            return Promise.resolve();
        }

        return CoreUser.invalidateParticipantsList(courseId);
    }

    /**
     * Check if the handler is enabled on a site level.
     *
     * @return Whether or not the handler is enabled on a site level.
     */
    isEnabled(): Promise<boolean> {
        return Promise.resolve(true);
    }

    /**
     * Whether or not the handler is enabled for a certain course.
     *
     * @param courseId The course ID.
     * @param accessData Access type and data. Default, guest, ...
     * @param navOptions Course navigation options for current user. See CoreCoursesProvider.getUserNavigationOptions.
     * @return True or promise resolved with true if enabled.
     */
    isEnabledForCourse(
        courseId: number,
        accessData: CoreCourseAccess,
        navOptions?: CoreCourseUserAdminOrNavOptionIndexed,
    ): boolean | Promise<boolean> {
        if (accessData && accessData.type == CoreCourseProvider.ACCESS_GUEST) {
            return false; // Not enabled for guests.
        }

        if (navOptions && navOptions.participants !== undefined) {
            return navOptions.participants;
        }

        return CoreUser.isPluginEnabledForCourse(courseId);
    }

    /**
     * @inheritdoc
     */
    getDisplayData(): CoreCourseOptionsHandlerData | Promise<CoreCourseOptionsHandlerData> {
        return {
            title: 'core.user.participants',
            class: 'core-user-participants-handler',
            page: PARTICIPANTS_PAGE_NAME,
        };
    }

    /**
     * Called when a course is downloaded. It should prefetch all the data to be able to see the addon in offline.
     *
     * @param course The course.
     * @return Promise resolved when done.
     */
    async prefetch(course: CoreEnrolledCourseDataWithExtraInfoAndOptions): Promise<void> {
        let offset = 0;
        let canLoadMore = true;

        do {
            const result = await CoreUser.getParticipants(course.id, offset, undefined, undefined, true);

            offset += result.participants.length;
            canLoadMore = result.canLoadMore;
        } while (canLoadMore);
    }

}

export const CoreUserCourseOptionHandler = makeSingleton(CoreUserCourseOptionHandlerService);


text:
'use strict';

var execFile = require('child_process').execFile;
var pngquant = require('pngquant-bin');

module.exports = function optimizePng(dest, src, next) {

  execFile(pngquant, ['-o', dest, src], next);

};


text:
package org.springframework.ldap.filter;

import com.gargoylesoftware.base.testing.EqualsTester;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Adam Skogman
 */
public class AndFilterTest {

    @Test
    public void testZero() {
        AndFilter aq = new AndFilter();

        assertEquals("", aq.encode());
    }

    @Test
    public void testOne() {
        AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b"));

        assertEquals("(a=b)", aq.encode());
    }

    @Test
    public void testTwo() {
        AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")).and(
                new EqualsFilter("c", "d"));

        assertEquals("(&(a=b)(c=d))", aq.encode());
    }

    @Test
    public void testThree() {
        AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")).and(
                new EqualsFilter("c", "d")).and(new EqualsFilter("e", "f"));

        assertEquals("(&(a=b)(c=d)(e=f))", aq.encode());
    }

    @Test
    public void testEquals() {
		EqualsFilter filter = new EqualsFilter("a", "b");
		AndFilter originalObject = new AndFilter().and(filter);
        AndFilter identicalObject = new AndFilter().and(filter);
		AndFilter differentObject = new AndFilter().and(new EqualsFilter("b", "b"));
        AndFilter subclassObject = new AndFilter() {
        }.and(filter);

        new EqualsTester(originalObject, identicalObject, differentObject,
                subclassObject);
    }
}


text:
all: modules/server/build/luvit/build/luvit lib

modules/server/build/luvit/build/luvit:
	make -C modules/server

lib:
	-which moonc && rm -fr lib && ( cd src ; moonc -t ../lib * )

.PHONY: all lib


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class Montage\Montage</title>

	<link rel="stylesheet" href="resources/bootstrap.min.css?973e37a8502921d56bc02bb55321f45b072b6f71">
	<link rel="stylesheet" href="resources/style.css?49f43d3208c5d7e33fa16d36107a345bf11cc00d">

				Overview

                <form id="search" class="navbar-form navbar-left" role="search">
                    <input type="hidden" name="cx" value="">
                    <input type="hidden" name="ie" value="UTF-8">

                        <input type="text" name="q" class="search-query form-control" placeholder="Search">

				</form>

						Namespace

Class

Namespaces

							Montage

							Exceptions

Classes

Documents

Montage

Query

Schema

Class Montage

Our base Montage class.  All interactions with the Montage API happen
through this class.

Class Montage

		Namespace: Montage

		Package: Montage

			Located at Montage.php

Methods summary

				 public

			#
			__construct(  <var>$subdomain</var>, null <var>$token</var> = null, integer <var>$version</var> = 1 )

Parameters

<var>$subdomain</var>

<var>$token</var>

<var>$version</var>

				 public
				Montage\Schema

			#
			__call(  <var>$name</var>,  <var>$args</var> )

Access a Schema directly as a method of the Montage API class.

Access a Schema directly as a method of the Montage API class.

Parameters

<var>$name</var>

<var>$args</var>

Returns

						Montage\Schema

				 public

			#
			setDebug( boolean <var>$debug</var> = false )

Enable / disable debug info when making api calls.

Enable / disable debug info when making api calls.

Parameters

<var>$debug</var>

Returns

$this

				 public
				mixed

			#
			request(  <var>$type</var>,  <var>$url</var>, array <var>$args</var> = [] )

Our main request method to Montage.  Uses Guzzle under
the hood to make the request, and will return the
json_decoded response from Montage.

Our main request method to Montage.  Uses Guzzle under
the hood to make the request, and will return the
json_decoded response from Montage.

Parameters

<var>$type</var>

<var>$url</var>

<var>$args</var>

Returns

						mixed

				 public

			#
			auth( null <var>$user</var> = null, null <var>$password</var> = null )

Authenticate with Montage and set the local token.

Authenticate with Montage and set the local token.

Parameters

<var>$user</var>

<var>$password</var>

Returns

$this

Throws

						Montage\Exceptions\MontageAuthException

				 public
				mixed

			#
			getUser( )

Returns

						mixed

Throws

						Montage\Exceptions\MontageAuthException

				 public
				string

			#
			url(  <var>$endpoint</var>, null <var>$schema</var> = null, null <var>$doc_id</var> = null, null <var>$file_id</var> = null )

Gets a formatted Montage endpoint, prefixed with api version.

Gets a formatted Montage endpoint, prefixed with api version.

Parameters

<var>$endpoint</var>

<var>$schema</var>

<var>$doc_id</var>

<var>$file_id</var>

Returns

						string

Throws

						Montage\Exceptions\MontageUnknownEndpointException

				 public
				mixed

			#
			schemas(  <var>$schemaName</var> = null )

Get a list of all schemas for the given users token.

Get a list of all schemas for the given users token.

Returns

						mixed

				 public
				Montage\Schema

			#
			schema(  <var>$name</var> )

Set the Schema for this instance of Montage.

Set the Schema for this instance of Montage.

Parameters

<var>$name</var>

Returns

						Montage\Schema

Properties summary

				public
				string

					<var>$domain</var>

					#
					'dev.montagehot.club'

				public
				string

					<var>$token</var>

					#
					''

		 API documentation generated by ApiGen


text:
"""
Neural network - nsp
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

def draw_circle(position, neuron_radius):
    circle = plt.Circle(position, radius=neuron_radius, fill=True, fc='Black')
    plt.gca().add_patch(circle)

def draw_line(position1, position2, weight=0.8):
    if weight >= 0:
        #Positive
        line = plt.Line2D((position1[0], position2[0]),
                          (position1[1], position2[1]),
                          color='Green',
                          linewidth=weight)
    else:
        # Negative
        line = plt.Line2D((position1[0], position2[0]),
                          (position1[1], position2[1]),
                          color='Red',
                          linewidth=abs(weight))

    plt.gca().add_line(line)

def draw_network(layer, Wi, Wo, title='Neural network'):
    neuron_distance = 3
    neuron_radius = 0.2
    layer_distance = 4
    padding = 1.5

    network_height = max(layer) + 1  # add 1 for bias neuron
    network_width = len(layer)

    center = (network_height-1)*neuron_distance/2

    # Setup the figure
    xmin = -padding
    xmax = (network_width-1)*layer_distance + padding
    ymin = -padding
    ymax = (network_height-1)*neuron_distance + padding
    fig = plt.figure('Diagram')
    fig.suptitle(title)
    plt.axis('scaled')
    ax = fig.add_subplot(111)
    ax.axis([xmin, xmax, ymin, ymax])
    ax.set_xlabel('Layers')
    plt.xticks(np.arange(network_width)*layer_distance,
               np.arange(network_width))

    neurons = []

    # Get positions for all neurons
    for level in range(network_width):
        if level < (network_width-1):
            n = layer[level] + 1
        else:
            n = layer[level]

        displacement = np.linspace(-(n-1)/2, (n-1)/2, n)*neuron_distance
        position_y = np.ones(n)*center + displacement

        neuron_set = []

        for position in position_y:
            position_x = layer_distance*level
            neuron_set.append((position_x, position))

        neurons.append(neuron_set)

    # Draw connection (2)
    for level in range(len(neurons[:-1])):
        ii = 0
        for i in np.arange(len(neurons[level]), 0, -1)-1:
            jj = 0
            for j in np.arange(len(neurons[level+1]), 0, -1)-1:
                # Take top left first, connect its neurons in level+1, continue
                # Skip the bias neuron
                if j != 0:
                    weight = Wi[ii, jj]
                    draw_line(neurons[level][i], neurons[level+1][j], weight)
                    jj = jj + 1

                if (level+1) == (network_width-1):
                    # Output layer
                    weight = Wo[ii]
                    draw_line(neurons[level][i], neurons[level+1][j], weight)
                    jj = jj + 1

            ii = ii + 1

    # Draw neurons
    for level in neurons:
        for neuron in level:
            if neuron == level[0]:
                # Bias
                draw_circle(neuron, neuron_radius)
                if level is not neurons[network_width-1]:
                    ax.text(neuron[0]-0.5, neuron[1]-1.0, r'Bias', fontsize=10)
            else:
                draw_circle(neuron, neuron_radius)

    # Finish
    plt.draw()
    plt.show()

if __name__ == "__main__":
    # Define the layers (without bias, and no output bias)
    layer = [2, 8, 1]

    multiply = 2.0
    Wi = np.random.randn(2+1, 8)*multiply
    Wo = np.random.randn(8+1, 1)*multiply

    print Wi
    print Wo

    draw_network(layer, Wi, Wo)


text:
package ecc

// NewDjbECPrivateKey returns a new EC private key with the given bytes.
func NewDjbECPrivateKey(key [32]byte) *DjbECPrivateKey {
	private := DjbECPrivateKey{
		privateKey: key,
	}
	return &private
}

// DjbECPrivateKey implements the ECPrivateKey interface and uses Curve25519.
type DjbECPrivateKey struct {
	privateKey [32]byte
}

// PrivateKey returns the private key as a byte-array.
func (d *DjbECPrivateKey) PrivateKey() [32]byte {
	return d.privateKey
}

// Serialize returns the private key as a byte-array.
func (d *DjbECPrivateKey) Serialize() [32]byte {
	return d.privateKey
}

// Type returns the EC type value.
func (d *DjbECPrivateKey) Type() int {
	return DjbType
}


text:
package com.linkedin.datahub.upgrade.nocode;

import com.linkedin.datahub.upgrade.impl.DefaultUpgradeStepResult;
import com.linkedin.datahub.upgrade.UpgradeContext;
import com.linkedin.datahub.upgrade.UpgradeStep;
import com.linkedin.datahub.upgrade.UpgradeStepResult;
import io.ebean.EbeanServer;
import java.util.function.Function;

public class CreateAspectTableStep implements UpgradeStep {

  private static final String DB_TYPE_ARG = "dbType";

  enum DbType {
    MYSQL,
    POSTGRES,
    MARIA
  }

  private final EbeanServer _server;

  public CreateAspectTableStep(final EbeanServer server) {
    _server = server;
  }

  @Override
  public String id() {
    return "CreateAspectTableStep";
  }

  @Override
  public int retryCount() {
    return 1;
  }

  @Override
  public Function<UpgradeContext, UpgradeStepResult> executable() {
    return (context) -> {

      DbType targetDbType = context.parsedArgs().containsKey(DB_TYPE_ARG)
          ? DbType.valueOf(context.parsedArgs().get(DB_TYPE_ARG).get())
          : DbType.MYSQL;

      String sqlUpdateStr;

      switch (targetDbType) {
        case POSTGRES:
          sqlUpdateStr = "CREATE TABLE IF NOT EXISTS metadata_aspect_v2 (\n"
              + "  urn                           varchar(500) not null,\n"
              + "  aspect                        varchar(200) not null,\n"
              + "  version                       bigint not null,\n"
              + "  metadata                      text not null,\n"
              + "  systemmetadata                text,\n"
              + "  createdon                     timestamp not null,\n"
              + "  createdby                     varchar(255) not null,\n"
              + "  createdfor                    varchar(255),\n"
              + "  constraint pk_metadata_aspect_v2 primary key (urn,aspect,version)\n"
              + ")";
          break;
        default:
          // both mysql and maria
          sqlUpdateStr = "CREATE TABLE IF NOT EXISTS metadata_aspect_v2 (\n"
              + "  urn                           varchar(500) not null,\n"
              + "  aspect                        varchar(200) not null,\n"
              + "  version                       bigint(20) not null,\n"
              + "  metadata                      longtext not null,\n"
              + "  systemmetadata                longtext,\n"
              + "  createdon                     datetime(6) not null,\n"
              + "  createdby                     varchar(255) not null,\n"
              + "  createdfor                    varchar(255),\n"
              + "  constraint pk_metadata_aspect_v2 primary key (urn,aspect,version)\n"
              + ")";
          break;
      }

      try {
        _server.execute(_server.createSqlUpdate(sqlUpdateStr));
      } catch (Exception e) {
        context.report().addLine(String.format("Failed to create table metadata_aspect_v2: %s", e.toString()));
        return new DefaultUpgradeStepResult(
            id(),
            UpgradeStepResult.Result.FAILED);
      }
      return new DefaultUpgradeStepResult(id(), UpgradeStepResult.Result.SUCCEEDED);
    };
  }
}


text:
Moonshine::Couchdb
==================

Introduction
------------

Welcome to Moonshine::Couchdb, a [Moonshine](http://github.com/railsmachine/moonshine) plugin for installing and managing [couchdb](http://www.couchbase.com/products-and-services/couchbase-single-server)

Here's some quick links:

 * [Homepage](http://github.com/railsmachine/moonshine_couchdb)
 * [Issues](http://github.com/railsmachine/moonshine_couchdb/issues)
 * [Wiki](http://github.com/railsmachine/moonshine_couchdb/wiki)
 * [Mailing List](http://groups.google.com/group/railsmachine-moonshine)
 * Resources for using Couchdb:
   * [Couchdb Homepage](http://www.google.com/search?q=couchdb)

Quick Start
-----------

`Moonshine::Couchdb` is installed like any other Rails plugin:

    # Rails 2.x.x
    script/plugin install git://github.com/railsmachine/moonshine_couchdb.git
    # Rails 3.x.x
    script/rails plugin install git://github.com/railsmachine/moonshine_couchdb.git

Once it's installed, you can include it in your manifest:

    # app/manifests/application_manifest.rb
    class ApplicationManifest < Moonshine::Manifest:Rails
       recipe :couchdb
    end

Commit and deploy, and there you go.

Configuration
---------------------

Here are the current options availble:

 * `:version`: a string representing the version to install, defaults to 1.1

These are namespaced under `:couchdb`. They can be configured a few ways:

    # in global config/moonshine.yml
    :couchdb:
      :version: 1.1

    # in stage-specific moonshine.yml,
    # config/moonshine/staging.yml and config/moonshine/production.yml
    :couchdb:
      :version: 1.1

    # `configure` call in app/manifests/application_manifest.rb
    configure :couchdb => { :version => '1.1' }

Literate Documentation
----------------------

`Moonshine::Couchdb` uses a literate programming style of documentation, generated by [rocco](https://github.com/rtomayko/rocco) . You can view the latest version [here](lib/moonshine/couchdb.html).

In Use
----------

Originally commissioned by our friends at [PeepCode Screencasts](http://peepcode.com)
for use in an internal reporting system hosted at
[Rails Machine](http://railsmachine.com).

***

Unless otherwise specified, all content copyright © 2014, [Rails Machine, LLC](http://railsmachine.com)


text:
import { List } from 'immutable'

/**
 * @private
 * @function
 * @since v0.1.0
 * @category lang.util.js
 * @param {*} value
 * @returns {ImmutableList} A new ImmutableList
 * @example
 */
const ImmutableList = List

export default ImmutableList


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20.HarvestEXAM
{
    class Program
    {
        static void Main(string[] args)
        {
            var vineyard = int.Parse(Console.ReadLine());
            var grapes = double.Parse(Console.ReadLine());
            var wineRequired = int.Parse(Console.ReadLine());
            var workers = int.Parse(Console.ReadLine());

            var totalWine = 0.4 * vineyard * grapes / 2.5;

            if (totalWine < wineRequired)
            {
                var insufficientWine = wineRequired - totalWine;
                Console.WriteLine("It will be a tough winter! More {0} liters wine needed.", Math.Floor(insufficientWine));
            }
            else
            {
                var wineRemaining = totalWine - wineRequired;
                var perPerson = wineRemaining / workers;
                Console.WriteLine("Good harvest this year! Total wine: {0} liters.", Math.Floor(totalWine));
                Console.WriteLine("{0} liters left -> {1} liters per person.", Math.Ceiling(wineRemaining), Math.Ceiling(perPerson));
            }
        }
    }
}