text:
import logging
import typing

import discord
from asyncpg.exceptions import PostgresError
from discord.ext import commands
from discord.ext.commands import BucketType, has_permissions

from bot.bot import command, group, cooldown
from bot.converters import CommandConverter
from bot.formatter import Paginator
from bot.globals import BlacklistTypes, PermValues
from cogs.cog import Cog
from utils.utilities import (split_string, send_paged_message)

logger = logging.getLogger('terminal')
perms = discord.Permissions(8)

class CommandBlacklist(Cog):
    def __init__(self, bot):
        super().__init__(bot)

    @group(no_pm=True, invoke_without_command=True)
    @has_permissions(administrator=True)
    @cooldown(1, 5, type=BucketType.guild)
    async def blacklist(self, ctx, commands_: commands.Greedy[CommandConverter] = None,
                        *, mention: typing.Union[discord.TextChannel, discord.Role, discord.User] = None):
        """Blacklist a command for a user, role or channel
        To blacklist multiple commands at the same time wrap the command names in quotes
        like this {prefix}{name} \"command1 command2 command3\" #channel
        The hierarchy of `blacklist` and `whitelist` is as follows
        Whitelist always overrides blacklist of the same level

        Then levels of scope it can have are as follows
        `User` > `Role` > `Channel` > `Server` where each level overrides every scope perm after it
        e.g. Blacklisting command ping for role Member and whitelisting it for role Mod
        would make it so people with Member role wouldn't be able to use it unless they had Mod role

        Also if you further whitelisted ping from a single member
        that user would be able to use the command always
        since user whitelist overrides every other scope

        To blacklist a command server wide specify the commands and don't specify the mention param
        like this `{prefix}blacklist "cmd1 cmd2 etc"` which would blacklist those commands
        for everyone in the server unless they have it whitelisted
        Whitelisting server wide isn't possible

        For dangers of whitelisting see `{prefix}help whitelist`"""
        guild = ctx.guild

        if not commands_ and mention is None:
            return await ctx.send('No parameters given')

        async def _blacklist(name):
            if mention is None:
                whereclause = "guild=$1 AND type IN (%s, %s) AND command=$2 AND channel IS NULL AND role IS NULL AND uid IS NULL" % (
                               BlacklistTypes.BLACKLIST, BlacklistTypes.WHITELIST)
                success = await self._set_blacklist(ctx, whereclause, guild=guild.id, command=name)
                if success:
                    return 'Blacklisted command {} from this server'.format(name)
                elif success is None:
                    return 'Removed blacklist for command {} on this server'.format(name)

            elif isinstance(mention, discord.User):
                return await self._add_user_blacklist(ctx, name, mention, guild)

            elif isinstance(mention, discord.Role):
                return await self._add_role_blacklist(ctx, name, mention, guild)

            elif isinstance(mention, discord.TextChannel):
                return await self._add_channel_blacklist(ctx, name, mention, guild)

        s = ''
        if commands_ is None:
            val = await self._set_all_commands(ctx, mention)
            if isinstance(val, str):
                s += val
        else:
            for command_ in commands_:
                if command_.name == 'privacy':
                    await ctx.send("Cannot blacklist privacy command as it's required that anyone can see it")
                    continue

                val = await _blacklist(command_.name)
                if isinstance(val, str):
                    s += val + '\n'

        if not s:
            return

        for msg in split_string(s, splitter='\n'):
            await ctx.send(msg)

    @blacklist.command(no_pm=True)
    @has_permissions(administrator=True)
    async def toggle(self, ctx):
        """
        Disable all commands on this server (owner will still be able to use them)
        Whitelisting commands also overrides this rule
        Won't override existing commands that have been blacklisted so when you toggle
        again the commands that have been specifically blacklisted are still blacklisted
        """

        guild = ctx.guild
        values = {'command': None, 'guild': guild.id, 'type': BlacklistTypes.BLACKLIST}
        where = 'guild=%s AND command IS NULL AND NOT type=%s AND uid IS NULL AND role IS NULL AND channel IS NULL' % (guild.id, BlacklistTypes.GLOBAL)
        success = await self._set_blacklist(ctx, where, (), **values)
        if success:
            msg = 'All commands disabled on this server for non whitelisted users'
        elif success is None:
            msg = 'Commands are usable on this server again'
        else:
            return

        await ctx.send(msg)

    async def _set_all_commands(self, ctx, scope, type=BlacklistTypes.BLACKLIST):
        guild = ctx.guild
        values = {'command': None, 'guild': guild.id, 'type': type}
        where = 'guild=%s AND command IS NULL AND NOT type=%s AND ' % (guild.id, BlacklistTypes.GLOBAL)
        type_string = 'Blacklisted' if type == BlacklistTypes.BLACKLIST else 'Whitelisted'
        type_string2 = 'blacklist' if type == BlacklistTypes.BLACKLIST else 'whitelist'
        message = None
        if isinstance(scope, discord.User):
            userid = scope.id
            success = await self._set_blacklist(ctx, where + 'uid=%s' % userid, (), uid=userid, **values)
            if success:
                message = f'{type_string} all commands for user {scope} `{userid}`'
            elif success is None:
                message = f'removed {type_string2} from user {scope}, `{userid}`'

        elif isinstance(scope, discord.Role):
            success = await self._set_blacklist(ctx, where + 'role=%s' % scope.id, (), role=scope.id, **values)
            if success:
                message = '{0} all commands from role {1} `{1.id}`'.format(type_string, scope)
            elif success is None:
                message = 'Removed {0} from role {1} `{1.id}`'.format(type_string2, scope)

        elif isinstance(scope, discord.TextChannel):
            success = await self._set_blacklist(ctx, where + 'channel=%s' % scope.id, (),
                                                channel=scope.id, **values)
            if success:
                message = '{0} all commands from channel {1} `{1.id}`'.format(type_string, scope)
            elif success is None:
                message = 'Removed {0} from channel {1} `{1.id}`'.format(type_string2, scope)

        else:
            return 'No valid mentions'

        return message

    @command(no_pm=True)
    @has_permissions(administrator=True)
    @cooldown(1, 5, type=BucketType.guild)
    async def whitelist(self, ctx, commands_: commands.Greedy[CommandConverter], *, mention: typing.Union[discord.TextChannel, discord.Role, discord.User]):
        """Whitelist a command for a user, role or channel
        To whitelist multiple commands at the same time wrap the command names in quotes
        like this {prefix}{name} \"command1 command2 command3\" #channel

        To see specifics on the hierarchy of whitelist/blacklist see `{prefix}help blacklist`

        **WHITELISTING COULD BE DANGEROUS IF YOU DON'T KNOW WHAT YOU ARE DOING!**
        Before whitelisting read the following

        Whitelisting WILL OVERRIDE ANY REQUIRED PERMS for the command being called
        If a command requires ban perms and you whitelist it for a role
        everyone with that role can use that command even when they don't have ban perms

        Due to safety reasons whitelisting commands from this module is not allowed.
        Give the users correct discord perms instead
        """
        msg = ctx.message
        guild = msg.guild

        async def _whitelist(_command):
            name = _command.name
            if _command.cog_name == self.__class__.__name__:
                return f"Due to safety reasons commands from {_command.cog_name} module can't be whitelisted"

            elif isinstance(mention, discord.User):
                return await self._add_user_whitelist(ctx, name, mention, guild)

            elif isinstance(mention, discord.Role):
                return await self._add_role_whitelist(ctx, name, mention, guild)

            elif isinstance(mention, discord.TextChannel):
                return await self._add_channel_whitelist(ctx, name, mention, guild)

        s = ''
        for command_ in commands_:
            val = await _whitelist(command_)
            if isinstance(val, str):
                s += val + '\n'

        if not s:
            return

        for msg in split_string(s, splitter='\n'):
            await ctx.send(msg)

    async def _set_blacklist(self, ctx, whereclause, whereargs=None, type_=BlacklistTypes.BLACKLIST, **values):
        """
        Args:
            ctx: Context object that error messages can be sent to
            whereclause: The whereclause to search records
            whereargs: Args that are used in the whereclause. If not defined
                       values.values() will be used
            type_:
            **values: Keyword values that are used to set database columns
                      Uses the format column name=column value

        Returns:
            True when new permissions are set
            None when permission is removed. e.g. blacklist to no blacklist
            False when operation failed
        """
        type_string = 'blacklist' if type_ == BlacklistTypes.BLACKLIST else 'whitelist'
        sql = 'SELECT id, type FROM command_blacklist WHERE %s' % whereclause
        whereargs = whereargs if whereargs is not None else values.values()

        try:
            row = await self.bot.dbutil.fetch(sql, whereargs, fetchmany=False)
        except PostgresError:
            logger.exception('Failed to remove blacklist')
            await ctx.send('Failed to remove %s' % type_string)
            return False

        if row:
            if row['type'] == type_:
                sql = 'DELETE FROM command_blacklist WHERE %s' % whereclause
                try:
                    await self.bot.dbutil.execute(sql, whereargs)
                except PostgresError:
                    logger.exception(f'Could not update {type_string} with whereclause {whereclause}')
                    await ctx.send(f'Failed to remove {type_string}')
                    return False
                else:
                    return
            else:
                sql = 'UPDATE command_blacklist SET type=$1 WHERE id=$2'
                try:
                    await self.bot.dbutil.execute(sql, (type_, row['id']))
                except PostgresError:
                    logger.exception(f'Could not update {type_string} with whereclause {whereclause}')
                    await ctx.send(f'Failed to remove {type_string}')
                    return False
                else:
                    return True
        else:
            # Dynamically create a insert that looks like this
            # INSERT INTO command_blacklist (v1, v2, v3) VALUES ($1, $2, $3)
            sql = 'INSERT INTO command_blacklist ('
            values['type'] = type_
            keys = values.keys()
            val = '('
            l = len(keys)
            for idx, k in enumerate(keys):
                sql += '"%s"' % k
                val += '$%s' % (idx + 1)
                if idx != l - 1:
                    sql += ', '
                    val += ', '

            sql += ') VALUES ' + val + ')'
            try:
                await self.bot.dbutil.execute(sql, values.values())
            except PostgresError:
                logger.exception(f'Could not set values {values}')
                await ctx.send(f'Failed to set {type_string}')
                return False

        return True

    async def _add_user_blacklist(self, ctx, command_name, user, guild):
        whereclause = 'guild=$1 AND command=$2 AND uid=$3 AND NOT type=$4'
        success = await self._set_blacklist(ctx, whereclause, guild=guild.id,
                                            command=command_name,
                                            uid=user.id,
                                            type=BlacklistTypes.GLOBAL)
        if success:
            return 'Blacklisted command {0} from user {1} `{1.id}`'.format(command_name, user)
        elif success is None:
            return 'Removed command {0} blacklist from user {1} `{1.id}`'.format(command_name, user)

    async def _add_role_blacklist(self, ctx, command_name, role, guild):
        whereclause = 'guild=$1 AND command=$2 AND role=$3 AND NOT type=$4'
        success = await self._set_blacklist(ctx, whereclause, guild=guild.id,
                                            command=command_name,
                                            role=role.id,
                                            type=BlacklistTypes.GLOBAL)
        if success:
            return 'Blacklisted command {0} from role {1} `{1.id}`'.format(command_name, role)
        elif success is None:
            return 'Removed command {0} blacklist from role {1} `{1.id}`'.format(command_name, role)

    async def _add_channel_blacklist(self, ctx, command_name, channel, guild):
        whereclause = 'guild=$1 AND command=$2 AND channel=$3 AND NOT type=$4'
        success = await self._set_blacklist(ctx, whereclause, guild=guild.id,
                                            command=command_name,
                                            channel=channel.id,
                                            type=BlacklistTypes.GLOBAL)
        if success:
            return 'Blacklisted command {0} from channel {1} `{1.id}`'.format(command_name, channel)
        elif success is None:
            return 'Removed command {0} blacklist from channel {1} `{1.id}`'.format(command_name, channel)

    async def _add_user_whitelist(self, ctx, command_name, user, guild):
        whereclause = 'guild=$1 AND command=$2 AND uid=$3 AND NOT type=$4'
        success = await self._set_blacklist(ctx, whereclause,
                                            type_=BlacklistTypes.WHITELIST,
                                            guild=guild.id,
                                            command=command_name,
                                            uid=user.id,
                                            type=BlacklistTypes.GLOBAL)
        if success:
            return 'Whitelisted command {0} from user {1} `{1.id}`'.format(command_name, user)
        elif success is None:
            return 'Removed command {0} whitelist from user {1} `{1.id}`'.format(command_name, user)

    async def _add_role_whitelist(self, ctx, command_name, role, guild):
        whereclause = 'guild=$1 AND command=$2 AND role=$3 AND NOT type=$4'
        success = await self._set_blacklist(ctx, whereclause,
                                            type_=BlacklistTypes.WHITELIST,
                                            guild=guild.id,
                                            command=command_name,
                                            role=role.id,
                                            type=BlacklistTypes.GLOBAL)
        if success:
            return 'Whitelisted command {0} from role {1} `{1.id}`'.format(command_name, role)
        elif success is None:
            return 'Removed command {0} whitelist from role {1} `{1.id}`'.format(command_name, role)

    async def _add_channel_whitelist(self, ctx, command_name, channel, guild):
        whereclause = 'guild=$1 AND command=$2 AND channel=$3 AND NOT type=$4'
        success = await self._set_blacklist(ctx, whereclause,
                                            type_=BlacklistTypes.WHITELIST,
                                            guild=guild.id,
                                            command=command_name,
                                            channel=channel.id,
                                            type=BlacklistTypes.GLOBAL)
        if success:
            return 'Whitelisted command {0} from channel {1} `{1.id}`'.format(command_name, channel)
        elif success is None:
            return 'Removed command {0} whitelist from channel {1} `{1.id}`'.format(command_name, channel)

    @command(owner_only=True)
    async def test_perms(self, ctx, user: discord.Member, command_):
        value = await self.bot.dbutil.check_blacklist(f"(command='{command_}' OR command IS NULL)", user, ctx, True)
        await ctx.send(value or 'No special perms')

    async def get_rows(self, whereclause, select='*'):
        sql = 'SELECT %s FROM command_blacklist WHERE %s' % (select, whereclause)
        rows = await self.bot.dbutil.fetch(sql)
        return rows

    @staticmethod
    def get_applying_perm(command_rows, return_type=False):
        smallest = 18
        smallest_row = None
        perm_type = 0x10  # guild
        for row in command_rows:
            if row['type'] == BlacklistTypes.GLOBAL:
                return False

            if row['type'] == BlacklistTypes.WHITELIST:
                v1 = PermValues.VALUES['whitelist']
            else:
                v1 = PermValues.VALUES['blacklist']

            if row['uid'] is not None:
                v2 = PermValues.VALUES['user']
            elif row['role'] is not None:
                v2 = PermValues.VALUES['role']
            else:
                continue

            v = v1 | v2
            if v < smallest:
                smallest = v
                perm_type = v2
                smallest_row = row

        if return_type:
            return smallest_row, perm_type

        return smallest_row

    @command(no_pm=True)
    @cooldown(1, 30, BucketType.user)
    async def role_perms(self, ctx, *, role: discord.Role=None):
        """Show white- and blacklist for all or specified role"""
        guild = ctx.guild

        if role:
            where = 'guild={} AND uid IS NULL AND channel IS NULL AND role={}'.format(guild.id, role.id)
        else:
            where = 'guild={} AND uid IS NULL AND channel IS NULL AND NOT role IS NULL ORDER BY role, type'.format(guild.id)

        rows = await self.get_rows(where)
        if not rows:
            return await ctx.send('No perms found')

        paginator = Paginator('Role perms')
        last = None
        last_type = None

        def get_command(row):
            return 'All commands' if row['command'] is None else row['command']

        for row in rows:
            if row['role'] != last:
                last = row['role']
                role = guild.get_role(row['role'])
                if role is None:
                    logger.warning('Role {} has been deleted and it has perms'.format(row['role']))
                    last = None
                    continue

                last_type = row['type']
                perm_type = 'Whitelisted:\n' if last_type == BlacklistTypes.WHITELIST else 'Blacklisted:\n'
                paginator.add_field('{0.name} {0.id}'.format(role), perm_type + get_command(row) + '\n')

            else:
                s = ''
                if row['type'] != last_type:
                    last_type = row['type']
                    s = '\nWhitelisted:\n' if last_type == BlacklistTypes.WHITELIST else '\nBlacklisted:\n'

                s += get_command(row) + '\n'
                paginator.add_to_field(s)

        paginator.finalize()
        pages = paginator.pages
        for idx, page in enumerate(pages):
            page.set_footer(text='Page {}/{}'.format(idx + 1, len(pages)))

        await send_paged_message(ctx, pages, embed=True)

    @command(no_pm=True, aliases=['sp'])
    @cooldown(1, 10, BucketType.guild)
    async def show_perms(self, ctx, *, type_: typing.Union[discord.Role, discord.User, discord.TextChannel]=None):
        """
        Shows all server perms in one paged embed.
        If type is a role, user or a text channel will only show permissions for that.
        """
        sql = f'SELECT command, type, uid, role, channel FROM command_blacklist WHERE guild={ctx.guild.id}'

        # Add extra filters to sql
        if isinstance(type_, discord.Role):
            sql += f" AND role={type_.id}"
        elif isinstance(type_, discord.User):
            sql += f" AND uid={type_.id}"
        elif isinstance(type_, discord.TextChannel):
            sql += f" AND channel={type_.id}"

        sql += " ORDER BY uid, role, channel"

        rows = await self.bot.dbutil.fetch(sql)
        if not rows:
            await ctx.send(f'No perms found for {type_ or "guild"}')
            return

        perms = {'guild': [], 'channel': [], 'role': [], 'user': []}

        for row in rows:
            if row['uid']:
                perms['user'].append(row)
            elif row['channel']:
                perms['channel'].append(row)
            elif row['role']:
                perms['role'].append(row)
            else:
                perms['guild'].append(row)

        ITEMS_PER_PAGE = 10

        # Flatten dict to key value pairs
        newperms = []
        for k in perms:
            newperms.extend([(perm, k) for perm in sorted(perms[k], key=lambda r: r['type'])])

        paginator = Paginator(title=f"Permissions for guild {ctx.guild.name}", init_page=False)

        for i in range(0, len(newperms), ITEMS_PER_PAGE):
            s = ''
            for row, type_ in newperms[i:i+ITEMS_PER_PAGE]:
                t, e = ('whitelisted', '✅') if row['type'] == BlacklistTypes.WHITELIST else ('disabled', '❌')
                cmd = f'Command `{row["command"]}`' if row["command"] else 'All commands'

                if type_ == 'guild':
                    s += f'🖥{e} {cmd} {t} for this guild\n'

                elif type_ == 'channel':
                    s += f'📝{e} {cmd} {t} in channel <#{row["channel"]}>\n'

                elif type_ == 'role':
                    role = '<@&{0}> {0}'.format(row['role'])
                    s += f'⚙{e} {cmd} {t} for role {role}\n'

                elif type_ == 'user':
                    user = self.bot.get_user(row['uid']) or ''
                    s += f'👤{e} {cmd} {t} for user <@{row["uid"]}> {user}\n'

            paginator.add_page(description=s)

        paginator.finalize()
        await send_paged_message(ctx, paginator.pages, embed=True)

    @command(name='commands', no_pm=True)
    @cooldown(1, 30, type=BucketType.user)
    async def commands_(self, ctx, user: discord.Member=None):
        """Get your or the specified users white- and blacklisted commands on this server"""
        guild = ctx.guild
        if not user:
            user = ctx.author

        if user.roles:
            roles = '(role IS NULL OR role IN ({}))'.format(', '.join(map(lambda r: str(r.id), user.roles)))
        else:
            roles = 'role IS NULL'

        where = f'guild={guild.id} AND (uid={user.id} or uid IS NULL) AND channel IS NULL AND {roles}'

        rows = await self.get_rows(where)

        commands = {}
        for row in rows:
            name = row['command']

            if name in commands:
                commands[name].append(row)
            else:
                commands[name] = [row]

        whitelist = []
        blacklist = []
        global_blacklist = []
        for name, rows in commands.items():
            row = self.get_applying_perm(rows)
            name = f'`{name}`'
            if row is False:
                global_blacklist.append(name)
                continue

            # Don't want channel or server specific blacklists
            if row is None:
                continue

            if row['type'] == BlacklistTypes.WHITELIST:
                whitelist.append(name)

            elif row['type'] == BlacklistTypes.BLACKLIST:
                blacklist.append(name)

        s = ''
        if whitelist:
            s += f'{user}s whitelisted commands\n' + '\n'.join(whitelist) + '\n\n'

        if blacklist:
            s += f'Commands blacklisted fom {user}\n' + '\n'.join(blacklist) + '\n\n'

        if global_blacklist:
            s += f'Commands globally blacklisted for {user}\n' + '\n'.join(global_blacklist) + '\n\n'

        if not s:
            s = '{0} has no special perms set up on the server {1}'.format(user, guild.name)
        else:
            s += '{}s perms on server {}\nChannel specific perms are not checked'.format(user, guild.name)

        s = split_string(s, maxlen=2000, splitter='\n')
        for ss in s:
            await ctx.author.send(ss)

def setup(bot):
    bot.add_cog(CommandBlacklist(bot))


text:
//
//  ALPHANotificationModel.h
//  Alpha
//
//  Created by Dal Rupnik on 02/06/15.
//  Copyright © 2015 Unified Sense. All rights reserved.
//

#import "ALPHAModel.h"

@interface ALPHANotificationModel : ALPHAModel

/*!
 *  Contains string with enabled notification types that
 */
@property (nonatomic, copy) NSString* enabledNotificationTypes;

/*!
 *  Contains registered remote notification token
 */
@property (nonatomic, copy) NSString* remoteNotificationToken;

/*!
 *  Holds remote registration description based on register calls
 */
@property (nonatomic, copy) NSString* remoteRegistrationDescription;

/*!
 *  Received remote notifications
 */
@property (nonatomic, copy) NSArray* remoteNotifications;

/*!
 *  Currently scheduled local notifications
 */
@property (nonatomic, copy) NSArray* scheduledLocalNotifications;

/*!
 *  Already fired local notifications
 */
@property (nonatomic, copy) NSArray* firedLocalNotifications;

@end

redpajama_set_name: RedPajamaGithub


text:
@import '@teamleader/ui-colors';
@import '@teamleader/ui-animations';

.overlay {
  bottom: 0;
  height: 100vh;
  left: 0;
  position: fixed;
  top: 0;
  transition: background var(--animation-duration) var(--animation-curve-default);
  width: 100vw;
}

.is-entered {
  &.dark {
    background-color: color(var(--color-teal-dark) a(50%));
  }
}


text:
from typing import Any, List
import numpy as np

class AccuracyEvaluator(object):
    # pylint: disable=too-few-public-methods

    def __init__(self,
                 name: str = "Accuracy") -> None:
        self.name = name

    def __call__(self,
                 decoded: List[List[Any]],
                 references: List[List[Any]]) -> float:
        collected_info = [d == r
                          for dec, ref in zip(decoded, references)
                          for d, r in zip(dec, ref)]
        if collected_info == []:
            mean = 0
        else:
            mean = np.mean(collected_info)
        return mean

    @staticmethod
    def compare_scores(score1: float, score2: float) -> int:
        # the bigger the better
        return (score1 > score2) - (score1 < score2)

class AccuracySeqLevelEvaluator(object):
    # pylint: disable=too-few-public-methods

    def __init__(self,
                 name: str = "AccuracySeqLevel") -> None:
        self.name = name

    def __call__(self,
                 decoded: List[Any],
                 references: List[Any]) -> float:
        collected_info = [dec == ref
                          for dec, ref in zip(decoded, references)]

        if collected_info == []:
            mean = 0
        else:
            mean = np.mean(collected_info)
        return mean

    @staticmethod
    def compare_scores(score1: float, score2: float) -> int:
        # the bigger the better
        return (score1 > score2) - (score1 < score2)

# pylint: disable=invalid-name
Accuracy = AccuracyEvaluator()
AccuracySeqLevel = AccuracySeqLevelEvaluator()
# pylint: enable=invalid-name


text:
* Change `DistributorVendor` variable in `Variables.wxi` to your company name (`DistributorVendor` combined with `DistributorProductName` compose the Program Name in the Add/Remove Programs list; by default, the full Program Name is _My Company Software Potential Distributor_)

### Distributor Server installation and uninstallation
* A successful build of the Installer project generates a `DistributorSetup.msi` file in the output directory (`bin\$(Configuration)`).
* Distributor Server can be installed by double-clicking the `DistributorSetup.msi` file in the Windows Explorer. Alternatively, `msiexec /i DistributorSetup.msi` can be used from the command line.
    - Distributor Server will be registered as a Windows Service (_Software Potential Distributor_)
    - Also, the full Program Name will appear in Programs and Features (or Add/Remove Programs) list. By default, the full Program Name is _My Company Software Potential Distributor_ (see _Configuring the sample_ section for the information how to customize it)
* Distributor Server can be uninstalled from the Add/Remove Programs (Programs and Features) list in the Control Panel. Alternatively, `msiexec /x DistributorSetup.msi` can be used from the command line.

### Upgrading to a newer Distributor Server version
* Upgrade your `Sp.Distributor-<PermutationShortCode>` NuGet package to a newer version in the Package Manager
* Build the Installer project
* A new version of `DistributorSetup.msi` is generated in the output directory
* Installing the new version of `DistributorSetup.msi` will perform a complete upgrade of Distributor Server on the target machine

# Troubleshooting
## The Installer project fails to load in Visual Studio
* Please make sure that the [WiX toolset](http://wixtoolset.org) is installed (including the Visual Studio extension)

## You get a _Could not find a Software Potential Distributor Server_ error message when you build the Installer project
* Please either:
 1. add the `Sp.Distributor-<PermutationShortCode>` package to your solution to have it auto-discovered.
 2. OR override the path by assigning a valid directory path to `$(DistributorSourceDirectory)` in the .props file.
* If you have installed `Sp.Distributor-<PermutationShortCode>` package but the problem persists, check where NuGet stores packages for your solution. The default location is the `packages` folder in the solution folder.
    - If the NuGet packages aren't stored in the default location, please open the `Sp.Distributor.Wix.props` file and amend the `NugetRepositoryFolder` property (e.g. `..\..\MyNugetPackagesRepositoryCustomDir`)
    -  Alternatively, please open the `Sp.Distributor.Wix.props` file and set `DistributorSourceDirectory` to the full path to the Distributor Server Host (e.g. `..\packages\Sp.Distributor-abcde\Slps.Distributor.Host`)

## Visual Studio seems to ignore changes made in .targets or .props files
* Please re-open the solution as .targets and .props files may be cached by Visual Studio


text:
/**
 *
 */
package li.moskito.awtt.server;

/**
 * Exception that is thrown when the AWTT server can not be started
 *
 * @author Gerald
 */
public class StartupException extends Exception {

    private static final long serialVersionUID = 1870057938181777816L;

    /**
     * @param cause
     */
    public StartupException(final Exception cause) {
        super(cause);
    }

}


text:
{% extends "twocol.html" %}
{% load cache pages_tags %}

{% block title %}
{% if current_page %}
	{% show_content current_page "title" %}
{% endif %}
{% endblock %}

{% block contentleft %}

		Print this page

Home

Help!

{% if current_page.get_root %}

    {% pages_menu current_page.get_root %}

{% endif %}
{% endblock %}

{% block breadcrumbs %}
{% if current_page.get_ancestors %}

    {% pages_breadcrumb current_page %}

{% endif %}
{% endblock %}

{% block content %}
	{% if current_page %}

{% placeholder body on current_page with TinyMCE parsed  %}

	{% endif %}
{% endblock %}


text:
.class Lcom/ub/main/account/AccountMain$6;
.super Ljava/lang/Object;
.source "AccountMain.java"

# interfaces
.implements Landroid/content/DialogInterface$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/ub/main/account/AccountMain;->showDialogPhoneCall()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/ub/main/account/AccountMain;

# direct methods
.method constructor <init>(Lcom/ub/main/account/AccountMain;)V
    .locals 0
    .parameter

    .prologue
    .line 1
    iput-object p1, p0, Lcom/ub/main/account/AccountMain$6;->this$0:Lcom/ub/main/account/AccountMain;

    .line 602
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/content/DialogInterface;I)V
    .locals 3
    .parameter "dialog"
    .parameter "whichButton"

    .prologue
    .line 604
    new-instance v0, Landroid/content/Intent;

    const-string v1, "android.intent.action.CALL"

    const-string v2, "tel:4001528528"

    invoke-static {v2}, Landroid/net/Uri;->parse(Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v2

    invoke-direct {v0, v1, v2}, Landroid/content/Intent;-><init>(Ljava/lang/String;Landroid/net/Uri;)V

    .line 605
    .local v0, intent:Landroid/content/Intent;
    iget-object v1, p0, Lcom/ub/main/account/AccountMain$6;->this$0:Lcom/ub/main/account/AccountMain;

    invoke-virtual {v1, v0}, Lcom/ub/main/account/AccountMain;->startActivity(Landroid/content/Intent;)V

    .line 607
    return-void
.end method


text:
/*************************************************************************/
/*  gdscript_byte_codegen.h                                              */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef GDSCRIPT_BYTE_CODEGEN
#define GDSCRIPT_BYTE_CODEGEN

#include "gdscript_codegen.h"

#include "gdscript_function.h"
#include "gdscript_utility_functions.h"

class GDScriptByteCodeGenerator : public GDScriptCodeGenerator {
	struct StackSlot {
		Variant::Type type = Variant::NIL;
		Vector<int> bytecode_indices;

		StackSlot() = default;
		StackSlot(Variant::Type p_type) :
				type(p_type) {}
	};

	const static int RESERVED_STACK = 3; // For self, class, and nil.

	bool ended = false;
	GDScriptFunction *function = nullptr;
	bool debug_stack = false;

	Vector<int> opcodes;
	List<Map<StringName, int>> stack_id_stack;
	Map<StringName, int> stack_identifiers;
	List<int> stack_identifiers_counts;
	Map<StringName, int> local_constants;

	Vector<StackSlot> locals;
	Vector<StackSlot> temporaries;
	List<int> used_temporaries;
	Map<Variant::Type, List<int>> temporaries_pool;

	List<GDScriptFunction::StackDebug> stack_debug;
	List<Map<StringName, int>> block_identifier_stack;
	Map<StringName, int> block_identifiers;

	int max_locals = 0;
	int current_line = 0;
	int instr_args_max = 0;
	int ptrcall_max = 0;

#ifdef DEBUG_ENABLED
	List<int> temp_stack;
#endif

	HashMap<Variant, int, VariantHasher, VariantComparator> constant_map;
	Map<StringName, int> name_map;
#ifdef TOOLS_ENABLED
	Vector<StringName> named_globals;
#endif
	Map<Variant::ValidatedOperatorEvaluator, int> operator_func_map;
	Map<Variant::ValidatedSetter, int> setters_map;
	Map<Variant::ValidatedGetter, int> getters_map;
	Map<Variant::ValidatedKeyedSetter, int> keyed_setters_map;
	Map<Variant::ValidatedKeyedGetter, int> keyed_getters_map;
	Map<Variant::ValidatedIndexedSetter, int> indexed_setters_map;
	Map<Variant::ValidatedIndexedGetter, int> indexed_getters_map;
	Map<Variant::ValidatedBuiltInMethod, int> builtin_method_map;
	Map<Variant::ValidatedConstructor, int> constructors_map;
	Map<Variant::ValidatedUtilityFunction, int> utilities_map;
	Map<GDScriptUtilityFunctions::FunctionPtr, int> gds_utilities_map;
	Map<MethodBind *, int> method_bind_map;

	// Lists since these can be nested.
	List<int> if_jmp_addrs;
	List<int> for_jmp_addrs;
	List<Address> for_iterator_variables;
	List<Address> for_counter_variables;
	List<Address> for_container_variables;
	List<int> while_jmp_addrs;
	List<int> continue_addrs;

	// Used to patch jumps with `and` and `or` operators with short-circuit.
	List<int> logic_op_jump_pos1;
	List<int> logic_op_jump_pos2;

	List<Address> ternary_result;
	List<int> ternary_jump_fail_pos;
	List<int> ternary_jump_skip_pos;

	List<List<int>> current_breaks_to_patch;
	List<List<int>> match_continues_to_patch;

	void add_stack_identifier(const StringName &p_id, int p_stackpos) {
		if (locals.size() > max_locals) {
			max_locals = locals.size();
		}
		stack_identifiers[p_id] = p_stackpos;
		if (debug_stack) {
			block_identifiers[p_id] = p_stackpos;
			GDScriptFunction::StackDebug sd;
			sd.added = true;
			sd.line = current_line;
			sd.identifier = p_id;
			sd.pos = p_stackpos;
			stack_debug.push_back(sd);
		}
	}

	void push_stack_identifiers() {
		stack_identifiers_counts.push_back(locals.size());
		stack_id_stack.push_back(stack_identifiers);
		if (debug_stack) {
			Map<StringName, int> block_ids(block_identifiers);
			block_identifier_stack.push_back(block_ids);
			block_identifiers.clear();
		}
	}

	void pop_stack_identifiers() {
		int current_locals = stack_identifiers_counts.back()->get();
		stack_identifiers_counts.pop_back();
		stack_identifiers = stack_id_stack.back()->get();
		stack_id_stack.pop_back();
#ifdef DEBUG_ENABLED
		if (!used_temporaries.is_empty()) {
			ERR_PRINT("Leaving block with non-zero temporary variables: " + itos(used_temporaries.size()));
		}
#endif
		locals.resize(current_locals);
		if (debug_stack) {
			for (Map<StringName, int>::Element *E = block_identifiers.front(); E; E = E->next()) {
				GDScriptFunction::StackDebug sd;
				sd.added = false;
				sd.identifier = E->key();
				sd.line = current_line;
				sd.pos = E->get();
				stack_debug.push_back(sd);
			}
			block_identifiers = block_identifier_stack.back()->get();
			block_identifier_stack.pop_back();
		}
	}

	int get_name_map_pos(const StringName &p_identifier) {
		int ret;
		if (!name_map.has(p_identifier)) {
			ret = name_map.size();
			name_map[p_identifier] = ret;
		} else {
			ret = name_map[p_identifier];
		}
		return ret;
	}

	int get_constant_pos(const Variant &p_constant) {
		if (constant_map.has(p_constant)) {
			return constant_map[p_constant];
		}
		int pos = constant_map.size();
		constant_map[p_constant] = pos;
		return pos;
	}

	int get_operation_pos(const Variant::ValidatedOperatorEvaluator p_operation) {
		if (operator_func_map.has(p_operation)) {
			return operator_func_map[p_operation];
		}
		int pos = operator_func_map.size();
		operator_func_map[p_operation] = pos;
		return pos;
	}

	int get_setter_pos(const Variant::ValidatedSetter p_setter) {
		if (setters_map.has(p_setter)) {
			return setters_map[p_setter];
		}
		int pos = setters_map.size();
		setters_map[p_setter] = pos;
		return pos;
	}

	int get_getter_pos(const Variant::ValidatedGetter p_getter) {
		if (getters_map.has(p_getter)) {
			return getters_map[p_getter];
		}
		int pos = getters_map.size();
		getters_map[p_getter] = pos;
		return pos;
	}

	int get_keyed_setter_pos(const Variant::ValidatedKeyedSetter p_keyed_setter) {
		if (keyed_setters_map.has(p_keyed_setter)) {
			return keyed_setters_map[p_keyed_setter];
		}
		int pos = keyed_setters_map.size();
		keyed_setters_map[p_keyed_setter] = pos;
		return pos;
	}

	int get_keyed_getter_pos(const Variant::ValidatedKeyedGetter p_keyed_getter) {
		if (keyed_getters_map.has(p_keyed_getter)) {
			return keyed_getters_map[p_keyed_getter];
		}
		int pos = keyed_getters_map.size();
		keyed_getters_map[p_keyed_getter] = pos;
		return pos;
	}

	int get_indexed_setter_pos(const Variant::ValidatedIndexedSetter p_indexed_setter) {
		if (indexed_setters_map.has(p_indexed_setter)) {
			return indexed_setters_map[p_indexed_setter];
		}
		int pos = indexed_setters_map.size();
		indexed_setters_map[p_indexed_setter] = pos;
		return pos;
	}

	int get_indexed_getter_pos(const Variant::ValidatedIndexedGetter p_indexed_getter) {
		if (indexed_getters_map.has(p_indexed_getter)) {
			return indexed_getters_map[p_indexed_getter];
		}
		int pos = indexed_getters_map.size();
		indexed_getters_map[p_indexed_getter] = pos;
		return pos;
	}

	int get_builtin_method_pos(const Variant::ValidatedBuiltInMethod p_method) {
		if (builtin_method_map.has(p_method)) {
			return builtin_method_map[p_method];
		}
		int pos = builtin_method_map.size();
		builtin_method_map[p_method] = pos;
		return pos;
	}

	int get_constructor_pos(const Variant::ValidatedConstructor p_constructor) {
		if (constructors_map.has(p_constructor)) {
			return constructors_map[p_constructor];
		}
		int pos = constructors_map.size();
		constructors_map[p_constructor] = pos;
		return pos;
	}

	int get_utility_pos(const Variant::ValidatedUtilityFunction p_utility) {
		if (utilities_map.has(p_utility)) {
			return utilities_map[p_utility];
		}
		int pos = utilities_map.size();
		utilities_map[p_utility] = pos;
		return pos;
	}

	int get_gds_utility_pos(const GDScriptUtilityFunctions::FunctionPtr p_gds_utility) {
		if (gds_utilities_map.has(p_gds_utility)) {
			return gds_utilities_map[p_gds_utility];
		}
		int pos = gds_utilities_map.size();
		gds_utilities_map[p_gds_utility] = pos;
		return pos;
	}

	int get_method_bind_pos(MethodBind *p_method) {
		if (method_bind_map.has(p_method)) {
			return method_bind_map[p_method];
		}
		int pos = method_bind_map.size();
		method_bind_map[p_method] = pos;
		return pos;
	}

	void alloc_ptrcall(int p_params) {
		if (p_params >= ptrcall_max) {
			ptrcall_max = p_params;
		}
	}

	int address_of(const Address &p_address) {
		switch (p_address.mode) {
			case Address::SELF:
				return GDScriptFunction::ADDR_SELF;
			case Address::CLASS:
				return GDScriptFunction::ADDR_CLASS;
			case Address::MEMBER:
				return p_address.address | (GDScriptFunction::ADDR_TYPE_MEMBER << GDScriptFunction::ADDR_BITS);
			case Address::CONSTANT:
				return p_address.address | (GDScriptFunction::ADDR_TYPE_CONSTANT << GDScriptFunction::ADDR_BITS);
			case Address::LOCAL_VARIABLE:
			case Address::FUNCTION_PARAMETER:
				return p_address.address | (GDScriptFunction::ADDR_TYPE_STACK << GDScriptFunction::ADDR_BITS);
			case Address::TEMPORARY:
				temporaries.write[p_address.address].bytecode_indices.push_back(opcodes.size());
				return -1;
			case Address::NIL:
				return GDScriptFunction::ADDR_NIL;
		}
		return -1; // Unreachable.
	}

	void append(GDScriptFunction::Opcode p_code, int p_argument_count) {
		opcodes.push_back((p_code & GDScriptFunction::INSTR_MASK) | (p_argument_count << GDScriptFunction::INSTR_BITS));
		instr_args_max = MAX(instr_args_max, p_argument_count);
	}

	void append(int p_code) {
		opcodes.push_back(p_code);
	}

	void append(const Address &p_address) {
		opcodes.push_back(address_of(p_address));
	}

	void append(const StringName &p_name) {
		opcodes.push_back(get_name_map_pos(p_name));
	}

	void append(const Variant::ValidatedOperatorEvaluator p_operation) {
		opcodes.push_back(get_operation_pos(p_operation));
	}

	void append(const Variant::ValidatedSetter p_setter) {
		opcodes.push_back(get_setter_pos(p_setter));
	}

	void append(const Variant::ValidatedGetter p_getter) {
		opcodes.push_back(get_getter_pos(p_getter));
	}

	void append(const Variant::ValidatedKeyedSetter p_keyed_setter) {
		opcodes.push_back(get_keyed_setter_pos(p_keyed_setter));
	}

	void append(const Variant::ValidatedKeyedGetter p_keyed_getter) {
		opcodes.push_back(get_keyed_getter_pos(p_keyed_getter));
	}

	void append(const Variant::ValidatedIndexedSetter p_indexed_setter) {
		opcodes.push_back(get_indexed_setter_pos(p_indexed_setter));
	}

	void append(const Variant::ValidatedIndexedGetter p_indexed_getter) {
		opcodes.push_back(get_indexed_getter_pos(p_indexed_getter));
	}

	void append(const Variant::ValidatedBuiltInMethod p_method) {
		opcodes.push_back(get_builtin_method_pos(p_method));
	}

	void append(const Variant::ValidatedConstructor p_constructor) {
		opcodes.push_back(get_constructor_pos(p_constructor));
	}

	void append(const Variant::ValidatedUtilityFunction p_utility) {
		opcodes.push_back(get_utility_pos(p_utility));
	}

	void append(const GDScriptUtilityFunctions::FunctionPtr p_gds_utility) {
		opcodes.push_back(get_gds_utility_pos(p_gds_utility));
	}

	void append(MethodBind *p_method) {
		opcodes.push_back(get_method_bind_pos(p_method));
	}

	void patch_jump(int p_address) {
		opcodes.write[p_address] = opcodes.size();
	}

public:
	virtual uint32_t add_parameter(const StringName &p_name, bool p_is_optional, const GDScriptDataType &p_type) override;
	virtual uint32_t add_local(const StringName &p_name, const GDScriptDataType &p_type) override;
	virtual uint32_t add_local_constant(const StringName &p_name, const Variant &p_constant) override;
	virtual uint32_t add_or_get_constant(const Variant &p_constant) override;
	virtual uint32_t add_or_get_name(const StringName &p_name) override;
	virtual uint32_t add_temporary(const GDScriptDataType &p_type) override;
	virtual void pop_temporary() override;

	virtual void start_parameters() override;
	virtual void end_parameters() override;

	virtual void start_block() override;
	virtual void end_block() override;

	virtual void write_start(GDScript *p_script, const StringName &p_function_name, bool p_static, MultiplayerAPI::RPCMode p_rpc_mode, const GDScriptDataType &p_return_type) override;
	virtual GDScriptFunction *write_end() override;

#ifdef DEBUG_ENABLED
	virtual void set_signature(const String &p_signature) override;
#endif
	virtual void set_initial_line(int p_line) override;

	virtual void write_type_adjust(const Address &p_target, Variant::Type p_new_type) override;
	virtual void write_unary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand) override;
	virtual void write_binary_operator(const Address &p_target, Variant::Operator p_operator, const Address &p_left_operand, const Address &p_right_operand) override;
	virtual void write_type_test(const Address &p_target, const Address &p_source, const Address &p_type) override;
	virtual void write_type_test_builtin(const Address &p_target, const Address &p_source, Variant::Type p_type) override;
	virtual void write_and_left_operand(const Address &p_left_operand) override;
	virtual void write_and_right_operand(const Address &p_right_operand) override;
	virtual void write_end_and(const Address &p_target) override;
	virtual void write_or_left_operand(const Address &p_left_operand) override;
	virtual void write_or_right_operand(const Address &p_right_operand) override;
	virtual void write_end_or(const Address &p_target) override;
	virtual void write_start_ternary(const Address &p_target) override;
	virtual void write_ternary_condition(const Address &p_condition) override;
	virtual void write_ternary_true_expr(const Address &p_expr) override;
	virtual void write_ternary_false_expr(const Address &p_expr) override;
	virtual void write_end_ternary() override;
	virtual void write_set(const Address &p_target, const Address &p_index, const Address &p_source) override;
	virtual void write_get(const Address &p_target, const Address &p_index, const Address &p_source) override;
	virtual void write_set_named(const Address &p_target, const StringName &p_name, const Address &p_source) override;
	virtual void write_get_named(const Address &p_target, const StringName &p_name, const Address &p_source) override;
	virtual void write_set_member(const Address &p_value, const StringName &p_name) override;
	virtual void write_get_member(const Address &p_target, const StringName &p_name) override;
	virtual void write_assign(const Address &p_target, const Address &p_source) override;
	virtual void write_assign_true(const Address &p_target) override;
	virtual void write_assign_false(const Address &p_target) override;
	virtual void write_assign_default_parameter(const Address &p_dst, const Address &p_src) override;
	virtual void write_store_named_global(const Address &p_dst, const StringName &p_global) override;
	virtual void write_cast(const Address &p_target, const Address &p_source, const GDScriptDataType &p_type) override;
	virtual void write_call(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
	virtual void write_super_call(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
	virtual void write_call_async(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
	virtual void write_call_utility(const Address &p_target, const StringName &p_function, const Vector<Address> &p_arguments) override;
	virtual void write_call_gdscript_utility(const Address &p_target, GDScriptUtilityFunctions::FunctionPtr p_function, const Vector<Address> &p_arguments) override;
	virtual void write_call_builtin_type(const Address &p_target, const Address &p_base, Variant::Type p_type, const StringName &p_method, const Vector<Address> &p_arguments) override;
	virtual void write_call_method_bind(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override;
	virtual void write_call_ptrcall(const Address &p_target, const Address &p_base, MethodBind *p_method, const Vector<Address> &p_arguments) override;
	virtual void write_call_self(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
	virtual void write_call_self_async(const Address &p_target, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
	virtual void write_call_script_function(const Address &p_target, const Address &p_base, const StringName &p_function_name, const Vector<Address> &p_arguments) override;
	virtual void write_construct(const Address &p_target, Variant::Type p_type, const Vector<Address> &p_arguments) override;
	virtual void write_construct_array(const Address &p_target, const Vector<Address> &p_arguments) override;
	virtual void write_construct_typed_array(const Address &p_target, const GDScriptDataType &p_element_type, const Vector<Address> &p_arguments) override;
	virtual void write_construct_dictionary(const Address &p_target, const Vector<Address> &p_arguments) override;
	virtual void write_await(const Address &p_target, const Address &p_operand) override;
	virtual void write_if(const Address &p_condition) override;
	virtual void write_else() override;
	virtual void write_endif() override;
	virtual void start_for(const GDScriptDataType &p_iterator_type, const GDScriptDataType &p_list_type) override;
	virtual void write_for_assignment(const Address &p_variable, const Address &p_list) override;
	virtual void write_for() override;
	virtual void write_endfor() override;
	virtual void start_while_condition() override;
	virtual void write_while(const Address &p_condition) override;
	virtual void write_endwhile() override;
	virtual void start_match() override;
	virtual void start_match_branch() override;
	virtual void end_match() override;
	virtual void write_break() override;
	virtual void write_continue() override;
	virtual void write_continue_match() override;
	virtual void write_breakpoint() override;
	virtual void write_newline(int p_line) override;
	virtual void write_return(const Address &p_return_value) override;
	virtual void write_assert(const Address &p_test, const Address &p_message) override;

	virtual ~GDScriptByteCodeGenerator();
};

#endif // GDSCRIPT_BYTE_CODEGEN


text:
import zstackwoodpecker.test_state as ts_header
TestAction = ts_header.TestAction
def path():

    return dict(initial_formation="template5", path_list=[
        [TestAction.create_mini_vm, "vm1", 'data_volume=false', 'cpu=2', 'memory=2', 'provisiong=thin'],
        [TestAction.reboot_vm, "vm1"],
        [TestAction.create_volume, "volume1", "=scsi,thin"],
        [TestAction.attach_volume, "vm1", "volume1"],
        [TestAction.create_volume_backup, "volume1", "backup1"],
        [TestAction.create_mini_vm, "vm2", 'data_volume=false', 'cpu=random', 'memory=2', 'provisiong=thin'],
        [TestAction.resize_data_volume, "volume1", 5*1024*1024],
        [TestAction.create_volume, "volume2", "=scsi,thin"],
        [TestAction.attach_volume, "vm1", "volume2"],
        [TestAction.create_mini_vm, "vm3", 'data_volume=false', 'cpu=random', 'memory=2', 'network=random', 'provisiong=thin'],
        [TestAction.create_volume, "volume3", "=scsi,thin"],
        [TestAction.add_image, "image1", 'root', "http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2"],
        [TestAction.delete_volume_backup, "backup1"],
        [TestAction.delete_image, "image1"],
        [TestAction.expunge_image, "image1"],
        [TestAction.create_volume_backup, "volume1", "backup2"],
        [TestAction.create_mini_vm, "vm4", 'data_volume=false', 'cpu=random', 'memory=2', 'network=random',
         'provisiong=thin'],
        [TestAction.create_image_from_volume, "vm1", "vm1-image1"],
        [TestAction.create_image_from_volume, "vm2", "vm2-image1"],
        [TestAction.create_image_from_volume, "vm3", "vm3-image1"],
        [TestAction.create_image_from_volume, "vm4", "vm4-image1"],
        [TestAction.create_volume, "volume4", "=scsi,thin"],
        [TestAction.attach_volume, "vm4", "volume4"],
        [TestAction.delete_volume, "volume4"],
        [TestAction.recover_volume, "volume4"],
        [TestAction.stop_vm, "vm4"],
        [TestAction.add_image, "image2", 'root', "http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2"],
        [TestAction.delete_volume, "volume4"],
        [TestAction.expunge_volume, "volume4"],
        [TestAction.change_vm_ha, "vm4"],
        [TestAction.create_vm_backup, "vm4", "backup3"],
        [TestAction.create_image_from_volume, "vm4", "vm4-image2"],
        [TestAction.delete_image, "image2"],
        [TestAction.recover_image, "image2"],
        [TestAction.delete_volume_backup, "backup2"],
        [TestAction.add_image, "image3", 'root', "http://172.20.1.28/mirror/diskimages/centos_vdbench.qcow2"]])


text:
1.0.2 / 2014-09-02
==================

 * Changed docker image name and repo name

1.0.1 / 2014-09-02
==================

 * Updated to new base image.
 * Added sample info.php.
 * Updated configs

1.0.0 / 2014-08-25
==================

 * Version bump
 * Added link to Docker Hub and Usage Instructions
 * Added php5 config files
 * Initial commit


text:
include $(TOPDIR)/rules.mk

LUCI_TITLE:=LuCI Support for Aria2
LUCI_DEPENDS:=+aria2
LUCI_PKGARCH:=all

PKG_MAINTAINER:=Xingwang Liao <kuoruan@gmail.com>
PKG_LICENSE:=MIT

include ../../luci.mk

# call BuildPackage - OpenWrt buildroot signature


text:
package pl.chormon.aod.gc.graph;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.TreeMap;

/**
 *
 * @author Chormon
 */
public class Graph {

    /**
     * Wierzchołki w grafie.
     */
    protected final Map<Integer, Vertex> vertices;

    /**
     * Rozmiar grafu.
     */
    protected final int size;

    /**
     * Stworzenie grafu o danym rozmiarze.
     * @param size rozmiar grafu
     */
    public Graph(int size) {
        this.vertices = new TreeMap<>();
        for (int i = 0; i < size; i++) {
            Vertex node = new Vertex(i);
            this.vertices.put(i, node);
        }
        this.size = size;
    }

    /**
     * Dodanie krawędzi pomiędzy wierzchołkami.
     * @param v1 wierzchołek początkowy
     * @param v2 wierzchołek docelowy
     */
    public void addNeighbor(int v1, int v2) {
        addNeighbor(v1, v2, false);
    }

    /**
     * Dodanie krawędzi pomiędzy wierzchołkami.
     * @param v1 wierzchołek początkowy
     * @param v2 wierzchołek docelowy
     * @param undirect czy krawędź ma prowadzić w obie strony
     */
    public void addNeighbor(int v1, int v2, boolean undirect) {
        if (v1 < vertices.size() && v2 < vertices.size()) {
            vertices.get(v1).addNeightbour(vertices.get(v2));
            if (undirect) {
                vertices.get(v2).addNeightbour(vertices.get(v1));
            }
        } else {
            int v = v1 > v2 ? v1 : v2;
            System.out.println("Nie można dodać sąsiada! Wierzhołek o indeksie " + v + " nie istnieje!");
        }
    }

    /**
     * Sprawdzenie, czy graf jest niepokolorowany.
     * @return Czy graf jest niepokolorowany
     */
    public boolean uncolored() {
        for (Vertex v : vertices.values()) {
            if (v.getColor() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * Pobranie wierzchołków.
     * @return Listę wierzchołków w grafie
     */
    public List<Vertex> getVertices() {
        List<Vertex> list = new ArrayList<>(vertices.values());
        return list;
    }

    /**
     * Pobranie sąsiadów wierzchołka.
     * @param v wierzchołek
     * @return Listę wierzchołków będącymi sąsiadami wierzchołka v
     */
    public List<Vertex> getNeighbors(int v) {
        return vertices.get(v).getNeighbours();
    }

    /**
     * Wypisanie listy sąsiedztwa.
     */
    public void print() {
        System.out.println("Lista sąsiedztwa grafu:");
        for (Vertex v : vertices.values()) {
            System.out.print(v.getId());
            if (!v.getNeighbours().isEmpty()) {
                System.out.print("->");
            }
            ListIterator<Vertex> i = v.getNeighbours().listIterator();
            while (i.hasNext()) {
                System.out.print(i.next().getId());
                if (i.hasNext()) {
                    System.out.print("->");
                }
            }
            System.out.println("");
        }
    }

    /**
     * Pobranie rozmiaru grafu.
     * @return Rozmiar grafu
     */
    public int getSize() {
        return size;
    }

    /**
     * Sprawdzenie, czy graf jest pokolorowany legalnie.
     * @return Czy graf jest pokolorowany legalnie
     */
    public boolean isLegal() {
        for (Vertex v : vertices.values()) {
            int c = v.getColor();
            for (Vertex n : v.getNeighbours()) {
                if (n.getColor() == c) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Wypisanie kolorów wierzchołków.
     */
    public void printColors() {
        for (Vertex v : vertices.values()) {
            System.out.println("W: " + v.getId() + " K: " + v.getColor());
        }
    }

    /**
     * Zresetowanie kolorów wierzchołków.
     */
    public void resetColors() {
        for (Vertex v : vertices.values()) {
            v.setColor(0);
        }
    }
}


text:
package stacktemplates

import (
	"fmt"
	"net/http"
	"testing"

	th "github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/testhelper"
	fake "github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/testhelper/client"
)

// GetExpected represents the expected object from a Get request.
var GetExpected = &Template{
	Description:         "Simple template to test heat commands",
	HeatTemplateVersion: "2013-05-23",
	Parameters: map[string]interface{}{
		"flavor": map[string]interface{}{
			"default": "m1.tiny",
			"type":    "string",
		},
	},
	Resources: map[string]interface{}{
		"hello_world": map[string]interface{}{
			"type": "OS::Nova::Server",
			"properties": map[string]interface{}{
				"key_name": "heat_key",
				"flavor": map[string]interface{}{
					"get_param": "flavor",
				},
				"image":     "ad091b52-742f-469e-8f3c-fd81cadf0743",
				"user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n",
			},
		},
	},
}

// GetOutput represents the response body from a Get request.
const GetOutput = `
{
  "heat_template_version": "2013-05-23",
  "description": "Simple template to test heat commands",
  "parameters": {
    "flavor": {
      "default": "m1.tiny",
      "type": "string"
    }
  },
  "resources": {
    "hello_world": {
      "type": "OS::Nova::Server",
      "properties": {
        "key_name": "heat_key",
        "flavor": {
          "get_param": "flavor"
        },
        "image": "ad091b52-742f-469e-8f3c-fd81cadf0743",
        "user_data": "#!/bin/bash -xv\necho \"hello world\" > /root/hello-world.txt\n"
      }
    }
  }
}`

// HandleGetSuccessfully creates an HTTP handler at `/stacks/postman_stack/16ef0584-4458-41eb-87c8-0dc8d5f66c87/template`
// on the test handler mux that responds with a `Get` response.
func HandleGetSuccessfully(t *testing.T, output string) {
	th.Mux.HandleFunc("/stacks/postman_stack/16ef0584-4458-41eb-87c8-0dc8d5f66c87/template", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "GET")
		th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
		th.TestHeader(t, r, "Accept", "application/json")

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, output)
	})
}

// ValidateExpected represents the expected object from a Validate request.
var ValidateExpected = &ValidatedTemplate{
	Description: "Simple template to test heat commands",
	Parameters: map[string]interface{}{
		"flavor": map[string]interface{}{
			"Default":     "m1.tiny",
			"Type":        "String",
			"NoEcho":      "false",
			"Description": "",
			"Label":       "flavor",
		},
	},
}

// ValidateOutput represents the response body from a Validate request.
const ValidateOutput = `
{
	"Description": "Simple template to test heat commands",
	"Parameters": {
		"flavor": {
			"Default": "m1.tiny",
			"Type": "String",
			"NoEcho": "false",
			"Description": "",
			"Label": "flavor"
		}
	}
}`

// HandleValidateSuccessfully creates an HTTP handler at `/validate`
// on the test handler mux that responds with a `Validate` response.
func HandleValidateSuccessfully(t *testing.T, output string) {
	th.Mux.HandleFunc("/validate", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "POST")
		th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
		th.TestHeader(t, r, "Accept", "application/json")

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, output)
	})
}


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

class Migration_dev_client_seed extends CI_Migration {

	/**
	 * Constructor
	 *
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Insert test client
	 *
	 */
	public function up()
	{
		if (ENVIRONMENT === 'development')
		{
			echo "\n Adding dev client 'client' data";
			$client = array(
				'name'				=> 'Client',
				'slug'				=> 'client',
				'user_id'			=> 1,
				'admin_user_id'		=> 1,
				'language'			=> DEFAULT_LANGUAGE,
				'country_iso'		=> DEFAULT_COUNTRY_ISO,
				'time_zone'			=> DEFAULT_TIMEZONE,
				'currency'			=> DEFAULT_CURRENCY,
			);
			$this->load->model('client_model');
			$client_id = $this->client_model->insert($client);

			echo "\n Schema changes successful";
		}
	}

	/**
	 * Delete test client
	 *
	 */
	public function down()
	{
		if (ENVIRONMENT === 'development')
		{
			$this->load->model('client_model');
			$client = $this->client_model->get_by('slug', 'client');

			if ($client)
			{
				$client_id = $client->id;

				echo "\n Removing dev client 'client' data";
				$this->client_model->delete($client_id);
			}

			echo "\n Schema changes successful";
		}
	}

}


text:
package com.charmyin.cmstudio.basic.pagination.interceptor;

import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import com.charmyin.cmstudio.basic.pagination.page.Page;
import com.charmyin.cmstudio.basic.pagination.uitls.Reflections;

import java.sql.Connection;
import java.util.Properties;

/**
 * <p>
 * Mybatis数据库分页插件.
 * 拦截StatementHandler的prepare方法
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2011-11-18 下午12:31
 * @since JDK 1.5
 */
@SuppressWarnings("UnusedDeclaration")
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})
})
public class PreparePaginationInterceptor extends BaseInterceptor {
    /**
     * 序列化
     */
    private static final long serialVersionUID = -6075937069117597841L;

    public PreparePaginationInterceptor() {
        super();
    }

    @Override
    public Object intercept(Invocation ivk) throws Throwable {
        if (ivk.getTarget().getClass().isAssignableFrom(RoutingStatementHandler.class)) {
            final RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();
            final BaseStatementHandler delegate = (BaseStatementHandler) Reflections.getFieldValue(statementHandler, DELEGATE);
            final MappedStatement mappedStatement = (MappedStatement) Reflections.getFieldValue(delegate, MAPPED_STATEMENT);

            if (mappedStatement.getId().matches(_SQL_PATTERN)) { //拦截需要分页的SQL
                BoundSql boundSql = delegate.getBoundSql();
                //分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
                Object parameterObject = boundSql.getParameterObject();
                if (parameterObject == null) {
                    log.error("参数未实例化");
                    throw new NullPointerException("parameterObject尚未实例化!");
                } else {
                    final Connection connection = (Connection) ivk.getArgs()[0];
                    final String sql = boundSql.getSql();
                    //记录统计
                    final int count = SQLHelp.getCount(sql, connection,
                            mappedStatement, parameterObject, boundSql);
                    Page page = null;
                    page = convertParameter(parameterObject, page);
                    page.init(count, page.getPageSize(), page.getCurrentPage());
                    String pagingSql = SQLHelp.generatePageSql(sql, page, DIALECT);
                    if (log.isDebugEnabled()) {
                        log.debug("分页SQL:" + pagingSql);
                    }
                    //将分页sql语句反射回BoundSql.
                    Reflections.setFieldValue(boundSql, "sql", pagingSql);
                }
            }
        }
        return ivk.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
        initProperties(properties);
    }
}


text:
<!DOCTYPE html>

<title>Novi nalog</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

    Novi nalog

                                {{Auth::user()->fullname}}
 Service Point

                                Kreiran je novi nalog br. {{ $random_string }} u {{Auth::user()->fullname}} service pointu.

                                                        Pogledaj nalog

                                                            computer-centar.com | Vozišće 5, 51216, Viškovo


text:
Retrieve a list of chartpoint objects.
## HTTP request
```http
GET /workbook/worksheets/{id|name}/charts/{name}/series/{undefined}/points
```

## Optional query parameters
You can use the [OData query parameters](odata-optional-query-parameters.md) to restrict the shape of the objects returned from this call.
## Request headers
| Name       | Type | Description|
|:-----------|:------|:----------|
| X-Session-Id   | string  | The Excel workbook session id required to join the session managed by the server. If the session token has expired or is invalid, an error is returned.|

## Request body
Do not supply a request body for this method.
## Response
If successful, this method returns a `200 OK` response code and collection of [ChartPoint](../resources/chartpoint.md) objects in the response body.
## Example
### HTTP request
### Response


text:
layout: page
title: King - Long Wedding
date: 2016-05-24
author: Virginia Roth
tags: weekly links, java
status: published
summary: Donec sit amet metus cursus, dignissim neque interdum, rhoncus.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 01/17/2016
  endDate: 01/21/2016
  ctyhocn: CTVGAHX
  groupCode: KLW
published: true
---
Integer eu erat est. Aenean eu pharetra felis, quis luctus leo. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque quis metus nec magna eleifend blandit. Quisque dictum convallis vestibulum. Sed sed enim sit amet ipsum tincidunt fringilla. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum non purus eu eros mollis ultricies ut eget lorem. Fusce euismod posuere enim ut mattis.

1 Curabitur a ante at risus accumsan ornare
1 Maecenas sed purus suscipit, ultricies ante vitae, dignissim lectus
1 Curabitur facilisis tortor a augue auctor, sed ultrices sem fringilla
1 Sed id mauris sit amet sapien bibendum pharetra ac volutpat est.

Donec sagittis sapien non commodo elementum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent magna arcu, consectetur rutrum nisl in, viverra venenatis sem. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean tincidunt, felis vitae bibendum condimentum, tellus quam dapibus massa, at malesuada magna tellus et lectus. Proin mollis at elit nec congue. Aliquam accumsan, diam in ullamcorper vestibulum, dui orci dignissim massa, quis pharetra odio purus maximus nisl. Vivamus interdum est ut nulla lobortis, in accumsan odio suscipit.
Maecenas fringilla congue augue, in semper odio. Sed diam sem, fringilla non nisi non, imperdiet convallis odio. Quisque tempor volutpat lobortis. Duis tristique sem sapien, in tincidunt risus blandit eu. Aenean ultricies pellentesque dui. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam convallis augue in felis pulvinar, eu euismod leo semper. Nunc vitae posuere purus. Cras sit amet porttitor enim.


text:
package com.araujo.jordan.wearrow;

import android.content.Intent;

import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;

public class DataLayerListenerService extends WearableListenerService {

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        if (messageEvent.getPath().equals("/start-activity")) {
            Intent startIntent = new Intent(this, MainActivity.class);
            startIntent.putExtra("location", messageEvent.getData());
            startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startIntent);
        }
    }

}


text:
package some.experimental.dependency;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DependencyAutoConfiguration {

    @Bean
    public DependencySpringComponent dependencySpringComponent(ApplicationContext applicationContext) {

        return new DependencySpringComponent(applicationContext);
    }
}


text:
package com.spotify.heroic.shell;

import com.spotify.heroic.lifecycle.LifeCycle;

import javax.inject.Named;

public interface ShellServerComponent {
    @Named("shellServer")
    LifeCycle shellServerLife();
}


text:
package com.example.leipe.architecture.ui.gank.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.leipe.architecture.R;
import com.example.leipe.architecture.app.Router;
import com.example.leipe.architecture.base.BaseFragment;
import com.example.leipe.architecture.base.http.GankObserver;
import com.example.leipe.architecture.model.bean.GankItemBean;
import com.example.leipe.architecture.model.http.result.GankHttpResponse;
import com.example.leipe.architecture.ui.gank.adapter.GankTechAdapter;
import com.example.leipe.architecture.viewmodel.gank.GankViewModel;

import java.util.List;

import butterknife.BindView;

/**
 * Created by 被咯苏州 on 2017/7/31.
 */
@Route(path = Router.Gank_TECH_LIST)
public class GankTechFragment extends BaseFragment {
    private final int layout = R.layout.list_fragment;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.loading_tv)
    TextView loadingTv;
    @BindView(R.id.products_list)
    RecyclerView list;

    private boolean isLoading = true;
    GankViewModel viewModel;
    private GankTechAdapter adapter;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setToolbar(toolbar, "Android技术前线");
        viewModel = (GankViewModel) getViewModel(GankViewModel.class, new GankViewModel());
        adapter = new GankTechAdapter(null, _mActivity);
        list.setLayoutManager(new LinearLayoutManager(_mActivity));
        list.setAdapter(adapter);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        isLoading();
        viewModel.getTechList(10, 1)
                .observe(this, new GankObserver<GankHttpResponse<List<GankItemBean>>, List<GankItemBean>>() {
                    @Override
                    public void onData(List<GankItemBean> gankItemBeen) {
                        isLoading = false;
                        isLoading();
                        adapter.setList(gankItemBeen);
                    }

                    @Override
                    public void onErrorCode(int code, String msg) {
                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void isLoading() {
        if (isLoading) {
            loadingTv.setVisibility(View.VISIBLE);
            list.setVisibility(View.GONE);
        } else {
            loadingTv.setVisibility(View.GONE);
            list.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected int getLayoutId() {
        return layout;
    }
}


text:
#include "Sample.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkMakeUnique.h"

static sk_sp<SkShader> make_grad(SkScalar w, SkScalar h) {
    SkColor colors[] = { 0xFF000000, 0xFF333333 };
    SkPoint pts[] = { { 0, 0 }, { w, h } };
    return SkGradientShader::MakeLinear(pts, colors, nullptr, 2, SkShader::kClamp_TileMode);
}

class BigGradientView : public Sample {
public:
    BigGradientView() {}

protected:
    bool onQuery(Sample::Event* evt) override {
        if (Sample::TitleQ(*evt)) {
            Sample::TitleR(evt, "BigGradient");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    void onDrawContent(SkCanvas* canvas) override {
        SkRect r;
        r.set(0, 0, this->width(), this->height());
        SkPaint p;
        p.setShader(make_grad(this->width(), this->height()));
        canvas->drawRect(r, p);
    }

private:
    typedef Sample INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

DEF_SAMPLE( return new BigGradientView(); )

///////////////////////////////////////////////////////////////////////////////

#include "SkRasterHandleAllocator.h"

class GraphicsPort {
protected:
    SkCanvas* fCanvas;

public:
    GraphicsPort(SkCanvas* canvas) : fCanvas(canvas) {}
    virtual ~GraphicsPort() {}

    void save() { fCanvas->save(); }
    void saveLayer(const SkRect& bounds, SkAlpha alpha) {
        fCanvas->saveLayerAlpha(&bounds, alpha);
    }
    void restore() { fCanvas->restore(); }

    void translate(float x, float y) { fCanvas->translate(x, y); }
    void scale(float s) { fCanvas->scale(s, s); }
    void clip(const SkRect& r) { fCanvas->clipRect(r); }

    void drawOval(const SkRect& r, SkColor c) {
        SkPaint p;
        p.setColor(c);
        fCanvas->drawOval(r, p);
    }

    virtual void drawRect(const SkRect& r, SkColor c) {
        SkPaint p;
        p.setColor(c);
        fCanvas->drawRect(r, p);
    }

    SkCanvas* peekCanvas() const { return fCanvas; }
};

#ifdef SK_BUILD_FOR_MAC

#include "SkCGUtils.h"
class CGGraphicsPort : public GraphicsPort {
public:
    CGGraphicsPort(SkCanvas* canvas) : GraphicsPort(canvas) {}

    void drawRect(const SkRect& r, SkColor c) override {
        CGContextRef cg = (CGContextRef)fCanvas->accessTopRasterHandle();

        CGColorRef color = CGColorCreateGenericRGB(SkColorGetR(c)/255.f,
                                                   SkColorGetG(c)/255.f,
                                                   SkColorGetB(c)/255.f,
                                                   SkColorGetA(c)/255.f);

        CGContextSetFillColorWithColor(cg, color);
        CGContextFillRect(cg, CGRectMake(r.x(), r.y(), r.width(), r.height()));
    }
};

static CGAffineTransform matrix_to_transform(CGContextRef cg, const SkMatrix& ctm) {
    SkMatrix matrix;
    matrix.setScale(1, -1);
    matrix.postTranslate(0, SkIntToScalar(CGBitmapContextGetHeight(cg)));
    matrix.preConcat(ctm);

    return CGAffineTransformMake(matrix[SkMatrix::kMScaleX],
                                 matrix[SkMatrix::kMSkewY],
                                 matrix[SkMatrix::kMSkewX],
                                 matrix[SkMatrix::kMScaleY],
                                 matrix[SkMatrix::kMTransX],
                                 matrix[SkMatrix::kMTransY]);
}

class Allocator_CG : public SkRasterHandleAllocator {
public:
    Allocator_CG() {}

    bool allocHandle(const SkImageInfo& info, Rec* rec) override {
        // let CG allocate the pixels
        CGContextRef cg = SkCreateCGContext(SkPixmap(info, nullptr, 0));
        if (!cg) {
            return false;
        }
        rec->fReleaseProc = [](void* pixels, void* ctx){ CGContextRelease((CGContextRef)ctx); };
        rec->fReleaseCtx = cg;
        rec->fPixels = CGBitmapContextGetData(cg);
        rec->fRowBytes = CGBitmapContextGetBytesPerRow(cg);
        rec->fHandle = cg;
        CGContextSaveGState(cg);    // balanced each time updateContext is called
        return true;
    }

    void updateHandle(Handle hndl, const SkMatrix& ctm, const SkIRect& clip) override {
        CGContextRef cg = (CGContextRef)hndl;

        CGContextRestoreGState(cg);
        CGContextSaveGState(cg);
        CGContextClipToRect(cg, CGRectMake(clip.x(), clip.y(), clip.width(), clip.height()));
        CGContextConcatCTM(cg, matrix_to_transform(cg, ctm));
    }
};

#define MyPort CGGraphicsPort
#define MyAllocator Allocator_CG

#elif defined(WIN32)

static RECT toRECT(const SkIRect& r) {
    return { r.left(), r.top(), r.right(), r.bottom() };
}

class GDIGraphicsPort : public GraphicsPort {
public:
    GDIGraphicsPort(SkCanvas* canvas) : GraphicsPort(canvas) {}

    void drawRect(const SkRect& r, SkColor c) override {
        HDC hdc = (HDC)fCanvas->accessTopRasterHandle();

        COLORREF cr = RGB(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c));// SkEndian_Swap32(c) >> 8;
        RECT rounded = toRECT(r.round());
        FillRect(hdc, &rounded, CreateSolidBrush(cr));

        // Assuming GDI wrote zeros for alpha, this will or-in 0xFF for alpha
        SkPaint paint;
        paint.setBlendMode(SkBlendMode::kDstATop);
        fCanvas->drawRect(r, paint);
    }
};

static void DeleteHDCCallback(void*, void* context) {
    HDC hdc = static_cast<HDC>(context);
    HBITMAP hbitmap = static_cast<HBITMAP>(SelectObject(hdc, nullptr));
    DeleteObject(hbitmap);
    DeleteDC(hdc);
}

// We use this static factory function instead of the regular constructor so
// that we can create the pixel data before calling the constructor. This is
// required so that we can call the base class' constructor with the pixel
// data.
static bool Create(int width, int height, bool is_opaque, SkRasterHandleAllocator::Rec* rec) {
    BITMAPINFOHEADER hdr;
    memset(&hdr, 0, sizeof(hdr));
    hdr.biSize = sizeof(BITMAPINFOHEADER);
    hdr.biWidth = width;
    hdr.biHeight = -height;  // Minus means top-down bitmap.
    hdr.biPlanes = 1;
    hdr.biBitCount = 32;
    hdr.biCompression = BI_RGB;  // No compression.
    hdr.biSizeImage = 0;
    hdr.biXPelsPerMeter = 1;
    hdr.biYPelsPerMeter = 1;
    void* pixels;
    HBITMAP hbitmap = CreateDIBSection(nullptr, (const BITMAPINFO*)&hdr, 0, &pixels, 0, 0);
    if (!hbitmap) {
        return false;
    }

    size_t row_bytes = width * sizeof(SkPMColor);
    sk_bzero(pixels, row_bytes * height);

    HDC hdc = CreateCompatibleDC(nullptr);
    if (!hdc) {
        DeleteObject(hbitmap);
        return false;
    }
    SetGraphicsMode(hdc, GM_ADVANCED);
    SelectObject(hdc, hbitmap);

    rec->fReleaseProc = DeleteHDCCallback;
    rec->fReleaseCtx = hdc;
    rec->fPixels = pixels;
    rec->fRowBytes = row_bytes;
    rec->fHandle = hdc;
    return true;
}

/**
*  Subclass of SkRasterHandleAllocator that returns an HDC as its "handle".
*/
class GDIAllocator : public SkRasterHandleAllocator {
public:
    GDIAllocator() {}

    bool allocHandle(const SkImageInfo& info, Rec* rec) override {
        SkASSERT(info.colorType() == kN32_SkColorType);
        return Create(info.width(), info.height(), info.isOpaque(), rec);
    }

    void updateHandle(Handle handle, const SkMatrix& ctm, const SkIRect& clip_bounds) override {
        HDC hdc = static_cast<HDC>(handle);

        XFORM xf;
        xf.eM11 = ctm[SkMatrix::kMScaleX];
        xf.eM21 = ctm[SkMatrix::kMSkewX];
        xf.eDx = ctm[SkMatrix::kMTransX];
        xf.eM12 = ctm[SkMatrix::kMSkewY];
        xf.eM22 = ctm[SkMatrix::kMScaleY];
        xf.eDy = ctm[SkMatrix::kMTransY];
        SetWorldTransform(hdc, &xf);

        RECT clip_bounds_RECT = toRECT(clip_bounds);
        HRGN hrgn = CreateRectRgnIndirect(&clip_bounds_RECT);
        int result = SelectClipRgn(hdc, hrgn);
        SkASSERT(result != ERROR);
        result = DeleteObject(hrgn);
        SkASSERT(result != 0);
    }
};

#define MyPort GDIGraphicsPort
#define MyAllocator GDIAllocator

#endif

#ifdef MyAllocator
class RasterAllocatorSample : public Sample {
public:
    RasterAllocatorSample() {}

protected:
    bool onQuery(Sample::Event* evt) override {
        if (Sample::TitleQ(*evt)) {
            Sample::TitleR(evt, "raster-allocator");
            return true;
        }
        return this->INHERITED::onQuery(evt);
    }

    void doDraw(GraphicsPort* port) {
        SkAutoCanvasRestore acr(port->peekCanvas(), true);

        port->drawRect({0, 0, 256, 256}, SK_ColorRED);
        port->save();
        port->translate(30, 30);
        port->drawRect({0, 0, 30, 30}, SK_ColorBLUE);
        port->drawOval({10, 10, 20, 20}, SK_ColorWHITE);
        port->restore();

        port->saveLayer({50, 50, 100, 100}, 0x80);
        port->drawRect({55, 55, 95, 95}, SK_ColorGREEN);
        port->restore();

        port->clip({150, 50, 200, 200});
        port->drawRect({0, 0, 256, 256}, 0xFFCCCCCC);
    }

    void onDrawContent(SkCanvas* canvas) override {
        GraphicsPort skp(canvas);
        doDraw(&skp);

        const SkImageInfo info = SkImageInfo::MakeN32Premul(256, 256);
        std::unique_ptr<SkCanvas> c2 =
            SkRasterHandleAllocator::MakeCanvas(skstd::make_unique<MyAllocator>(), info);
        MyPort cgp(c2.get());
        doDraw(&cgp);

        SkPixmap pm;
        c2->peekPixels(&pm);
        SkBitmap bm;
        bm.installPixels(pm);
        canvas->drawBitmap(bm, 280, 0, nullptr);
    }

private:
    typedef Sample INHERITED;
};
DEF_SAMPLE( return new RasterAllocatorSample; )
#endif


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

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

Click inside the frame below to start the game

  <APPLET ARCHIVE="javakazrace.jar" CODE="javakazrace.class" WIDTH=610 HEIGHT=340 VIEWASTEXT>No Java ???</APPLET>

  Arrow Up or 'A' = accelerate

  Arrow Down or Space = brake

  Arrow Left/Right = steer

  Code and graphics by Davide Pasca 2001