text:
#ifndef _DECAF_UTIL_ZIP_INFLATERINPUTSTREAM_H_
#define _DECAF_UTIL_ZIP_INFLATERINPUTSTREAM_H_

#include <decaf/util/Config.h>

#include <decaf/io/FilterInputStream.h>
#include <decaf/io/IOException.h>
#include <decaf/util/zip/Inflater.h>

#include <vector>

namespace decaf {
namespace util {
namespace zip {

    /**
     * A FilterInputStream that decompresses data read from the wrapped InputStream instance.
     *
     * @since 1.0
     */
    class DECAF_API InflaterInputStream : public decaf::io::FilterInputStream {
    protected:

        /**
         * The Inflater instance to use.
         */
        Inflater* inflater;

        /**
         * The buffer to hold chunks of data read from the stream before inflation.
         */
        std::vector<unsigned char> buff;

        /**
         * The amount of data currently stored in the input buffer.
         */
        int length;

        bool ownInflater;
        bool atEOF;

        static const int DEFAULT_BUFFER_SIZE;

    private:

        InflaterInputStream(const InflaterInputStream&);
        InflaterInputStream& operator=(const InflaterInputStream&);

    public:

        /**
         * Create an instance of this class with a default inflater and buffer size.
         *
         * @param inputStream
         *      The InputStream instance to wrap.
         * @param own
         *      Should this Filter take ownership of the InputStream pointer (defaults to false).
         */
        InflaterInputStream(decaf::io::InputStream* inputStream, bool own = false);

        /**
         * Creates a new InflaterInputStream with a user supplied Inflater and a default buffer size.
         * When the user supplied a Inflater instance the InflaterInputStream does not take ownership
         * of the Inflater pointer unless the ownInflater parameter is set to true, otherwise the
         * caller is still responsible for deleting the Inflater.
         *
         * @param inputStream
         *      The InputStream instance to wrap.
         * @param inflater
         *      The user supplied Inflater to use for decompression. (
         * @param own
         *      Should this filter take ownership of the InputStream pointer (default is false).
         * @param ownInflater
         *      Should the filter take ownership of the passed Inflater object (default is false).
         *
         * @throws NullPointerException if the Inflater given is NULL.
         */
        InflaterInputStream(decaf::io::InputStream* inputStream, Inflater* inflater,
                            bool own = false, bool ownInflater = false);

        /**
         * Creates a new DeflateOutputStream with a user supplied Inflater and specified buffer size.
         * When the user supplied a Inflater instance the InflaterInputStream does not take ownership
         * of the Inflater pointer unless the ownInflater parameter is set to true, otherwise the caller
         * is still responsible for deleting the Inflater.
         *
         * @param inputStream
         *      The InputStream instance to wrap.
         * @param inflater
         *      The user supplied Inflater to use for decompression.
         * @param bufferSize
         *      The size of the input buffer.
         * @param own
         *      Should this filter take ownership of the InputStream pointer (default is false).
         * @param ownInflater
         *      Should the filter take ownership of the passed Inflater object (default is false).
         *
         * @throws NullPointerException if the Inflater given is NULL.
         * @throws IllegalArgumentException if the bufferSize value is zero.
         */
        InflaterInputStream(decaf::io::InputStream* inputStream, Inflater* inflater,
                            int bufferSize, bool own = false, bool ownInflater = false);

        virtual ~InflaterInputStream();

        /**
         * {@inheritDoc}
         *
         * Until EOF this method always returns 1, thereafter it always returns 0.
         */
        virtual int available() const;

        /**
         * {@inheritDoc}
         *
         * Closes any resources associated with this InflaterInputStream.
         */
        virtual void close();

        /**
         * {@inheritDoc}
         *
         * Skips the specified amount of uncompressed input data.
         */
        virtual long long skip(long long num);

        /**
         * {@inheritDoc}
         *
         * Does nothing.
         */
        virtual void mark(int readLimit);

        /**
         * {@inheritDoc}
         *
         * Always throws an IOException when called.
         */
        virtual void reset();

        /**
         * {@inheritDoc}
         *
         * Always returns false.
         */
        virtual bool markSupported() const;

    protected:

        /**
         * Fills the input buffer with the next chunk of data.
         *
         * @throws IOException if an I/O error occurs.
         */
        virtual void fill();

    protected:

        virtual int doReadByte();

        virtual int doReadArrayBounded(unsigned char* buffer, int size, int offset, int length);

    };

}}}

#endif /* _DECAF_UTIL_ZIP_INFLATERINPUTSTREAM_H_ */


text:
"""
This file is part of ranger, the console file manager.
This configuration file is licensed under the same terms as ranger.
===================================================================

NOTE: If you copied this file to ~/.config/ranger/commands_full.py,
then it will NOT be loaded by ranger, and only serve as a reference.

===================================================================
This file contains ranger's commands.
It's all in python; lines beginning with # are comments.

Note that additional commands are automatically generated from the methods
of the class ranger.core.actions.Actions.

You can customize commands in the file ~/.config/ranger/commands.py.
It has the same syntax as this file.  In fact, you can just copy this
file there with `ranger --copy-config=commands' and make your modifications.
But make sure you update your configs when you update ranger.

===================================================================
Every class defined here which is a subclass of `Command' will be used as a
command in ranger.  Several methods are defined to interface with ranger:
  execute():   called when the command is executed.
  cancel():    called when closing the console.
  tab(tabnum): called when <TAB> is pressed.
  quick():     called after each keypress.

tab() argument tabnum is 1 for <TAB> and -1 for <S-TAB> by default

The return values for tab() can be either:
  None: There is no tab completion
  A string: Change the console to this string
  A list/tuple/generator: cycle through every item in it

The return value for quick() can be:
  False: Nothing happens
  True: Execute the command afterwards

The return value for execute() and cancel() doesn't matter.

===================================================================
Commands have certain attributes and methods that facilitate parsing of
the arguments:

self.line: The whole line that was written in the console.
self.args: A list of all (space-separated) arguments to the command.
self.quantifier: If this command was mapped to the key "X" and
     the user pressed 6X, self.quantifier will be 6.
self.arg(n): The n-th argument, or an empty string if it doesn't exist.
self.rest(n): The n-th argument plus everything that followed.  For example,
     if the command was "search foo bar a b c", rest(2) will be "bar a b c"
self.start(n): Anything before the n-th argument.  For example, if the
     command was "search foo bar a b c", start(2) will be "search foo"

===================================================================
And this is a little reference for common ranger functions and objects:

self.fm: A reference to the "fm" object which contains most information
     about ranger.
self.fm.notify(string): Print the given string on the screen.
self.fm.notify(string, bad=True): Print the given string in RED.
self.fm.reload_cwd(): Reload the current working directory.
self.fm.thisdir: The current working directory. (A File object.)
self.fm.thisfile: The current file. (A File object too.)
self.fm.thistab.get_selection(): A list of all selected files.
self.fm.execute_console(string): Execute the string as a ranger command.
self.fm.open_console(string): Open the console with the given string
     already typed in for you.
self.fm.move(direction): Moves the cursor in the given direction, which
     can be something like down=3, up=5, right=1, left=1, to=6, ...

File objects (for example self.fm.thisfile) have these useful attributes and
methods:

tfile.path: The path to the file.
tfile.basename: The base name only.
tfile.load_content(): Force a loading of the directories content (which
     obviously works with directories only)
tfile.is_directory: True/False depending on whether it's a directory.

For advanced commands it is unavoidable to dive a bit into the source code
of ranger.
===================================================================
"""

from __future__ import absolute_import, division, print_function

# Standard Library
import re
from glob import iglob
from os import environ, makedirs, mknod, getenv
from os.path import exists, expanduser, isfile, join, lexists
from pathlib import Path
from subprocess import DEVNULL, PIPE, Popen, run
from typing import Iterable, List, Optional, Pattern, Set

# 3rd Party
# You always need to import ranger.api.commands here to get the Command class:
from ranger.api.commands import Command

def get_flags(cmd: str) -> Set[str]:
    help = run([cmd, '--help'], stderr=DEVNULL, stdout=PIPE).stdout
    flags = run(['grep', '-E', '-o'], input=help, stdout=PIPE, stderr=DEVNULL).stdout.decode('utf-8').split('\n')
    return set(flags)

class git(Command):
    """git <subcommand> [<option>, ...] [--] [<file>, ...]

    Wrapper for git commands. Good completion.
    """

    non_i_cmds: Set[str] = {
        'add',
        'archive',
        'clean',
        'clone',
        'fetch',
        'init',
        'mv',
        'pull',
        'push',
        'rm',
    }

    opts: Set[str] = {
        '--bare',
        '--exec-path',
        '--git-dir',
        '--help',
        '--html-path',
        '--info-path',
        '--man-path',
        '--namespace',
        '--no-pager',
        '--no-replace-objects',
        '--paginate',
        '--version',
        '--work-tree',
        '-C',
        '-c',
        '-p',
    }

    refs: Set[str] = {
        'HEAD',
        'HEAD^1',
        'HEAD^2',
        'HEAD^3',
        'HEAD~1',
        'HEAD~2',
        'HEAD~3',
        'FETCH_HEAD',
        'ORIG_HEAD',
        'master',
    }

    cmds: Set[str] = {
        'am',
        'apply',
        'bisect',
        'blame',
        'branch',
        'cat-file',
        'checkout',
        'checkout-index',
        'cherry',
        'commit',
        'commit-tree',
        'count-objects',
        'diff',
        'diff-files',
        'diff-index',
        'diff-tree',
        'fast-export',
        'filter-branch',
        'for-each-ref',
        'for-ls-tree',
        'grep',
        'hash-object',
        'help',
        'index-pack',
        'log',
        'ls-files',
        'merge',
        'merge-file',
        'merge-index',
        'mktag',
        'mktree',
        'name-rev',
        'pack-redundant',
        'prune-packed',
        'read-tree',
        'rebase',
        'reflog',
        'remote',
        'repack',
        'reset',
        'rev-list',
        'show',
        'show-branches',
        'status',
        'symbolic-ref',
        'tag',
        'unpack-file',
        'update-ref',
        'var',
        'verify-pack',
        'worktree',
        'write-tree',
    }

    def _get_subcmd(self) -> Optional[str]:
        if not self.args or len(self.args) == 1:
            return None
        for word in self.args[1:]:
            if not word.startswith('-') and (word in git.cmds or word in git.non_i_cmds):
                return word
        return None

    def execute(self):

        if len(self.args) < 2:
            return

        sub_cmd: Optional[str] = self._get_subcmd()

        if sub_cmd is None:
            return

        elif (sub_cmd not in git.cmds) and (sub_cmd not in git.non_i_cmds):
            return

        is_i: bool = sub_cmd in git.cmds

        cmd: List[str] = ['git'] + \
                         (['--paginate'] if is_i else []) + self.args[1:]

        # if any files marked add them to args
        if len(self.fm.thistab.get_selection()) > 1:
            cmd.append('--')
            cmd.extend((i.path for i in self.fm.thistab.get_selection()))

        try:
            # synchronized
            if is_i:
                run(cmd)
            # async
            else:
                from threading import Thread
                thread: Thread = Thread(target=Popen, name=f"git-{sub_cmd}", kwargs={
                    'args': cmd, 'stdout': DEVNULL, 'stderr': DEVNULL})
                thread.start()
                self.fm.notify(f'{" ".join(cmd)} spawned')

            self.fm.ui.redraw_main_column()
            self.fm.ui.need_redraw = True

        except Exception as e:
            self.fm.notify(f'An error has occurred {e}', bad=True)

    def tab(self, tabnum):

        if len(self.args) == 1:
            return (f"git {cmd}" for cmd in
                    (git.cmds | git.non_i_cmds | git.opts))

        elif len(self.args) > 1:

            # complete flags
            if self.args[-1].startswith('-'):

                subcmd: Optional[str] = self._get_subcmd()

                flags: Iterable[str] = None

                if subcmd:
                    pat: Pattern[str] = re.compile(
                        r'--[a-z][-a-z_]+|-[a-zA-Z]')
                    s: str = run(['git', '--no-pager', subcmd, '-h'],
                                 stdout=PIPE,
                                 stderr=DEVNULL).stdout.decode('utf-8')
                    flags = (
                        (" ".join(self.args[:-1]) +
                         ' ' + match.group(0)).strip()
                        for match in pat.finditer(s))
                else:
                    flags = (
                        (" ".join(self.args[:-1]) + " " + opt).strip()
                        for opt in git.opts)

                if self.args[-1] == '-' or self.args[-1] == '--':
                    return flags

                else:
                    return (flag for flag in flags
                            if (flag in self.args[-1]) or
                            (self.args[-1] in flag))

            # relative paths
            elif self.args[-1].startswith('./'):
                return ((" ".join(self.args[:-1]) + " " + node).strip()
                        for node in iglob(join(self.args[-1], '*'))
                        if self.args[-1] in node or node in self.args[-1])

            else:

                pat: Pattern[str] = re.compile(r'\w+')
                stdout: str = run(
                    ['git', '--no-pager', 'branch'], stdout=PIPE, stderr=DEVNULL).stdout.decode('utf-8')

                branches: Iterable[str] = {match.group(0) for match in pat.finditer(stdout)}

                commit_SHAs: Set[str] = {line.split(' ')[0] for line in
                                         run(['git', 'log', '--format=oneline'], stdout=PIPE).stdout.decode(
                                             'utf-8').split('\n')}

                return (
                    (" ".join(self.args[:-1]) + " " + cmd)
                    for cmd in
                    git.cmds | git.non_i_cmds | git.refs | commit_SHAs | branches | {f'origin/{ref}' for ref in
                                                                                (git.refs | branches)}
                    if self.args[-1].startswith(cmd) or cmd.startswith(self.args[-1])
                )

class toPDF(Command):
    """:toPDF [<file>, ...]
    Convert files to PDF.

    NOTE requires libreoffice
    """

    def execute(self):
        d = Path('.')
        did_files = []
        args = ['libreoffice', '--headless', '--invisible', '--convert-to', 'pdf']
        if len(self.args) > 1:
            for node in self.args[1:]:
                try:
                    run(args + [node])
                    did_files.append(node)
                except Exception as e:
                    self.fm.notify(str(e), bad=True)
        else:
            for ext in ['ppt', 'pptx', 'doc', 'docx']:
                for node in d.glob(f'*.{ext}'):
                    try:
                        run(args + [node])
                        did_files.append(node)
                    except Exception as e:
                        self.fm.notify(str(e), bad=True)
        if len(did_files) == 0:
            self.fm.notify('no *.{doc,docx,ppt,pptx} files', bad=True)
        else:
            self.fm.notify(f'converted {", ".join(did_files)}')

    def tab(self, tabnum):
        return self._tab_directory_content()

class vim(Command):
    """:vim [<option>, ...] [<filename>, ...]
    Open marked files in vim.

    NOTE marking only works for the current directory.
    """

    def execute(self):
        cmd = [getenv('EDITOR', 'vim')] + self.args[1:]
        if len(self.fm.thistab.get_selection()) > 1:
            cmd.append('--')
            cmd.extend((i.path for i in self.fm.thistab.get_selection()))
        run(cmd, stdout=DEVNULL)
        self.fm.ui.need_redraw = True
        self.fm.ui.redraw_main_column()

    def tab(self, tabnum):

        opts: Set[str] = {'-t',
                          '+',
                          '-S',
                          '--cmd',
                          '-d',
                          '-M',
                          '-m',
                          '-o',
                          '-O',
                          '-p',
                          '-R'}

        if len(self.args) > 1:
            if self.args[-1].startswith('-'):
                return ((" ".join(self.args[:-1]) + " " + opt).strip()
                        for opt in opts
                        if self.args[-1] in opt or opt in self.args[-1])
            else:
                return ((" ".join(self.args[:-1]) + " " + node).strip()
                        for node in iglob(join(self.args[-1], '*'))
                        if self.args[-1] in node or node in self.args[-1])
        elif len(self.args) == 1:
            return (f"vim {i}" for i in opts)
        else:
            return None

class lines_of_code(Command):
    """:lines_of_code [<extension>]

    Counts lines of code recursively from the current directory.
    Optionally accepts an extension.
    """

    extensions = {
        t for t in run(['tokei', '-l'], stderr=DEVNULL, stdout=PIPE).stdout.decode('utf-8').split('\n') if ' ' not in t
    }

    def execute(self):
        return run(['less'],
                   input=run(['tokei'] if len(self.args) == 1 else ['tokei', '--type', self.args[1]], stdout=PIPE,
                             stderr=DEVNULL).stdout)

    def tab(self, tabnum):
        return {
            "lines_of_code {0}".format(ext) for ext in lines_of_code.extensions
            if self.args[-1].lower() in ext.lower() or ext.lower() in self.args[-1].lower()
        }

class grep(Command):
    """:grep <string>

    Looks for a string in all marked files or directories.

    Ripgrep will be attempted before ranger will fallback on git grep and grep.
    """

    def execute(self):

        if self.rest(1):

            # try ripgrep
            if exists(expanduser('~/.cargo/bin/rg')):

                x = run([
                            'rg', '--pretty', '--smart-case', '--threads=4',
                            '--after-context=1', '--before-context=1', '--regexp'
                        ] + self.args[1:],
                        stdout=PIPE)

            # try git grep if in a git repo
            elif exists(
                    run(['git', 'rev-parse', '--show-toplevel'],
                        PIPE).stdout.decode('utf-8')
            ):

                x = run([
                            'git', 'grep', '--line-number', '--color=always', '-I',
                            '--after-context=3', '--threads=4', '--extended-regexp',
                            '--heading', '--break', '-e'
                        ] + self.args[1:],
                        stdout=PIPE)

            # fallback on grep
            else:
                x = run([
                            'grep', '--line-number', '--extended-regexp',
                            '--color=always', '--with-filename', '-r', '-e'
                        ] + self.args[1:])

            if x.stdout:
                run(['less', '-R', '-X', '-I'], input=x.stdout)
                self.fm.ui.need_redraw = True
                self.fm.ui.redraw_main_column()
            else:
                self.fm.notify('no matches', bad=True)

    def tab(self, tabnum):
        for flag in ('--after-context', '--basic-regexp', '--before-context', '--binary-files', '--byte-offset',
                     '--dereference-recursive', '--exclude-dir', '--exclude-from', '--extended-regexp', '--files-with',
                     '--files-without', '--fixed-strings', '--ignore-case', '--initial-tab', '--invert-match',
                     '--line-buffered', '--line-number', '--line-regexp', '--max-count', '--no-filename',
                     '--no-messages', '--null-data', '--only-matching', '--perl-regexp', '--unix-byte',
                     '--with-filename', '--word-regexp'):
            if self.args[-1] in flag or flag in self.args[-1]:
                yield f'{" ".join(self.args[:-1])} {flag}'

class untracked(Command):
    """:untracked

    List files not tracked by git (ignored).

    Same as git --paginate ls-files --others
    """

    def execute(self):
        run(['git', '--paginate', 'ls-files', '--others'])

class tracked(Command):
    """:tracked

    List files tracked by git.

    Same as git --paginate ls-files
    """

    def execute(self):
        run(['git', '--paginate', 'ls-files'])
        self.fm.ui.need_redraw = True
        self.fm.ui.redraw_main_column()

class mkdir(Command):
    """:mkdir [<dirname>, ...]

    Creates a directories with given names.
    """

    def execute(self):
        if not self.args[1:]:
            return

        for i in self.args[1:]:

            dirname = join(self.fm.thisdir.path, expanduser(i))

            if not lexists(dirname):
                makedirs(dirname, exist_ok=True)

            else:
                self.fm.notify(f"directory {dirname} exists!", bad=True)
                break

    def tab(self, tabnum):
        return self._tab_directory_content()

class touch(Command):
    """:touch [<fname>, ...]

    Creates files with given names.
    """

    def execute(self):
        if not self.args[1:]:
            return

        for arg in self.args[1:]:
            fname = join(self.fm.thisdir.path, expanduser(arg))

            if not lexists(fname):
                mknod(fname)

            else:
                self.fm.notify(f"file {fname} exists!", bad=True)
                break

    def tab(self, tabnum):
        return self._tab_directory_content()

class make(Command):
    """:make <subcommand>

    Run make with specified rule.

    NOTE Must have a Makefile in the same directory.
    """

    def execute(self):
        run(['make'] + self.args[1:], stdout=DEVNULL)

    def tab(self, tabnum):
        if not isfile('Makefile'):
            self.fm.notify('No Makefile in this dir', bad=True)
            return

        with open('./Makefile', mode='r', encoding='utf-8') as f:
            text: str = f.read()

        pat = re.compile(r'^(\w+):', flags=re.M)

        return (f'make {match.group(1)}' for match in pat.finditer(text))

class modified(Command):
    """:modified

    List files modified (Git).

    Same as git --paginate ls-files --modified
    """

    def execute(self):
        run(['git', '--paginate', 'ls-files', '--modified'])

        self.fm.ui.need_redraw = True
        self.fm.ui.redraw_main_column()

class vimdiff(Command):
    """:vimdiff <file1> <file2> | <file1> <file2> <file3>

    Open vim in diff mode with passed files.

    NOTE when you mark them, only the ones in the current directory's will be passed to vim.
         Also, you can diff at most 3 files.
    """

    def execute(self):

        command = ['vim', '-d', '--']

        if len(self.fm.thistab.get_selection()) > 1:
            command.extend([i.path
                            for i in self.fm.thistab.get_selection()][:3])

        elif self.args[1:]:
            command.extend(self.args[1:4])

        else:
            return

        run(command, stdout=DEVNULL)

        self.fm.ui.need_redraw = True
        self.fm.ui.redraw_main_column()

class edit(Command):
    """:edit [<filename>, ...]

    Open file in $EDITOR
    """

    def execute(self):
        if not self.arg(1):
            run([environ['EDITOR'], self.fm.thisfile.path])
        else:
            run([environ['EDITOR']] + self.args[1:])

    def tab(self, tabnum):
        return self._tab_directory_content()

redpajama_set_name: RedPajamaGithub


text:
git config --global user.name "$GIT_USERNAME"
git config --global user.email "$GIT_EMAIL"

#Editor & Diff
git config --global core.editor vi
git config --global merge.tool vimdiff

#Output color
git config --global color.diff auto
git config --global color.status auto
git config --global color.branch auto
git config --global color.interactive auto
git config --global color.ui auto

#LF Normalization (Linux & MacOS)
git config --global core.autocrlf input

#LF Normalization (Windows)
#git config --global core.autocrlf true

#Global gitignore
ln -s $SCRIPT_DIR/git/gitignore ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global


text:
#ifndef __TEGRA_PCM_H__
#define __TEGRA_PCM_H__

#include <mach/dma.h>

struct tegra_pcm_dma_params {
	unsigned long addr;
	unsigned long wrap;
	unsigned long width;
	unsigned long req_sel;
};

struct tegra_runtime_data {
	struct snd_pcm_substream *substream;
	spinlock_t lock;
	int running;
	int dma_pos;
	int dma_pos_end;
	int period_index;
	int dma_req_idx;
	struct tegra_dma_req dma_req[2];
	struct tegra_dma_channel *dma_chan;
};

#endif


text:
<?php

namespace Freedom\UserBundle\Form\User;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ProfileFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('firstname')
        ->add('lastname')
        ->remove('username')
        // ->add('pictureFile', 'vich_file', array(
        //     'required'      => false,
        //     'mapping'       => 'profile_picture', // mandatory
        //     'allow_delete'  => false, // not mandatory, default is true
        //     'download_link' => false, // not mandatory, default is true
        // ));
        ->add('pictureFile', 'file');
    }
    public function getParent()
    {
        return 'fos_user_profile';
    }

    public function getName()
    {
        return 'freedom_user_profile';
    }

}


text:
package com.github.brandonbai.smartmonitor.pojo;

/**
 *
 * Node
 * 节点类
 * @author brandonbai
 * @since 2016年10月11日
 *
 */
public class Node {

	private Integer id;
	private String name;
	private String description;

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}

}


text:
<?php

declare(strict_types=1);

namespace Arcanedev\SeoHelper\Tests\Entities;

use Arcanedev\SeoHelper\Entities\Keywords;
use Arcanedev\SeoHelper\Tests\TestCase;

/**
 * Class     KeywordsTest
 *
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class KeywordsTest extends TestCase
{
    /* -----------------------------------------------------------------
     |  Properties
     | -----------------------------------------------------------------
     */

    /** @var  \Arcanedev\SeoHelper\Contracts\Entities\Keywords */
    private $keywords;

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    public function setUp(): void
    {
        parent::setUp();

        $config         = $this->getKeywordsConfig();
        $this->keywords = new Keywords($config);
    }

    public function tearDown(): void
    {
        unset($this->keywords);

        parent::tearDown();
    }

    /* -----------------------------------------------------------------
     |  Tests
     | -----------------------------------------------------------------
     */

    /** @test */
    public function it_can_be_instantiated(): void
    {
        $expectations = [
            \Arcanedev\SeoHelper\Contracts\Renderable::class,
            \Arcanedev\SeoHelper\Contracts\Entities\Keywords::class,
            Keywords::class
        ];

        foreach ($expectations as $expected) {
            static::assertInstanceOf($expected,   $this->keywords);
        }
    }

    /** @test */
    public function it_can_get_default_content(): void
    {
        $content = $this->getDefaultContent();

        static::assertCount(count($content), $this->keywords->getContent());
        static::assertSame($content, $this->keywords->getContent());
    }

    /** @test */
    public function it_can_set_and_get_content(): void
    {
        $content = $this->getDefaultContent();

        $this->keywords->set($content);

        static::assertCount(count($content), $this->keywords->getContent());
        static::assertSame($content, $this->keywords->getContent());

        $this->keywords->set(implode(',', $content));

        static::assertCount(count($content), $this->keywords->getContent());
        static::assertSame($content, $this->keywords->getContent());

        $keyword = 'one-keyword';
        $this->keywords->set($keyword);

        static::assertCount(1, $this->keywords->getContent());
        static::assertSame([$keyword], $this->keywords->getContent());

        $this->keywords->set(null);

        static::assertCount(0, $this->keywords->getContent());
        static::assertEmpty($this->keywords->getContent());
    }

    /** @test */
    public function it_can_add_a_keyword(): void
    {
        $content = $this->getDefaultContent();

        $this->keywords->set($content);

        static::assertCount(count($content), $this->keywords->getContent());
        static::assertSame($content, $this->keywords->getContent());

        $content[] = $keyword = 'keyword-6';
        $this->keywords->add($keyword);

        static::assertCount(count($content), $this->keywords->getContent());
        static::assertSame($content, $this->keywords->getContent());
    }

    /** @test */
    public function it_can_add_many_keywords(): void
    {
        $content = $this->getDefaultContent();

        $this->keywords->set($content);

        static::assertCount(count($content), $this->keywords->getContent());
        static::assertSame($content, $this->keywords->getContent());

        $keywords = ['keyword-6', 'keyword-7', 'keyword-8'];
        $content  = array_merge($content, $keywords);

        $this->keywords->addMany($keywords);

        static::assertCount(count($content), $this->keywords->getContent());
        static::assertSame($content, $this->keywords->getContent());
    }

    /** @test */
    public function it_can_render(): void
    {
        $content  = $this->getDefaultContent();
        $expected = '<meta name="keywords" content="'.implode(', ', $content).'">';

        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords);
        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords->render());

        $this->keywords->set(implode(',', $content));

        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords);
        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords->render());

        $this->keywords->set(implode(' ,', $content));

        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords);
        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords->render());

        $this->keywords->set(implode(', ', $content));

        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords);
        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords->render());

        $this->keywords->set(implode(' , ', $content));

        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords);
        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords->render());

        $this->keywords->set(null);

        static::assertEmpty((string) $this->keywords);
        static::assertEmpty($this->keywords->render());
    }

    /** @test */
    public function it_can_make(): void
    {
        $keywords       = $this->getDefaultContent();
        $this->keywords = Keywords::make($keywords);

        static::assertSame($keywords, $this->keywords->getContent());

        $expected = '<meta name="keywords" content="'.implode(', ', $keywords).'">';

        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords);
        static::assertHtmlStringEqualsHtmlString($expected, $this->keywords->render());
    }

    /* -----------------------------------------------------------------
     |  Other Methods
     | -----------------------------------------------------------------
     */

    /**
     * Get keywords config.
     *
     * @return array
     */
    private function getKeywordsConfig(): array
    {
        return $this->getSeoHelperConfig('keywords', []);
    }

    /**
     * Get keywords default content.
     *
     * @return array|string
     */
    private function getDefaultContent()
    {
        return $this->getSeoHelperConfig('keywords.default', []);
    }
}


text:
html, body {
	color:#222;
	font-family:Microsoft YaHei,Helvitica,Verdana,Tohoma,Arial,san-serif;
	margin:0;
	padding: 0;
	text-decoration: none;
}
body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td {
	margin:0;
	padding:0;
}
img {
	border:0;
}
ol, ul {
	list-style: none outside none;
	margin:0;
	padding: 0;
}
a {
	color:#000000;
	text-decoration: none;
}
.clr {
	display:block;
	clear:both;
	height:0;
	overflow:hidden;
}
.copyright{padding:8px;text-align:center;font-size:14px;color:#666;}
.copyright a{color:#666;}

body { background-color:#eee;}
body  .mainmenu { overflow:hidden;display: block;;}
body  .mainmenu li{ float:left;  width:50%;   background-color:#0099cb; height:25%; overflow:hidden}

body  .mainmenu li a{ display:block;  color:#FFF;   }
body  .mainmenu li a i{ display:block; height:41%}
body  .mainmenu li a img{ float: left; width:50%; }
body  .mainmenu li a p{ width:50%; float:left}
body  .mainmenu li a p b{ display:block; line-height:18px; font-size:14px;  padding:10% 5% 0px;   overflow:hidden; text-overflow:ellipsis; white-space:nowrap}
body  .mainmenu li a p span{ display:block; height:32px;  padding:0% 5% 0px; font-size:8px; line-height:16px; margin-top:5px; overflow:hidden}
body  .mainmenu li a:active{ opacity:0.4}
body  .mainmenu li:nth-child(8n+1){ background-color:#ffcc9a}
body  .mainmenu li:nth-child(8n+2){ background-color:#9bcbcd}
body  .mainmenu li:nth-child(8n+3){ background-color:#e7ccb1}
body  .mainmenu li:nth-child(8n+4){ background-color:#77a5bc}
body  .mainmenu li:nth-child(8n+5){ background-color:#9bafb0}
body  .mainmenu li:nth-child(8n+6){ background-color:#e7ccb1}
body  .mainmenu li:nth-child(8n+7){ background-color:#77a5bc}
body  .mainmenu li:nth-child(8n+8){ background-color:#ffcc9a}

body  .mainmenu li:nth-child(8n+3) img{ float:right}
body  .mainmenu li:nth-child(8n+4) img{float:right}
body  .mainmenu li:nth-child(8n+7) img{ float:right}
body  .mainmenu li:nth-child(8n+8) img{float:right}


text:
author('Wouter Beek', 'wouter@triply.cc').
download('https://github.com/wouterbeek/Prolog-Library-Collection/releases/*.zip').
home('https://github.com/wouterbeek/Prolog-Library-Collection').
maintainer('Wouter Beek', 'wouter@triply.cc').
name(plc).
packager('Wouter Beek', 'wouter@triply.cc').
title('Prolog Library Collection').
version('1.0.1').


text:
<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * Class PhotoRepository.
 *
 * @category Repository
 *
 * @author   Anton Serra <aserratorta@gmail.com>
 */
class PhotoRepository extends EntityRepository
{
}


text:
require File.expand_path('spec_helper', File.dirname(__FILE__))

describe 'Nesta::Path' do
  before(:each) do
    @root = File.expand_path('..', File.dirname(__FILE__))
    @local_foo_bar = File.join(@root, 'foo/bar')
  end

  it 'should return local path' do
    Nesta::Path.local.should == @root
  end

  it 'should return path for file within local directory' do
    Nesta::Path.local('foo/bar').should == @local_foo_bar
  end

  it 'should combine path components' do
    Nesta::Path.local('foo', 'bar').should == @local_foo_bar
  end

  it 'should return themes path' do
    Nesta::Path.themes.should == File.expand_path('themes', @root)
  end

  it 'should return path for file within themes directory' do
    Nesta::Path.themes('foo/bar').should == File.join(@root, 'themes/foo/bar')
  end
end


text:
#include "qsequencetype_p.h"

QT_BEGIN_NAMESPACE

using namespace QPatternist;

SequenceType::~SequenceType()
{
}

bool SequenceType::matches(const SequenceType::Ptr other) const
{
    Q_ASSERT(other);

    return itemType()->xdtTypeMatches(other->itemType()) &&
           cardinality().isMatch(other->cardinality());
}

bool SequenceType::is(const SequenceType::Ptr &other) const
{
    return matches(other) && other->matches(Ptr(this));
}

QT_END_NAMESPACE


text:
FITeagle

Future Internet Testbed Experimentation and Management Framework

Edit profile

Manage public keys

Download certificate

Sign Out

					<form class="form-search">

								<input type="text" class="search-query top10" placeholder="Search">
								<button type="submit" class="btn btn-inverse"></button>

					</form>

Your Slices

							Manage Slices

Testslice 1

Testslice 2

Testslice 3

Available Testbeds

AV

Hardware

 Databases

 Monitoring

 Software

 Fraunhofer FOCUS

Hardware

 Databases

 Monitoring

 Software

NITOS

GENI

PlanetLab Europe

Edit User Profile

									Username
									<input class="span8" type="text" id="inputUsername" disabled>

									First Name
									<input class="span8" type="text" id="inputFirstName">

									Last Name
									<input class="span8" type="text" id="inputLastName">

									Affiliation
									<input class="span8" type="text" id="inputAffiliation">

									Email
									<input class="span8" type="email" id="inputEmail">

										<button id="deleteUserBtn" class="btn btn-danger">

											 Delete User

										</button>

								<button id="saveProfileInfo" class="btn btn-inverse disabled span2 nomargin">Save</button>

								<button type="button" class="close" data-dismiss="modal" aria-hidden="true">

								</button>

Delete User Profile

Are you sure that you want to delete your user profile ?

									<button id='deleteUserProfileBtn' class="btn btn-danger btn-large">
										Yes
									</button>
									<button class="btn btn-success btn-large left40" data-dismiss="modal" aria-hidden="true">
										No
									</button>

								Manage Public Keys

Existing User Keys

Upload New User Keys

										Key Description*

											<input class="span12" type="text" id="inputKeyDescription" required>

											Key Value

												<textarea class="span12" rows=6 disabled style="resize:none"></textarea>

												<button id="uploadNewPublicKey" class="btn btn-inverse span5">

												</button>

											No file selected

											<button id="selectFromFile" class="span3 btn btn-inverse">

												Select from File
											</button>

											<input type="file" class="hidden"></input>

Download Certificates

Certificate From Existing Key

										<button id="genPubKey" class="btn btn-inverse span2 nomargin">
											Generate
										</button>

New Keypair with Certificate

										Pass-phrase

											<input class="span12" id="inputPassphrase"  type="password" required>

										<button id="genKeyAndCertificate" class="btn btn-inverse span2 nomargin ">
											Generate
										</button>


text:
	<entity-list list-title='Highlighted packages'
		list-entities='vm.highlighted'
		list-object-filter='{}' />


text:
package org.breizhcamp.video.uploader.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

/**
 * WebSocket with Socks.JS config
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/stomp").withSockJS();
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
		registry.enableSimpleBroker("/");
	}
}


text:
UUID is a package created for adding a UUID (Universal Unique Identifier) on the fly.

---

## Installation

*From the command line run the following code.*

```sh
$ meteor add rwatts:uuid
```

## Explanation of Use
There are often times when you simply want to create a unique id without using the mongo `_:id`.

Situations where you want to have a unique ID for coding or session purposes on the client,
but do not want to expose the mongo `_:id`

The UUID can also be stored and used as a foreign key for those whom are familiar with `sql` type databases.

The `uuid.new()` method is a 128-bit hash that returns a possibility of 340 *undecillion* combinations.

## Quick API
In your js file call the `uuid.new()` method to generate a UUID.

>To review the api visit the **[docs](https://github.com/rwatts3/meteor-packages/tree/master/uuid/docs)** directory and review the **api.md** file.

## Quick Example

**Generating a new UUID**
```js
var customerID = uuid.new();
```

**Checking the new UUID**
```js
var customerID = uuid.new();
console.log(customerID);
```

## Latest Updates
Version 0.1.0 Introduces a new method `uuid.tiny()`.
This method generates a 4 character UUID with the possibility of 1.6 **million** combinations .

>For more information on advanced usage visit the repository , and review the **[docs](https://github.com/rwatts3/meteor-packages/tree/master/uuid/docs)** directory.


text:
package com.soomla.store;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import com.soomla.billing.Consts;
import com.soomla.billing.IabException;
import com.soomla.billing.IabHelper;
import com.soomla.billing.IabResult;
import com.soomla.billing.Inventory;
import com.soomla.billing.Purchase;
import com.soomla.store.data.ObscuredSharedPreferences;
import com.soomla.store.data.StoreInfo;
import com.soomla.store.domain.GoogleMarketItem;
import com.soomla.store.domain.NonConsumableItem;
import com.soomla.store.domain.PurchasableVirtualItem;
import com.soomla.store.events.BillingNotSupportedEvent;
import com.soomla.store.events.BillingSupportedEvent;
import com.soomla.store.events.IabServiceStartedEvent;
import com.soomla.store.events.IabServiceStoppedEvent;
import com.soomla.store.events.ItemPurchasedEvent;
import com.soomla.store.events.PlayPurchaseCancelledEvent;
import com.soomla.store.events.PlayPurchaseEvent;
import com.soomla.store.events.PlayPurchaseStartedEvent;
import com.soomla.store.events.PlayRefundEvent;
import com.soomla.store.events.RestoreTransactionsEvent;
import com.soomla.store.events.RestoreTransactionsStartedEvent;
import com.soomla.store.events.StoreControllerInitializedEvent;
import com.soomla.store.events.UnexpectedStoreErrorEvent;
import com.soomla.store.exceptions.VirtualItemNotFoundException;
import com.soomla.store.StoreConfig;

import java.util.List;

/**
 * This class holds the basic assets needed to operate the Store.
 * You can use it to purchase products from Google Play.
 *
 * This is the only class you need to initialize in order to use the SOOMLA SDK.
 *
 * To properly work with this class you must initialize it with the @{link #initialize} method.
 */
public class StoreController {

    /**
     * This initializer also initializes {@link StoreInfo}.
     * @param storeAssets is the definition of your application specific assets.
     * @param publicKey is the public key given to you from Google.
     * @param customSecret is your encryption secret (it's used to encrypt your data in the database)
     */

    private List<String> skuList = null;
    public boolean initialize(IStoreAssets storeAssets, String publicKey, String customSecret, List<String> a_skuList) {
        if (mInitialized) {
            String err = "StoreController is already initialized. You can't initialize it twice!";
            StoreUtils.LogError(TAG, err);
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(err));
            return false;
        }

        StoreUtils.LogDebug(TAG, "StoreController Initializing ...");

        SharedPreferences prefs = new ObscuredSharedPreferences(SoomlaApp.getAppContext().getSharedPreferences(StoreConfig.PREFS_NAME, Context.MODE_PRIVATE));
        SharedPreferences.Editor edit = prefs.edit();

        if (publicKey != null && publicKey.length() != 0) {
            edit.putString(StoreConfig.PUBLIC_KEY, publicKey);
        } else if (prefs.getString(StoreConfig.PUBLIC_KEY, "").length() == 0) {
        	String err = "publicKey is null or empty. Can't initialize store!!";
        	StoreUtils.LogError(TAG, err);
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(err));
            return false;
        }

        if (customSecret != null && customSecret.length() != 0) {
            edit.putString(StoreConfig.CUSTOM_SEC, customSecret);
        } else if (prefs.getString(StoreConfig.CUSTOM_SEC, "").length() == 0) {
        	String err = "customSecret is null or empty. Can't initialize store!!";
            StoreUtils.LogError(TAG, err);
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(err));
            return false;
        }
        edit.putInt("SA_VER_NEW", storeAssets.getVersion());
        edit.commit();

        if (storeAssets != null) {
            StoreInfo.setStoreAssets(storeAssets);
        }

        // Update SOOMLA store from DB
        StoreInfo.initializeFromDB();

        // Set up helper for the first time, querying and synchronizing inventory
        StoreUtils.LogDebug(TAG, "Querying and Synchronizing inventory ...");
        skuList = a_skuList;
        startIabHelper(new StoreController.OnIabStartedListener() {
            @Override
            public void onIabStarted() {
                StoreUtils.LogDebug(TAG, "Setup successful, consuming unconsumed items and handling refunds");
                mHelper.queryInventoryAsync(true, skuList, mPostInitQueryListener);
            }
        });

        mInitialized = true;
        BusProvider.getInstance().post(new StoreControllerInitializedEvent());

        return true;
    }

    public void startIabServiceInBg() {
        keepIabServiceOpen = true;
        startIabHelper(null);
    }

    public void stopIabServiceInBg() {
        keepIabServiceOpen = false;
        stopIabHelper();
    }

    /**
     * Initiate the restoreTransactions process
     * @{link #storeOpen} must be called before this method or your helper will be destroyed.
     */
    public void restoreTransactions() {
        startIabHelper(new OnIabStartedListener() {
            @Override
            public void onIabStarted() {
                mHelper.queryInventoryAsync(true, skuList, mPostInitQueryListener);
                BusProvider.getInstance().post(new RestoreTransactionsStartedEvent());
            }
        });
    }

    /**
     * Start a purchase process with Google Play.
     *
     * @param googleMarketItem is the item to purchase. This item has to be defined EXACTLY the same in Google Play.
     * @param payload a payload to get back when this purchase is finished.
     * @throws IllegalStateException
     */
    public void buyWithGooglePlay(GoogleMarketItem googleMarketItem, String payload) throws IllegalStateException {
        SharedPreferences prefs = new ObscuredSharedPreferences(SoomlaApp.getAppContext().getSharedPreferences(StoreConfig.PREFS_NAME, Context.MODE_PRIVATE));
        String publicKey = prefs.getString(StoreConfig.PUBLIC_KEY, "");
        if (publicKey.length() == 0 || publicKey.equals("[YOUR PUBLIC KEY FROM GOOGLE PLAY]")) {
            StoreUtils.LogError(TAG, "You didn't provide a public key! You can't make purchases.");
            throw new IllegalStateException();
        }

        try {
            final Intent intent = new Intent(SoomlaApp.getAppContext(), IabActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(PROD_ID, googleMarketItem.getProductId());
            intent.putExtra(EXTRA_DATA, payload);

            startIabHelper(new OnIabStartedListener() {
                @Override
                public void onIabStarted() {
                    SoomlaApp.getAppContext().startActivity(intent);
                }
            });
        } catch(Exception e){
        	StoreUtils.LogError(TAG, "(buyWithGooglePlay) Error purchasing item " + e.getMessage());
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(e.getMessage()));
        }
    }

    /**
     *  Used for internal starting of purchase with Google Play. Do *NOT* call this on your own.
     */
    // TODO: implement checking if item is already owned in google play
    private boolean buyWithGooglePlayInner(final Activity activity, final String sku, final String payload) {
        final PurchasableVirtualItem pvi;
        try {
            pvi = StoreInfo.getPurchasableItem(sku);
        } catch (VirtualItemNotFoundException e) {
            String msg = "Couldn't find a purchasable item associated with: " + sku;
            StoreUtils.LogError(TAG, msg);
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(msg));
            return false;
        }

        startIabHelper(new OnIabStartedListener() {
            @Override
            public void onIabStarted() {
                StoreUtils.LogDebug(TAG, "Trying to buy sku: " + sku);

                mHelper.launchPurchaseFlow(activity, sku, Consts.RC_REQUEST, mPurchaseFinishedListener, payload);
                BusProvider.getInstance().post(new PlayPurchaseStartedEvent(pvi));
            }
        });

        return true;
    }

    /**
     * Create a new IAB helper and set it up.
     *
     * @param onIabSetupFinishedListener is a callback that lets users to add their own implementation for when the Iab is started
     */
    private synchronized void startIabHelper(StoreController.OnIabStartedListener onIabSetupFinishedListener) {
        if(mHelper != null)
        {
            StoreUtils.LogDebug(TAG, "The helper is started. Just running the post start function.");
            if (onIabSetupFinishedListener != null) {
                onIabSetupFinishedListener.onIabStarted();
            }
            return;
        }

        StoreUtils.LogDebug(TAG, "Creating IAB helper.");
        mHelper = new IabHelper();

        StoreUtils.LogDebug(TAG, "IAB helper Starting setup.");
        mHelper.startSetup(onIabSetupFinishedListener);
    }

    /**
     * Dispose of the helper to prevent memory leaks
     */
    private synchronized void stopIabHelper() {
        if (keepIabServiceOpen) {
            StoreUtils.LogDebug(TAG, "Not stopping Iab Helper b/c the user run 'startIabServiceInBg'. Keeping it open.");
            return;
        }

        if (mHelper == null) {
            StoreUtils.LogError(TAG, "Tried to stop IAB Helper when it was null.");
            return;
        }

        if (!mHelper.isAsyncInProgress())
        {
            StoreUtils.LogDebug(TAG, "Stopping Iab helper");
            mHelperStop = false;
            mHelper.dispose();
            mHelper = null;
            BusProvider.getInstance().post(new IabServiceStoppedEvent());
        }
        else
        {
            String msg = "Cannot close store during async process. Will be stopped when async operation is finished.";
            mHelperStop = true;
            StoreUtils.LogDebug(TAG, msg);
//        	BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(msg));
        }
    }

    /* Callbacks for the IabHelper */

    /**
     * Check the state of the purchase and respond accordingly, giving the user an item,
     * throwing an error, or taking the item away and paying him back
     *
     * @param purchase
     */
    private void purchaseActionResultOk(Purchase purchase) {
        String sku = purchase.getSku();
        String developerPayload = purchase.getDeveloperPayload();
        StoreUtils.LogDebug(TAG, "developerPayload : " + developerPayload);

        PurchasableVirtualItem pvi;
        try {
            pvi = StoreInfo.getPurchasableItem(sku);
        } catch (VirtualItemNotFoundException e) {
            StoreUtils.LogError(TAG, "(purchaseActionResultOk - purchase or query-inventory) ERROR : Couldn't find the " +
                    " VirtualCurrencyPack OR GoogleMarketItem  with productId: " + sku +
                    ". It's unexpected so an unexpected error is being emitted.");
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent("Couldn't find the sku of a product after purchase or query-inventory."));
            return;
        }

        switch (purchase.getPurchaseState()) {
            case 0:
                StoreUtils.LogDebug(TAG, "Purchase successful.");
                BusProvider.getInstance().post(new PlayPurchaseEvent(pvi, purchase.getOriginalJson(), purchase.getSignature()));
                pvi.give(1);
                BusProvider.getInstance().post(new ItemPurchasedEvent(pvi));

                consumeIfConsumable(purchase);
                break;
            case 1:
            case 2:
                StoreUtils.LogDebug(TAG, "Purchase refunded.");
                if (!StoreConfig.friendlyRefunds) {
                    pvi.take(1);
                }
                BusProvider.getInstance().post(new PlayRefundEvent(pvi, developerPayload));
                break;
        }
    }

    /**
     * Post an event containing a PurchasableVirtualItem corresponding to the purchase,
     * or an unexpected error event if the item was not found.
     *
     * @param purchase
     */
    private void purchaseActionResultCancelled(Purchase purchase) {
        String sku = purchase.getSku();
        try {
            PurchasableVirtualItem v = StoreInfo.getPurchasableItem(sku);
            BusProvider.getInstance().post(new PlayPurchaseCancelledEvent(v));
        } catch (VirtualItemNotFoundException e) {
            StoreUtils.LogError(TAG, "(purchaseActionResultCancelled) ERROR : Couldn't find the " +
                    "VirtualCurrencyPack OR GoogleMarketItem  with productId: " + sku +
                    ". It's unexpected so an unexpected error is being emitted.");
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent());
        }
    }

    private void consumeIfConsumable(Purchase purchase) {
        String sku = purchase.getSku();
        try {
            PurchasableVirtualItem pvi = StoreInfo.getPurchasableItem(sku);

            if (!(pvi instanceof NonConsumableItem)) {
                mHelper.consume(purchase);
            }
        } catch (VirtualItemNotFoundException e) {
            StoreUtils.LogError(TAG, "(purchaseActionResultCancelled) ERROR : Couldn't find the " +
                    "VirtualCurrencyPack OR GoogleMarketItem  with productId: " + sku +
                    ". It's unexpected so an unexpected error is being emitted.");
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent());
        } catch (IabException e) {
            StoreUtils.LogDebug(TAG, "Error while consuming: " + sku);
            BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(e.getMessage()));
        }
    }

    /**
     * Post an unexpected error event saying the purchase failed.
     * @param result
     */
    private void purchaseActionResultUnexpected(IabResult result) {
        BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(result.getMessage()));
        StoreUtils.LogError(TAG, "ERROR: Purchase failed: " + result.getMessage());
    }

    /**
     * Wait to see if the purchase succeeded, then start the consumption process.
     */
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

            StoreUtils.LogDebug(TAG, "Purchase finished: " + result + ", purchase: " + purchase);
            if (result.getResponse() == IabHelper.BILLING_RESPONSE_RESULT_OK) {
                purchaseActionResultOk(purchase);
            } else if (result.getResponse() == IabHelper.BILLING_RESPONSE_RESULT_USER_CANCELED) {
                purchaseActionResultCancelled(purchase);
            } else {
                if (result.getResponse() == IabHelper.BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED) {
                    StoreUtils.LogDebug(TAG, "Tried to buy an item that was not consumed. Trying to consume it if it's non consumable.");
                    consumeIfConsumable(purchase);
                }

                purchaseActionResultUnexpected(result);
            }

            stopIabHelper();
        }
    };

    /**
     * Handle incomplete purchase and refund after initialization
     */
    IabHelper.QueryInventoryFinishedListener mPostInitQueryListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            StoreUtils.LogDebug(TAG, "gameegg : Query inventory succeeded");
            if (result.getResponse() == IabHelper.BILLING_RESPONSE_RESULT_OK) {
                List<String> itemSkus = inventory.getAllOwnedSkus(IabHelper.ITEM_TYPE_INAPP);
                StoreInfo.setInventory(inventory);
                for (String sku: itemSkus) {
                    Purchase purchase = inventory.getPurchase(sku);
                    purchaseActionResultOk(purchase);
                }
            } else {
                StoreUtils.LogError(TAG, "Query inventory error: " + result.getMessage());
                purchaseActionResultUnexpected(result);
            }

            BusProvider.getInstance().post(new RestoreTransactionsEvent(true));

            stopIabHelper();
        }
    };

    /**
     *  A wrapper to access IabHelper.handleActivityResult from outside
     */
    private boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
        return (mHelper != null) && mHelper.handleActivityResult(requestCode, resultCode, data);
    }

    /* Singleton */
    private static StoreController sInstance = null;

    public static StoreController getInstance() {
        if (sInstance == null) {
            sInstance = new StoreController();
        }
        return sInstance;
    }

    private StoreController() {
    }

    /* Private Members */
    private static final String PROD_ID    = "PRD#ID";
    private static final String EXTRA_DATA = "EXTR#DT";

    private static final String TAG = "SOOMLA StoreController";

    private boolean mInitialized   = false;
    private boolean keepIabServiceOpen = false;

    private IabHelper mHelper;
    private boolean mHelperStop = false;

    private abstract class OnIabStartedListener implements IabHelper.OnIabSetupFinishedListener {

        @Override
        public void onIabSetupFinished(IabResult result) {
            StoreUtils.LogDebug(TAG, "IAB helper Setup finished.");
            if (result.isFailure()) {
                String msg = "There's no connectivity with the billing service.";
                StoreUtils.LogDebug(TAG, msg);
                BusProvider.getInstance().post(new BillingNotSupportedEvent());
//                BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(msg));
                stopIabHelper();
                return;
            }

            BusProvider.getInstance().post(new BillingSupportedEvent());
            BusProvider.getInstance().post(new IabServiceStartedEvent());

            onIabStarted();
        }

        public abstract void onIabStarted();
    }
    /**
     * Android In-App Billing v3 requires and activity to receive the result of the billing process.
     * This activity's job is to do just that, it also contains the white/green IAB window.  Please
     * Do not start it on your own.
     */
    public static class IabActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Intent intent = getIntent();
            String productId = intent.getStringExtra(StoreController.PROD_ID);
            String payload = intent.getStringExtra(StoreController.EXTRA_DATA);

            try {
                if (!StoreController.getInstance().buyWithGooglePlayInner(this, productId, payload)) {
                    finish();
                }
            }catch (Exception e) {
                StoreUtils.LogError(TAG, "(onCreate) Error purchasing item " + e.getMessage());
                BusProvider.getInstance().post(new UnexpectedStoreErrorEvent(e.getMessage()));
                finish();
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			if (!StoreController.getInstance().handleActivityResult(requestCode, resultCode, data)) {
				super.onActivityResult(requestCode, resultCode, data);

                if (StoreController.getInstance().mHelper == null)
                {
                    StoreUtils.LogError(TAG, "helper is null in onActivityResult.");
                    BusProvider.getInstance().post(new UnexpectedStoreErrorEvent());
                }
            }

			finish();
        }
    }
}


text:
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint-env jest */
import setMeta from '../setMeta';

const TestField = 'testField';
const TestValue = 'testValue';
const TestValueGetter = () => TestValue;

describe('`setMeta`', () => {
  it('should return ActionEnhancer', () => {
    const enhancer = setMeta(TestField, TestValueGetter);
    expect(enhancer).toBeInstanceOf(Function);

    const enhancerFn = enhancer();
    expect(enhancerFn).toBeInstanceOf(Function);
  });

  it('should set specified field in `meta`', () => {
    const enhancer = setMeta(TestField, TestValueGetter)();
    const action = { meta: {} };

    enhancer(action);

    expect(action.meta[TestField]).toBe(TestValue);
  });

  it('should call getter with arguments', () => {
    const valueGetter = jest.fn(TestValueGetter);
    const enhancer = setMeta(TestField, valueGetter)();
    const action = { meta: {} };

    enhancer(action, 'arg1', 'arg2');

    expect(valueGetter).toBeCalledWith('arg1', 'arg2');
  });
});


text:
<?php

namespace Itsallagile\APIBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Itsallagile\CoreBundle\Document\Story;
use Itsallagile\APIBundle\Form\PartialUpdateSubscriber;

/**
 * Form for stories in the API
 */
abstract class ApiForm extends AbstractType
{
    protected $isUpdateForm = false;

    public function __construct($isUpdate = false)
    {
        $this->isUpdateForm = (bool)$isUpdate;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($this->isUpdateForm) {
            $subscriber = new PartialUpdateSubscriber($builder->getFormFactory());
            $builder->addEventSubscriber($subscriber);
        }
    }
}


text:
// Copyright 2014 Albert L. Hives
//
// 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.

namespace Hare.Tests
{
    using NUnit.Framework;
    using Scenario;

    [TestFixture]
    public class UserTests
    {
        [Test]
        public void Test()
        {
            var client = HareFactory.New(x =>
                                             {
                                                 x.ConnectTo("http://localhost:15672");
                                                 x.EnableLogging(y => y.Logger("HareDuLogger"));
                                             });
            var response = client.Factory<CreateNewUser>(x => x.Credentials("guest", "guest"))
                                 .New(x => x.User("haredu_2"))
                                 .With(x => x.Password("haredu"))
                                 .Having(x => x.Rights(s => s.Admin()))
                                 .On(x => x.VirtualHost("MyVirtualHostScenarioTest1"));

            Assert.IsTrue(response);
        }
    }
}


text:
def pytest_itemcollected(item):
    marks = getattr(item.module, '__PYTEST_MARK__', None)
    if marks is None:
        return
    if isinstance(marks, str):
        marks = [marks]
    for mark in marks:
        item.add_marker(mark)

# TODO: nicer output strings for git commit status
# see https://docs.pytest.org/en/latest/example/simple.html#post-process-test-reports-failures
#@pytest.hookimpl(tryfirst=True, hookwrapper=True)
#def pytest_runtest_makereport(item, call):i
#    pass
# Also possibly useful:  item.add_report_section


text:
module Jekyll

    # Jekyll-CleanTheWeb v0.1.0
    class CleanTheWebTag < Liquid::Tag

        def render(context)
            return "<!-- JEKYLL-CLEANTHEWEB CONFIGURATION MISSING -->" unless context['site'].has_key?('cleantheweb')

            if !context['site']['cleantheweb']['quiet'].nil? && context['site']['cleantheweb']['quiet']
                result = ""
            else
                result = "<!-- Jekyll-CleanTheWeb v0.1.0 by Sanjay Parekh -->\n"
            end

            # If cleantheweb disabled/false globally or for this page, then return immediately.
            return result if (context['site']['cleantheweb']['enable'].nil? || !context['site']['cleantheweb']['enable']) || ((context.has_key?('page') && context['page'].has_key?('cleantheweb') && context['page']['cleantheweb'].has_key?('enable')) && !context['page']['cleantheweb']['enable'])

            # If initial is set on the page, that has priority.  Otherwise grab the global value.  If neither exists, set to an empty string.
            if (context.has_key?('page') && context['page'].has_key?('cleantheweb') && context['page']['cleantheweb'].has_key?('initial'))
                initial = context['page']['cleantheweb']['initial']
            elsif (context.has_key?('site') && context['site'].has_key?('cleantheweb') && context['site']['cleantheweb'].has_key?('initial'))
                initial = context['site']['cleantheweb']['initial']
            else
                initial = ""
            end

            if context.has_key?('page') && context['page']['date'].nil?
                if initial.nil?
                    return result
                else
                    return result + "<meta name=\"ROBOTS\" content=\"" + initial + "\">"
                end
            end

            # If old is set on the page, that has priority.  Otherwise grab the global value.  If neither exists, set to an empty string.
            if (context.has_key?('page') && context['page'].has_key?('cleantheweb') && context['page']['cleantheweb'].has_key?('old'))
                old = context['page']['cleantheweb']['old']
            elsif (context.has_key?('site') && context['site'].has_key?('cleantheweb') && context['site']['cleantheweb'].has_key?('old'))
                old = context['site']['cleantheweb']['old']
            else
                old = ""
            end

            # If days_to_age is set on the page, that has priority.  Otherwise grab the global value.  If neither exists, set to zero.
            if (context.has_key?('page') && context['page'].has_key?('cleantheweb') && context['page']['cleantheweb'].has_key?('days_to_age'))
                days_to_age = context['page']['cleantheweb']['days_to_age'].to_i
            elsif (context.has_key?('site') && context['site'].has_key?('cleantheweb') && context['site']['cleantheweb'].has_key?('days_to_age'))
                days_to_age = context['site']['cleantheweb']['days_to_age'].to_i
            else
                days_to_age = 0
            end

            # If date is set on the page, use that as the date to switch instead of calculating based on the days_to_age variable.
            if (context.has_key?('page') && context['page'].has_key?('cleantheweb') && context['page']['cleantheweb'].has_key?('activate_date'))
                activate_date = Date.parse(context['page']['cleantheweb']['activate_date'].to_s)
            else
                activate_date = Date.parse(context['page']['date'].to_s) + days_to_age
            end

            if Date.today > activate_date
                result += "<meta name=\"ROBOTS\" content=\"" + old + "\">" if !old.nil?
            else
                result += "<meta name=\"ROBOTS\" content=\"" + initial + "\">" if !initial.nil?
            end

            return result

        end

    end
end

Liquid::Template.register_tag('cleantheweb', Jekyll::CleanTheWebTag)


text:
<!DOCTYPE html><title>README</title><link href="http://www.jboss.org/jdf/stylesheets/documentation.css" rel="stylesheet"></link><link href="http://www.jboss.org/jdf/stylesheets/pygments.css" rel="stylesheet"></link>

ejb-remote: Remote EJB Client Example

Author: Jaikiran Pai, Mike Musgrove

Level: Intermediate

Technologies: EJB

Summary: Shows how to access an EJB from a remote Java client program using JNDI

Target Product: EAP

Product Versions: EAP 6.1, EAP 6.2

Source: https://github.com/jboss-developer/jboss-eap-quickstarts/

What is it?

This example shows how to access an EJB from a remote Java client application. It demonstrates the use of EJB 3.1 and JNDI in Red Hat JBoss Enterprise Application Platform.

There are two components to this example:

A server side component:

The server component is comprised of a stateful EJB and a stateless EJB. It provides both an EJB JAR that is deployed to the server and a JAR file containing the remote business interfaces required by the remote client application.

A remote client application that accesses the server component.

The remote client application depends on the remote business interfaces from the server component. This application looks up the stateless and stateful beans via JNDI and invokes a number of methods on them.

Each component is defined in its own standalone Maven module. The quickstart provides a top level Maven module to simplify the packaging of the artifacts.

System requirements

The application this project produces is designed to be run on Red Hat JBoss Enterprise Application Platform 6.1 or later.

All you need to build this project is Java 6.0 (Java SDK 1.6) or later, Maven 3.0 or later.

Configure Maven

If you have not yet done so, you must Configure Maven before testing the quickstarts.

Start the JBoss Server

Open a command line and navigate to the root of the JBoss server directory.

The following shows the command line to start the server:

For Linux:   JBOSS_HOME/bin/standalone.sh
For Windows: JBOSS_HOME\bin\standalone.bat

Build and Deploy the Quickstart

Since this quickstart builds two separate components, you can not use the standard Build and Deploy commands used by most of the other quickstarts. You must follow these steps to build, deploy, and run this quickstart.

Make sure you have started the JBoss server. See the instructions in the previous section.

Open a command line and navigate to the ejb-remote quickstart directory

Build and install the server side component:

Navigate to the server-side subdirectory:

cd server-side

Build the EJB and client interfaces JARs and install them in your local Maven repository.

mvn clean install

Deploy the EJB JAR to your server. This maven goal will deploy server-side/target/jboss-ejb-remote-server-side.jar. You can check the JBoss server console to see information messages regarding the deployment.

mvn jboss-as:deploy

Build and run the client application

Navigate to the server-side subdirectory:

cd ../client

Compile the client code

mvn clean compile

Execute the client application within Maven

mvn exec:exec

Investigate the Console Output

When the client application runs, it performs the following steps:

Obtains a stateless session bean instance.

Sends method invocations to the stateless bean to add two numbers, and then displays the result.

Sends a second invocation to the stateless bean subtract two numbers, and then displays the result.

Obtains a stateful session bean instance.

Sends several method invocations to the stateful bean to increment a field in the bean, displaying the result each time.

Sends several method invocations to the stateful bean to decrement a field in the bean, displaying the result each time.

The output in the terminal window  will look like the following:

  Obtained a remote stateless calculator for invocation
  Adding 204 and 340 via the remote stateless calculator deployed on the server
  Remote calculator returned sum = 544
  Subtracting 2332 from 3434 via the remote stateless calculator deployed on the server
  Remote calculator returned difference = 1102
  Obtained a remote stateful counter for invocation
  Counter will now be incremented 5 times
  Incrementing counter
  Count after increment is 1
  Incrementing counter
  Count after increment is 2
  Incrementing counter
  Count after increment is 3
  Incrementing counter
  Count after increment is 4
  Incrementing counter
  Count after increment is 5
  Counter will now be decremented 5 times
  Decrementing counter
  Count after decrement is 4
  Decrementing counter
  Count after decrement is 3
  Decrementing counter
  Count after decrement is 2
  Decrementing counter
  Count after decrement is 1
  Decrementing counter
  Count after decrement is 0

Logging statements have been removed from this output here to make it clearer.

Build and Run The Quickstart as an Executable JAR

The remote client application can also be built as a standalone executable JAR with all of its dependencies.

Open a command line and navigate to the ejb-remote/client quickstart directory

cd client

Type the following in the command line:

mvn clean assembly:assembly

You can then run the executable JAR using the java -jar command. You will see the same console output as above.

java -jar target/jboss-ejb-remote-client-jar-with-dependencies.jar

Undeploy the Archive

To undeploy the server side component from the JBoss server:

Navigate to the server-side subdirectory:

cd ../server-side

Type the following command:

mvn jboss-as:undeploy

Run the Quickstart in JBoss Developer Studio or Eclipse

You can also start the server and deploy the quickstarts from Eclipse using JBoss tools. For more information, see Use JBoss Developer Studio or Eclipse to Run the Quickstarts

Debug the Application

If you want to debug the source code or look at the Javadocs of any library in the project, run either of the following commands to pull them into your local repository. The IDE should then detect them.

    mvn dependency:sources
    mvn dependency:resolve -Dclassifier=javadoc


text:
namespace Database.Entity
{
    using System;
    using System.Collections.Generic;

    public partial class Misc
    {
        public string DbViewerPw { get; set; }
        public int TimersCreated { get; set; }
        public int RemindersCreated { get; set; }
        public int ExportCount { get; set; }
        public int ImportCount { get; set; }
        public int MessageCount { get; set; }
        public int Id { get; set; }
        public int RecoverCount { get; set; }
        public int PreviewCount { get; set; }
        public int DuplicateCount { get; set; }
        public int HideCount { get; set; }
        public int PostponeCount { get; set; }
        public int SkipCount { get; set; }
        public int PermanentelyDeleteCount { get; set; }
    }
}


text:
#include "bulkDataSenderEx1Impl.h"

using namespace ACSBulkDataError;

BulkDataSenderEx1Impl::BulkDataSenderEx1Impl(const ACE_CString& name,maci::ContainerServices* containerServices) :
    BulkDataSenderDefaultImpl(name,containerServices)
{
    ACS_TRACE("BulkDataSenderEx1Impl::BulkDataSenderEx1Impl");
}

BulkDataSenderEx1Impl::~BulkDataSenderEx1Impl()
{
    ACS_TRACE("BulkDataSenderEx1Impl::~BulkDataSenderEx1Impl");
}

void BulkDataSenderEx1Impl::startSend()
{
    ACS_TRACE("BulkDataSenderEx1Impl::startSend");

    try
	{
	int size;

	/******************************** flow 1 *********************************/

	size = 10000;

	ACE_Message_Block *mb1;
	mb1 = new ACE_Message_Block(size);

	for (CORBA::Long j = 0; j < (size-1); j++)
	    {
	    *mb1->wr_ptr()='p';
	    mb1->wr_ptr(sizeof(char));
	    }
	*mb1->wr_ptr()='\0';
	mb1->wr_ptr(sizeof(char));

	CORBA::ULong flowNumber = 1;
	getSender()->startSend(flowNumber, mb1);

	ACS_SHORT_LOG ((LM_DEBUG,"flow 1 length start parameter sent = %d", mb1->length()));

	mb1->release();

	/******************************** flow 2 *********************************/

	size = 12000;

	char *buf = 0;
	buf = new char[size];
	for(CORBA::Long j = 0; j < (size-1); j++)
	    {
	    buf[j]='1';
	    }
	buf[size-1] = '\0';

	flowNumber = 2;
	getSender()->startSend(flowNumber, buf, size);

	ACS_SHORT_LOG ((LM_DEBUG,"flow 2 length start parameter sent = %d", size));

	delete [] buf;

	/******************************** flow 3 *********************************/

	size = 256;

	char fileName[size];

	ACE_OS::strcpy(fileName, "bulkDataOutput.txt");

	const char * ptr = fileName;

	flowNumber = 3;
	getSender()->startSend(flowNumber,ptr,size);

	ACS_SHORT_LOG ((LM_DEBUG,"flow 3 start parameter sent = %s", fileName));

	/******************************** flow 4 *********************************/

	flowNumber = 4;
	getSender()->startSend(flowNumber);
	}

    catch (AVInvalidFlowNumberExImpl & ex)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::startSend AVInvalidFlowNumberExImpl exception catched !"));
	AVStartSendErrorExImpl err = AVStartSendErrorExImpl(ex,__FILE__,__LINE__,"BulkDataSenderImpl::startSend");
	throw err.getAVStartSendErrorEx();
	}
    catch (AVSendFrameErrorExImpl & ex)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::startSend AVSendFrameErrorExImpl exception catched !"));
	AVStartSendErrorExImpl err = AVStartSendErrorExImpl(ex,__FILE__,__LINE__,"BulkDataSenderImpl::startSend");
	throw err.getAVStartSendErrorEx();
	}
    catch (AVFlowEndpointErrorExImpl & ex)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::startSend  AVFlowEndpointErrorExImplexception catched !"));
	AVStartSendErrorExImpl err = AVStartSendErrorExImpl(ex,__FILE__,__LINE__,"BulkDataSenderImpl::startSend");
	throw err.getAVStartSendErrorEx();
	}
    catch (AVProtocolErrorExImpl & ex)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::startSend  AVProtocolErrorExImplexception catched !"));
	AVStartSendErrorExImpl err = AVStartSendErrorExImpl(ex,__FILE__,__LINE__,"BulkDataSenderImpl::startSend");
	throw err.getAVStartSendErrorEx();
	}
    catch (...)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::startSend UNKNOWN exception"));
	AVStartSendErrorExImpl err = AVStartSendErrorExImpl(__FILE__,__LINE__,"BulkDataSenderImpl::startSend");
	throw err.getAVStartSendErrorEx();
	}
}

void BulkDataSenderEx1Impl::paceData()
{
    ACS_TRACE("BulkDataSenderImpl::paceData");

    try
	{
	int size;
	CORBA::ULong flowNumber;

	/******************************** flow 1 *********************************/

	size = 14000000;

	ACE_Message_Block *mb1;
	mb1 = new ACE_Message_Block(size);

	for (CORBA::Long j = 0; j < (size-1); j++)
	    {
	    *mb1->wr_ptr()='d';
	    mb1->wr_ptr(sizeof(char));
	    }
	*mb1->wr_ptr()='\0';
	mb1->wr_ptr(sizeof(char));

	flowNumber = 1;
	getSender()->sendData(flowNumber, mb1);

	ACS_SHORT_LOG ((LM_DEBUG,"flow 1 length sent data = %d", mb1->length()));

	mb1->release();

	/******************************** flow 2 *********************************/

	size = 12000000;

	char *buf = 0;
	buf = new char[size];
	for(CORBA::Long j = 0; j < (size-1); j++)
	    {
	    buf[j]='2';
	    }
	buf[size-1] = '\0';

	flowNumber = 2;
	getSender()->sendData(flowNumber, buf, size);

	ACS_SHORT_LOG ((LM_DEBUG,"flow 2 length sent data = %d", size));

	delete [] buf;

	/******************************** flow 3 *********************************/

	ACE_Message_Block mb(BUFSIZ);

	FILE * fp = ACE_OS::fopen("bulkDataInput.txt","r");
	if (fp == 0)
	    {
	    ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl<>::paceData file not open successfully"));
	    AVCouldNotOpenFileExImpl err = AVCouldNotOpenFileExImpl(__FILE__,__LINE__,"BulkDataSenderImpl::paceData");
	    throw err;
	    }

	// Continue to send data till the file is read to the end.
	while (1)
	    {
	    // Read from the file into a message block.
	    int n = ACE_OS::fread(mb.rd_ptr (),
				  1,
				  mb.size (),
				  fp);

	    if (n < 0)
		{
		ACS_SHORT_LOG((LM_DEBUG," BulkDataSenderImpl<>::paceData sending file"));
		break;
		}

	    if (n == 0)
		{
		if (feof (fp))
		    {
		    // At end of file break the loop and end the client.
		    ACS_SHORT_LOG((LM_DEBUG,"BulkDataSenderImpl<>::paceData end of file"));
		    break;
		    }
		}

	    mb.wr_ptr (n);

	    flowNumber = 3;
	    getSender()->sendData(flowNumber,&mb);

	    ACS_SHORT_LOG ((LM_DEBUG,"flow 3 file bulkDatainput.txt sent"));

	    // Reset the mb.
	    mb.reset ();
	    } // end while

	// Close the input file
	ACE_OS::fclose(fp);

	/******************************** flow 4 *********************************/

	size = 37000000;

	ACE_Message_Block *mb2;
	mb2 = new ACE_Message_Block(size);

	for (CORBA::Long j = 0; j < (size-1); j++)
	    {
	    *mb2->wr_ptr()='d';
	    mb2->wr_ptr(sizeof(char));
	    }
	*mb2->wr_ptr()='\0';
	mb2->wr_ptr(sizeof(char));

	flowNumber = 4;
	getSender()->sendData(flowNumber, mb2);

	ACS_SHORT_LOG ((LM_DEBUG,"flow 4 length sent data = %d", mb2->length()));

	mb2->release();
	}

    catch (AVInvalidFlowNumberExImpl & ex)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::paceData AVInvalidFlowNumberExImpl exception catched !"));
	AVPaceDataErrorExImpl err = AVPaceDataErrorExImpl(ex,__FILE__,__LINE__,"BulkDataSenderImpl::paceData");
	throw err.getAVPaceDataErrorEx();
	}
    catch (AVSendFrameErrorExImpl & ex)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::paceData AVSendFrameErrorExImpl exception catched !"));
	AVPaceDataErrorExImpl err = AVPaceDataErrorExImpl(ex,__FILE__,__LINE__,"BulkDataSenderImpl::paceData");
	throw err.getAVPaceDataErrorEx();
	}
    catch (AVCouldNotOpenFileExImpl & ex)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::paceData AVCouldNotOpenFileExImpl exception catched !"));
	AVPaceDataErrorExImpl err = AVPaceDataErrorExImpl(ex,__FILE__,__LINE__,"BulkDataSenderImpl::paceData");
	throw err.getAVPaceDataErrorEx();
	}
    catch (...)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::paceData UNKNOWN exception"));
	AVPaceDataErrorExImpl err = AVPaceDataErrorExImpl(__FILE__,__LINE__,"BulkDataSenderImpl::paceData");
	throw err.getAVPaceDataErrorEx();
	}
}

void BulkDataSenderEx1Impl::stopSend()
{
    ACS_TRACE("BulkDataSenderImpl::stopSend");

    try
	{
	CORBA::ULong flowNumber = 1;
	getSender()->stopSend(flowNumber);

	flowNumber = 2;
	getSender()->stopSend(flowNumber);

	flowNumber = 3;
	getSender()->stopSend(flowNumber);

	flowNumber = 4;
	getSender()->stopSend(flowNumber);
	}

    catch (AVInvalidFlowNumberExImpl & ex)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::stopSend AVInvalidFlowNumberExImpl exception catched !"));
	AVStopSendErrorExImpl err = AVStopSendErrorExImpl(ex,__FILE__,__LINE__,"BulkDataSenderImpl::stopSend");
	throw err.getAVStopSendErrorEx();
	}
    catch (...)
	{
	ACS_SHORT_LOG((LM_INFO,"BulkDataSenderImpl::stopSend UNKNOWN exception"));
	AVStopSendErrorExImpl err = AVStopSendErrorExImpl(__FILE__,__LINE__,"BulkDataSenderImpl::stopSend");
	throw err.getAVStopSendErrorEx();
	}
}

/* --------------- [ MACI DLL support functions ] -----------------*/
#include <maciACSComponentDefines.h>
MACI_DLL_SUPPORT_FUNCTIONS(BulkDataSenderEx1Impl)
/* ----------------------------------------------------------------*/


text:
zend_class_entry *gdal_gdaldataset_ce;
zend_object_handlers gdaldataset_object_handlers;

//
// PHP stuff
//

void gdaldataset_free_storage(void *object TSRMLS_DC)
{
  char *msg;
  int i;
  php_gdaldataset_object *obj = (php_gdaldataset_object *)object;

  obj->dataset->Dereference();
  zend_hash_destroy(obj->std.properties);
  FREE_HASHTABLE(obj->std.properties);
  efree(obj);
}

zend_object_value gdaldataset_create_handler(zend_class_entry *type TSRMLS_DC)
{
  zval *tmp;
  zend_object_value retval;

  php_gdaldataset_object *obj =
    (php_gdaldataset_object *)emalloc(sizeof(php_gdaldataset_object));
  memset(obj, 0, sizeof(php_gdaldataset_object));
  obj->std.ce = type;

  ALLOC_HASHTABLE(obj->std.properties);
  zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
#if PHP_VERSION_ID < 50399
  zend_hash_copy(obj->std.properties, &type->default_properties,
                 (copy_ctor_func_t)zval_add_ref,
                 (void *)&tmp, sizeof(zval *));
#else
  object_properties_init(&obj->std, type);
#endif

  retval.handle =
    zend_objects_store_put(obj, NULL,
                           gdaldataset_free_storage, NULL TSRMLS_CC);
  retval.handlers = &gdaldataset_object_handlers;

  return retval;

  //pdo_stmt_construct(stmt, return_value, dbstmt_ce, ctor_args TSRMLS_CC);

}

//
// CLASS METHODS
//

PHP_METHOD(GDALDataset, GetRasterXSize)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  RETURN_LONG(dataset->GetRasterXSize());
}

PHP_METHOD(GDALDataset, GetRasterYSize)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  RETURN_LONG(dataset->GetRasterYSize());
}

PHP_METHOD(GDALDataset, GetRasterCount)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  RETURN_LONG(dataset->GetRasterCount());
}

PHP_METHOD(GDALDataset, FlushCache)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  dataset->FlushCache();
}

PHP_METHOD(GDALDataset, GetProjectionRef)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  const char *ref = dataset->GetProjectionRef();
  if (ref) {
    RETURN_STRING((char *)ref, 1);
  } else {
    RETURN_NULL();
  }
}

PHP_METHOD(GDALDataset, SetProjection)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;
  char *ref;
  int ref_len;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s",
                            &ref, &ref_len) == FAILURE) {
    return;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  RETURN_LONG(dataset->SetProjection(ref));
}

PHP_METHOD(GDALDataset, GetGeoTransform)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;
  double d;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"d",
                            &d) == FAILURE) {
    return;
  }
  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;

  RETURN_LONG(dataset->GetGeoTransform(&d));
}

PHP_METHOD(GDALDataset, SetGeoTransform)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;
  double d;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"d",
                            &d) == FAILURE) {
    return;
  }
  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;

  RETURN_LONG(dataset->SetGeoTransform(&d));
}

PHP_METHOD(GDALDataset, GetDriver)
{
  GDALDataset *dataset;
  GDALDriver *driver;
  php_gdaldataset_object *obj;
  php_gdaldriver_object *driver_obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  driver = dataset->GetDriver();
  if (!driver) {
    RETURN_NULL();
  }
  if (object_init_ex(return_value, gdal_gdaldriver_ce) != SUCCESS) {
    RETURN_NULL();
  }
  driver_obj = (php_gdaldriver_object*)
    zend_object_store_get_object(return_value TSRMLS_CC);
  driver_obj->driver = driver;
}

PHP_METHOD(GDALDataset, GetGCPCount)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  RETURN_LONG(dataset->GetGCPCount());
}

PHP_METHOD(GDALDataset, CreateMaskBand)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;
  long nFlags;

  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l",
                            &nFlags) == FAILURE) {
    return;
  }
  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;

  RETURN_LONG(dataset->CreateMaskBand(nFlags));
}

PHP_METHOD(GDALDataset, Reference)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  RETURN_LONG(dataset->Reference());
}

PHP_METHOD(GDALDataset, Dereference)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  RETURN_LONG(dataset->Dereference());
}

PHP_METHOD(GDALDataset, GetShared)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  RETURN_LONG(dataset->GetShared());
}

PHP_METHOD(GDALDataset, MarkAsShared)
{
  GDALDataset *dataset;
  php_gdaldataset_object *obj;

  if (ZEND_NUM_ARGS() != 0) {
    WRONG_PARAM_COUNT;
  }

  obj = (php_gdaldataset_object *)
    zend_object_store_get_object(getThis() TSRMLS_CC);
  dataset = obj->dataset;
  dataset->MarkAsShared();
}

//
// PHP stuff
//

zend_function_entry gdaldataset_methods[] = {
  PHP_ME(GDALDataset, GetRasterXSize, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, GetRasterYSize, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, GetRasterCount, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, GetRasterBand, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, FlushCache, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, GetProjectionRef, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, SetProjection, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, GetGeoTransform, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, SetGeoTransform, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, AddBand, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, GetDriver, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, GetFileList, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, GetGCPCount, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, GetGCPProjection, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, GetGCPs, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, SetGCPs, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, AdviseRead, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, CreateMaskBand, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, BeginAsyncReader, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, EndAsyncReader, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, RasterIO, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, Reference, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, Dereference, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, GetAccess, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, GetShared, NULL, ZEND_ACC_PUBLIC)
  PHP_ME(GDALDataset, MarkAsShared, NULL, ZEND_ACC_PUBLIC)
  // PHP_ME(GDALDataset, GetOpenDatasets, NULL, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
  // PHP_ME(GDALDataset, BuildOverviews, NULL, ZEND_ACC_PUBLIC)
  {NULL, NULL, NULL}
};

void php_gdal_gdaldataset_startup(INIT_FUNC_ARGS)
{
  zend_class_entry ce;
  INIT_CLASS_ENTRY(ce, "GDALDataset", gdaldataset_methods);
  gdal_gdaldataset_ce = zend_register_internal_class(&ce TSRMLS_CC);
  gdal_gdaldataset_ce->create_object = gdaldataset_create_handler;
  memcpy(&gdaldataset_object_handlers,
         zend_get_std_object_handlers(), sizeof(zend_object_handlers));
  gdaldataset_object_handlers.clone_obj = NULL;
}


text:
package eventstore
package core
package settings

import java.net.InetSocketAddress
import scala.concurrent.duration._
import ScalaCompat.JavaConverters._
import com.typesafe.config.Config
import syntax._
import cluster.GossipSeedsOrDns

/**
 * Contains settings relating to a connection to a cluster.
 *
 * @param gossipSeedsOrDns Gossip seeds or DNS settings
 * @param dnsLookupTimeout The time given to resolve dns
 * @param maxDiscoverAttempts Maximum number of attempts for discovering endpoints
 * @param discoverAttemptInterval The interval between cluster discovery attempts
 * @param discoveryInterval The interval at which to keep discovering cluster
 * @param gossipTimeout Timeout for cluster gossip.
 */
@SerialVersionUID(1L)
final case class ClusterSettings(
    gossipSeedsOrDns:        GossipSeedsOrDns = GossipSeedsOrDns.GossipSeeds("127.0.0.1" :: 2113),
    dnsLookupTimeout:        FiniteDuration   = 2.seconds,
    maxDiscoverAttempts:     Int              = 10,
    discoverAttemptInterval: FiniteDuration   = 500.millis,
    discoveryInterval:       FiniteDuration   = 1.second,
    gossipTimeout:           FiniteDuration   = 1.second
) {
  require(maxDiscoverAttempts >= 1, s"maxDiscoverAttempts must be >= 1, but is $maxDiscoverAttempts")
}

object ClusterSettings {

  def opt(conf: Config): Option[ClusterSettings] = {
    def opt(conf: Config) = {
      def option[T](path: String, f: String => T): Option[T] = {
        if (conf hasPath path) Option(f(path)) else None
      }

      def clusterDns = option("dns", conf.getString).map { dns =>
        GossipSeedsOrDns(
          clusterDns = dns,
          externalGossipPort = conf getInt "external-gossip-port"
        )
      }

      def gossipSeeds = option("gossip-seeds", conf.getStringList).flatMap { ss =>
        if (ss.isEmpty) None
        else {
          val seeds = ss.asScala.map { s =>
            s.split(":") match {
              case Array(host, port) => new InetSocketAddress(host, port.toInt)
              case _                 => sys.error(s"Cannot parse address from $s, expected format is host:port")
            }
          }
          Some(GossipSeedsOrDns.GossipSeeds(seeds.toList))
        }
      }

      (clusterDns orElse gossipSeeds).map { gossipSeedsOrDns =>
        ClusterSettings(
          gossipSeedsOrDns =        gossipSeedsOrDns,
          dnsLookupTimeout =        conf duration "dns-lookup-timeout",
          maxDiscoverAttempts =     conf getInt "max-discover-attempts",
          discoverAttemptInterval = conf duration "discover-attempt-interval",
          discoveryInterval =       conf duration "discovery-interval",
          gossipTimeout =           conf duration "gossip-timeout"
        )
      }
    }
    opt(conf getConfig "eventstore.cluster")
  }
}