text:
import argparse
import asyncio
import logging
import operator
import re
from datetime import datetime

import discord
import numpy
from asyncpg.exceptions import PostgresError
from discord.ext.commands import BucketType
from emoji import emoji_count

from bot.bot import command, has_permissions, cooldown, bot_has_permissions
from bot.formatter import EmbedLimits
from cogs.cog import Cog
from utils.utilities import (get_emote_name_id, parse_time, get_avatar)

logger = logging.getLogger('terminal')

def parse_emote(emote, only_id=False):
    if not emote.strip():
        return

    animated, name, emote_id = get_emote_name_id(emote)
    if name is None:
        if len(emote) > 7 or emoji_count(emote) == 0:
            # If length is more than 7 it's most likely not an unicode char
            return

        return emote

    if only_id:
        return int(emote_id)

    elif animated:
        return 'a:', name, emote_id
    else:
        return '', name, emote_id

class ProxyArgs:
    def __init__(self, strict=False, emotes=None, no_duplicate_votes=False,
                 multiple_votes=False, max_winners=1, giveaway: bool=False):

        self.strict = strict
        self.emotes = emotes or []
        self.ignore_on_dupe = no_duplicate_votes
        self.multiple_votes = multiple_votes
        self.max_winners = max_winners
        self.giveaway = giveaway

    def parse_giveaway(self, s):
        if not s.startswith('-g'):
            return

        self.giveaway = True
        match = re.findall('React with (.+?) to participate', s)
        if not match:
            self.emotes = ['🎉']
            return

        emote = parse_emote(match[0], True)
        self.emotes = [emote or '🎉']

    def parse_strict(self, s):
        if not s.startswith('-s'):
            return

        self.strict = True
        if self.emotes:
            return

        for emote in s[54:].split(' '):
            emote = parse_emote(emote, True)
            if emote:
                self.emotes.append(emote)

    def parse_winners(self, s):
        match = re.findall(r'of winners (\d+) \(might be', s)
        if match:
            self.max_winners = int(match[0])

    def sanity_check(self):
        if not self.giveaway:
            if self.strict and not self.emotes:
                raise ValueError('Strict mode without emotes')

            if self.ignore_on_dupe and self.multiple_votes:
                raise ValueError('No multiple votes and allow multiple votes on at the same time')

        if self.max_winners < 1:
            raise ValueError('Max winners less than 1')

        if self.max_winners > 30:
            raise ValueError('Maximum amount of winners is 30')

    def __dict__(self):
        return {'strict': self.strict, 'emotes': self.emotes,
                'no_duplicate_votes': self.ignore_on_dupe,
                'multiple_votes': self.multiple_votes,
                'max_winners': self.max_winners,
                'giveaway': self.giveaway}

class Poll:
    def __init__(self, bot, message, channel, title, expires_at=None,
                 strict=False, emotes=None, no_duplicate_votes=False,
                 multiple_votes=False, max_winners=1, after=None,
                 giveaway: bool=False):
        """
        Args:
            message: either `class`: discord.Message or int
            others explained in VoteManager
        """
        self._bot = bot
        self.message = message
        self.channel = channel
        self.title = title
        self.expires_at = expires_at
        self.strict = strict
        self._emotes = emotes or []
        self.ignore_on_dupe = no_duplicate_votes
        self.multiple_votes = multiple_votes
        self.max_winners = max_winners
        self.giveaway = giveaway
        self._task = None
        self._stopper = asyncio.Event(loop=self.bot.loop)
        self._after = after

    @property
    def bot(self):
        return self._bot

    def add_emote(self, emote_id):
        # Used when recreating the poll
        self._emotes.append(emote_id)

    def start(self):
        self._stopper.clear()
        self._task = asyncio.run_coroutine_threadsafe(self._wait(), loop=self.bot.loop)
        if callable(self._after):
            self._task.add_done_callback(self._after)

    def stop(self):
        if self._task:
            self._task.cancel()

    def count_now(self):
        self._stopper.set()

    async def _wait(self):
        try:
            if self.expires_at is not None:
                time_ = self.expires_at - datetime.utcnow()
                time_ = time_.total_seconds()
                if time_ > 0:
                    await asyncio.wait_for(self._stopper.wait(), timeout=time_, loop=self.bot.loop)
        except asyncio.TimeoutError:
            pass
        except asyncio.CancelledError:
            return

        try:
            await self.count_votes()
        except:
            logger.exception('Failed to count votes')
            raise

    async def count_votes(self):
        if isinstance(self.message, discord.Message):
            self.message = self.message.id

        try:
            chn = self.bot.get_channel(self.channel)
            if chn is None:
                return

            msg = await chn.fetch_message(self.message)
        except discord.DiscordException:
            logger.exception('Failed to end poll')
            channel = self.bot.get_channel(self.channel)
            sql = 'DELETE FROM polls WHERE message=%s' % self.message
            try:
                await self.bot.dbutil.execute(sql)
            except PostgresError:
                logger.exception('Could not delete poll')
            return await channel.send('Failed to end poll.\nReason: Could not get the poll message')

        votes = {}
        for reaction in msg.reactions:
            if self.strict:
                id = reaction.emoji if isinstance(reaction.emoji, str) else str(reaction.emoji.id)
                if id not in self._emotes:
                    continue

            async for user in reaction.users(limit=reaction.count):
                if user.bot:
                    continue

                if self.ignore_on_dupe and user.id in votes:
                    votes[user.id] = None
                elif not self.multiple_votes:
                    votes[user.id] = [str(reaction.emoji)]
                else:
                    if user.id in votes:
                        votes[user.id] += (str(reaction.emoji), )
                    else:
                        votes[user.id] = [str(reaction.emoji)]

        if self.giveaway:
            users = list(votes.keys())
            if not users:
                s = f'No winners for {self.title} `{self.message}`'
                winners = 'None'
            else:
                self.max_winners = min(len(users), self.max_winners)
                winners = numpy.random.choice(users, self.max_winners, False)
                winners = ', '.join(map(lambda u: f'<@{u}>', winners))
                s = f'Winners of {self.title} `{self.message}` are\n{winners}'

            if msg.author.id == self.bot.user.id:
                try:
                    embed = msg.embeds[0]
                    field = None
                    for idx, f in enumerate(embed.fields):
                        if f.name == 'Winners':
                            field = True
                            embed.set_field_at(idx, name='Winners', value=winners)
                            break

                    if not field:
                        embed.add_field(name='Winners', value=winners)

                    await msg.edit(embed=embed)
                except discord.HTTPException:
                    pass

        else:

            scores = {}
            for _, reacts in votes.items():
                if reacts is None:
                    continue

                for r in reacts:
                    score = scores.get(r, 0)
                    scores[r] = score + 1

            scores = sorted(scores.items(), key=operator.itemgetter(1),  reverse=True)
            if scores:
                current_winners = []
                winners = 0
                current_score = -1
                end = '\nWinner(s) are '
                for emote, score in scores:
                    if score > current_score:
                        current_score = score
                        current_winners.append(emote)
                    elif score == current_score:
                        current_winners.append(emote)
                    elif self.max_winners > winners and current_score >= score:
                        if current_score > score:
                            end += '{} with the score of {} '.format(' '.join(current_winners), current_score)
                            current_winners = []
                            current_score = score

                        current_winners.append(emote)
                    else:
                        break

                    winners += 1

                end += '{} with the score of {}'.format(' '.join(current_winners), current_score)
            else:
                end = ' with no winners'

            s = 'Poll ``{}`` ended{}'.format(self.title, end)

        try:
            await chn.send(s)
        except discord.HTTPException:
            pass

        sql = 'DELETE FROM polls WHERE message= %s' % self.message
        try:
            await self.bot.dbutil.execute(sql)
        except PostgresError:
            logger.exception('Could not delete poll')
            await chn.send('Could not delete poll from database. The poll result might be recalculated')

class VoteManager(Cog):
    def __init__(self, bot):
        super().__init__(bot)
        self.polls = self.bot.polls
        asyncio.run_coroutine_threadsafe(self.load_polls(), self.bot.loop)
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument('-header', nargs='+')
        self.parser.add_argument('-time', default='60s', nargs='+')
        self.parser.add_argument('-emotes', default=None, nargs='+')
        self.parser.add_argument('-description', default=None, nargs='+')
        self.parser.add_argument('-max_winners', default=1, type=int)
        self.parser.add_argument('-strict', action='store_true')
        self.parser.add_argument('-no_duplicate_votes', action='store_true')
        self.parser.add_argument('-allow_multiple_entries', action='store_true')
        self.parser.add_argument('-giveaway', action='store_true')

    def __unload(self):
        for poll in list(self.polls.values()):
            poll.stop()

    async def load_polls(self):
        sql = 'SELECT polls.title, polls.message, polls.channel, polls.expires_in, polls.ignore_on_dupe, polls.multiple_votes, polls.strict, polls.max_winners, polls.giveaway, emotes.emote ' \
              'FROM polls LEFT OUTER JOIN pollemotes pe ON polls.message = pe.poll_id LEFT OUTER JOIN emotes ON emotes.emote = pe.emote_id'
        poll_rows = await self.bot.dbutil.fetch(sql)
        polls = {}
        for row in poll_rows:
            poll = polls.get(row['message'], Poll(self.bot, row['message'], row['channel'], row['title'],
                                                  expires_at=row['expires_in'],
                                                  strict=row['strict'],
                                                  no_duplicate_votes=row['ignore_on_dupe'],
                                                  multiple_votes=row['multiple_votes'],
                                                  max_winners=row['max_winners'] or 1,
                                                  after=lambda f: self.polls.pop(row['message'], None),
                                                  giveaway=row['giveaway']))

            r = self.polls.get(row['message'])
            if r:
                r.stop()

            polls[row['message']] = poll
            poll.add_emote(row['emote'])

        for poll in polls.values():
            self.polls[poll.message] = poll
            poll.start()

    @command(owner_only=True)
    async def recalculate(self, ctx, msg_id: int, channel_id: int, *, message):
        """Recalculate a poll result"""
        # Add -header if it's not present so argparser can recognise the argument
        message = '-header ' + message if not message.startswith('-h') else message
        try:
            parsed = self.parser.parse_args(message.split(' '))
        except SystemExit:
            await ctx.send('Failed to parse arguments')
            return

        if parsed.strict and not parsed.emotes:
            return await ctx.send('Cannot set strict mode without specifying any emotes')

        if parsed.no_duplicate_votes and parsed.allow_multiple_entries:
            return await ctx.send('Cannot have -n and -a specified at the same time. That would be dumb')

        if parsed.max_winners < 1:
            return await ctx.send('Max winners needs to be an integer bigger than 0')

        parsed.max_winners = min(parsed.max_winners, 20)

        title = ' '.join(parsed.header)

        emotes = []
        if parsed.emotes:
            for emote in parsed.emotes:
                if not emote.strip():
                    continue

                _, name, emote_id = get_emote_name_id(emote)
                if name is None:
                    if len(emote) > 2:
                        # If length is more than 2 it's most likely not an unicode char
                        continue

                    emotes.append(emote)
                else:
                    emotes.append((name, emote_id))

        emotes_list = []
        for emote in emotes:
            if not isinstance(emote, tuple):
                emotes_list.append(emote)
            else:
                name, id = emote
                emotes_list.append(id)

        poll = Poll(self.bot, msg_id, channel_id, title, strict=parsed.strict,
                    emotes=emotes_list, no_duplicate_votes=parsed.no_duplicate_votes,
                    multiple_votes=parsed.allow_multiple_entries, max_winners=parsed.max_winners)

        await poll.count_votes()

    @command(no_pm=True)
    @has_permissions(manage_messages=True, manage_guild=True)
    @cooldown(1, 5, BucketType.guild)
    async def reroll(self, ctx, message_id: int):
        """
        Reroll a poll or giveaway based on the message_id. Message doesn't have
        to be from this bot as long as the format is the same
        """

        try:
            msg = await ctx.channel.fetch_message(message_id)
        except discord.HTTPException:
            return await ctx.send('Message not found')

        if not msg.embeds:
            return await ctx.send('Embed not found')

        embed = None
        for em in msg.embeds:
            if isinstance(em, discord.Embed):
                embed = em
                break

        if not embed:
            return await ctx.send('Embed not found')

        title = embed.title if isinstance(embed.title, str) else 'No title'
        modifiers = None

        for field in embed.fields:
            if field.name == 'Modifiers':
                modifiers = field.value
                break

        if not modifiers:
            await ctx.send('Modifiers field not found')

        modifiers = modifiers.split('\n')
        args = ProxyArgs()

        for mod in modifiers:
            if mod.startswith('-s '):
                args.parse_strict(mod)

            elif mod.startswith('-n '):
                args.ignore_on_dupe = True

            elif mod.startswith('-a '):
                args.multiple_votes = True

            elif mod.startswith('-m '):
                args.parse_winners(mod)

            elif mod.startswith('-g '):
                args.parse_giveaway(mod)

        try:
            args.sanity_check()
        except ValueError as e:
            return await ctx.send(f'Sanity check failed\n{e}')

        # skipcq: PYL-E1102
        poll = Poll(self.bot, msg.id, ctx.channel.id, title, **args.__dict__())
        poll.start()

    @command(no_pm=True)
    @bot_has_permissions(embed_links=True)
    @has_permissions(manage_messages=True, manage_guild=True)
    @cooldown(1, 20, BucketType.guild)
    async def poll(self, ctx, *, message):
        """
        Creates a poll that expires by default in 60 seconds
        Examples of use: {prefix}{name} title -d description -e <:GWjojoGappyGoodShit:364223863888019468> 👌 -a
        available arguments
        `-d` `-description` Description for the poll
        `-t` `-time` Time after which the poll is expired. Maximum time is 1 week
        `-e` `-emotes` Optional emotes that are automatically added to the poll

        These options require no arguments. Default values that are used when they aren't specified are marked in square brackets []
        `-g` `-giveaway` Activates giveaway mode. In this mode max one emote can be specified
        and winners are randomly selected when the poll ends. Available arguments with this are -d, -t, -e and -m
        `-m` `-max_winners` [1] Maximum amount of winners. It might be more in case of a draw
        `-s` `-strict` [false] Only count emotes specified in the -emotes argument
        `-n` `-no_duplicate_votes` [false] Ignores users who react to more than one emote
        `-a` `-allow_multiple_entries` [false] Count all reactions from the user. Even if that user reacted with multiple emotes.
        """

        # Add -header if it's not present so argparser can recognise the argument
        message = '-header ' + message if not message.startswith('-h') else message
        try:
            parsed = self.parser.parse_args(message.split(' '))
        except SystemExit:
            await ctx.send('Failed to parse arguments')
            return

        if not parsed.giveaway:
            if parsed.strict and not parsed.emotes:
                return await ctx.send('Cannot set strict mode without specifying any emotes')

            if parsed.no_duplicate_votes and parsed.allow_multiple_entries:
                return await ctx.send('Cannot have -n and -a specified at the same time. That would be dumb')

        if parsed.max_winners < 1:
            return await ctx.send(
                'Max winners needs to be an integer bigger than 0')

        if parsed.max_winners > 30:
            return await ctx.send('Max winners cannot be bigger than 20')

        title = ' '.join(parsed.header)
        if len(title) > EmbedLimits.Title:
            await ctx.send(f'Max characters allowed for title is {EmbedLimits.Title}')
            return

        expires_in = parse_time(' '.join(parsed.time))
        if expires_in.total_seconds() == 0:
            await ctx.send('No time specified or time given is 0 seconds')
            ctx.command.reset_cooldown(ctx)
            return
        if expires_in.days > 14:
            ctx.command.reset_cooldown(ctx)
            await ctx.send('Maximum time is 14 days')
            return

        now = datetime.utcnow()
        expired_date = now + expires_in
        sql_date = expired_date
        parsed.time = sql_date

        emotes = []
        emote = ''  # Used with giveaways
        failed = []
        if parsed.emotes:
            for emote in parsed.emotes:
                emote = parse_emote(emote)
                if emote:
                    emotes.append(emote)

        if parsed.giveaway:
            if not emotes:
                emote = '🎉'
                emotes = [emote]
            else:
                emote = emotes[0]
                emotes = [emote]
                emote = '<{}{}:{}>'.format(*emote) if isinstance(emote, tuple) else emote

        if parsed.description:
            description = ' '.join(parsed.description)
        else:
            description = discord.Embed.Empty

        embed = discord.Embed(title=title, description=description, timestamp=expired_date)
        if parsed.time:
            embed.add_field(name='Valid for',
                            value='%s' % str(expires_in))
        embed.set_footer(text='Expires at', icon_url=get_avatar(ctx.author))

        options = ''
        if parsed.giveaway:
            options += f'-g Giveaway mode. React with {emote} to participate\n'
        else:
            if parsed.strict:
                fmt_emotes = ['<{}:{}:{}>'.format(*emote) if isinstance(emote, tuple) else emote for emote in emotes]
                options += f'-s Strict mode on. Only specified emotes are counted. {" ".join(fmt_emotes)}\n'

            if parsed.no_duplicate_votes:
                options += '-n Voting for more than one valid option will invalidate your vote\n'
            elif not parsed.allow_multiple_entries:
                options += 'If user votes multiple times only 1 reaction is counted'

            if parsed.allow_multiple_entries:
                options += '-a All all valid votes are counted from a user\n'

        if parsed.max_winners > 1:
            options += '-m Max amount of winners %s (might be more in case of a tie)' % parsed.max_winners

        if options:
            embed.add_field(name='Modifiers', value=options)

        msg = await ctx.send(embed=embed)

        # add reactions to message
        for emote in emotes:
            try:
                emote = '{}{}:{}'.format(*emote) if isinstance(emote, tuple) else emote
                await msg.add_reaction(emote)
            except discord.DiscordException:
                failed.append(emote)
        if failed:
            await ctx.send('Failed to get emotes `{}`'.format('` `'.join(failed)),
                           delete_after=60)

        async with self.bot.pool.acquire() as conn:
            tr = conn.transaction()
            await tr.start()
            sql = 'INSERT INTO polls (guild, title, strict, message, channel, expires_in, ignore_on_dupe, multiple_votes, max_winners, giveaway) ' \
                  'VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)'
            d = (
                ctx.guild.id,
                title,
                parsed.strict,
                msg.id,
                ctx.channel.id,
                parsed.time,
                parsed.no_duplicate_votes,
                parsed.allow_multiple_entries,
                parsed.max_winners,
                parsed.giveaway
            )

            try:
                await conn.execute(sql, *d)

                emotes_list = []
                if emotes:
                    sql = 'INSERT INTO emotes (name, emote, guild) VALUES ($1, $2, $3) '
                    values = []
                    # We add all successfully parsed emotes even if the bot failed to
                    # add them so strict mode will count them in too
                    for emote in emotes:
                        if not isinstance(emote, tuple):
                            name, id_ = emote, emote
                            emotes_list.append(id_)
                            guild = None
                        else:
                            # Prefix is the animated emoji prefix a: or empty str
                            prefix, name, id_ = emote
                            name = prefix + name
                            emotes_list.append(id_)
                            guild = ctx.guild.id
                        values.append((name, str(id_), guild))

                    # No need to run these if no user set emotes are used
                    if values:
                        # If emote is already in the table update its name
                        sql += ' ON CONFLICT (emote) DO UPDATE SET name=EXCLUDED.name'
                        await conn.executemany(sql, values)

                        sql = 'INSERT INTO pollemotes (poll_id, emote_id) VALUES ($1, $2) ON CONFLICT DO NOTHING '
                        values = []
                        for id_ in emotes_list:
                            values.append((msg.id, str(id_)))

                        await conn.executemany(sql, values)

                await tr.commit()
            except PostgresError:
                await tr.rollback()
                logger.exception('Failed sql query')
                await ctx.send('Failed to save poll. Exception has been logged')
                return

        if isinstance(emotes_list, str):
            # Error happened when this is a string. Otherwise it's a list
            return await ctx.send(emotes_list)

        poll = Poll(self.bot, msg.id, msg.channel.id, title, expires_at=expired_date, strict=parsed.strict,
                    emotes=emotes_list, no_duplicate_votes=parsed.no_duplicate_votes,
                    multiple_votes=parsed.allow_multiple_entries, max_winners=parsed.max_winners,
                    after=lambda f: self.polls.pop(msg.id, None), giveaway=parsed.giveaway)
        poll.start()
        self.polls[msg.id] = poll

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


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yanlu.android.services.app" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.yanlu.android.services.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name="com.yanlu.android.services.app.service.BackgroundService" />
        <service
            android:name="com.yanlu.android.services.app.service.StockQuoteService"
            android:enabled="true"
            android:exported="true" >
        </service>
        <service
            android:name="com.yanlu.android.services.app.service.MyIntentService"
            android:exported="false" >
        </service>
    </application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

        <meta charset="utf-8">
        <title>iFront-Row</title>
        <meta name="description" content="iFrontRow is the web resurrection of Apple (c) FrontRow">
        <meta name="author" content="Abhishek Dev">
        <meta name="viewport" content="width=device-width">
        <meta property="og:title" content="iFrontRow" />
        <meta property="og:type" content="movie" />
        <meta property="og:url" content="http://ifrontrows.appspot.com/" />
        <meta property="og:image" content="" />
        <meta property="og:site_name" content="iFrontRow" />
        <meta property="fb:admins" content="100000337500038" />
        <meta itemprop="name" content="iFrontRow"/>
		<meta itemprop="description" content="iFrontRow is the web resurrection of Apple (c) FrontRow. For all who liked to watch Apple trailers but now on web"/>
        <link href='http://fonts.googleapis.com/css?family=Asap:400,700' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="lib/eSlidenav/jquery.ad-eSlidenav.css"/>
        <link rel="stylesheet" href="lib/fancybox/jquery.fancybox.css"/>
        <link rel="stylesheet" href="resource/css/global.css"/>
        <link rel="stylesheet" href="resource/css/ifr-app.css"/>

<input id="ifr_updateDbBtn" class="dontDisplay" type="button" value="Force Fetch Trailer List"/>
                <input id="ifr_aboutBtn" type="button" value="About"/>

                     Tweet

                                    Actors

                                    Director

                                    Genre

                                    In Theatre

Theatrical Trailers

                Show/Hide Config

            	x

About iFrontRow

Resurrected By

Abhishek Dev

Credits

                        GUI shamelessly adapted from the original Apple (c) Front Row Application

                        iFrontRow name suggested by anshul10s (Anshul Gupta)

Made Using

                	jQuery & jQuery UI

                    jQuery eSlidenav plugin

                    jQuery fancybox plugin

                    Modernizr

                    iTunes Service (trailers.apple.com)

License

                	Source available under the MIT License

                    Fork at http://github.com/abhishekdev/iFrontRow

NOTES and Known Issues

                    - Trailers run best in Safari on Mac.

                    - Please report any bugs or requests at Github Issues Page.

                    - Chrome/Opera fail to run trailer on second run (Fix coming ASAP).

                    - Quick Time Player is required to be installed for other devices.


text:
from time import sleep

from .helper.test_helper import BaseTestCase

ANDROID_LATIN = 'com.android.inputmethod.latin/.LatinIME'  # Android L/M/N
GOOGLE_LATIN = 'com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME'  # Android O/P

class TestIME(BaseTestCase):
    def test_available_ime_engines(self) -> None:
        engines = self.driver.available_ime_engines
        assert isinstance(engines, list)
        assert ANDROID_LATIN in engines or GOOGLE_LATIN in engines

    def test_is_ime_active(self) -> None:
        assert self.driver.is_ime_active()

    def test_active_ime_engine(self) -> None:
        engines = self.driver.available_ime_engines
        assert self.driver.active_ime_engine in engines

    def test_activate_ime_engine(self) -> None:
        engines = self.driver.available_ime_engines

        self.driver.activate_ime_engine(engines[-1])
        assert self.driver.active_ime_engine == engines[-1]

    def test_deactivate_ime_engine(self) -> None:
        engines = self.driver.available_ime_engines
        self.driver.activate_ime_engine(engines[-1])

        assert self.driver.active_ime_engine == engines[-1]

        self.driver.deactivate_ime_engine()
        sleep(1)
        assert self.driver.active_ime_engine != engines[-1]


text:
package info.bitrich.xchangestream.serum;

import com.knowm.xchange.serum.SerumConfigs.Solana;
import com.knowm.xchange.serum.SerumExchange;
import info.bitrich.xchangestream.core.ProductSubscription;
import info.bitrich.xchangestream.core.StreamingExchange;
import info.bitrich.xchangestream.core.StreamingMarketDataService;
import info.bitrich.xchangestream.service.netty.ConnectionStateModel;
import io.reactivex.Completable;
import io.reactivex.Observable;
import org.knowm.xchange.ExchangeSpecification;

public class SerumStreamingExchange extends SerumExchange implements StreamingExchange {

  private SerumStreamingService streamingService;

  @Override
  public Completable connect(ProductSubscription... args) {

    final String url =
        Solana.valueOf(
                String.valueOf(getExchangeSpecification().getExchangeSpecificParametersItem("Env")))
            .wsUrl();
    this.streamingService = new SerumStreamingService(url);
    return this.streamingService.connect();
  }

  @Override
  public Completable disconnect() {
    final SerumStreamingService service = streamingService;
    streamingService = null;
    return service.disconnect();
  }

  @Override
  public Observable<Throwable> reconnectFailure() {
    return streamingService.subscribeReconnectFailure();
  }

  @Override
  public Observable<Object> connectionSuccess() {
    return streamingService.subscribeConnectionSuccess();
  }

  @Override
  public Observable<ConnectionStateModel.State> connectionStateObservable() {
    return streamingService.subscribeConnectionState();
  }

  @Override
  public boolean isAlive() {
    return streamingService != null && streamingService.isSocketOpen();
  }

  @Override
  public StreamingMarketDataService getStreamingMarketDataService() {
    return null;
  }

  @Override
  public void useCompressedMessages(boolean compressedMessages) {
    streamingService.useCompressedMessages(compressedMessages);
  }

  @Override
  public ExchangeSpecification getDefaultExchangeSpecification() {
    final ExchangeSpecification exchangeSpec = new ExchangeSpecification(this.getClass());
    exchangeSpec.setSslUri(Solana.MAINNET.restUrl());
    exchangeSpec.setHost("projectserum.com");
    exchangeSpec.setPort(80);
    exchangeSpec.setExchangeName("Serum");
    exchangeSpec.setExchangeDescription(
        "Serum is a decentralized cryptocurrency exchange built on Solana.");
    exchangeSpec.setExchangeSpecificParametersItem("Env", "MAINNET");

    return exchangeSpec;
  }
}


text:
package com.htcursos.htapp.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;

import com.htcursos.htapp.R;
import com.htcursos.htapp.models.User;
import com.htcursos.htapp.utils.Constants;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by viniciuslm on 17/10/15.
 */
public class FActivity extends AppCompatActivity {

    @Bind(R.id.edit_text)
    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_f);
        ButterKnife.bind(this);
        if(getIntent().getExtras().containsKey(Constants.EXTRA_FOR_F)){
            User user = (User) getIntent().getSerializableExtra(Constants.EXTRA_FOR_F);
            editText.setText(user.getLogin() +":"+ user.getPassword());
        }
    }

    @OnClick(R.id.btn_go_to_g)
    public void goToActivityG(){
        Intent i = new Intent(FActivity.this, GActivity.class);
        i.putExtra(Constants.EXTRA_FOR_G ,editText.getText().toString());
        startActivity(i);
    }

}


text:
package org.jbpm.task.performance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityManagerFactory;

import org.jbpm.services.task.HumanTaskServicesBaseTest;
import org.jbpm.services.task.utils.TaskFluent;
import org.junit.Assert;
import org.junit.Test;
import org.kie.api.task.model.Status;
import org.kie.api.task.model.Task;
import org.kie.api.task.model.TaskSummary;
import org.kie.internal.query.QueryFilter;

import bitronix.tm.resource.jdbc.PoolingDataSource;

public abstract class HTPerformanceBaseTest extends HumanTaskServicesBaseTest {

    protected PoolingDataSource pds;
    protected EntityManagerFactory emf;

    @Test
    public void testBasicUserTaskAddingAndQuering() throws Exception {
        System.out.println("Starting testBasicUserTaskAddingAndQuering ...");
        long beforeStartTime = System.currentTimeMillis();
        int times = 10;
        double totalAdding = 0;
        double totalQuerying = 0;
        for(int j = 1; j < times + 1 ; j ++){
            long beforeAddTime = System.currentTimeMillis();
            int amount = 1000;
            System.out.println("Adding " + amount + " tasks....");

            for (int i = 0; i < amount; i++) {

                 Task task = new TaskFluent()
                                            .setName("Task #" + i)
                                            .addI18NName("en-UK","First Language Task #"+i)
                                            .addI18NName("en-US", "Second Language Task #"+i)
                                            .addI18NName("es-AR", "Third Language Task #"+i)
                                            .addPotentialUser("salaboy")
                                            .setAdminUser("Administrator")
                                            .getTask();

                taskService.addTask(task, new HashMap<String, Object>());

            }

            double thisRoundAdding = ((double)(System.currentTimeMillis() - beforeAddTime)/1000);
            totalAdding += thisRoundAdding;
            System.out.println("Finish Adding tasks...." + thisRoundAdding);

        }

        for(int i = 0; i < times; i++){
            long beforeQueryTime = System.currentTimeMillis();
            System.out.println("Querying tasks....");
            List<TaskSummary> tasksAssignedAsPotentialOwner = taskService.getTasksAssignedAsPotentialOwner("salaboy",null, null, new QueryFilter(i * 1000,1000));
            double thisRoundQuerying = ((double)(System.currentTimeMillis() - beforeQueryTime)/1000);
            totalQuerying += thisRoundQuerying;
            System.out.println("Finishing query tasks (Page "+i * 1000+")...." + thisRoundQuerying);
            //Assert.assertEquals(amount * j, tasksAssignedAsPotentialOwner.size());
            Assert.assertEquals(1000, tasksAssignedAsPotentialOwner.size());
        }

        System.out.println("Finishing testBasicUserTaskAddingAndQuering ... "+((double)(System.currentTimeMillis()-beforeStartTime)/1000));
        System.out.println(" AVG Addition... "+ (totalAdding / times));
        System.out.println(" AVG Querying... "+ (totalQuerying / times));
    }

    @Test
    public void testBasicGroupTaskAddingAndQueringAndClaimingSimple() throws Exception {
        System.out.println("Starting testBasicGroupTaskAddingAndQueringAndClaimingSimple ...");

        long beforeStartTime = System.currentTimeMillis();
        int times = 10;
        double totalAdding = 0;
        double totalQuerying = 0;
        for(int j = 1; j < times + 1 ; j ++){
            int amount = 1000;
            long beforeAddTime = System.currentTimeMillis();
            System.out.println("Adding " + amount + " tasks....");

            for (int i = 0; i < amount; i++) {
                 Task task = new TaskFluent()
                                                .setName("Task #" + i)
                                                .addI18NName("en-UK","First Language Task #"+i)
                                                .addI18NName("en-US", "Second Language Task #"+i)
                                                .addI18NName("es-AR", "Third Language Task #"+i)
                                                .addPotentialGroup("Knights Templer")
                                                .setAdminUser("Administrator")
                                                .getTask();
                taskService.addTask(task, new HashMap<String, Object>());
            }

            double thisRoundAdding = ((double)(System.currentTimeMillis() - beforeAddTime)/1000);
            totalAdding += thisRoundAdding;
            System.out.println("Finish Adding tasks...." + thisRoundAdding);

            long beforeQueryTime = System.currentTimeMillis();
            System.out.println("Querying tasks potOwner (Ready)....");
            List<Status> statuses = new ArrayList<Status>();

            //Getting only the group tasks
            statuses.add(Status.Ready);
            List<TaskSummary> tasksAssignedAsPotentialOwner = taskService.getTasksAssignedAsPotentialOwner("salaboy",null, statuses, new QueryFilter(0,0));
            double thisRoundQuerying = ((double)(System.currentTimeMillis() - beforeQueryTime)/1000);
            totalQuerying += thisRoundQuerying;
            System.out.println("Finishing query tasks (Ready)...." + thisRoundQuerying);
            Assert.assertEquals(amount, tasksAssignedAsPotentialOwner.size());

            //We need to check that this are all group tasks!
            for (TaskSummary ts : tasksAssignedAsPotentialOwner) {
                Assert.assertTrue(ts.getStatus().name().equals("Ready"));
            }

            long beforeClaimingTime = System.currentTimeMillis();
            for (TaskSummary ts : tasksAssignedAsPotentialOwner) {
                taskService.claim(ts.getId(), "salaboy");
            }
            System.out.println("After claiming  tasks...." + ((double)(System.currentTimeMillis() - beforeClaimingTime)/1000));

            beforeQueryTime = System.currentTimeMillis();
            System.out.println("Querying tasks potOwner (Reserved)....");
            statuses = new ArrayList<Status>();
            //Getting only my tasks
            statuses.add(Status.Reserved);
            tasksAssignedAsPotentialOwner = taskService.getTasksAssignedAsPotentialOwner("salaboy",null, statuses, new QueryFilter(0,0));
            thisRoundQuerying = ((double)(System.currentTimeMillis() - beforeQueryTime)/1000);
            totalQuerying += thisRoundQuerying;
            System.out.println("Finishing query tasks (Reserved)...." + thisRoundQuerying);
            Assert.assertEquals(amount, tasksAssignedAsPotentialOwner.size());

            long beforeStartingTime = System.currentTimeMillis();
            System.out.println("Before starting  tasks...." );
            for (TaskSummary ts : tasksAssignedAsPotentialOwner) {
                taskService.start(ts.getId(), "salaboy");
            }
            System.out.println("After starting  tasks...." + ((double)(System.currentTimeMillis() - beforeStartingTime)/1000));

            beforeQueryTime = System.currentTimeMillis();
            System.out.println("Querying tasks potOwner (InProgress)....");
            statuses = new ArrayList<Status>();
            //Getting only my tasks in progress
            statuses.add(Status.InProgress);
            tasksAssignedAsPotentialOwner = taskService.getTasksAssignedAsPotentialOwner("salaboy",null, statuses, new QueryFilter(0,0));
            thisRoundQuerying = ((double)(System.currentTimeMillis() - beforeQueryTime)/1000);
            totalQuerying += thisRoundQuerying;
            System.out.println("Finishing query tasks (InProgress)...." + thisRoundQuerying);
            Assert.assertEquals(amount, tasksAssignedAsPotentialOwner.size());

            long beforeCompletingTime = System.currentTimeMillis();
            System.out.println("Before completing  tasks...." );
            for (TaskSummary ts : tasksAssignedAsPotentialOwner) {
                taskService.complete(ts.getId(), "salaboy", null);
            }
            System.out.println("After completing  tasks...." + ((double)(System.currentTimeMillis() - beforeCompletingTime)/1000));

            beforeQueryTime = System.currentTimeMillis();
            System.out.println("Querying tasks potOwner (Completed)....");
            statuses = new ArrayList<Status>();
            //Getting only my tasks completed
            statuses.add(Status.Completed);
            tasksAssignedAsPotentialOwner = taskService.getTasksAssignedAsPotentialOwner("salaboy",null, statuses, new QueryFilter(0,0));
            System.out.println("Finishing query potOwner (Completed )tasks...." + ((double)(System.currentTimeMillis() - beforeQueryTime)/1000));
            Assert.assertEquals(amount * j, tasksAssignedAsPotentialOwner.size());

        }

        System.out.println("Finishing testBasicGroupTaskAddingAndQueringAndClaimingSimple ..." +
                ((double)(System.currentTimeMillis() - beforeStartTime)/1000));
        System.out.println(" AVG Addition... "+ (totalAdding / times));
        System.out.println(" AVG Querying... "+ (totalQuerying / times / 4));
    }

}


text:
namespace Smi.Sample.AppCore.Player.Commands
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using Smi.Infra.Messages;

    public interface IAddPlayerVictories
    {
        Guid PlayerId { get; set; }
        int VictoriesToAdd { get; set; }
        int ExperienceToAdd { get; set; }
    }

    public class AddPlayerVictoriesCommand : BaseCommand, IAddPlayerVictories
    {
        [Required]
        public Guid PlayerId { get; set; }

        [Required]
        public int VictoriesToAdd { get; set; }

        [Required]
        public int ExperienceToAdd { get; set; }

    }
}


text:
<!DOCTYPE html>

<TITLE>Manpage of ABRT\-ACTION\-GENERA</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

ABRT\-ACTION\-GENERA

Section: ABRT Manual (1)
Updated: 06/22/2012
Index
Return to Main Contents

NAME

abrt-action-generate-backtrace - Analyzes coredump, generates and saves backtrace.

SYNOPSIS

abrt-action-generate-backtrace [-v] [-d DIR] [-i DIR1[:DIR2]...] [-t NUM]

DESCRIPTION

This tool runs gdb(1) on a file named coredump in problem directory DIR. gdb(1) generates backtrace and other diagnostic information about the state of the application at the moment when coredump was generated. Then the tool saves it as new element backtrace in this problem directory.

Integration with libreport events

abrt-action-generate-backtrace can be used as an analyzer for application crashes which dump core.

Example usage in report_event.conf:

EVENT=analyze analyzer=CCpp
        abrt-action-generate-backtrace

OPTIONS

-d DIR

Path to problem directory.

-v

Be more verbose. Can be given multiple times.

-i DIR1[:DIR2]

Additional debuginfo directories

-t NUM

Kill gdb if it runs for more than NUM seconds

AUTHORS

*

ABRT team

Index

NAME

SYNOPSIS

DESCRIPTION

Integration with libreport events

OPTIONS

AUTHORS

This document was created by
man2html,
using the manual pages.

Time: 05:29:01 GMT, December 24, 2015


text:
fieldtrip-overlays
==================

Fieldtrip Overlays is a Fieldtrip Open plugin for adding overlays to to the map.


text:
package org.apache.james.mailbox.model;

import java.util.Iterator;

import org.apache.james.mailbox.exception.MailboxException;
import org.apache.james.mailbox.model.MessageResult.FetchGroup;
import org.apache.james.mailbox.model.MessageResult.Header;

public interface Headers extends Content{
    /**
     * Gets headers for the message.
     *
     * @return Header Iterator, or null if
     *         {@link FetchGroup#HEADERS} was not fetched
     */
    Iterator headers() throws MailboxException;

}


text:
import { compose } from 'redux';
var devtools = window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f;
export default compose(devtools);


text:
import { fromGlobalId } from 'graphql-relay';

const types = {};

export const registerType = (model, type, lookupFn) => {
	types[type.name] = { type, model, lookupFn };
};

export const getNode = globalId => {

	const { type : typeName, id} = fromGlobalId(globalId);

	if (types[typeName]) {
		return types[typeName].lookupFn(id);
	} else {
		return null;
	}

};

export const getNodeType = obj => {

	for (let typeName of Object.keys(types)) {
		if (obj instanceof types[typeName].model) {
			return types[typeName].type;
		}
	}

	return null;
};


text:
import boto
import uuid
import time
import urllib
import csv
import sys
import os
import MySQLdb
import random
import memcache
import hashlib
from random_query_generator import setquery
# Instantiate a new client for Amazon Simple Storage Service (S3). With no
# parameters or configuration, the AWS SDK for Python (Boto) will look for
# access keys in these environment variables:
#
#    AWS_ACCESS_KEY_ID='...'
#    AWS_SECRET_ACCESS_KEY='...'
#
# For more information about this interface to Amazon S3, see:
# http://boto.readthedocs.org/en/latest/s3_tut.html

# Referenced from :: http://stackoverflow.com/questions/20749599/connecting-to-mysql-db-on-amazon-rds
def connect_to_database():
    cnx= {
        'host': 'nisudb.crsevmpdcmrk.us-west-2.rds.amazonaws.com',
        'username': 'nispand',
        'password': 'nispand1492',
        'db': 'assignment4'
        }
    try:
        db = MySQLdb.connect(host=cnx['host'],user=cnx['username'],passwd= cnx['password'],db= cnx['db'])
        cursr = db.cursor()
        query = "Use assignment4"
        cursr.execute(query)
        print "Connected to Schema"
        return cursr
    except Exception as e:
        return "Unable to connect::" + str(e)

def create_table(cursr):
        query = "CREATE TABLE IF NOT EXISTS mytable(Lang VARCHAR(7) NOT NULL, segment_id INTEGER(6) NOT NULL PRIMARY KEY" \
                ", contract_id VARCHAR(5) NOT NULL, plan_id INTEGER(3) NOT NULL, contract_year INTEGER(4) NOT NULL" \
                ", tier_level INTEGER(3) NOT NULL, tier_type_desc VARCHAR(22) NOT NULL, sentences_sort_order INTEGER(4) NOT NULL" \
                ", category_code INTEGER(2) NOT NULL)"
        cursr.execute(query)
        print "Table Created Successfully"
        #query = "DROP TABLE test"
        #cursr.execute(query)
        #print "Table dropped successfull"
        return  "Connection Successfull"

def insert_in_table(crsr):
    start_time_dbi = time.time()
    with open('nispand.csv','r') as csvfile:
        csv_data = csv.reader(csvfile,delimiter=',',quotechar = '"')
        for row in csv_data:
            print "Inserting into table"
            query = "INSERT INTO mytable(Lang,segment_id,contract_id,plan_id,contract_year,tier_level,tier_type_desc,sentences_sort_order,category_code) VALUES ('"+str(row[0])+"',"+row[1]+",'"+row[2]+"',"+row[3]+","+row[4]+","+row[5]+",'"+row[6]+"',"+row[7]+","+row[8]+");"
        print query
        try:
            crsr.execute(query)
        except Exception as e:
            print "Cannot Insert"

    time_to_ins = time.time() - start_time_dbi
    print "Time takne to insert data into Database..." + str(time_to_ins) + "seconds"
    return "Data Inserted Successfully"

def get_file():

    testfile = urllib.URLopener()
    testfile.retrieve("https://dl.dropboxusercontent.com/s/j9102nm9laul8to/data_assg3.csv?dl=0","nispand.csv")

    myfile = open("nispand.csv",'rt')
    try:
        reader = csv.reader(myfile)
    except Exception as e :
        print "Cannot read file" + e

    print reader

    return "file downloaded successfully"

def qry_exec(flag):
    lim = random.randint(200,800)
    raw_input("Enter key to Execute 1000 queries")
    start_time_1000 = time.time()
    try:
        qrytoexec = setquery(1000)
        for i in range(0,len(qrytoexec)):
            qrytoexec[i] = qrytoexec[i] + str(lim)
            if flag == 0:
                data1 = result.execute(qrytoexec[i])
            elif flag == 1:
                    hash_obj = hashlib.md5(qrytoexec[i].encode())
                    hash_obj = hash_obj.hexdigest()
                    data1 = s.get(hash_obj)
                    if not data1 :
                        data1 = result.execute(qrytoexec[i])

            """ for row in data:
            print row"""
    except Exception as e:
        print "No result for this one"

    end_time = time.time()-start_time_1000
    print "time taken to execute 1000 queries::" + str(end_time)

    raw_input("Enter key to Execute 5000 queries")
    start_time_5000 = time.time()
    try:
        qrytoexec5 = setquery(5000)
        for i in range(0,len(qrytoexec5)):
            qrytoexec5[i] = qrytoexec5[i] + str(lim)
            if flag == 0:
                data5 = result.execute(qrytoexec5[i])
            elif flag == 1:
                    hash_obj = hashlib.md5(qrytoexec5[i].encode())
                    hash_obj = hash_obj.hexdigest()
                    data5 = s.get(hash_obj)
                    if not data5 :
                        data5 = result.execute(qrytoexec5[i])

    except Exception as e:
            print "No result for this one"

    end_time = time.time()-start_time_5000
    print "time taken to execute 5000 queries::" + str(end_time)

    raw_input("Enter key to Execute 20000 queries")
    start_time_20000 = time.time()
    try:
        qrytoexec20 = setquery(1000)
        for i in range(0,len(qrytoexec20)):
            qrytoexec20[i] = qrytoexec20[i] + str(lim)
            if flag == 0:
                data20 = result.execute(qrytoexec20[i])
            elif flag == 1:
                    hash_obj = hashlib.md5(qrytoexec[i].encode())
                    hash_obj = hash_obj.hexdigest()
                    data20 = s.get(hash_obj)
                    if not data20 :
                        data20 = result.execute(qrytoexec[i])
    except Exception as e:
        print "No result for this one"

    end_time = time.time()-start_time_20000
    print "time taken to execute 20000 queries::" + str(end_time)
    return "Data fetched"

s3 = boto.connect_s3()

# Everything uploaded to Amazon S3 must belong to a bucket. These buckets are
# in the global namespace, and must have a unique name.
#
# For more information about bucket name restrictions, see:
# http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
bucket_name = "assignment4bucket1"
print "Creating new bucket with name: " + bucket_name
bucket = s3.create_bucket(bucket_name)

#connect to Elastic Cache
s = memcache.Client(["nispand.6czzrp.cfg.usw2.cache.amazonaws.com:11211"])
# Files in Amazon S3 are called "objects" and are stored in buckets. A specific
# object is referred to by its key (i.e., name) and holds data. Here, we create
# a new object with the key "python_sample_key.txt" and content "Hello World!".
#
# For more information on keys and set_contents_from_string, see:
# http://boto.readthedocs.org/en/latest/s3_tut.html#storing-data
from boto.s3.key import Key
k = Key(bucket)
k.key = 'sample_data.csv'
contents = get_file()
start_time = time.time()
print "Uploading some data to " + bucket_name + " with key: " + k.key
k.set_contents_from_filename('nispand.csv')
time_taken = time.time()-start_time
print "time taken to upload data in bucket " + str(time_taken) +" seconds"
# Fetch the key to show that we stored something. Key.generate_url will
# construct a URL that can be used to access the object for a limited time.
# Here, we set it to expire in 30 minutes.
#
# For a more detailed overview of generate_url's options, see:
# http://boto.readthedocs.org/en/latest/ref/s3.html#boto.s3.key.Key.generate_url
expires_in_seconds = 1800

print "Generating a public URL for the object we just uploaded. This URL will be active for %d seconds" % expires_in_seconds
print
print k.generate_url(expires_in_seconds)
print

raw_input("Press enter to connect to MySQLdb...")
result = connect_to_database()
ans = create_table(result)
print ans
qry = insert_in_table(result)
print qry
raw_input("Enter a key to delete the bucket")
# Buckets cannot be deleted unless they're empty. Since we still have a
# reference to the key (object), we can just delete it.
print "Deleting the object."
k.delete()
result.execute("commit")
raw_input("Enter any key to Fetch Query Using EC Memcache")
ans = qry_exec(1)
print ans
raw_input("Enter any key to Fetch Query Without EX Memcache")
ans = qry_exec(0)
print ans
# Now that the bucket is empty, we can delete it.
print "Deleting the bucket."
s3.delete_bucket(bucket_name)


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package io;

import edu.wpi.first.wpilibj.Joystick;

/**
 * Represents a gamepad connected to the driver
 * station. Note: the drivers for the gamepad should
 * be installed on the driver station netbook.
 * @author Connor Willison
 */
public class Gamepad extends Joystick{

    //floating-point values:
    public static final int leftStick_X = 1;
    public static final int leftStick_Y = 2;
    public static final int shoulderAxis = 3;
    public static final int rightStick_X = 4;
    public static final int rightStick_Y = 5;
    public static final int dpadAxis = 6;

    //boolean buttons:
    public static final int button_A = 1;
    public static final int button_B = 2;
    public static final int button_X = 3;
    public static final int button_Y = 4;
    public static final int button_L_Shoulder = 5;
    public static final int button_R_Shoulder = 6;
    public static final int button_Back = 7;
    public static final int button_Start = 8;
    public static final int button_LeftStick = 9;
    public static final int button_RightStick = 10;	//only 12 buttons allowed - must find out which can be read

    private static final double axis_deadzone = .1;
    /**
     * Creates a gamepad attached to
     * the specified port on the driver station.
     * @param port
     */
    public Gamepad(int port){
	super(port);
    }

    /**
     * Get the value of a gamepad axis, adjusting
     * for a dead zone.
     * @param axis
     * @return
     */
    public double getAxis(int axis){
	double val = getRawAxis(axis);
        if(Math.abs(val) <= axis_deadzone){
            return 0;
        }else{
            return val;
        }
    }

    /**
     * Get the value of a gamepad button.
     * @param button
     * @return
     */
    public boolean getButton(int button){
	return getRawButton(button);
    }
}


text:
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Builders.Extensions;
using Umbraco.Cms.Tests.Common.Testing;
using Umbraco.Cms.Tests.Integration.Testing;
using Umbraco.Extensions;

namespace Umbraco.Cms.Tests.Integration.Umbraco.Core.Mapping;

[TestFixture]
[UmbracoTest(Mapper = true, Database = UmbracoTestOptions.Database.NewSchemaPerTest)]
public class UmbracoMapperTests : UmbracoIntegrationTest
{
    [SetUp]
    public void SetUp()
    {
        _sut = Services.GetRequiredService<IUmbracoMapper>();

        _dataTypeService = Services.GetRequiredService<IDataTypeService>();
        _propertyEditorCollection = Services.GetRequiredService<PropertyEditorCollection>();
        _mediaBuilder = new MediaBuilder();
        _contentBuilder = new ContentBuilder();
        _contentTypeBuilder = new ContentTypeBuilder();
        _contentTypeService = Services.GetRequiredService<IContentTypeService>();
        _localizedTextService = Services.GetRequiredService<ILocalizedTextService>();
    }

    private IUmbracoMapper _sut;
    private IDataTypeService _dataTypeService;
    private PropertyEditorCollection _propertyEditorCollection;
    private MediaBuilder _mediaBuilder;
    private ContentBuilder _contentBuilder;
    private ContentTypeBuilder _contentTypeBuilder;
    private IContentTypeService _contentTypeService;
    private ILocalizedTextService _localizedTextService;

    [Test]
    public void To_Media_Item_Simple()
    {
        var content = _mediaBuilder
            .AddMediaType()
            .AddPropertyGroup()
            .AddPropertyType()
            .Done()
            .Done()
            .Done()
            .WithCreatorId(Constants.Security.SuperUserId)
            .Build();

        var result = _sut.Map<IMedia, ContentItemBasic<ContentPropertyBasic>>(content);

        AssertBasics(result, content);

        foreach (var p in content.Properties)
        {
            AssertBasicProperty(result, p);
        }
    }

    [Test]
    public void To_Content_Item_Simple()
    {
        var content = _contentBuilder
            .AddContentType()
            .AddPropertyGroup()
            .AddPropertyType()
            .Done()
            .Done()
            .Done()
            .WithCreatorId(Constants.Security.SuperUserId)
            .Build();

        var result = _sut.Map<IContent, ContentItemBasic<ContentPropertyBasic>>(content);

        AssertBasics(result, content);

        foreach (var p in content.Properties)
        {
            AssertBasicProperty(result, p);
        }
    }

    [Test]
    public void To_Content_Item_Dto()
    {
        var content = _contentBuilder
            .AddContentType()
            .AddPropertyGroup()
            .AddPropertyType()
            .Done()
            .Done()
            .Done()
            .WithCreatorId(Constants.Security.SuperUserId)
            .Build();

        var result = _sut.Map<IContent, ContentPropertyCollectionDto>(content);

        foreach (var p in content.Properties)
        {
            AssertProperty(result, p);
        }
    }

    [Test]
    public void To_Media_Item_Dto()
    {
        var content = _mediaBuilder
            .AddMediaType()
            .AddPropertyGroup()
            .AddPropertyType()
            .Done()
            .Done()
            .Done()
            .Build();

        var result = _sut.Map<IMedia, ContentPropertyCollectionDto>(content);

        Assert.GreaterOrEqual(result.Properties.Count(), 1);
        Assert.AreEqual(content.Properties.Count, result.Properties.Count());
        foreach (var p in content.Properties)
        {
            AssertProperty(result, p);
        }
    }

    private void AssertDisplayProperty<T>(IContentProperties<T> result, IProperty p)
        where T : ContentPropertyBasic
    {
        var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias);
        Assert.IsNotNull(pDto);

        // pDto.Alias = p.Alias;
        // pDto.Description = p.PropertyType.Description;
        // pDto.Label = p.PropertyType.Name;
        // pDto.Config = applicationContext.Services.DataTypeService.GetPreValuesByDataTypeId(p.PropertyType.DataTypeDefinitionId);
    }

    [Test]
    public void To_Display_Model()
    {
        var contentType = _contentTypeBuilder
            .WithId(0)
            .AddPropertyGroup()
            .WithId(1)
            .AddPropertyType()
            .Done()
            .Done()
            .AddPropertyGroup()
            .WithId(2)
            .AddPropertyType()
            .Done()
            .Done()
            .AddPropertyGroup()
            .WithId(3)
            .AddPropertyType()
            .Done()
            .Done()
            .AddPropertyGroup()
            .WithId(4)
            .AddPropertyType()
            .Done()
            .Done()
            .Build();
        _contentTypeService.Save(contentType);

        var content = _contentBuilder
            .WithContentType(contentType)
            .WithCreatorId(Constants.Security.SuperUserId)
            .Build();

        var result = _sut.Map<IContent, ContentItemDisplay>(content);

        AssertBasics(result, content);

        var invariantContent = result.Variants.First();
        foreach (var p in content.Properties)
        {
            AssertBasicProperty(invariantContent, p);
            AssertDisplayProperty(invariantContent, p);
        }

        Assert.AreEqual(4, invariantContent.Tabs.Count());
        Assert.IsTrue(invariantContent.Tabs.First().IsActive);
        Assert.IsTrue(invariantContent.Tabs.Except(new[] { invariantContent.Tabs.First() })
            .All(x => x.IsActive == false));
    }

    [Test]
    public void To_Display_Model_No_Tabs()
    {
        var contentType = _contentTypeBuilder
            .WithId(0)
            .Build();
        _contentTypeService.Save(contentType);

        var content = _contentBuilder
            .WithContentType(contentType)
            .WithCreatorId(Constants.Security.SuperUserId)
            .Build();

        var result = _sut.Map<IContent, ContentItemDisplay>(content);

        AssertBasics(result, content);

        var invariantContent = result.Variants.First();
        foreach (var p in content.Properties)
        {
            AssertBasicProperty(invariantContent, p);
            AssertDisplayProperty(invariantContent, p);
        }

        Assert.AreEqual(contentType.CompositionPropertyGroups.Count(), invariantContent.Tabs.Count());
    }

    [Test]
    public void To_Display_Model_With_Non_Grouped_Properties()
    {
        var contentType = _contentTypeBuilder
            .WithId(0)
            .AddPropertyType()
            .WithId(1)
            .WithValueStorageType(ValueStorageType.Ntext)
            .WithPropertyEditorAlias("nonGrouped1")
            .WithName("Non Grouped 1")
            .Done()
            .AddPropertyType()
            .WithId(2)
            .WithValueStorageType(ValueStorageType.Ntext)
            .WithPropertyEditorAlias("nonGrouped2")
            .WithName("Non Grouped 2")
            .Done()
            .Build();
        _contentTypeService.Save(contentType);

        var content = _contentBuilder
            .WithContentType(contentType)
            .WithCreatorId(Constants.Security.SuperUserId)
            .Build();

        var result = _sut.Map<IContent, ContentItemDisplay>(content);

        AssertBasics(result, content);

        var invariantContent = result.Variants.First();
        foreach (var p in content.Properties)
        {
            AssertBasicProperty(invariantContent, p);
            AssertDisplayProperty(invariantContent, p);
        }

        Assert.AreEqual(contentType.CompositionPropertyGroups.Count(), invariantContent.Tabs.Count() - 1);
        Assert.IsTrue(
            invariantContent.Tabs.Any(x => x.Label == _localizedTextService.Localize("general", "properties")));
        Assert.AreEqual(
            2,
            invariantContent.Tabs.Where(x => x.Label == _localizedTextService.Localize("general", "properties"))
                .SelectMany(x => x.Properties.Where(p => p.Alias.StartsWith("_umb_") == false)).Count());
    }

    private void AssertBasics(ContentItemDisplay result, IContent content)
    {
        Assert.AreEqual(content.Id, result.Id);

        var ownerId = content.CreatorId;
        if (ownerId != 0)
        {
            Assert.IsNotNull(result.Owner);
            Assert.AreEqual(Constants.Security.SuperUserId, result.Owner.UserId);
            Assert.AreEqual("Administrator", result.Owner.Name);
        }
        else
        {
            Assert.IsNull(result.Owner); // because, 0 is no user
        }

        var invariantContent = result.Variants.First();

        Assert.AreEqual(content.ParentId, result.ParentId);
        Assert.AreEqual(content.UpdateDate, invariantContent.UpdateDate);
        Assert.AreEqual(content.CreateDate, invariantContent.CreateDate);
        Assert.AreEqual(content.Name, invariantContent.Name);
        Assert.AreEqual(
            content.Properties.Count(),
            ((IContentProperties<ContentPropertyDisplay>)invariantContent).Properties.Count(x =>
                x.Alias.StartsWith("_umb_") == false));
    }

    private void AssertBasics<T, TPersisted>(ContentItemBasic<T> result, TPersisted content)
        where T : ContentPropertyBasic
        where TPersisted : IContentBase
    {
        Assert.AreEqual(content.Id, result.Id);

        var ownerId = content.CreatorId;
        if (ownerId != 0)
        {
            Assert.IsNotNull(result.Owner);
            Assert.AreEqual(Constants.Security.SuperUserId, result.Owner.UserId);
            Assert.AreEqual("Administrator", result.Owner.Name);
        }
        else
        {
            Assert.IsNull(result.Owner); // because, 0 is no user
        }

        Assert.AreEqual(content.ParentId, result.ParentId);
        Assert.AreEqual(content.UpdateDate, result.UpdateDate);
        Assert.AreEqual(content.CreateDate, result.CreateDate);
        Assert.AreEqual(content.Name, result.Name);
        Assert.AreEqual(content.Properties.Count(), result.Properties.Count(x => x.Alias.StartsWith("_umb_") == false));
    }

    private void AssertBasicProperty<T>(IContentProperties<T> result, IProperty p)
        where T : ContentPropertyBasic
    {
        var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias);
        Assert.IsNotNull(pDto);
        Assert.AreEqual(p.Alias, pDto.Alias);
        Assert.AreEqual(p.Id, pDto.Id);

        if (p.GetValue() == null)
        {
            Assert.AreEqual(pDto.Value, string.Empty);
        }
        else if (p.GetValue() is decimal decimalValue)
        {
            Assert.AreEqual(pDto.Value, decimalValue.ToString(NumberFormatInfo.InvariantInfo));
        }
        else
        {
            Assert.AreEqual(pDto.Value, p.GetValue().ToString());
        }
    }

    private void AssertProperty(IContentProperties<ContentPropertyDto> result, IProperty p)
    {
        AssertBasicProperty(result, p);

        var pDto = result.Properties.SingleOrDefault(x => x.Alias == p.Alias);
        Assert.IsNotNull(pDto);
        Assert.AreEqual(p.PropertyType.Mandatory, pDto.IsRequired);
        Assert.AreEqual(p.PropertyType.ValidationRegExp, pDto.ValidationRegExp);
        Assert.AreEqual(p.PropertyType.Description, pDto.Description);
        Assert.AreEqual(p.PropertyType.Name, pDto.Label);
        Assert.AreEqual(_dataTypeService.GetDataType(p.PropertyType.DataTypeId), pDto.DataType);
        Assert.AreEqual(_propertyEditorCollection[p.PropertyType.PropertyEditorAlias], pDto.PropertyEditor);
    }

    private void AssertContentItem<T>(ContentItemBasic<ContentPropertyDto> result, T content)
        where T : IContentBase
    {
        AssertBasics(result, content);

        foreach (var p in content.Properties)
        {
            AssertProperty(result, p);
        }
    }
}


text:
'''OpenGL extension EXT.blend_logic_op

This module customises the behaviour of the
OpenGL.raw.GL.EXT.blend_logic_op to provide a more
Python-friendly API

Overview (from the spec)

	A single additional blending equation is specified using the interface
	defined by EXT_blend_minmax.  This equation is a simple logical
	combination of the source and destination colors, where the specific
	logical operation is as specified by LogicOp.  While only the XOR
	operation may find wide application, the generality of full logical
	operations is allowed.

The official definition of this extension is available here:
http://www.opengl.org/registry/specs/EXT/blend_logic_op.txt
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.EXT.blend_logic_op import *
### END AUTOGENERATED SECTION


text:
require 'rspec'
require 'active_support'
require 'active_support/core_ext'
require 'action_dispatch'

require 'zipline'
require 'paperclip'
require 'fog-aws'
require 'carrierwave'

Dir["#{File.expand_path('..', __FILE__)}/support/**/*.rb"].each { |f| require f }

CarrierWave.configure do |config|
  config.fog_provider = 'fog/aws'
  config.fog_credentials = {
		provider:              'AWS',
		aws_access_key_id:     'dummy',
		aws_secret_access_key: 'data',
		region:                'us-west-2',
	}

end

RSpec.configure do |config|
  config.color = true
  config.order = :random
  config.run_all_when_everything_filtered = true
end


text:
class SkiReport::Report

  attr_accessor :all_resorts, :state

  def initialize(state)
    @state = state
    save_resorts(get_resorts(SkiReport::Scraper.new.scrape_state(state)))
  end

  def print_report
    longest_resort_name = @all_resorts.max_by {|resort| resort.name.length}.name.length

    puts "\nSnow Report's for #{@state}:"

    printf("%-#{longest_resort_name + 1}s|%10s|%10s|%10s\n",
      "Resort",
      "24Hr Total",
      "72Hr Total",
      "Base Depth"
      )

    puts "-------------------------------------------------------------------"

    @all_resorts.each do |resort|
      printf("%-#{longest_resort_name + 1}s|    %-6s|    %-6s|%10s\n",
        resort.name,
        resort.one_day_snowfall + '"',
        resort.three_day_snowfall + '"',
        resort.base_depth
      )
    end
  end

  def get_resorts(scraped_data)
    find_valid_resorts(scraped_data.css(".resScrollCol8 table tr"))
  end

  def find_valid_resorts(resorts)
    resorts.reject{|resort| resort.css('.name').text == ""}
  end

  def save_resorts(resorts_scraped_data)
    @all_resorts = resorts_scraped_data.collect do |resort|
      SkiReport::Resort.new(resort.css('.name').text,
                            resort.css('.rLeft b').first.text.slice(/\d+/),
                            resort.css('.rLeft b').last.text.slice(/\d+/),
                            resort.css('.rMid b').text,
                            resort.css(".rMid a").attribute('href').value
                           )
    end
  end

end


text:
<?php
namespace rikcage\bfp;

use Yii;

/**
 * Renders several attributes in one grid column
 */
class BfpClass extends \yii\base\Module
{
    public $controllerNamespace = 'rikcage\bfp\controllers';
    public $theme = false;

    public function init()
    {
        parent::init();

        if ($this->theme) {
            Yii::$app->view->theme = new \yii\base\Theme($this->theme);
        }
    }

}


text:
package org.vaadin.appbase.enums;

public enum ErrorSeverity
{
  WARNING, USER_ERROR, BUG, FATAL;
}


text:
> Force downloads in your Statamic site.

## Installation

* Copy `hooks.download.php` and `pi.download.php` into `_add-ons/download/`

## Usage

Create a download URL by using the plugin tag:

~~~
Download Photo
~~~

The `file` parameter can also be `filename` or `url`. Whichever you prefer.
The `as` parameter is optional. This will let you control the filename of the downloaded file.


text:
/**
 * @license Angular v6.1.2
 * (c) 2010-2018 Google, Inc. https://angular.io/
 * License: MIT
 */

import { Location, LocationStrategy } from '@angular/common';
import { MockLocationStrategy, SpyLocation } from '@angular/common/testing';
import { Compiler, Injectable, Injector, NgModule, NgModuleFactoryLoader, Optional } from '@angular/core';
import { ChildrenOutletContexts, NoPreloading, PreloadingStrategy, ROUTER_CONFIGURATION, ROUTES, Router, RouterModule, UrlHandlingStrategy, UrlSerializer, provideRoutes, ɵROUTER_PROVIDERS, ɵflatten } from '@angular/router';

/**
 * @fileoverview added by tsickle
 * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
 */
/**
 * \@description
 *
 * Allows to simulate the loading of ng modules in tests.
 *
 * ```
 * const loader = TestBed.get(NgModuleFactoryLoader);
 *
 * \@Component({template: 'lazy-loaded'})
 * class LazyLoadedComponent {}
 * \@NgModule({
 *   declarations: [LazyLoadedComponent],
 *   imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])]
 * })
 *
 * class LoadedModule {}
 *
 * // sets up stubbedModules
 * loader.stubbedModules = {lazyModule: LoadedModule};
 *
 * router.resetConfig([
 *   {path: 'lazy', loadChildren: 'lazyModule'},
 * ]);
 *
 * router.navigateByUrl('/lazy/loaded');
 * ```
 *
 *
 */
class SpyNgModuleFactoryLoader {
    /**
     * @param {?} compiler
     */
    constructor(compiler) {
        this.compiler = compiler;
        /**
         * \@docsNotRequired
         */
        this._stubbedModules = {};
    }
    /**
     * \@docsNotRequired
     * @param {?} modules
     * @return {?}
     */
    set stubbedModules(modules) {
        /** @type {?} */
        const res = {};
        for (const t of Object.keys(modules)) {
            res[t] = this.compiler.compileModuleAsync(modules[t]);
        }
        this._stubbedModules = res;
    }
    /**
     * \@docsNotRequired
     * @return {?}
     */
    get stubbedModules() { return this._stubbedModules; }
    /**
     * @param {?} path
     * @return {?}
     */
    load(path) {
        if (this._stubbedModules[path]) {
            return this._stubbedModules[path];
        }
        else {
            return /** @type {?} */ (Promise.reject(new Error(`Cannot find module ${path}`)));
        }
    }
}
SpyNgModuleFactoryLoader.decorators = [
    { type: Injectable }
];
/** @nocollapse */
SpyNgModuleFactoryLoader.ctorParameters = () => [
    { type: Compiler }
];
/**
 * @param {?} opts
 * @return {?}
 */
function isUrlHandlingStrategy(opts) {
    // This property check is needed because UrlHandlingStrategy is an interface and doesn't exist at
    // runtime.
    return 'shouldProcessUrl' in opts;
}
/**
 * Router setup factory function used for testing.
 *
 *
 * @param {?} urlSerializer
 * @param {?} contexts
 * @param {?} location
 * @param {?} loader
 * @param {?} compiler
 * @param {?} injector
 * @param {?} routes
 * @param {?=} opts
 * @param {?=} urlHandlingStrategy
 * @return {?}
 */
function setupTestingRouter(urlSerializer, contexts, location, loader, compiler, injector, routes, opts, urlHandlingStrategy) {
    /** @type {?} */
    const router = new Router(/** @type {?} */ ((null)), urlSerializer, contexts, location, injector, loader, compiler, ɵflatten(routes));
    if (opts) {
        // Handle deprecated argument ordering.
        if (isUrlHandlingStrategy(opts)) {
            router.urlHandlingStrategy = opts;
        }
        else {
            // Handle ExtraOptions
            if (opts.malformedUriErrorHandler) {
                router.malformedUriErrorHandler = opts.malformedUriErrorHandler;
            }
            if (opts.paramsInheritanceStrategy) {
                router.paramsInheritanceStrategy = opts.paramsInheritanceStrategy;
            }
        }
    }
    if (urlHandlingStrategy) {
        router.urlHandlingStrategy = urlHandlingStrategy;
    }
    return router;
}
/**
 * \@description
 *
 * Sets up the router to be used for testing.
 *
 * The modules sets up the router to be used for testing.
 * It provides spy implementations of `Location`, `LocationStrategy`, and {\@link
 * NgModuleFactoryLoader}.
 *
 * ### Example
 *
 * ```
 * beforeEach(() => {
 *   TestBed.configureTestModule({
 *     imports: [
 *       RouterTestingModule.withRoutes(
 *         [{path: '', component: BlankCmp}, {path: 'simple', component: SimpleCmp}]
 *       )
 *     ]
 *   });
 * });
 * ```
 *
 *
 */
class RouterTestingModule {
    /**
     * @param {?} routes
     * @param {?=} config
     * @return {?}
     */
    static withRoutes(routes, config) {
        return {
            ngModule: RouterTestingModule,
            providers: [
                provideRoutes(routes),
                { provide: ROUTER_CONFIGURATION, useValue: config ? config : {} },
            ]
        };
    }
}
RouterTestingModule.decorators = [
    { type: NgModule, args: [{
                exports: [RouterModule],
                providers: [
                    ɵROUTER_PROVIDERS, { provide: Location, useClass: SpyLocation },
                    { provide: LocationStrategy, useClass: MockLocationStrategy },
                    { provide: NgModuleFactoryLoader, useClass: SpyNgModuleFactoryLoader }, {
                        provide: Router,
                        useFactory: setupTestingRouter,
                        deps: [
                            UrlSerializer, ChildrenOutletContexts, Location, NgModuleFactoryLoader, Compiler, Injector,
                            ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()]
                        ]
                    },
                    { provide: PreloadingStrategy, useExisting: NoPreloading }, provideRoutes([])
                ]
            },] }
];

/**
 * @fileoverview added by tsickle
 * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
 */

/**
 * @fileoverview added by tsickle
 * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
 */
// This file only reexports content of the `src` folder. Keep it that way.

/**
 * @fileoverview added by tsickle
 * @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
 */

/**
 * Generated bundle index. Do not edit.
 */

export { setupTestingRouter, SpyNgModuleFactoryLoader, RouterTestingModule };
//# sourceMappingURL=testing.js.map


text:
package com.yo1000.bluefairy.model.repository;

import com.yo1000.bluefairy.model.entity.docker.Container;
import com.yo1000.bluefairy.model.entity.docker.ContainerCreate;
import com.yo1000.bluefairy.model.entity.docker.ContainerCreated;
import com.yo1000.bluefairy.model.entity.docker.ContainerInspect;

/**
 * Created by yoichi.kikuchi on 15/03/12.
 */
public interface ContainerRepository {
    public Container[] getJson();
    public Container[] getJson(boolean all);
    public ContainerInspect getInspect(String id);
    public ContainerCreated postCreate(ContainerCreate containerCreate);
    public ContainerCreated postCreate(ContainerCreate containerCreate, String name);
    public void postStart(String id);
    public void postStop(String id);
    public void postStop(String id, long wait);
    public void deleteRemove(String id);
    public void deleteRemove(String id, boolean volume, boolean force);
}


text:
# LionFire.Execution

Implementations required to execute IExecutables.


text:
import {assert, should, test} from 'gs-testing';

import {$pipe} from '../collect/operators/pipe';
import {take} from '../collect/operators/take';

import {fromSeed} from './random';
import {FakeSeed} from './testing/fake-seed';

test('@tools/random/random', () => {
  test('iterable', () => {
    should('return iterable with values', () => {
      const values = $pipe(
          fromSeed(new FakeSeed([1, 2, 3])).iterable(),
          take(5),
      );

      assert(values).to.haveExactElements([1, 2, 3, 3, 3]);
    });
  });

  test('next', () => {
    should('get the next value of the seed', () => {
      const random = fromSeed(new FakeSeed([1, 2, 3])).next();

      assert(random).to.equal(1);
    });
  });
});


text:
{{define "content"}}

 {{.Constellation.SentinelCount}}

 Sentinels

			 More info

 {{.Constellation.PodCount}}

 All Pods

			 More info

		{{if .Constellation.HasPodsInErrorState}}

		{{else}}

		{{end}}

 {{.Constellation.NumErrorPods}}

 Pods With Errors

			 More info

 Pods With Errors

 All Errors ({{.Constellation.NumErrorPods}})

 No Quorum ({{.Data.NoQuorum}})

 Missing Sentinels ({{.Data.MissingSentinels}})

 Too Many Sentinels ({{.Data.TooManySentinels}})

 No Valid Slave ({{.Data.NoValidSlave}})

 Invalid Auth ({{.Data.InvalidAuth}})

								Name
								Quorum
								Master
								Slave Count
								Sentinel Count

							{{range .Constellation.PodsInError }}
								{{ if ne .Name "" }}

										 {{.Info.Name}}

										{{if .HasQuorum}}

										{{else}}

										{{end}}

									 {{.Info.IP}}:{{.Info.Port}}
									{{if .HasInfo }}

											{{if eq .Master.Info.Replication.ConnectedSlaves 0}}

											{{else}}

											{{end}}
												{{.Master.Info.Replication.ConnectedSlaves}}

									{{else}}
										  0
									{{end}}
									{{if .HasQuorum }}
										{{if .MissingSentinels }}
										{{.SentinelCount}} of {{.NeededSentinels}}
										{{else}}
										{{.SentinelCount }} of {{.NeededSentinels}}
										{{end}}
									{{else}}
									{{.SentinelCount }} of {{.NeededSentinels}}
									{{end}}

								{{end}}
							{{end}}

 Problem

 These pods are unable to failover because they lack quorum. This is due to not having enough sentinels active to initiate a failover.

 Solution

 To fix this the constellation needs rebalanced. For now this is a global action, but pod-specific actions will be added.

								Name
								Quorum
								Master
								Slave Count
								Sentinel Count

							{{range .Constellation.PodsInError }}
								{{if .HasQuorum }}
								{{else}}

										 {{.Info.Name}}

									{{.Info.Quorum}}
									{{.Info.IP}}:{{.Info.Port}}
										{{if .HasInfo }}
											{{.Master.Info.Replication.ConnectedSlaves}}
										{{else}}
											0
										{{end}}
										{{.SentinelCount}}

								{{end}}
							{{end}}

 Problem

 These pods are missing one or more sentinels. They may have quorum but do not have quorum+1 sentinels actively monitoring it.

 Solution

 To fix this you will need to reset the pod from the pod view.

								Name
								Active Sentinel Count
								Needed Sentinels
								Reported Sentinels

							{{range .Constellation.PodsInError }}
								{{if .MissingSentinels }}

									  {{.Info.Name}}
									{{.SentinelCount}}
									{{.NeededSentinels}}
									{{.ReportedSentinelCount}}

								{{end}}
							{{end}}

 Problem: Too Many Sentinels

 These pods have more sentinels than quorum*2 listed in sentinel. This means there is a possibility of split-brain operation.

							Due to the way Sentinel currently reports other
							sentinels, this can occur when the pod has been
							added to sentinels and then removed from some. It
							is also possible that a failvoer can not occur
							because Sentinel currently insists on a majority of
							the sentinels it has ever seen - regardless of
							current state. Thus if some of the listed sentinels
							are not available there may be no ability for the
							sentinels to elect a leader to activater a
							failover.

 Solution

							To fix this you should first reset the pod from the
							pod view. This will clear out any sentinels which
							are not currently active. Then you will need to
							manually remove any remaining surplus sentinels or
							increase quorum to ensure you have at least half of
							the total sentinels as quorum.

								Name
								Quorum
								Needed Sentinels
								Reported Sentinel Count
								Active Sentinels

							{{range .Constellation.PodsInError }}
							{{if .Name }}
								{{if .TooManySentinels}}

									  {{.Info.Name}}
									{{.Info.Quorum}}
									{{.NeededSentinels}}
									{{.ReportedSentinelCount}}
									{{.SentinelCount}}

								{{end}}
							{{end}}
							{{end}}

 Problem

 These pods do not have a valid slave attached to the master, or we were unable to obtain slave info.

 Solution

 To fix this the master first ensure the pod has the correct authentication information. If not correct that issue first and see if it persists. If it persists or is correct, the master will need to have a slave added to it.

								Name
								Slave Count

							{{range .Constellation.PodsInError }}
								{{ if ne .Name "" }}
								{{if .CanFailover }}
								{{else}}

									  {{.Info.Name}}
									{{if .HasInfo }}
										{{.Master.Info.Replication.ConnectedSlaves}}
									{{else}}
										0
									{{end}}

								{{end}}
								{{end}}
							{{end}}

 Problem

 These pods do not have a valid authentication token set in the sentinels.

 Solution

 To fix this the pod will need to have it's auth set in sentinel. Currently this is a manual process  using "sentinel set auth-pass PODNAME AUTH" in the sentinel CLI and needs done on each sentinel.

								Name
								Master

							{{range .Data.Groups.InvalidAuth }}
								{{ if ne .Name "" }}
									{{if .ValidAuth }}
									{{else}}

										  {{.Info.Name}}
										{{.Info.IP}}:{{.Info.Port}}

									{{end}}
								{{end}}
							{{end}}

{{end}}


text: Problems and their solution for FYS3150 course


text:
require 'spec_helper'

describe Gws::Memo::Category, type: :model, dbscope: :example do
  context "blank params" do
    subject { described_class.new.valid? }
    it { expect(subject).to be_falsey }
  end

  context "default params" do
    subject { create :gws_memo_category }
    it { expect(subject.errors.size).to eq 0 }
  end

  describe ".tree_sort" do
    before do
      create(:gws_memo_category, name: 'A')
      create(:gws_memo_category, name: 'A/AA', order: 100)
      create(:gws_memo_category, name: 'B')
      create(:gws_memo_category, name: 'B/BB')
    end

    subject { described_class.all.tree_sort.to_a }

    it do
      expect(subject.count).to eq 4

      subject[0].tap do |category|
        expect(category.name).to eq 'A'
        expect(category.depth).to eq 0
        expect(category.trailing_name).to eq 'A'
      end

      subject[1].tap do |category|
        expect(category.name).to eq 'A/AA'
        expect(category.depth).to eq 1
        expect(category.trailing_name).to eq 'AA'
      end

      subject[2].tap do |category|
        expect(category.name).to eq 'B'
        expect(category.depth).to eq 0
        expect(category.trailing_name).to eq 'B'
      end

      subject[3].tap do |category|
        expect(category.name).to eq 'B/BB'
        expect(category.depth).to eq 1
        expect(category.trailing_name).to eq 'BB'
      end
    end
  end

  describe ".to_options" do
    before do
      create(:gws_memo_category, name: 'A')
      create(:gws_memo_category, name: 'A/AA', order: 100)
      create(:gws_memo_category, name: 'B')
      create(:gws_memo_category, name: 'B/BB')
    end

    subject { described_class.all.tree_sort.to_options }

    it do
      subject[0].tap do |category|
        expect(category[0]).to eq 'A'
        expect(category[1]).to eq 1
      end

      subject[1].tap do |category|
        expect(category[0]).to eq '+---- AA'
        expect(category[1]).to eq 2
      end

      subject[2].tap do |category|
        expect(category[0]).to eq 'B'
        expect(category[1]).to eq 3
      end

      subject[3].tap do |category|
        expect(category[0]).to eq '+---- BB'
        expect(category[1]).to eq 4
      end
    end
  end
end


text:
from setuptools import setup
from xmlstats import __version__

setup(
  name = 'python-xmlstats',
  packages = ['xmlstats'],
  version = __version__,
  description = 'Client for https://erikberg.com/api',
  author = 'Serbokryl Oleg',
  author_email = 'chezar1995@gmail.com',
  url = 'https://github.com/Krokop/python-xmlstats',
  download_url = 'https://github.com/Krokop/python-xmlstats/tarball/0.14',
  keywords = ['NBA stas api', 'xmlstats', 'NBA API', 'nba api stats'],
  classifiers = [],
  install_requires=[],
)


text:
![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.web/function-app-storage-private-endpoints/PublicLastTestDate.svg)
![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.web/function-app-storage-private-endpoints/PublicDeployment.svg)

![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.web/function-app-storage-private-endpoints/FairfaxLastTestDate.svg)
![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.web/function-app-storage-private-endpoints/FairfaxDeployment.svg)

![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.web/function-app-storage-private-endpoints/BestPracticeResult.svg)
![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/quickstarts/microsoft.web/function-app-storage-private-endpoints/CredScanResult.svg)

[![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.web%2Ffunction-app-storage-private-endpoints%2Fazuredeploy.json)  [![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2Fquickstarts%2Fmicrosoft.web%2Ffunction-app-storage-private-endpoints%2Fazuredeploy.json)

This sample Azure Resource Manager template deploys an Azure Function App that communicates with the Azure Storage account referenced by the [AzureWebJobsStorage](https://docs.microsoft.com/azure/azure-functions/functions-app-settings#azurewebjobsstorage) and [WEBSITE_CONTENTAZUREFILECONNECTIONSTRING](https://docs.microsoft.com/azure/azure-functions/functions-app-settings#website_contentazurefileconnectionstring) app settings, [via private endpoints](https://docs.microsoft.com/en-us/azure/azure-functions/functions-networking-options#private-endpoints).

![Function App with Storage Private Endpoints](/quickstarts/microsoft.web/function-app-storage-private-endpoints/images/function-app-storage-privateendponts.png)

### Azure Function App

The Function App uses the AzureWebJobsStorage and WEBSITE_CONTENTAZUREFILECONNECTIONSTRING app settings to connect to a private endpoint-secured Storage Account.

### Elastic Premium Plan

The Azure Function app provisioned in this sample uses an [Azure Functions Elastic Premium plan](https://docs.microsoft.com/azure/azure-functions/functions-premium-plan#features).

### Azure Storage account

The Storage account that the Function uses for operation and for file contents.

### Virtual Network

Azure resources in this sample either integrate with or are placed within a virtual network. The use of private endpoints keeps network traffic contained with the virtual network.

The sample uses two subnets:

- Subnet for Azure Function virtual network integration.  This subnet is delegated to the Function App.
- Subnet for private endpoints.  Private IP addresses are allocated from this subnet.

### Private Endpoints

[Azure Private Endpoints](https://docs.microsoft.com/azure/private-link/private-endpoint-overview) are used to connect to specific Azure resources using a private IP address  This ensures that network traffic remains within the designated virtual network, and access is available only for specific resources.  This sample configures private endpoints for the following Azure resources:

- [Azure Storage](https://docs.microsoft.com/azure/storage/common/storage-private-endpoints)
  - Azure File storage
  - Azure Blob storage
  - Azure Queue storage
  - Azure Table storage

### Private DNS Zones

Using a private endpoint to connect to Azure resources means connecting to a private IP address instead of the public endpoint.  Existing Azure services are configured to use existing DNS to connect to the public endpoint.  The DNS configuration will need to be overridden to connect to the private endpoint.

A private DNS zone will be created for each Azure resource configured with a private endpoint.  A DNS A record is created for each private IP address associated with the private endpoint.

The following DNS zones are created in this sample:

- privatelink.queue.core.windows.net
- privatelink.blob.core.windows.net
- privatelink.table.core.windows.net
- privatelink.file.core.windows.net

### Application Insights

[Application Insights](https://docs.microsoft.com/azure/azure-monitor/app/app-insights-overview) is used to [monitor the Azure Function](https://docs.microsoft.com/azure/azure-functions/functions-monitoring).


text:
//Soft uni debugging excercise from Programing Fundamentals - Methods and debugging

using System;

/// <summary>
/// Debugging Exercise: Instruction Set
/// Write an ** instruction interpreter** that executes an arbitrary number of** instructions.** The program should** parse the
///  instructions, execute** them and** print the result.** The following instruction set should be supported:
/// - **INC < operand1>** – increments the operand by 1
/// - ** DEC <operand1>** – decrements the operand by 1
/// + ** ADD <operand1> <operand2>** – performs addition on the two operands
/// - ** MLA <operand1> <operand2>**– performs multiplication on the two operands
/// - ** END** – end of input
/// The result of each instruction should be printed on a separate line on the console.
/// - The operands will be valid integers in the range [−2 147 483 648 … 2 147 483 647].
/// </summary>
public class InstructionSet_broken
{
    public static void Main()
    {
        string opCode = string.Empty;
        long result = 0;

        while (opCode != "END")
        {
            opCode = Console.ReadLine();
            string[] codeArgs = opCode.Split(' ');

            switch (codeArgs[0])
            {
                case "INC":
                    {
                        long operandOne = int.Parse(codeArgs[1]);
                        result = ++operandOne;
                        break;
                    }
                case "DEC":
                    {
                        long operandOne = int.Parse(codeArgs[1]);
                        result = --operandOne;
                        break;
                    }
                case "ADD":
                    {
                        long operandOne = int.Parse(codeArgs[1]);
                        long operandTwo = int.Parse(codeArgs[2]);
                        result = operandOne + operandTwo;
                        break;
                    }
                case "MLA":
                    {
                        long operandOne = int.Parse(codeArgs[1]);
                        long operandTwo = int.Parse(codeArgs[2]);
                        result = (operandOne * operandTwo);
                        break;
                    }
                case "END":
                    break;
            }
            if (codeArgs[0] != "END")
            {
                Console.WriteLine(result);
            }

        }
    }
}


text:
package com.intellij.openapi.vcs.vfs;

import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.ChangesUtil;
import com.intellij.openapi.vcs.changes.ContentRevision;
import com.intellij.openapi.vcs.history.ShortVcsRevisionNumber;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

import java.nio.charset.StandardCharsets;
import java.util.Set;

public final class ContentRevisionVirtualFile extends AbstractVcsVirtualFile {
  @NotNull private final ContentRevision myContentRevision;

  private volatile byte[] myContent;
  private volatile boolean myContentLoadFailed;
  private final Object LOCK = new Object();

  private static final Set<ContentRevisionVirtualFile> ourCache = ContainerUtil.createWeakSet();

  public static ContentRevisionVirtualFile create(@NotNull ContentRevision contentRevision) {
    synchronized (ourCache) {
      for (ContentRevisionVirtualFile file : ourCache) {
        if (contentRevision.equals(file.getContentRevision())) return file;
      }
      ContentRevisionVirtualFile file = new ContentRevisionVirtualFile(contentRevision);
      ourCache.add(file);
      return file;
    }
  }

  private ContentRevisionVirtualFile(@NotNull ContentRevision contentRevision) {
    super(contentRevision.getFile().getPath(), VcsFileSystem.getInstance());
    myContentRevision = contentRevision;
    setCharset(StandardCharsets.UTF_8);
  }

  @Override
  public boolean isDirectory() {
    return false;
  }

  @Override
  public byte @NotNull [] contentsToByteArray() {
    if (myContentLoadFailed) {
      return ArrayUtilRt.EMPTY_BYTE_ARRAY;
    }
    if (myContent == null) {
      loadContent();
    }
    return myContent;
  }

  private void loadContent() {
    try {
      byte[] bytes = ChangesUtil.loadContentRevision(myContentRevision);

      synchronized (LOCK) {
        myContent = bytes;
        myContentLoadFailed = false;
        setRevision(myContentRevision.getRevisionNumber().asString());
      }
    }
    catch (VcsException e) {
      synchronized (LOCK) {
        myContentLoadFailed = true;
        myContent = ArrayUtilRt.EMPTY_BYTE_ARRAY;
        setRevision("0");
      }
      showLoadingContentFailedMessage(e);
    }
  }

  @NotNull
  public ContentRevision getContentRevision() {
    return myContentRevision;
  }

  @Nls
  @Override
  protected @NotNull String getPresentableName(@Nls @NotNull String baseName) {
    VcsRevisionNumber number = getContentRevision().getRevisionNumber();
    if (number instanceof ShortVcsRevisionNumber) {
      return baseName + " (" + ((ShortVcsRevisionNumber) number).toShortString() + ")";
    }
    return super.getPresentableName(baseName);
  }
}