text:
"""Smart Grid Game model definition."""

import datetime
import random
from django.core.exceptions import ObjectDoesNotExist

from django.db import models, IntegrityError
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.core.urlresolvers import reverse
from django.conf import settings
from django.template.loader import render_to_string
from django.contrib.localflavor.us.models import PhoneNumberField
import os
from apps.managers.challenge_mgr import challenge_mgr

from apps.managers.score_mgr import score_mgr
from apps.managers.score_mgr.models import PointsTransaction
from apps.managers.team_mgr.models import Post
from apps.utils.utils import media_file_path
from apps.widgets.badges import badges
from apps.widgets.notifications.models import UserNotification
from apps.managers.cache_mgr import cache_mgr
from apps.widgets.smartgrid import NOSHOW_PENALTY_DAYS, SETUP_WIZARD_ACTIVITY
from django.core.validators import MaxValueValidator

_MEDIA_LOCATION_ACTION = os.path.join("smartgrid", "actions")
"""location for the uploaded files for actions."""

_MEDIA_LOCATION_MEMBER = os.path.join("smartgrid", "members")
"""location for the uploaded files for actionmembers."""

def activity_image_file_path(instance=None, filename=None, user=None):
    """Returns the file path used to save an activity confirmation image."""
    if instance:
        user = user or instance.user
    return os.path.join(settings.MAKAHIKI_MEDIA_PREFIX, _MEDIA_LOCATION_MEMBER,
                        user.username, filename)

class TextPromptQuestion(models.Model):
    """Represents questions that can be asked of users in order to verify participation
    in activities."""

    action = models.ForeignKey("Action")
    question = models.TextField(help_text="The question text.")
    answer = models.CharField(max_length=255,
                              help_text="The answer of question (max 255 characters).",
                              null=True, blank=True)

    def __unicode__(self):
        return "Question: '%s' Answer: '%s'" % (self.question, self.answer)

class QuestionChoice(models.Model):
    """Represents questions's multiple choice"""

    question = models.ForeignKey("TextPromptQuestion")
    action = models.ForeignKey("Action")
    choice = models.CharField(max_length=255,
                              help_text="The choice of question (max 255 characters).")

    def __unicode__(self):
        return self.choice

class Level(models.Model):
    """Associates the actions to different levels."""
    name = models.CharField(max_length=50,
                            help_text="The name of the level.")
    slug = models.SlugField(help_text="Automatically generated if left blank.",
                            null=True)
    priority = models.IntegerField(
        default=1,
        help_text="Levels with lower values (higher priority) will be listed first."
    )
    unlock_condition = models.CharField(
        max_length=400, null=True, blank=True,
        help_text="if the condition is True, the level will be unlocked. " +
                   settings.PREDICATE_DOC_TEXT)
    unlock_condition_text = models.CharField(
        max_length=400, null=True, blank=True,
        help_text="The description of the unlock condition.")
    admin_tool_tip = "Smart Grid Level"

    def __unicode__(self):
        return self.name

    class Meta:
        """Meta"""
        ordering = ("priority",)

    def save(self, *args, **kwargs):
        """Custom save method to set fields."""
        super(Level, self).save(args, kwargs)
        cache_mgr.clear()

class ColumnName(models.Model):
    """ColumnNames are used to group actions in the Smart Grid."""
    name = models.CharField(max_length=255,
                            help_text="The name of the column (max 255 characters).")
    slug = models.SlugField(help_text="Automatically generated if left blank.",
                            null=True)

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        """Custom save method to set fields."""
        super(ColumnName, self).save(args, kwargs)
        cache_mgr.clear()

class Action(models.Model):
    """Activity Base class."""
    TYPE_CHOICES = (
        ('activity', 'Activity'),
        ('commitment', 'Commitment'),
        ('event', 'Event'),
        ('filler', 'Filler'),
        )
    RESOURCE_CHOICES = (
        ('energy', 'Energy'),
        ('water', 'Water'),
        ('waste', 'Waste'),
    )

    VIDEO_SOURCE_CHOICES = (
        ('youtube', 'youtube'),
    )

    users = models.ManyToManyField(User, through="ActionMember")

    name = models.CharField(
        max_length=20,
        help_text="The name of the action.")
    slug = models.SlugField(
        help_text="A unique identifier of the action. Automatically generated if left blank.",
        unique=True,
        )
    title = models.CharField(
        max_length=200,
        help_text="The title of the action.")
    image = models.ImageField(
        max_length=255, blank=True, null=True,
        upload_to=media_file_path(_MEDIA_LOCATION_ACTION),
        help_text="Uploaded image for the activity. This will appear under the title when "
                  "the action content is displayed.")
    video_id = models.CharField(
        null=True, blank=True,
        max_length=200,
        help_text="The id of the video (optional). Currently only YouTube video is supported. "
                  "This is the unique id of the video as identified by the YouTube video url.")
    video_source = models.CharField(
        null=True, blank=True,
        max_length=20,
        choices=VIDEO_SOURCE_CHOICES,
        help_text="The source of the video."
    )
    embedded_widget = models.CharField(
        null=True, blank=True,
        max_length=50,
        help_text="The name of the embedded widget (optional)."
    )
    description = models.TextField(
        help_text="The discription of the action. " + settings.MARKDOWN_TEXT
    )
    type = models.CharField(
        max_length=20,
        choices=TYPE_CHOICES,
        help_text="The type of the actions."
    )
    pub_date = models.DateField(
        default=datetime.date.today(),
        verbose_name="Publication date",
        help_text="Date from which the action will be available for users."
    )
    expire_date = models.DateField(
        null=True, blank=True,
        verbose_name="Expiration date",
        help_text="Date after which the action will be marked as expired."
    )
    unlock_condition = models.CharField(
        max_length=400, null=True, blank=True,
        help_text="if the condition is True, the action will be unlocked. " +
                  settings.PREDICATE_DOC_TEXT)
    unlock_condition_text = models.CharField(
        max_length=400, null=True, blank=True,
        help_text="The description of the unlock condition. It will be displayed to players when "
                  "the lock icon is clicked.")
    related_resource = models.CharField(
        max_length=20,
        null=True, blank=True,
        choices=RESOURCE_CHOICES,
        help_text="The resource type this action related.")
    social_bonus = models.IntegerField(
        default=0,
        help_text="Social bonus point value.")
    point_value = models.IntegerField(
        default=0,
        help_text="The point value to be awarded."
    )

    def get_classname(self):
        """Returns the classname."""
        return self._meta.module_name

    def __unicode__(self):
        return "%s: %s" % (self.type.capitalize(), self.title)

    def get_action(self, action_type):
        """Returns the concrete action object by type."""
        return action_type.objects.get(action_ptr=self.pk)

class Activity(Action):
    """Activities involve verifiable actions that users commit to.  These actions can be
   verified by asking questions or posting an image attachment that verifies the user did
   the activity."""

    CONFIRM_CHOICES = (
        ('text', 'Question and Answer'),
        ('image', 'Image Upload'),
        ('free', 'Free Response'),
        ('free_image', 'Free Response and Image Upload'),
        )

    expected_duration = models.IntegerField(
        verbose_name="Expected activity duration",
        help_text="Time (in minutes) that the activity is expected to take."
    )
    point_range_start = models.IntegerField(
        null=True,
        blank=True,
        help_text="Minimum number of points possible for a variable point activity."
    )
    point_range_end = models.IntegerField(
        null=True,
        blank=True,
        help_text="Maximum number of points possible for a variable point activity."
    )
    confirm_type = models.CharField(
        max_length=20,
        choices=CONFIRM_CHOICES,
        default="text",
        help_text="If the type is 'Question and Answer', please provide the "
                  "'Text prompt questions' section below.",
        verbose_name="Confirmation Type"
    )
    confirm_prompt = models.TextField(
        blank=True,
        verbose_name="Confirmation prompt",
        help_text=settings.MARKDOWN_TEXT
    )
    admin_note = models.TextField(
        null=True, blank=True,
        help_text="Notes for admins when approving this activity. " + settings.MARKDOWN_TEXT)

    def is_active(self):
        """Determines if the activity is available for users to participate."""
        return self.is_active_for_date(datetime.date.today())

    def is_active_for_date(self, date):
        """Determines if the activity is available for user participation at the given date."""
        pub_result = date - self.pub_date
        expire_result = self.expire_date - date
        if pub_result.days < 0 or expire_result.days < 0:
            return False
        return True

    def pick_question(self, user_id):
        """Choose a random question to present to a user."""
        if self.confirm_type != "text":
            return None

        questions = TextPromptQuestion.objects.filter(action=self)
        if questions:
            return questions[user_id % len(questions)]
        else:
            return None

    class Meta:
        """meta"""
        verbose_name_plural = "Activities"

class Commitment(Action):
    """Commitments involve non-verifiable actions that a user can commit to.
    Typically, they will be worth fewer points than activities."""
    commitment_length = models.IntegerField(
        default=5,
        help_text="Duration of commitment, in days."
    )

class Event(Action):
    """Events will be verified by confirmation code. It includes events and excursions."""

    expected_duration = models.IntegerField(
        verbose_name="Expected activity duration",
        help_text="Time (in minutes) that the activity is expected to take."
    )
    event_date = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name="Date and time of the event",
        help_text="Required for events."
    )
    event_location = models.CharField(
        blank=True,
        null=True,
        max_length=200,
        verbose_name="Event Location",
        help_text="Location of the event"
    )
    event_max_seat = models.IntegerField(
        default=1000,
        help_text="Specify the max number of seats available to the event."
    )

    def is_event_completed(self):
        """Determines if the event is completed."""
        if self.event_date:
            result = datetime.datetime.today() - self.event_date
            if result.days >= 0 and result.seconds >= 0:
                return True
        return False

class Filler(Action):
    """Filler action. It is always locked"""
    pass

class ColumnGrid(models.Model):
    """Defines the ColumnName positions in the Smart Grid."""
    level = models.ForeignKey(Level,
        help_text="The level of the action."
    )
    column = models.IntegerField(
        default=1,
        help_text="The column of the Smart Grid this Action is in.",
        validators=[MaxValueValidator(8)]
    )
    name = models.ForeignKey(ColumnName,
                             help_text="The ColumnName in this location.")

class Grid(models.Model):
    """Defines the Smart Grid, holds the level, column, row, and Action."""
    level = models.ForeignKey(Level,
        help_text="The level of the action."
    )
    column = models.IntegerField(
        default=1,
        help_text="The column of the Smart Grid this Action is in.",
        validators=[MaxValueValidator(8)]
    )
    row = models.IntegerField(
        default=1,
        help_text="The row of the Smart Grid this Action is in.",
        validators=[MaxValueValidator(8)]
    )
    action = models.ForeignKey(Action,
                               help_text="The Action in this location.")

    class Meta:
        """Meta"""
        ordering = ("level", "column", "row")

    def __unicode__(self):
        return "%s: [%s, x=%s, y=%s]" % (self.action, self.level, self.column, self.row)

class ActionMember(models.Model):
    """Represents the join between commitments and users.  Has fields for
    commenting on a commitment and whether or not the commitment is currently
    active."""

    STATUS_TYPES = (
        ('pending', 'Pending approval'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
        )

    user = models.ForeignKey(User)
    action = models.ForeignKey(Action)
    question = models.ForeignKey(TextPromptQuestion, null=True, blank=True)
    notifications = generic.GenericRelation(UserNotification, editable=False)
    pointstransactions = generic.GenericRelation(PointsTransaction, editable=False)

    submission_date = models.DateTimeField(
        editable=False,
        help_text="The submission date.")
    completion_date = models.DateField(
        null=True, blank=True,
        help_text="The completion date."
    )
    award_date = models.DateTimeField(
        null=True, blank=True, editable=False,
        help_text="The award date.")
    approval_status = models.CharField(
        max_length=20, choices=STATUS_TYPES, default="pending",
        help_text="The approval status.")
    social_bonus_awarded = models.BooleanField(default=False,
        help_text="Is the social bonus awarded?")
    comment = models.TextField(
        blank=True,
        help_text="The comment from user submission.")
    social_email = models.TextField(
        blank=True, null=True,
        help_text="Email address of the person the user went with.")
    response = models.TextField(
        blank=True,
        help_text="The response of the submission.")
    admin_comment = models.TextField(
        blank=True,
        help_text="Reason for approval/rejection")
    image = models.ImageField(
        max_length=1024, blank=True,
        upload_to=activity_image_file_path,
        help_text="Uploaded image for verification.")
    points_awarded = models.IntegerField(
        blank=True, null=True,
        help_text="Number of points to award for activities with variable point values.")
    created_at = models.DateTimeField(editable=False, auto_now_add=True)
    updated_at = models.DateTimeField(editable=False, auto_now=True, null=True)
    admin_link = models.CharField(max_length=100, blank=True, null=True)
    admin_tool_tip = "Player submission for Actions"

    class Meta:
        """meta"""
        unique_together = ('user', 'action', 'submission_date')
        verbose_name_plural = "Action Submissions"

    def __unicode__(self):
        return "%s : %s" % (self.action.title, self.user.username)

    def active(self):
        """return active member"""
        return self.approval_status == "approved"

    def user_link(self):
        """return the user first_name."""
        return '%s' % ("/admin/player_mgr/profile",
                                            self.user.get_profile().pk,
                                            self.user.username)
    user_link.allow_tags = True
    user_link.short_description = 'Link to profile'

    def days_left(self):
        """
        Returns how many days are left before the user can submit the activity.
        """
        diff = self.completion_date - datetime.date.today()
        if diff.days < 0:
            return 0

        return diff.days

    def check_admin_link(self):
        """Sets admin_link if not already set."""
        if not self.admin_link:
            link = "/admin/smartgrid/" + self.action.type + "/" + str(self.action.id)
            self.admin_link = link

    def save(self, *args, **kwargs):
        """custom save method."""

        self.check_admin_link()

        if self.social_bonus_awarded:
            # only awarding social bonus
            super(ActionMember, self).save(args, kwargs)
            return

        if self.approval_status == u"rejected":
            self.award_date = None
            super(ActionMember, self).save(args, kwargs)

            self._handle_activity_notification(self.approval_status)
        else:
            if self.approval_status == u"pending":
                # Mark pending items as submitted.

                self.submission_date = datetime.datetime.today()

                if self.action.type == "commitment" and not self.completion_date:
                    self.completion_date = self.submission_date + \
                        datetime.timedelta(days=self.action.commitment.commitment_length)

                super(ActionMember, self).save(args, kwargs)

                self._award_signup_points()

            else:    # is approved
                if not self.points_awarded:
                    self.points_awarded = self.action.point_value

                # Record dates.
                self.award_date = datetime.datetime.today()

                if self.submission_date:
                    if self.action.type in ("event", "excursion"):
                        # this is an event with signup
                        # must save before awarding point due to the generic foreign key relation
                        super(ActionMember, self).save(args, kwargs)
                        self._award_possible_reverse_penalty_points()
                else:
                    # always make sure the submission_date is set
                    self.submission_date = self.award_date

                # must save before awarding point due to the generic foreign key relation
                super(ActionMember, self).save(args, kwargs)
                self._award_points()

                self.social_bonus_awarded = self._award_possible_social_bonus()
                if self.social_bonus_awarded:
                    super(ActionMember, self).save(args, kwargs)

                self._handle_activity_notification(self.approval_status)

        self.post_to_wall()
        self.invalidate_cache()
        badges.award_possible_badges(self.user.get_profile(), "smartgrid")

    def _award_points(self):
        """Custom save method to award points."""
        profile = self.user.get_profile()

        points = self.points_awarded
        if not points:
            points = self.action.point_value

        if self.action.type == "activity":
            transaction_date = self.submission_date
        elif self.action.type == "commitment":
            transaction_date = self.award_date
        else:  # is Event
            transaction_date = self.award_date

        profile.add_points(points, transaction_date, self.action, self)

    def _award_possible_social_bonus(self):
        """award possible social bonus."""

        profile = self.user.get_profile()
        social_message = "%s (Social Bonus)" % self.action

        # award social bonus to others who referenced my email and successfully completed
        # the activity
        if self.user.email:
            ref_members = ActionMember.objects.filter(action=self.action,
                                                      approval_status="approved",
                                                      social_email=self.user.email)
            for m in ref_members:
                if not m.social_bonus_awarded:
                    ref_profile = m.user.get_profile()
                    ref_profile.add_points(m.action.social_bonus,
                                           m.award_date,
                                           social_message, self)
                    m.social_bonus_awarded = True
                    m.save()

        ## award social bonus to myself if the ref user had successfully completed the activity
        if self.social_email and not self.social_bonus_awarded:
            ref_members = ActionMember.objects.filter(user__email=self.social_email,
                                                      approval_status="approved",
                                                      action=self.action)
            if ref_members:
                profile.add_points(self.action.social_bonus,
                                   self.award_date,
                                   social_message, self)
                return True

        return False

    def _award_signup_points(self):
        """award the sign up point for commitment and event."""

        if self.action.type != "activity":
            #increase the point from signup
            message = "%s (Sign up)" % self.action
            self.user.get_profile().add_points(score_mgr.signup_points(),
                                               self.submission_date,
                                               message,
                                               self)

    def _drop_signup_points(self):
        """award the sign up point for commitment and event."""

        if self.action.type != "activity":
            #increase the point from signup
            message = "%s (Drop Sign up)" % self.action
            self.user.get_profile().remove_points(score_mgr.signup_points(),
                                               self.submission_date,
                                               message,
                                               self)

    def _award_possible_reverse_penalty_points(self):
        """ reverse event noshow penalty."""
        if self._has_noshow_penalty():
            message = "%s (Reverse No Show Penalty)" % self.action
            self.user.get_profile().add_points(
                score_mgr.noshow_penalty_points() + score_mgr.signup_points(),
                self.award_date,
                message,
                self)

    def _has_noshow_penalty(self):
        """if NOSHOW_PENALTY_DAYS past and has submission_date (signed up),
        return true as noshow penalty."""
        event = self.action.event
        diff = datetime.date.today() - event.event_date.date()
        if diff.days > NOSHOW_PENALTY_DAYS and self.submission_date:
            return True
        else:
            return False

    def _handle_activity_notification(self, status):
        """Creates a notification for rejected or approved tasks.
        This also creates an email message if it is configured.
        """
        # don't create notification if the action is the SETUP_WIZARD_ACTIVITY
        # that is used in the setup wizard.
        if self.action.slug == SETUP_WIZARD_ACTIVITY:
            return

        # Construct the message to be sent.
        status_nicely = 'not approved' if status != 'approved' else status
        message = 'Your response to "%s" %s was %s.' % (
            reverse("activity_task", args=(self.action.type, self.action.slug,)),
            self.action.title,
            # The below is to tell the javascript to convert into a pretty date.
            # See the prettyDate function in media/js/makahiki.js
            '' % self.submission_date.isoformat(),
            status_nicely,
            )

        if status != 'approved':
            challenge = challenge_mgr.get_challenge()
            message += " You can still get points by clicking on the link and trying again."
            UserNotification.create_error_notification(self.user, message, display_alert=True,
                                                       content_object=self)

            # only send out email notification for rejected action
            subject = "[%s] Your response to '%s' was %s" % (
                challenge.name, self.action.title, status_nicely)

            message = render_to_string("email/rejected_activity.txt", {
                "object": self,
                "COMPETITION_NAME": challenge.name,
                "domain": challenge.domain,
                "status_nicely": status_nicely,
                })
            html_message = render_to_string("email/rejected_activity.html", {
                "object": self,
                "COMPETITION_NAME": challenge.name,
                "domain": challenge.domain,
                "status_nicely": status_nicely,
                })

            UserNotification.create_email_notification(
                self.user.email, subject, message, html_message)
        else:
            points = self.points_awarded if self.points_awarded else self.action.point_value
            message += " You earned %d points!" % points

            UserNotification.create_success_notification(self.user, message, display_alert=True,
                                                         content_object=self)

            # if admin approve an activity (action_type==activity),
            # check to the submission queue is empty,
            # if so, remove the admin reminder object.
            if self.action.type == "activity":
                submission_count = ActionMember.objects.filter(
                    action__type="activity",
                    approval_status="pending").count()
                if not submission_count:
                    try:
                        admin = User.objects.get(username=settings.ADMIN_USER)
                        action = Action.objects.get(slug=SETUP_WIZARD_ACTIVITY)
                        EmailReminder.objects.filter(user=admin, action=action).delete()
                    except ObjectDoesNotExist:
                        pass

    def post_to_wall(self):
        """post to team wall as system post."""
        team = self.user.get_profile().team
        if team:
            if self.approval_status == "approved":
                # User completed the commitment
                message = "has completed the %s \"%s\"." % (self.action.type,
                                                            self.action.title,)
            else:
                # User is adding the commitment.
                message = "is participating in the %s \"%s\"." % (self.action.type,
                                                                  self.action.title,)

            post = Post(user=self.user,
                        team=team,
                        text=message,
                        style_class="system_post")
            post.save()

    def invalidate_cache(self):
        """Invalidate the categories cache."""
        username = self.user.username
        cache_mgr.delete('smartgrid-levels-%s' % username)
        cache_mgr.delete('smartgrid-completed-%s' % username)
        cache_mgr.delete('user_events-%s' % username)
        cache_mgr.delete('get_quests-%s' % username)
        cache_mgr.delete('golow_actions-%s' % username)

        team = self.user.get_profile().team
        if team:
            cache_mgr.invalidate_template_cache("team_avatar", self.action.id, team.id)
        cache_mgr.invalidate_template_cache("my_commitments", username)
        cache_mgr.invalidate_template_cache("my_achievements", username)
        cache_mgr.invalidate_template_cache("smartgrid", username)

    def delete(self, using=None):
        """Custom delete method to remove the points for completed action."""
        profile = self.user.get_profile()

        if self.approval_status == "approved":
            # remove all related point transaction
            profile.remove_related_points(self)
        else:
            # drop any possible signup transaction
            self._drop_signup_points()

        if profile.team:
            message = "is no longer participating in the %s \"%s\"." % (
                self.action.type, self.action.title,)
            post = Post(user=self.user,
                        team=profile.team,
                        text=message,
                        style_class="system_post")
            post.save()

        self.invalidate_cache()

        super(ActionMember, self).delete()

class Reminder(models.Model):
    """
    Sends a reminder for an activity to a user.  Reminders are queued up and sent later.
    """
    REMINDER_CHOICES = (
        ("email", "Email"),
        ("text", "Text"),
        )

    user = models.ForeignKey(User, editable=False)
    action = models.ForeignKey(Action, editable=False)

    send_at = models.DateTimeField(
        help_text="The send time of the reminder."
    )
    sent = models.BooleanField(
        default=False, editable=False,
        help_text="Is reminder sent?")

    created_at = models.DateTimeField(editable=False, auto_now_add=True)
    updated_at = models.DateTimeField(editable=False, auto_now=True, null=True)

    class Meta:
        """meta"""
        abstract = True
        unique_together = ("user", "action")

    def send(self):
        """send methods that subclass all required to implement."""
        raise NotImplementedError("Reminder subclasses need to implement send.")

class EmailReminder(Reminder):
    """Email Reminder Class"""
    email_address = models.EmailField(
        help_text="The email address."
    )

    def send(self):
        """
        Sends a reminder email to the user.
        """
        if not self.sent:
            challenge = challenge_mgr.get_challenge()
            subject = "[%s] Reminder for %s" % (challenge.name,
                                                self.action.title)
            message = render_to_string("email/activity_reminder.txt", {
                "action": self.action,
                "user": self.user,
                "COMPETITION_NAME": challenge.name,
                "domain": challenge.domain,
                })
            html_message = render_to_string("email/activity_reminder.html", {
                "action": self.action,
                "user": self.user,
                "COMPETITION_NAME": challenge.name,
                "domain": challenge.domain,
                })

            UserNotification.create_email_notification(self.email_address, subject, message,
                html_message)
            self.sent = True
            self.save()

class TextReminder(Reminder):
    """Text Reminder Class"""
    TEXT_CARRIERS = (
        ('att', 'AT&T'),
        ('sprint', 'Sprint'),
        ('tmobile', 'T-Mobile'),
        ('verizon', 'Verizon'),
        ('mobi', 'Mobi PCS'),
        ('virgin', 'Virgin Mobile'),
        ('alltel', "AllTel"),
        )
    TEXT_EMAILS = {
        "att": "txt.att.net",
        "verizon": "vtext.com",
        "tmobile": "tmomail.net",
        "sprint": "messaging.sprintpcs.com",
        "mobi": "mobipcs.net",
        "virgin": "vmobl.com",
        "alltel": "message.alltel.com",
        }
    text_number = PhoneNumberField(
        help_text="The phone number."
    )
    text_carrier = models.CharField(
        max_length=50, choices=TEXT_CARRIERS, null=True, blank=True,
        help_text="The phone carrier.")

    def send(self):
        """
        Sends a reminder text to the user via an email.
        """
        number = self.text_number.replace("-", "")
        email = number + "@" + self.TEXT_EMAILS[self.text_carrier]
        if not self.sent:
            message = render_to_string("email/activity_text_reminder.txt", {
                "activity": self.action,
                "user": self.user,
                })

            UserNotification.create_email_notification(email, "", message)
            self.sent = True
            self.save()

class ConfirmationCode(models.Model):
    """Represents confirmation codes for activities."""
    action = models.ForeignKey(Action)
    code = models.CharField(max_length=50, unique=True, db_index=True,
                            help_text="The confirmation code.")
    is_active = models.BooleanField(default=True, editable=False,
                                    help_text="Is the confirmation code still active?")
    user = models.ForeignKey(User, null=True, blank=True,
                             help_text="The user who claimed the code.")
    create_date = models.DateTimeField(default=datetime.datetime.now(),
                                   verbose_name="Date created",
                                   help_text="Date the code was created.")
    printed_or_distributed = models.BooleanField(default=False, editable=True,
                                help_text="Has the code been printed or distributed.")

    @staticmethod
    def generate_codes_for_activity(event, num_codes):
        """Generates a set of random codes for the activity."""
        values = 'abcdefghijkmnpqrstuvwxyz234789'

        # Use the first non-dash component of the slug.
        components = event.slug.split('-')
        header = components[0]
        # Need to see if there are other codes with this header.
        index = 1
        while ConfirmationCode.objects.filter(code__istartswith=header).exclude(
            action=event).count() > 0 and index < len(components):
            header += components[index]
            index += 1

        header += "-"
        for _ in range(0, num_codes):
            code = ConfirmationCode(action=event, code=header)
            valid = False
            while not valid:
                for value in random.sample(values, 5):
                    code.code += value
                try:
                    # print code.code
                    # Throws exception if the code is a duplicate.
                    code.save()
                    valid = True
                except IntegrityError:
                    # Try again.
                    code.code = header


text:
namespace :remote do

  # Remote DB:Diff_apply task
  #
  desc <<-DESC
  Works similarly to the local db:store_meeting_invitation task but for a remote DB.

Uploads a copy of a Meeting Manifest (assumed to be already in HTML/XHTML format)
from a local directory to the remote server. Then, the db:store_meeting_invitation
is invoked remotely to store the invitation/manifest into the remote DB.

At the end, the remote DB is dumped and downloaded, unless the +skip_download+
option is used.

  === OPTIONS ===

  Options: meeting_id=<meeting_id>
           file=<path_to_file>
           [warm_up=<warm_up_time> begin=<begin_time> [day_part=<day_part_type.code>]]
           [skip_download=<0>|1]

  DESC
  task :db_store_manifest do
    # Environment setup
    meeting_id    = ENV["meeting_id"].to_i
    full_pathname = ENV["file"]
    skip_download = ENV.include?("skip_download") && (ENV["skip_download"].to_i > 0)
    warm_up_time  = ENV.include?("warm_up") ? ENV["warm_up"] : nil
    begin_time    = ENV.include?("begin") ? ENV["begin"] : nil
    day_part_type_code = ENV.include?("day_part") ? ENV["day_part"] : 'P'

    run_locally do
      puts "\r\n*** remote:db_store_manifest ***"
      unless meeting_id > 0 && ENV.include?("file") && File.exists?( full_pathname )
        puts("This task needs at least a valid 'meeting_id' and 'file' parameters.")
        exit
      end
      text_file_contents = File.read( full_pathname )

      # Display some info:
      puts "Meeting ID...............: #{ meeting_id }"
      puts "warm_up_time.............: #{ warm_up_time }"
      puts "begin_time...............: #{ begin_time }"
      puts "day_part_type_code ......: #{ day_part_type_code }"
      puts "Processed Manifest.......: #{ full_pathname } (size: #{ text_file_contents.size })"
      puts "DB Dump Download phase...: #{ skip_download ? 'OFF' : '(enabled)' }"
    end

    # === UPLOAD phase: ===

    on roles(:app) do
      info "\r\nUploading file #{ full_pathname } ..."
      # Upload the SQL DB-Diff file:
      upload! full_pathname, '/tmp/temp_manifest.html'
      # Run the rake task to store the manifest:
      within release_path do
        with rails_env: :production do
          options = "db:store_meeting_manifest meeting_id=#{ meeting_id } file=\"/tmp/temp_manifest.html\""
          options << " warm_up=\"#{ warm_up_time }\"" if warm_up_time.to_s.size > 0
          options << " begin=\"#{ begin_time }\"" if begin_time.to_s.size > 0
          options << " day_part=\"#{ day_part_type_code }\"" if day_part_type_code.to_s.size > 0
          rake options
        end
      end

      # After execution remove temp files on dest host:
      info "Removing remote temp files..."
      execute :rm, '/tmp/temp_manifest.html'
    end

    unless skip_download
      puts "\r\nAlmost done: getting an updated remote PRODUCTION dump...\r\n"
      invoke "db:remote:sql_dump"
    else
      puts "\r\nRemote PRODUCTION dump download skipped by request.\r\nDone.\r\n"
    end
  end
  #-- -------------------------------------------------------------------------
  #++
end

redpajama_set_name: RedPajamaGithub


text:
package ru.mipt.transmitter;

import ru.mipt.agents.AgentInterface;
import ru.mipt.agents.model.Signal;

public interface VideoTransmitterAgentInterface
{
	Signal getVideoSignal();

}


text:
Sharing objects between fixtures
================================

Your models are likely to have relationships with each other. Because of
that, it can be interesting to create and persist an object in a
fixture, and then reference it in another fixture.

Assuming you have a ``User`` and a ``Role`` model, here is an example
showing how to use the ``AbstractFixture`` class to do that.

.. note::

   ``AbstractFixture`` implements ``FixtureInterface``, which means the
   requirement mentioned in the :doc:`previous how-to guide
   <loading-fixtures>` is satisfied if you extend ``AbstractFixture``.

.. code-block:: php
    <?php
    namespace MyDataFixtures;

    use Doctrine\Common\DataFixtures\AbstractFixture;
    use Doctrine\Persistence\ObjectManager;

    class UserRoleDataLoader extends AbstractFixture
    {
        public function load(ObjectManager $manager): void
        {
            $adminRole = new Role();
            $adminRole->setName('admin');

            $anonymousRole = new Role();
            $anonymousRole->setName('anonymous');

            $manager->persist($adminRole);
            $manager->persist($anonymousRole);
            $manager->flush();

            // store reference to admin role for User relation to Role
            $this->addReference('admin-role', $adminRole);
        }
    }

And the ``User`` data loading fixture:

.. code-block:: php
    <?php

    namespace MyDataFixtures;

    use Doctrine\Common\DataFixtures\AbstractFixture;
    use Doctrine\Persistence\ObjectManager;

    class UserDataLoader extends AbstractFixture
    {
        public function load(ObjectManager $manager): void
        {
            $user = new User();
            $user->setUsername('jwage');
            $user->setPassword('test');
            $user->setRole(
                $this->getReference('admin-role') // load the stored reference
            );

            $manager->persist($user);
            $manager->flush();

            // store reference of admin-user for other Fixtures
            $this->addReference('admin-user', $user);
        }
    }

Note that because that last fixture depends on the first one, the order
in which fixtures are loading becomes important. You can learn more
about how to manage loading order in :doc:`the dedicated guide
<fixture-ordering>`.


text:
class Api::V1::MatchSerializer < ActiveModel::Serializer
  attributes :id, :created_at, :updated_at, :teams

  def teams
    object.teams.map do |team|
      Api::V1::MatchSerializer::TeamSerializer.new(team, the_match: object)
    end
  end

  class TeamSerializer < ActiveModel::Serializer
    attributes :id, :name, :score, :users, :win, :goals

    def score
      get_teams_score[:home]
    end

    def win
      scores = get_teams_score
      scores[:home] > scores[:away]
    end

    def users
      object.serial_numbers.map do |sn|
        user = sn.user
        result = { name: user.name, display_name: user.display_name }
        result[:position] = object.sn1_position if sn.number == object.sn1
        result[:position] = object.sn2_position if sn.number == object.sn2
        result
      end
    end

    def goals
      goals = match.goals.map do |goal|
        if goal.team_id == object.id
          Api::V1::MatchSerializer::GoalSerializer.new(goal)
        end
      end
      goals.compact
    end

    protected

    def get_teams_score
      scores = { home: 0, away: 0 }
      match.goals.each do |goal|
        t = goal.team_id == object.id ? :home : :away
        scores[t] = scores[t] + goal.score
      end
      scores
    end

    def match
      @instance_options[:the_match]
    end

  end

  class GoalSerializer < ActiveModel::Serializer
    attributes :score, :team_id, :at
  end
end


text:
using System;

namespace Microsoft.DirectX.Direct3D
{
	public enum DeviceType
	{
		NullReference = 4,
		Software = 3,
		Reference = 2,
		Hardware = 1
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Paritanssi.DAL;
using Paritanssi.Models;

namespace Paritanssi.Logic {
    public class Repository<T> where T : IEntity {

        private DatabaseContext _context;

        public Repository() {
            _context = new DatabaseContext();
        }

        public Repository(DatabaseContext context) {
            _context = context;
        }

        public void Add() {

        }

    }
}


text:
const loadPrismLanguage = require(`../load-prism-language`)

describe(`load prism language`, () => {
  afterEach(() => {
    jest.resetModules()
  })

  it(`throw if language not support`, () => {
    expect(() => loadPrismLanguage(`imnotalanguage`)).toThrow(
      `Prism doesn't support language 'imnotalanguage'.`
    )
  })

  it(`load supported language`, () => {
    const language = `c`
    const Prism = require(`prismjs`)

    const languagesBeforeLoaded = Object.keys(Prism.languages)
    expect(Prism.languages).not.toHaveProperty(language)

    loadPrismLanguage(language)

    const languagesAfterLoaded = Object.keys(Prism.languages)
    expect(Prism.languages).toHaveProperty(language)
    expect(languagesAfterLoaded.length).toBe(languagesBeforeLoaded.length + 1)
  })

  it(`also load the required language`, () => {
    const language = `cpp`
    const requiredLanguage = `c`
    const Prism = require(`prismjs`)

    const languagesBeforeLoaded = Object.keys(Prism.languages)
    expect(Prism.languages).not.toHaveProperty(language)
    expect(Prism.languages).not.toHaveProperty(requiredLanguage)

    loadPrismLanguage(language)

    const languagesAfterLoaded = Object.keys(Prism.languages)
    expect(Prism.languages).toHaveProperty(language)
    expect(Prism.languages).toHaveProperty(requiredLanguage)
    expect(languagesAfterLoaded.length).toBe(languagesBeforeLoaded.length + 2)
  })
})


text:
function data = plotData(f, g, h)
%PLOTDATA   Useful data values for plotting a BNDFUN object.
%   DATA = PLOTDATA(F) returns a struct containing data that can be used for
%   plotting F. In particular, DATA.xLine and DATA.yLine are for plotting smooth
%   curves (usually passed to plot with '-') and DATA.xPoints and DATA.yPoints
%   contain the (x, F(x)) data used to represent F.
%
%   DATA = PLOTDATA(F, G) returns data for PLOT(F, G), i.e., (F(x), G(x)), and
%   DATA = PLOTDATA(F, G, H) returns data for plots of the form PLOT3(F, G, H).
%   In the latter case, DATA also contains the fields zLine and zPoints.
%
% See also PLOT.

% Copyright 2016 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% Get the data from the ONEFUN:
if ( (nargin == 1) || isempty(g) )
    % PLOT(F):
    data = plotData(f.onefun);
    % Map the 'x' data using f.mapping.For:
    data.xLine = f.mapping.For(data.xLine);
    data.xPoints = f.mapping.For(data.xPoints);

    % Sort out the jumps:
    data.xJumps = [f.domain(1) ; NaN ; f.domain(2)];
    data.yJumps = getJumps(f, data.yLine);

    % Overwrite the current xLim if it is provided by plotData@singfun:
    data.xLim = f.domain;

elseif ( nargin == 2 )
    % PLOT(F, G):
    data = plotData(f.onefun, g.onefun);

    % Sort out the jumps:
    data.xJumps = getJumps(f, data.xLine);
    data.yJumps = getJumps(g, data.yLine);

else
    % PLOT(F, G, H):
    data = plotData(f.onefun, g.onefun, h.onefun);

    % Sort out the jumps:
    data.xJumps = getJumps(f, data.xLine);
    data.yJumps = getJumps(g, data.yLine);
    data.zJumps = getJumps(h, data.zLine);

end

end

function jumps = getJumps(f, fLine)
    lvalF = get(f, 'lval');
    rvalF = get(f, 'rval');

    % Deal with functions which blow up:
    ind = isinf(lvalF);
    lvalF(ind) = fLine(2, ind);
    ind = isinf(rvalF);
    rvalF(ind) = fLine(end-1, ind);

    myNaN = nan(size(lvalF));
    jumps = [lvalF ; myNaN ; rvalF];
end


text:
import { NgModule } from '@angular/core';
import { IonicModule } from 'ionic-angular';
import { CoinListComponent } from './coin-list';
import { CoinComponentModule } from '../coin/coin.module';

@NgModule({
  declarations: [CoinListComponent],
  imports: [IonicModule, CoinComponentModule],
  exports: [CoinListComponent]
})
export class CoinListComponentModule {}


text:
package org.drools.guvnor.client.common;

import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.core.client.GWT;

import org.drools.guvnor.client.messages.Constants;
import org.drools.guvnor.client.resources.Images;

/**
 * This presents validation error messages to the user, from the server side.
 * Such as validation or compile errors.
 */
public class ValidationMessageWidget extends FormStylePopup {

    private Constants     constants = ((Constants) GWT.create( Constants.class ));
    private static Images images    = (Images) GWT.create( Images.class );

    /**
     * The heading is the short description in bold at the top.
     */
    public ValidationMessageWidget(String heading,
                                   String body) {

        super( images.attentionNeeded(),
               heading );
        addAttribute( constants.Detail(),
                      details( body ) );
    }

    private Widget details(String body) {
        TextArea area = new TextArea();
        area.setStyleName( "editable-Surface" );
        area.setVisibleLines( 12 );
        area.setText( body );
        area.setWidth( "100%" );
        return area;
    }
}


text:
#import <FBControlCore/FBTaskExecutor.h>

@interface FBTaskExecutor (Convenience)

/**
 @see executeShellCommand:returningError:
 */
- (NSString *)executeShellCommand:(NSString *)command;

/**
 Executes the given command using the shell and returns the result.
 The returned string has leading/trailing whitespace and new lines trimmed.
 Will error if the time taken to execute the command exceeds the default timeout.

 @param command The shell command to execute. File Paths must be quoted or escaped. Must not be nil.
 @param error NSError byref to be populated if an error occurs while executing the command. May be nil. Populates the userInfo with stdout.
 @return The stdout from the command. Returns nil if an Error occured.
 */
- (NSString *)executeShellCommand:(NSString *)command returningError:(NSError **)error;

/**
 Repeatedly runs the given command, passing the output to the block.
 When the block returns YES or the timeout is reached, the method will exit.
 If a non-zero exit code is returned, the method will exit.

 @param command the Command String to run.
 @param error Error Outparam for any error that occures
 @param block the predicate to verify stdOut against
 @return YES if the untilTrue block returns YES before the timeout, NO otherwise.
 */
- (BOOL)repeatedlyRunCommand:(NSString *)command withError:(NSError **)error untilTrue:( BOOL(^)(NSString *stdOut) )block;

@end


text:
package testutil.benchmark;

import com.sun.xml.ws.api.streaming.XMLStreamWriterFactory;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * Benchmark test driver.
 *
 * <p>
 * For historical reasons, many of the properties can be configured
 * both from system properties and command line options.
 *
 * @author JAX-RPC RI Development Team
 */
public class BenchmarkTests {

    @Argument
    private List<String> tests = new ArrayList<>();

    @Option(name="-l",usage="test the local transport")
    private boolean uselocal;

    private final PrintStream out = System.out;

    private XMLStreamWriter writer = null;
    private String version = "2.0";

    @Option(name="-p",usage="package name of the benchmark. either 'doclit' or 'rpclit'")
    private String testPackage = System.getProperty("package.prefix");

    @Option(name="-i",usage="number of iteration for the test")
    private int iterations = getIntProperty("iterations", 100);

    @Option(name="-w",usage="number of iteration for the warm up")
    private int warmup = getIntProperty("warmup",100);

    private String state = System.getProperty("state", "first");

    private final String classPrefix = "Echo";
    private final String classSuffix = "Benchmark";
    private final String xmlLog = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "jaxrpc-benchmark.xml";
    private final String htmlLog = System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "jaxrpc-benchmark.html";

    public static void main(String[] args) throws Exception {
        System.exit(new BenchmarkTests().run(args));
    }

    public BenchmarkTests() {
        String temp = System.getProperty("uselocal");
        uselocal = temp != null && temp.equals("true");
    }

    public int run(String[] args) throws Exception {
        CmdLineParser p = new CmdLineParser(this);
        try {
            p.parseArgument(args);
        } catch (CmdLineException e) {
            System.err.println(e);
            p.printUsage(System.err);
            return -1;
        }

        if(testPackage==null) {
            System.err.println("-p option is mandatory");
            return -1;
        }

        // ugly workaround. test code refers to this system property
        // everywhere. If you are serious about the transport independence,
        // you should be able to set a custom transport without relying
        // on a system property! But unless that is fixed, we need this.
        System.setProperty("uselocal",Boolean.toString(uselocal));

        boolean first = state.equalsIgnoreCase("first");
        FileOutputStream fos = new FileOutputStream(xmlLog, !first);
        writer = XMLStreamWriterFactory.create(fos, "UTF-8");
        if (first) {
            writer.writeStartElement("benchmark");
            writeEnvironment(writer);
        }
        writer.writeStartElement(testPackage);
        writer.writeAttribute("jaxrpc-version", version);
        writer.writeAttribute("jdk-version", System.getProperty("java.vm.version"));

        // run the tests
        if(tests.isEmpty()) {
            System.err.println("No test to run");
            return -1;
        }

        for( String test : tests )
            invoke(test);

        writer.writeEndElement();
        writer.close();
        fos.close();
        boolean last = state.equalsIgnoreCase("last");
        if (last) {
            fos = new FileOutputStream(xmlLog, true);
            fos.write("</benchmark>".getBytes());
            fos.flush();
            fos.close();
            out.println("******* XML log generated in \"" + xmlLog + "\"");
            convertToHTML();
        }

        return 0;
    }

    private void invoke(String classType) throws Exception {
	if ("\"\"".equals(classType)) {
		classType = "";
	}
        String className = "benchmark." + testPackage + ".client." + classPrefix + classType + classSuffix;
        @SuppressWarnings({"unchecked"})
        Class<? extends Benchmark> classObject = (Class<? extends Benchmark>) Class.forName(className);
        Constructor<? extends Benchmark> ctor = classObject.getConstructor(String.class);
        Benchmark benchmark = ctor.newInstance(className);

        double returnValue = run(benchmark,out);

        out.println(className + " : " + returnValue + " ns");
        writer.writeStartElement("".equals(classType) ? "All" : classType);
        writer.writeCharacters(String.valueOf(returnValue));
        writer.writeEndElement();
        cleanup();
        out.println();
    }

    /**
     * Run a {@link Benchmark} and returns the time it took to run.
     */
    public long run(Benchmark benchmark, PrintStream out) throws Exception {
        System.out.println("Iterations: " + iterations);
        System.out.println("Warmup: " + warmup);
        for (int i = 0; i < warmup; ++i) {
            benchmark.testOnce();
        }

        cleanup();

        long startTime = System.nanoTime();
        for (int i = 0; i < iterations; ++i) {
            benchmark.testOnce();
        }
        long endTime = System.nanoTime();

        long totalTime = endTime - startTime;
        return totalTime / iterations;
    }

    private void cleanup() throws InterruptedException {
        Runtime.getRuntime().gc();
        Thread.sleep(100);
        Runtime.getRuntime().gc();
    }

    private void convertToHTML()
            throws TransformerException,
                   IOException {
        StreamSource xslSource = new StreamSource(new File(System.getProperty("benchmark.stylesheet")));
        Transformer trans = TransformerFactory.newInstance().newTransformer(xslSource);
        Properties props = new Properties();
        props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperties(props);
        trans.transform(new StreamSource(new File(xmlLog)), new StreamResult(new FileOutputStream(htmlLog)));
        out.println("******* Benchmark results are available in \"" + htmlLog + "\"");
    }

    private void writeEnvironment(XMLStreamWriter writer) throws Exception {
        writer.writeStartElement("environment");

        writer.writeStartElement("date");
        writer.writeCharacters(new Date().toString());
        writer.writeEndElement();

        writer.writeStartElement("os");
        writer.writeCharacters(System.getProperty("os.name") + " " +
            System.getProperty("os.arch") + " " +System.getProperty("os.version"));
        writer.writeEndElement();

        writer.writeStartElement("memory");
        writer.writeCharacters(""+Runtime.getRuntime().maxMemory());
        writer.writeEndElement();

        writer.writeStartElement("warmup");
        writer.writeCharacters(System.getProperty("warmup"));
        writer.writeEndElement();

        writer.writeStartElement("iterations");
        writer.writeCharacters(System.getProperty("iterations"));
        writer.writeEndElement();

        writer.writeStartElement("local-http");
        writer.writeCharacters(uselocal ? "Local" : "HTTP");
        writer.writeEndElement();

        writer.writeEndElement();
    }

    /**
     * Gets the int value from system property.
     */
    private static int getIntProperty(String key, int defaultValue) {
        if (System.getProperty(key) == null) {
            return defaultValue;
        } else
            return Integer.valueOf(System.getProperty(key));
    }

}


text:
namespace AdventureWorks.API.Route.Module.Sales
{
    using System;

    public static class SalesRoute
    {
        public static string Base
        {
            get { return ""; }
        }

        public static string GetSales
        {
            get { return String.Format("{0}{1}", GeSalesMethod, GetSalesParameters); }
        }

        private static String GeSalesMethod
        {
            get
            {
                return "/getSales";
            }
        }
        private static String GetSalesParameters
        {
            get
            {
                return "/{page}";
            }
        }
    }
}


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class freenet_support_CPUInformation_CPUID */

#ifndef _Included_freenet_support_CPUInformation_CPUID
#define _Included_freenet_support_CPUInformation_CPUID
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     freenet_support_CPUInformation_CPUID
 * Method:    doCPUID
 * Signature: (I)Lfreenet/support/CPUInformation/CPUID$CPUIDResult;
 */
JNIEXPORT jobject JNICALL Java_freenet_support_CPUInformation_CPUID_doCPUID
  (JNIEnv *, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif


text:
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xml:lang="en">
  <info type="application/xhtml+xml" xml:lang="fr">
blah blah blah
</info>
  <copyright type="application/xhtml+xml">
Example test
</copyright>
</feed>


text:
using System.Linq;
using Assets.Scripts.Data;
using Assets.Scripts.UI;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts.Gameplay.Player
{
    [RequireComponent(typeof(PlayerIdentity))]
    public class PlayerUI : MonoBehaviour
    {
        public GameObject PlayerUIPrefab;
        public GameObject EmotionUI;
        public bool IsUIActive;
        public Vector3 Offset = Vector3.zero;
        public EmotionData EmotionsPack;

        private GameObject _uiObject;
        private Text _playerNameText;
        private PlayerIdentity _identity;

        void Start ()
        {
            _identity = GetComponent<PlayerIdentity>();
            _identity.NameChanged += name =>
            {
                if (_playerNameText != null)
                    _playerNameText.text = name;
            };

            var canvas = GameObject.FindObjectOfType<Canvas>();
            if (canvas != null)
            {
                if (PlayerUIPrefab != null)
                {
                    _uiObject = (GameObject)Instantiate(PlayerUIPrefab, canvas.transform);
                    _playerNameText = _uiObject.GetComponentInChildren<Text>();
                    _playerNameText.text = _identity.Name;
                }
                else
                {
                    Debug.LogWarning("Player's UI prefab is not set");
                }
            }
            else
            {
                Debug.LogWarning("Can't find main UI container");
            }
        }

        void Update ()
        {
            if (_uiObject != null && IsUIActive)
            {
                _uiObject.transform.position = Camera.main.WorldToScreenPoint(transform.position + Offset);
            }
        }

        void OnDestroy()
        {
            if(_uiObject != null)
                Destroy(_uiObject);
        }

        public void ShowEmotion(EmotionData.EmoticonType emotionType)
        {
            if (IsUIActive && EmotionUI != null && _uiObject != null)
            {
                var instance = GameObject.Instantiate(EmotionUI, Vector3.zero, Quaternion.identity) as GameObject;
                instance.transform.SetParent(_uiObject.transform);
                instance.transform.localPosition = Vector3.zero;
                instance.GetComponentsInChildren<Image>().Last().sprite = EmotionsPack.GetEmoticonSprite(emotionType);
            }
        }
    }
}


text:
# frozen_string_literal: true

ENV['RAILS_ENV'] ||= 'test'

require File.expand_path('dummy/config/environment', __dir__)

require 'spec_helper'
require 'rspec/rails'

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

RSpec.configure do |config|
  config.use_transactional_fixtures = true

  config.infer_spec_type_from_file_location!

  config.filter_rails_from_backtrace!

  config.include FactoryBot::Syntax::Methods
end


text:
package scala.collection.mutable

import scala.collection.{IterableFactoryDefaults, SeqFactory}

trait Seq[A]
  extends Iterable[A]
    with collection.Seq[A]
    with SeqOps[A, Seq, Seq[A]]
    with IterableFactoryDefaults[A, Seq] {

  override def iterableFactory: SeqFactory[Seq] = Seq
}

/**
  * $factoryInfo
  * @define coll mutable sequence
  * @define Coll `mutable.Seq`
  */
@SerialVersionUID(3L)
object Seq extends SeqFactory.Delegate[Seq](ArrayBuffer)

/**
  * @define coll mutable sequence
  * @define Coll `mutable.Seq`
  */
trait SeqOps[A, +CC[_], +C <: AnyRef]
  extends collection.SeqOps[A, CC, C]
    with Cloneable[C] {

  override def clone(): C = {
    val b = newSpecificBuilder
    b ++= this
    b.result()
  }

  /** Replaces element at given index with a new value.
    *
    *  @param idx      the index of the element to replace.
    *  @param elem     the new value.
    *  @throws   IndexOutOfBoundsException if the index is not valid.
    */
  @throws[IndexOutOfBoundsException]
  def update(idx: Int, elem: A): Unit

  @deprecated("Use `mapInPlace` on an `IndexedSeq` instead", "2.13.0")
  @`inline`final def transform(f: A => A): this.type = {
    var i = 0
    val siz = size
    while (i < siz) { this(i) = f(this(i)); i += 1 }
    this
  }
}

/** Explicit instantiation of the `Seq` trait to reduce class file size in subclasses. */
abstract class AbstractSeq[A] extends scala.collection.AbstractSeq[A] with Seq[A]


text:
package com.xeiam.xchange.btcchina.service.polling;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.btcchina.BTCChina;
import com.xeiam.xchange.btcchina.BTCChinaExchange;
import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaDepth;
import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTicker;
import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTickerObject;
import com.xeiam.xchange.btcchina.dto.marketdata.BTCChinaTrade;

/**
 * Implementation of the market data service for BTCChina.
 *

 *
Provides access to various market data values

 *

 *
 * @author ObsessiveOrange
 */
public class BTCChinaMarketDataServiceRaw extends BTCChinaBasePollingService {

  /**
   * Constructor
   *
   * @param exchange
   */
  public BTCChinaMarketDataServiceRaw(Exchange exchange) {

    super(exchange);
  }

  public Map<String, BTCChinaTickerObject> getBTCChinaTickers() throws IOException {

    return btcChina.getTicker(BTCChinaExchange.ALL_MARKET);
  }

  public BTCChinaTicker getBTCChinaTicker(String market) throws IOException {

    return btcChina.getTicker(market);
  }

  public BTCChinaDepth getBTCChinaOrderBook(String market) throws IOException {

    return btcChina.getFullDepth(market);
  }

  public BTCChinaDepth getBTCChinaOrderBook(String market, int limit) throws IOException {

    return btcChina.getOrderBook(market, limit);
  }

  /**
   * @deprecated Use {@link #getBTCChinaHistoryData(String)} instead.
   */
  @Deprecated
  public List<BTCChinaTrade> getBTCChinaTrades(String market) throws IOException {

    return btcChina.getTrades(market);
  }

  /**
   * @see BTCChina#getHistoryData(String)
   */
  public BTCChinaTrade[] getBTCChinaHistoryData(String market) throws IOException {

    return btcChina.getHistoryData(market);
  }

  /**
   * @deprecated Use {@link #getBTCChinaHistoryData(String, int)} instead.
   */
  @Deprecated
  public List<BTCChinaTrade> getBTCChinaTrades(String market, int limit) throws IOException {

    return btcChina.getTrades(market, limit);
  }

  /**
   * @see BTCChina#getHistoryData(String, int)
   */
  public BTCChinaTrade[] getBTCChinaHistoryData(String market, int limit) throws IOException {

    return btcChina.getHistoryData(market, limit);
  }

  /**
   * @deprecated Use {@link #getBTCChinaHistoryData(String, long)} instead.
   */
  @Deprecated
  public List<BTCChinaTrade> getBTCChinaTrades(String market, long since) throws IOException {

    return btcChina.getTrades(market, since);
  }

  /**
   * @see BTCChina#getHistoryData(String, long)
   */
  public BTCChinaTrade[] getBTCChinaHistoryData(String market, long since) throws IOException {

    return btcChina.getHistoryData(market, since);
  }

  /**
   * @deprecated Use {@link #getBTCChinaHistoryData(String, long, int)} instead.
   */
  @Deprecated
  public List<BTCChinaTrade> getBTCChinaTrades(String market, long since, int limit) throws IOException {

    return btcChina.getTrades(market, since, limit);
  }

  /**
   * @see BTCChina#getHistoryData(String, long, int)
   */
  public BTCChinaTrade[] getBTCChinaHistoryData(String market, long since, int limit) throws IOException {

    return btcChina.getHistoryData(market, since, limit);
  }

  /**
   * @deprecated Use {@link #getBTCChinaHistoryData(String, long, int, String)}
   *             instead.
   */
  @Deprecated
  public List<BTCChinaTrade> getBTCChinaTrades(String market, long since, int limit, String sinceType) throws IOException {

    return btcChina.getTrades(market, since, limit, sinceType);
  }

  /**
   * @see BTCChina#getHistoryData(String, long, int)
   */
  public BTCChinaTrade[] getBTCChinaHistoryData(String market, long since, int limit, String sinceType) throws IOException {

    return btcChina.getHistoryData(market, since, limit, sinceType);
  }

}


text:
package net.novaviper.zeroquest.client.gui;

import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import net.novaviper.zeroquest.common.container.ContainerPack;
import net.novaviper.zeroquest.common.entity.EntityCustomTameable;
import net.novaviper.zeroquest.common.entity.creature.EntityDarkZertum;
import net.novaviper.zeroquest.common.entity.creature.EntityDestroZertum;
import net.novaviper.zeroquest.common.entity.creature.EntityForisZertum;
import net.novaviper.zeroquest.common.entity.creature.EntityIceZertum;
import net.novaviper.zeroquest.common.entity.creature.EntityMetalZertum;
import net.novaviper.zeroquest.common.entity.creature.EntityRedZertum;
import net.novaviper.zeroquest.common.lib.Constants;
import net.novaviper.zeroquest.common.util.ResourceReference;

import org.lwjgl.opengl.GL11;

public class GuiPack extends GuiContainer {
	private float xSize_wolf;
	private float ySize_wolf;
	private final EntityCustomTameable entity;
	private final boolean mouseWasDown;

	public GuiPack(InventoryPlayer inventoryplayer, EntityCustomTameable entityCustomTameable) {
		super(new ContainerPack(inventoryplayer, entityCustomTameable));
		this.mouseWasDown = false;
		this.entity = entityCustomTameable;
		this.allowUserInput = false;
		this.ySize = ySize + 60;
	}

	@Override
	protected void drawGuiContainerForegroundLayer(int par1, int par2) {
		String s = this.entity.inventory.hasCustomName()
				? this.entity.inventory.getCommandSenderName()
				: StatCollector.translateToLocal(this.entity.inventory.getCommandSenderName());
		this.fontRendererObj.drawString(s, this.xSize / 2 - 10, 14, 4210752);
		this.fontRendererObj.drawString(StatCollector.translateToLocal("Inventory"), 8, this.ySize - 155 + 2, 4210752);
	}

	@Override
	public void drawScreen(int i, int j, float f) {
		super.drawScreen(i, j, f);
		xSize_wolf = i;
		ySize_wolf = j;
	}

	@Override
	protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
		GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
		if (entity instanceof EntityDarkZertum) {
			this.mc.getTextureManager().bindTexture(ResourceReference.getInventorySkins("Dark"));
		}
		else if (entity instanceof EntityDestroZertum) {
			this.mc.getTextureManager().bindTexture(ResourceReference.getInventorySkins("Destro"));
		}
		else if (entity instanceof EntityForisZertum) {
			this.mc.getTextureManager().bindTexture(ResourceReference.getInventorySkins("Foris"));
		}
		else if (entity instanceof EntityIceZertum) {
			this.mc.getTextureManager().bindTexture(ResourceReference.getInventorySkins("Ice"));
		}
		else if (entity instanceof EntityRedZertum) {
			this.mc.getTextureManager().bindTexture(ResourceReference.getInventorySkins("Red"));
		}
		else if (entity instanceof EntityMetalZertum) {
			this.mc.getTextureManager().bindTexture(ResourceReference.getInventorySkins("Metal"));
		}
		else {
			this.mc.getTextureManager().bindTexture(ResourceReference.getInventorySkins(""));
		}

		int l = (width - xSize) / 2;
		int i1 = (height - ySize) / 2;
		drawTexturedModalRect(l, i1, 0, 0, xSize, ySize);

		for (int j1 = 0; j1 < 3; j1++) {
			for (int k1 = 0; k1 < 5; k1++) {
				drawTexturedModalRect(l + 78 + 18 * k1, i1 + 9 + 18 * j1 + 15, 197, 2, 18, 18);
			}
		}

		GuiInventory.drawEntityOnScreen(l + 42, i1 + 51, 30, l + 51 - xSize_wolf, (i1 + 75) - 50 - ySize_wolf, this.entity);
	}
}


text:
<?php

namespace Groups\Controller\Component;

use Cake\Controller\Component;
use Cake\ORM\TableRegistry;

/**
 * Groups Component
 *
 * @property \Cake\Controller\Component\AuthComponent $Auth
 */
class GroupComponent extends Component
{
    public $components = ['Auth'];

    /**
     * Initialize method
     * @param  array  $config configuration array
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * Method that retrieves specified user's groups
     * @param  string $userId user id
     * @return mixed[]
     */
    public function getUserGroups(string $userId = ''): array
    {
        // if not specified, get current user's id
        if (empty($userId)) {
            $userId = $this->Auth->user('id');
        }

        $groups = TableRegistry::getTableLocator()->get('Groups.Groups');

        $query = $groups->find('list', [
            'keyField' => 'id',
            'valueField' => 'name',
        ]);
        $query->matching('Users', function ($q) use ($userId) {
            return $q->where(['Users.id' => $userId]);
        });

        return $query->toArray();
    }
}


text:
package google

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccDataSourceGoogleVpnGateway(t *testing.T) {
	t.Parallel()

	vpnGatewayName := fmt.Sprintf("tf-test-%s", randString(t, 10))
	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccDataSourceGoogleVpnGatewayConfig(vpnGatewayName),
				Check: resource.ComposeTestCheckFunc(
					testAccDataSourceGoogleVpnGatewayCheck("data.google_compute_vpn_gateway.my_vpn_gateway", "google_compute_vpn_gateway.foobar"),
				),
			},
		},
	})
}

func testAccDataSourceGoogleVpnGatewayCheck(data_source_name string, resource_name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		ds, ok := s.RootModule().Resources[data_source_name]
		if !ok {
			return fmt.Errorf("root module has no resource called %s", data_source_name)
		}

		rs, ok := s.RootModule().Resources[resource_name]
		if !ok {
			return fmt.Errorf("can't find %s in state", resource_name)
		}

		ds_attr := ds.Primary.Attributes
		rs_attr := rs.Primary.Attributes
		vpn_gateway_attrs_to_test := []string{
			"id",
			"name",
			"description",
			"network",
		}

		for _, attr_to_check := range vpn_gateway_attrs_to_test {
			if ds_attr[attr_to_check] != rs_attr[attr_to_check] {
				return fmt.Errorf(
					"%s is %s; want %s",
					attr_to_check,
					ds_attr[attr_to_check],
					rs_attr[attr_to_check],
				)
			}
		}

		if !compareSelfLinkOrResourceName("", ds_attr["self_link"], rs_attr["self_link"], nil) && ds_attr["self_link"] != rs_attr["self_link"] {
			return fmt.Errorf("self link does not match: %s vs %s", ds_attr["self_link"], rs_attr["self_link"])
		}

		return nil
	}
}

func testAccDataSourceGoogleVpnGatewayConfig(name string) string {
	return fmt.Sprintf(`
resource "google_compute_vpn_gateway" "foobar" {
  name        = "%s"
  description = "my-description"
  network     = "default"
}

data "google_compute_vpn_gateway" "my_vpn_gateway" {
  name = google_compute_vpn_gateway.foobar.name
}
`, name)
}


text:
title: Classification 1(Introduction)
layout: post
author:     "JongHyun"
header-img: "img/machine_learning_backboard.jpg"
categories: [Data Analysis, Machine Learning]
---

	In the supervised learning, there are two main categories. One is regression which is predicting value of input value based on previous training sets. The other is classification which is classifying input value into yes or no. The example of classification is determining whether the tumor is maligant or benign. I already dealt with regression before. Simply, the classification is used when we have discrete ouput. The simplest case is two output case. Also, there are multi output case which is called multi-class problem. We can represent classification case like this
	$$\text{Binary class : }y \in \{0,1\}$$
	$${0\text{ : Negative class}} \atopwithdelims [ ] {1\text{ : Positive class}}$$
	$$\text{Multi class : }y \in \{0,1,2,3,\cdots\}$$
	Let's assume that we have data which can be plotted like below figure.

	As we learned before, you may want to try use linear regression. It looks reasonable if we add some requirements that prdict "y=1" if hypothesis is larger than 0.5 and predict "y=0" if hypothesis is smaller than 0.5. However, if we add more training sets far from data sets like (30, 1), the linear regression cannot give best prediction. You can check this very simply.

	Now, we want new hypothesis model unlike linear regression. The requirement for new hypothesis is it's range is from 0 to 1 because we only have two y value (0, 1). Another requirement is it need to change its value rapidly at the threshold. The best candidates for this is logistic function or sigmoid function. Also, new regression using logistic function is called logistic regression(The reason why we use regression in classification is that the output of function is basically continuous)
	$$\text{Requirements : }0 \le h_\theta(x) \le 1$$
	$$\text{Hypothesis : }h_\theta(x) = g(\theta^T X)$$
	$$\text{Sigmoid function : }g(z) = \frac{1}{1+e^{-z}}$$
	$$\longrightarrow h_\theta(x) = \frac{1}{1+e^{-\theta^T X}}$$

	Then, how we can interpret the output of hypothesis? The best interpretation is probability. That is if we get the 0.6 hypothesis value, we can tell candidate have 60% chance of expected output. We can write this by equation
	$$h_\theta(x) = P(y=1|x;\theta)$$
	$$P(y=0|x;\theta) = 1-P(y=1|x;\theta) = 1- h_\theta(x)$$
	We can also bring new concept "Decision boundary". Because we have only two kinds of output 1 or 0, we need to predict result based on probability. The standard is 50% probability or 0.5 hypothesis output. If the result of hypothesis is larger than 0.5, we can predict the output is 1.
	$$\text{Predict }y=1\text{ if }h_\theta(x) \ge 0.5$$
	$$\text{Predict }y=0\text{ if }h_\theta(x) \lt 0.5$$
	In the sigmoid function, the function output become 0.5 when its input is 0.
	$$g(z) \ge 0.5 \text{ when } z \ge 0$$
	$$h_\theta(x) = g(\theta^TX) \ge 0.5 \text{ when } \theta^T X \ge 0$$
	$$"y=1" \text{ when } \theta^TX \ge 0$$
	$$"y=0" \text{ when } \theta^TX \lt 0$$
	$$\text{Decision boundary : }\theta^TX=0$$
	The classification also can be used when the results are categorized into circular form by adding high order polynomial term.


text:
 // Copyright (c) 2016 Intel Corporation. All rights reserved.
 // Use of this source code is governed by a MIT-style license that can be
 // found in the LICENSE file.

'use strict';

const slamAddon = require('bindings')('realsense_slam');
const EventEmitter = require('events').EventEmitter;
const assert = require('assert');

function inherits(target, source) {
  // eslint-disable-next-line guard-for-in
  for (let k in source.prototype) {
    target.prototype[k] = source.prototype[k];
  }
}
inherits(slamAddon.Instance, EventEmitter);

function checkReturn(obj, name, type, option) {
  let Result = true;
  if (type == 'typeof') {
    if(typeof(obj[name]) !== option) {
      Result = false;
    }
  }
  if (type == 'writable') {
    if (Object.getOwnPropertyDescriptor(obj, name).writable !== option) {
      writableResult = false;
      Result = false;
    }
  }
  return Result;
}
function tests(state, options) {
  describe('Slam Instance Test - getOccupancyMapUpdate()', function() {
    let slamInstance = null;
    afterEach(() => {
      return slamInstance.stop();
    });
    it('Should get correct data getOccupancyMapUpdate() -  ' + state, function() {
      return new Promise((resolve, reject) => {
        slamAddon.createInstance().then((Instance) => {
          slamInstance = Instance;
          return slamInstance.start();
        }).then(() => {
          if (options == null) {
            return slamInstance.getOccupancyMapUpdate();
          }else{
            return slamInstance.getOccupancyMapUpdate(options);
          }
        }).then((Data) => {
          // eslint-disable-next-line guard-for-in
          for (let i in caseResult) {
            assert.ok(checkReturn(Data, i, 'writable', caseResult[i].writable));
            assert.ok(checkReturn(Data, i, 'typeof', caseResult[i].type));
          }
          resolve();
        }).catch((err) => {
          reject(err);
        });
      });
    });
  });
}
let caseResult = {
  isDataPending: {type: 'boolean', writable: false},
  tileCount: {type: 'number', writable: false},
  data: {type: 'object', writable: false},
};
let argv = {
  minX: 1,
  minY: 1,
  maxX: 3,
  maxY: 3,
};
tests('Positive', null);
tests('Negative', argv);


text:
//%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements.  Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////////

#include "CQLChainedIdentifier.h"
#include "CQLChainedIdentifierRep.h"
#include <Pegasus/CQL/CQLFactory.h>
#include <Pegasus/Common/Tracer.h>
#include <Pegasus/Query/QueryCommon/QueryContext.h>
#include <Pegasus/Query/QueryCommon/QueryIdentifier.h>
#include <Pegasus/Query/QueryCommon/QueryException.h>

PEGASUS_NAMESPACE_BEGIN

CQLChainedIdentifierRep::CQLChainedIdentifierRep():
  QueryChainedIdentifierRep()
{
}

CQLChainedIdentifierRep::CQLChainedIdentifierRep(const String& inString):
  QueryChainedIdentifierRep()
{
    parse(inString);
}

CQLChainedIdentifierRep::CQLChainedIdentifierRep(const CQLIdentifier &id):
  QueryChainedIdentifierRep()
{
  _subIdentifiers.append(id);
}

CQLChainedIdentifierRep::CQLChainedIdentifierRep(
  const CQLChainedIdentifierRep* rep)
  :
  QueryChainedIdentifierRep()
{
    _subIdentifiers = rep->_subIdentifiers;
}

CQLChainedIdentifierRep::~CQLChainedIdentifierRep(){

}

Array<CQLIdentifier> CQLChainedIdentifierRep::getSubIdentifiers()const
{
  Array<CQLIdentifier> result;

  for (Uint32 i = 0; i < _subIdentifiers.size(); i++)
  {
    result.append(CQLIdentifier(_subIdentifiers[i]));
  }

    return result;
}

CQLIdentifier CQLChainedIdentifierRep::getLastIdentifier()const
{
    if(_subIdentifiers.size() > 0)
        return CQLIdentifier(_subIdentifiers[_subIdentifiers.size()-1]);
    return CQLIdentifier();
}

CQLIdentifier CQLChainedIdentifierRep::operator[](Uint32 index)const
{
    return CQLIdentifier(_subIdentifiers[index]);
}

void CQLChainedIdentifierRep::parse(const String & string)
{
    PEG_METHOD_ENTER(TRC_CQL, "CQLChainedIdentifierRep::parse");
    /*
      - parse string on "."
      - start from the end of string
      - if more than one substring found,
        -- store first found string then
        -- prepend remaining substrings
    */
    Char16 delim('.');
    Uint32 index;
    String range;

    index = string.reverseFind(delim);
    if(index == PEG_NOT_FOUND){
        _subIdentifiers.append(CQLIdentifier(string));
    }else{
        String tmp = string.subString(index+1);
        _subIdentifiers.append(CQLIdentifier(tmp));

        while(index != PEG_NOT_FOUND){
            tmp = string.subString(0,index);
            index = tmp.reverseFind(delim);
            if(index == PEG_NOT_FOUND){
                _subIdentifiers.prepend(CQLIdentifier(tmp));
            }
            else{
                _subIdentifiers.prepend(CQLIdentifier(tmp.subString(index+1)));
            }
        }
    }
    PEG_METHOD_EXIT();
}

PEGASUS_NAMESPACE_END


text:
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('power on')">Power On</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('up')">

      </button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('power off')">Power Off</button>

      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('left')">

      </button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('ok')">OK</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('right')">

      </button>

      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('exit')">Exit</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('down')">

      </button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('info')">Info</button>

      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('volume up')">
        Volume
      </button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('guide')">Guide</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('channel up')">
        Channel
      </button>

      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('volume down')">
        Volume
      </button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('mute')">Mute</button>
      <button type="button" class="btn btn-default col-xs-offset-8 col-xs-4" role="button" ng-click="sendCmd('channel down')">
        Channel
      </button>

      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('1')">1</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('2')">2</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('3')">3</button>

      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('4')">4</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('5')">5</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('6')">6</button>

      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('7')">7</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('8')">8</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('9')">9</button>

      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('-')">-</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('0')">0</button>
      <button type="button" class="btn btn-default col-xs-4" role="button" ng-click="sendCmd('previous')">Prev</button>

      <button type="button" class="btn btn-default btn-lg col-xs-6" role="button" ng-click="sendCmd('menu')">Menu</button>

        <button type="button" class="btn btn-default btn-lg dropdown-toggle col-xs-12" dropdown-toggle>
          Input
        </button>

TV

HDMI 1

HDMI 2

HDMI 3

HDMI 1

HDMI 2

AV 1

AV 2

Component 1

Component 2


text:
package org.apache.karaf.eik.core.configuration;

import java.util.List;

public interface FeaturesSection  extends ConfigurationSection {

    public List<String> getBootFeatureNames();

    public List<String> getRepositoryList();

    public void setBootFeatureNames(List<String> bootFeatureNames);

    public void setRepositoryList(List<String> repositoryList);

}


text:
package org.apache.giraph.graph;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

/**
 * The default vertex value combining approach is to simply keep the original
 * value.
 *
 * @param <I> Vertex id
 * @param <V> Vertex data
 * @param <E> Edge data
 */
public class DefaultVertexValueCombiner<I extends WritableComparable,
    V extends Writable, E extends Writable>
    implements VertexValueCombiner<V> {
  @Override
  public void combine(V originalVertexValue,
                      V vertexValue) {
    // Keep the original value, do nothing
  }
}


text:
package com.google.cloud.spring.vision;

import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.paging.Page;
import com.google.cloud.spring.storage.GoogleStorageLocation;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BlobListOption;
import com.google.cloud.vision.v1.AsyncAnnotateFileRequest;
import com.google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.GcsDestination;
import com.google.cloud.vision.v1.GcsSource;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.InputConfig;
import com.google.cloud.vision.v1.OperationMetadata;
import com.google.cloud.vision.v1.OutputConfig;
import com.google.cloud.vision.v1.TextAnnotation;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.springframework.util.Assert;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.SettableListenableFuture;

/**
 * Template providing convenient operations for interfacing with Google Cloud Vision's Document OCR
 * feature, which allows you to run OCR algorithms on documents (PDF or TIFF format) stored on
 * Google Cloud Storage.
 */
public class DocumentOcrTemplate {

  private static final Feature DOCUMENT_OCR_FEATURE =
      Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build();

  private final ImageAnnotatorClient imageAnnotatorClient;

  private final Storage storage;

  private final Executor executor;

  private final int jsonOutputBatchSize;

  public DocumentOcrTemplate(
      ImageAnnotatorClient imageAnnotatorClient,
      Storage storage,
      Executor executor,
      int jsonOutputBatchSize) {
    this.imageAnnotatorClient = imageAnnotatorClient;
    this.storage = storage;
    this.executor = executor;
    this.jsonOutputBatchSize = jsonOutputBatchSize;
  }

  /**
   * Runs OCR processing for a specified {@code document} and generates OCR output files under the
   * path specified by {@code outputFilePathPrefix}.
   *
   *
For example, if you specify an {@code outputFilePathPrefix} of
   * "gs://bucket_name/ocr_results/myDoc_", all the output files of OCR processing will be saved
   * under prefix, such as:
   *
   *

   *
gs://bucket_name/ocr_results/myDoc_output-1-to-5.json
   *
gs://bucket_name/ocr_results/myDoc_output-6-to-10.json
   *
gs://bucket_name/ocr_results/myDoc_output-11-to-15.json
   *

   *
   *
Note: OCR processing operations may take several minutes to complete, so it may not be
   * advisable to block on the completion of the operation. One may use the returned {@link
   * ListenableFuture} to register callbacks or track the status of the operation.
   *
   * @param document The {@link GoogleStorageLocation} of the document to run OCR processing
   * @param outputFilePathPrefix The {@link GoogleStorageLocation} of a file, folder, or a bucket
   *     describing the path for which all output files shall be saved under
   * @return A {@link ListenableFuture} allowing you to register callbacks or wait for the
   *     completion of the operation.
   */
  public ListenableFuture<DocumentOcrResultSet> runOcrForDocument(
      GoogleStorageLocation document, GoogleStorageLocation outputFilePathPrefix) {

    Assert.isTrue(
        document.isFile(), "Provided document location is not a valid file location: " + document);

    GcsSource gcsSource = GcsSource.newBuilder().setUri(document.uriString()).build();

    String contentType = extractContentType(document);
    InputConfig inputConfig =
        InputConfig.newBuilder().setMimeType(contentType).setGcsSource(gcsSource).build();

    GcsDestination gcsDestination =
        GcsDestination.newBuilder().setUri(outputFilePathPrefix.uriString()).build();

    OutputConfig outputConfig =
        OutputConfig.newBuilder()
            .setGcsDestination(gcsDestination)
            .setBatchSize(this.jsonOutputBatchSize)
            .build();

    AsyncAnnotateFileRequest request =
        AsyncAnnotateFileRequest.newBuilder()
            .addFeatures(DOCUMENT_OCR_FEATURE)
            .setInputConfig(inputConfig)
            .setOutputConfig(outputConfig)
            .build();

    OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> result =
        imageAnnotatorClient.asyncBatchAnnotateFilesAsync(Collections.singletonList(request));

    return extractOcrResultFuture(result);
  }

  /**
   * Parses the OCR output files who have the specified {@code jsonFilesetPrefix}. This method
   * assumes that all of the OCR output files with the prefix are a part of the same document.
   *
   * @param jsonOutputFilePathPrefix the folder location containing all of the JSON files of OCR
   *     output
   * @return A {@link DocumentOcrResultSet} describing the OCR content of a document
   */
  public DocumentOcrResultSet readOcrOutputFileSet(GoogleStorageLocation jsonOutputFilePathPrefix) {
    String nonNullPrefix =
        (jsonOutputFilePathPrefix.getBlobName() == null)
            ? ""
            : jsonOutputFilePathPrefix.getBlobName();

    Page<Blob> blobsInFolder =
        this.storage.list(
            jsonOutputFilePathPrefix.getBucketName(),
            BlobListOption.currentDirectory(),
            BlobListOption.prefix(nonNullPrefix));

    List<Blob> blobPages =
        StreamSupport.stream(blobsInFolder.getValues().spliterator(), false)
            .filter(blob -> blob.getContentType().equals("application/octet-stream"))
            .collect(Collectors.toList());

    return new DocumentOcrResultSet(blobPages);
  }

  /**
   * Parses a single JSON output file and returns the list of pages stored in the file.
   *
   *
Each page of the document is represented as a {@link TextAnnotation} which contains the
   * parsed OCR data.
   *
   * @param jsonFile the location of the JSON output file
   * @return the list of {@link TextAnnotation} containing the OCR results
   * @throws RuntimeException if the JSON file cannot be deserialized into a {@link TextAnnotation}
   *     object
   */
  public DocumentOcrResultSet readOcrOutputFile(GoogleStorageLocation jsonFile) {
    if (!jsonFile.isFile()) {
      throw new IllegalArgumentException(
          "Provided jsonOutputFile location is not a valid file location: " + jsonFile);
    }

    Blob jsonOutputBlob =
        this.storage.get(BlobId.of(jsonFile.getBucketName(), jsonFile.getBlobName()));
    return new DocumentOcrResultSet(Collections.singletonList(jsonOutputBlob));
  }

  private ListenableFuture<DocumentOcrResultSet> extractOcrResultFuture(
      OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> grpcFuture) {

    SettableListenableFuture<DocumentOcrResultSet> result = new SettableListenableFuture<>();

    ApiFutures.addCallback(
        grpcFuture,
        new ApiFutureCallback<AsyncBatchAnnotateFilesResponse>() {
          @Override
          public void onFailure(Throwable throwable) {
            result.setException(throwable);
          }

          @Override
          public void onSuccess(AsyncBatchAnnotateFilesResponse asyncBatchAnnotateFilesResponse) {

            String outputLocationUri =
                asyncBatchAnnotateFilesResponse
                    .getResponsesList()
                    .get(0)
                    .getOutputConfig()
                    .getGcsDestination()
                    .getUri();

            GoogleStorageLocation outputFolderLocation =
                new GoogleStorageLocation(outputLocationUri);
            result.set(readOcrOutputFileSet(outputFolderLocation));
          }
        },
        this.executor);

    return result;
  }

  private String extractContentType(GoogleStorageLocation document) {
    Blob documentBlob =
        this.storage.get(BlobId.of(document.getBucketName(), document.getBlobName()));
    if (documentBlob == null) {
      throw new IllegalArgumentException("Provided document does not exist: " + document);
    }

    return documentBlob.getContentType();
  }
}


text:
describe Staff do
  context 'search' do
    before :each do
      create :staff, email: 'foo@bar.com', first_name: 'John', last_name: 'Smith'
      create :staff, email: 'bar@foo.com', first_name: 'Jane', last_name: 'Doe'
    end

    it 'gets hits on emails' do
      results = Staff.search 'foo@bar.com'
      expect(results.size).to eq(1)
    end

    it 'gets hits on first name' do
      results = Staff.search 'John'
      expect(results.size).to eq(1)
    end

    it 'gets hits on last name' do
      results = Staff.search 'Smith'
      expect(results.size).to eq(1)
    end
  end
end


text: require 'English'


text:
'use strict';

const Promise 	= require('bluebird');
const Task 			= require('../models/task');

module.exports = Task.extend({
	run: function(options) {
		return new Promise(function(resolve, reject) {
			const endpoint = null;
			this.ui.writeInfoLine('Endpoint: ' + endpoint);
			resolve();
		}.bind(this));
	}
});


text:
package br.ufmg.dcc.labsoft.parameters;

import java.util.List;

@Deprecated
public class Method17 {

	//Ordem trocada.
	//Integer i, List<String> list --> List<String> list, Integer i
	public void m1(List<String> list, Integer i){

	}

}


text:
APPNAME = fakerl
DIALYZER = dialyzer
ERL = $(shell which erl)
ERLFLAGS= -pa $(CURDIR)/.eunit -pa $(CURDIR)/ebin -pa $(CURDIR)/deps/*/ebin -s $(APPNAME)
REBAR = ./rebar $(REBAR_ARGS)
REBAR_URL := https://github.com/rebar/rebar/wiki/rebar

.PHONY: all compile docs clean tests build-plt dialyze shell distclean pdf \
update-deps rebuild

# ================================================================
# Verify that porgrames needed by this Makefile are available
# ================================================================
ifeq ($(ERL),)
$(error "Erlang not running on this system")
endif

# ==============================================================
# Make build rules
# ==============================================================
all: app

app: rebar deps
	@$(REBAR) compile

deps:
	@$(REBAR) get-deps
	$(REBAR) compile

update-deps:
	$(REBAR) update-deps
	$(RENDER) compile

compile:
	$(REBAR) skip_deps=true compile

clean:
	- rm -rf $(CURDIR)/test/*.beam
	- rm -rf $(CURDIR)/ebin
	- rm -rf $(CURDIR)/*.dump
	$(REBAR) skip_deps=true clean

distclean: clean
	- rm -rvf $(CURDIR)/deps
	- rm -rf $(CURDIR)/doc/*

tests: REBAR_ARGS = -C rebar.test.config
tests: clean app eunit ct

eunit: compile clean
	@$(REBAR) eunit skip_deps=true

ct:
	@$(REBAR) ct skip_deps=true

build-plt:
	@$(DIALYZER) --build_plt --output_plt .$(APPNAME)_dialyzer.plt \
		--apps kernel stdlib sasl inets crypto public_key ssl

dialyze:
	@$(DIALYZER) --src src --plt .$(APPNAME)_dialyzer.plt --no_native \
		-Werror_handling -Wrace_conditions -Wunmatched_returns # -Wunderspecs

docs:
	@$(REBAR) doc skip_deps=true

pdf:
	pandoc README.md -o README.pdf

shell: deps compile
	- @$(REBAR) skip-deps=true eunit
	@$(ERL) $(ERLFLAGS)

rebar:
	$(ERL) -noshell -s inets -s ssl \
	-eval '{ok, saved_to_file} = httpc:request(get, {"$(REBAR_URL)", []}, [], [{stream, "./rebar"}])' \
	-s init stop
	chmod +x ./rebar


text:
<?xml version="1.0" encoding="utf-8"?>
<doc>
<assembly><name>FsUnit.CustomMatchers</name></assembly>
<members>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="">

</member>
<member name="T:FsUnit.CustomMatchers">

</member>
</members>
</doc>