text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Demo - Toast Plugin</title>
    <link href='http://fonts.googleapis.com/css?family=Roboto+Slab:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/jquery.toast.css">

Jquery Toast Plugin

Index

Quick Demos Some quick demos and the code to generate that, if you are in a hurry!

Generator A generator for you to easily generate the code for the kind of toast you want, so that you don't have to go through the documentation!

                Options
                Each of the options is accompanied by a demo explaining that option.

Specifying the heading

Making them sticky

Changing the toast hide timer

Changing the show/hide animation

Making the toast closeable or not

Setting the toast stack

Positioning the toast

Messages with icons

Background & text color

Setting the text alignment

Toast Events

Updating Toasts

Resetting Toasts

Latest Update

Toast loader has been introduced in the latest version. Check the demo below to see it in action

                Run code

$.toast('Here you can put the text of the toast')

Loader is enabled by default. In order to disable it or change the color, use the `loader` and `loaderBg` options. Have a look at the demo below

                Run code

$.toast({
    heading: 'Information',
    text: 'Loaders are enabled by default. Use `loader`, `loaderBg` to change the default behavior',
    icon: 'info',
    loader: true,        // Change it to false to disable loader
    loaderBg: '#9EC600'  // To change the background
})

Quick Demos

To generate a most simple toast, all you have to do is

            Run code

$.toast('Here you can put the text of the toast')

There are different kinds of toast types:

            Run code

$.toast({
    heading: 'Information',
    text: 'Now you can add icons to generate different kinds of toasts',
    showHideTransition: 'slide',
    icon: 'info'
})

            Run code

$.toast({
    heading: 'Error',
    text: 'Report any <a href="https://github.com/kamranahmedse/jquery-toast-plugin/issues">issues</a>',
    showHideTransition: 'fade',
    icon: 'error'
})

            Run code

$.toast({
    heading: 'Warning',
    text: 'It is going to be supper easy for you to use ;)',
    showHideTransition: 'plain',
    icon: 'warning'
})

            Run code

$.toast({
    heading: 'Success',
    text: 'And these were just the basic demos! Scroll down to check further details on how to customize the output.',
    showHideTransition: 'slide',
    icon: 'success'
})

Options

Of course that is not all what you can do using this plugin, there are a lot of other options. Let's start explaining each, one by one

You should note that, whenever you are going to use options, you have to pass an options object and specify the text as follows:

            Run code

$.toast({
    text: 'This will become the toast message'
})

The text can be an array:

            Run code

$.toast({
    heading: 'How to contribute?!',
    text: [
        'Fork the repository',
        'Improve/extend the functionality',
        'Create a pull request'
    ],
    icon: 'info'
})

Or put some HTML in the text

            Run code

$.toast({
    heading: 'Can I add <em>icons</em>?',
    text: 'Yes! check this <a href="https://github.com/kamranahmedse/jquery-toast-plugin/commits/master">update</a>.',
    hideAfter: false,
    icon: 'success'
})

1. Specifying the heading of toast message

You can use the heading to set the heading property to set the heading of the toast message

            Run Code

$.toast({
    heading: 'Headings',
    text: 'You can use the `heading` property to specify the heading of the toast message.',
})

2. Making them sticky:

There will be times, when you will want to have sticky toasts. To make them sticky, all you have to do is set the hideAfter to false. Here is a sticky toast

            Run Code

$.toast({
    text: 'Set the `hideAfter` property to false and the toast will become sticky.',
    hideAfter: false
})

* hideAfter property is basically used to set the timer after which the toast will get hidden. But you can set it to false in order to achieve the sticky toasts.

3. Changing the toast hide timer

You can use the property from the above option i.e. hideAfter to change the timer after which toast gets hidden. You have to specify the timer in milliseconds

            Run Code

$.toast({
    text: 'Set the `hideAfter` property to milliseconds and the toast will hide after the specified milli seconds.',
    hideAfter: 5000   // in milli seconds
})

4. Changing the show/hide animation

You can use showHideTransition property to set the animation. Following are the available options:

fade for fade transitions

slide for slide up and down transitions

plain simple show from and hide to corner transition

            Run Code

$.toast({
    text: 'Set the `showHideTransition` property to fade|plain|slide to achieve different transitions',
    heading: 'Slide transition',
    showHideTransition: 'slide'
})

            Run Code

$.toast({
    text: 'Set the `showHideTransition` property to fade|plain|slide to achieve different transitions',
    heading: 'Fade transition',
    showHideTransition: 'fade'
})

            Run Code

$.toast({
    text: 'Set the `showHideTransition` property to fade|plain|slide to achieve different transitions',
    heading: 'Plain transition',
    showHideTransition: 'plain'
})

5. Making the toast closeable or not

You can use allowToastClose to allow the user to close the toast or not. The only thing that this option does is make that little cross button show or hide itself

            Run Code

$.toast({
    heading: 'Closeable Toast',
    text: 'Set the `allowToastClose` property to true|false to make the toast closeable or not',
    allowToastClose: true
})

            Run Code

$.toast({
    heading: 'Non closeable Toast',
    text: 'Set the `allowToastClose` property to true|false to make the toast closeable or not',
    allowToastClose: false
})

6. Setting the toast stack

stack property can be used to specify how many maximum toasts you want to show at any point of time. By default this property is set to 5

            Run Code

$.toast({
    heading: 'Stack',
    text: 'If set to a number, it will show that number of toasts at max at a time',
    stack: 4
})

            Run Code

$.toast({
    heading: 'No stacking',
    text: 'If set to false, there will be only one toast at once.',
    stack: false
})

Note Hit the run button multiple times to test these demos.

7. Positioning the toast

position property can be used to specify the position. There are following predefined positions which you can use:

bottom-left value to show the toast at bottom left position

bottom-right value to show the toast at bottom right position

bottom-center value to..

top-right value to..

top-left value to..

top-center value to..

mid-center value to..

{ top: '-', bottom: '-', left: '-', right: '-' } javascript object with positioning properties as you set in CSS

            Run Code

$.toast().reset('all');$.toast({
    heading: 'Positioning',
    text: 'Specify the custom position object or use one of the predefined ones',
    position: 'bottom-left',
    stack: false
})

            Run Code

$.toast().reset('all');$.toast({
    heading: 'Positioning',
    text: 'Specify the custom position object or use one of the predefined ones',
    position: 'bottom-right',
    stack: false
})

            Run Code

$.toast().reset('all');$.toast({
    heading: 'Positioning',
    text: 'Use the predefined ones, or specify a custom object',
    position: 'bottom-center',
    stack: false
})

            Run Code

$.toast().reset('all');$.toast({
    heading: 'Positioning',
    text: 'Use the predefined ones, or specify a custom object',
    position: 'top-left',
    stack: false
})

            Run Code

$.toast().reset('all');$.toast({
    heading: 'Positioning',
    text: 'Use the predefined ones, or specify a custom position object.',
    position: 'top-right',
    stack: false
})

            Run Code

$.toast().reset('all');$.toast({
    heading: 'Positioning',
    text: 'Use the predefined ones, or specify a custom position object.',
    position: 'top-center',
    stack: false
})

            Run Code

$.toast().reset('all');$.toast({
    heading: 'Positioning',
    text: 'Use the predefined ones, or specify a custom position object.',
    position: 'mid-center',
    stack: false
})

            Run Code

$.toast().reset('all');$.toast({
    heading: 'Positioning',
    text: 'Use the predefined ones, or specify a custom position object.',
    position: {
        left: 120,
        top: 120
    },
    stack: false
})

Note It should be noted that, once you change the position of toast by using the `position` property, you'll have to reset the position for the next toasts, if you want them to appear at their default position i.e. the bottom left corner. Or else, each new toast generated will be appearing at the last position i.e. where you displayed the last positioned toast. You can reset the toast position by.

            Run Code

$.toast().reset('all');

8. Messages with icons

icon property can be used to specify the predefined types of toasts. Following are the predefined types:

info generates a toast with information icon

warning generates a toast with warning icon

error generates a toast with error icon

success generates a toast with success icon

            Run Code

$.toast({
    heading: 'Warning',
    text: 'Now you can seemlessly generate warnings using the icon property in the options',
    icon: 'warning'
})

            Run Code

$.toast({
    heading: 'Success',
    text: 'Here is some kind of success message with a success icon that you can notice at the left side.',
    icon: 'success'
})

            Run Code

$.toast({
    heading: 'Error',
    text: 'An unexpected error occured while trying to show you the toast! ..Just kidding, it is just a message, toast is right in front of you.',
    icon: 'error'
})

            Run Code

$.toast({
    heading: 'Information',
    text: 'Now you can add icons to the toasts as well.',
    icon: 'info'
})

9. Background & text color

bgColor property is used to specify the background color of the toast message. Default is '#444'

textColor property is used to specify the text color of the toast message. Default is '#eee'

            Run Code

$.toast({
    heading: 'Colors',
    text: 'Colors are specified using `bgColor` and `textColor` properties.',
    bgColor: '#FF1356',
    textColor: 'white'
})

10. Setting the text alignment

textAlign property is used to set the alignment of text inside the toast. Permitted values are:

left

right

center

            Run Code

$.toast({
    text: 'Processing! Please wait..',
    textAlign: 'center'
})

11. Toast Events

Toast exposes the following events for you to bind to whatever you want

beforeShow will be triggered right before the toast is about to appear

afterShown will be triggered after the toast has appeared

beforeHide will be triggered before the toast is about to hide

afterHidden will be triggered right after the toast gets hidden

            $.toast().reset('all');Run Code

$.toast({
    text: 'Triggers the events',

    beforeShow: function () {
        alert('The toast is about to appear');
    },

    afterShown: function () {
        alert('Toast has appeared.');
    },

    beforeHide: function () {
        alert('Toast is about to hide.');
    },

    afterHidden: function () {
        alert('Toast has been hidden.');
    }
})

12. Updating Toasts

If you have a reference to a toast and want to update that, you can do so by calling the update method on the instance.

        Run Code

var myToast = $.toast({
    heading: 'Information',
    text: 'Here is some information that will be later on turned to an error',
    icon: 'info',
    hideAfter: false
});

// Update the toast after three seconds.
window.setTimeout(function(){
    myToast.update({
        heading: 'Error',
        text: 'Here is an information that changed to error',
        icon: 'error',
        hideAfter: false
    });
}, 3000)

13. Resetting Toasts

If you have the reference to a specific toast, you can reset that by doing the following

var myToast = $.toast('Some toast that needs to be removed.');
myToast.reset(); // remove the toast "Some toast that needs to be removed"

If you do not have the reference to a specific toast and want to reset every toast, do the following:

$.toast().reset('all');

Customize Plugin

            Text
            <input type="text" id="toast-text" class="toast-text" value="Don't forget to star the repository if you like it.">

            Heading
            <input type="text" id="toast-heading" class="toast-heading" value="Note">

            Transition
            <select name="toast-transition" id="toast-transition" class="toast-transition">
              <option value="fade">Fade</option>
              <option value="slide">Slide</option>
              <option value="plain">Plain</option>
            </select>

            Allow Toast Close
            <select name="allow-toast-close" id="allow-toast-close" class="allow-toast-close">
              <option value="true">True</option>
              <option value="false">False</option>
            </select>

            Auto Hide
            <select name="auto-hide-toast" id="auto-hide-toast" class="auto-hide-toast">
              <option value="true">True</option>
              <option value="false">False</option>
            </select>

            Hide (with transition^) after (ms)
            <input type="text" id="autohide-after" class="autohide-after" value="3000">

            Stack toasts
            <select name="stack-toasts" id="stack-toasts" class="stack-toasts">
              <option value="true">Yes</option>
              <option value="false">No</option>
            </select>

            Stack Length
            <input type="text" id="stack-length" class="stack-length" value="5">

            Toast Position
            <select name="toast-position" id="toast-position" class="toast-position">
              <option value="bottom-left">Bottom Left</option>
              <option value="bottom-right">Bottom Right</option>
              <option value="top-left">Top Left</option>
              <option value="top-right">Top Right</option>
              <option value="top-center">Top Center</option>
              <option value="bottom-center">Bottom Center</option>
              <option value="mid-center">Mid Center</option>
              <option value="custom-position">Custom</option>
            </select>

            Custom Toast Position

                Left
                <input type="text" class="left-position" id="left-position">

                Right
                <input type="text" class="right-position" id="right-position">

                Top
                <input type="text" class="top-position" id="top-position">

                Bottom
                <input type="text" class="bottom-position" id="bottom-position">

            Icon
            <select name="icon-type" id="icon-type" class="text-align">
              <option value="">-- No icon --</option>
              <option selected="selected" value="warning">Warning</option>
              <option value="success">Success</option>
              <option value="error">Error</option>
              <option value="info">Information</option>
            </select>

                Background Color
                <input type="color" id="toast-bg" class="toast-bg" value="#444444">

                Text Color
                <input type="color" id="toast-text-color" class="toast-text-color" value="#eeeeee">

            Text Alignment
            <select name="text-align" id="text-align" class="text-align">
              <option value="left">Left</option>
              <option value="right">Right</option>
              <option value="center">Center</option>
            </select>

            Toast Events
            <select name="add-toast-events" id="add-toast-events" class="add-toast-events">
              <option value="true">True</option>
              <option value="false">False</option>
            </select>

            Show Loader
            <select name="show-loader" id="show-loader" class="show-loader">
              <option value="true">True</option>
              <option value="false">False</option>
            </select>

            Loader Color
            <input type="color" id="loader-bg" class="loader-bg" value="#9EC600">

            Generate

$.toast({
    text: "Hey there fellas, here is a simple toast. Change the options above and then see the code that generates that toast", // Text that is to be shown in the toast
    heading: 'How to use', // Optional heading to be shown on the toast
    icon: 'warning', // Type of toast icon
    showHideTransition: 'fade', // fade, slide or plain
    allowToastClose: <spna class="kt toast-allowToastClose">true</spna>, // Boolean value true or false
    hideAfter: 3000, // false to make it sticky or number representing the miliseconds as time after which toast needs to be hidden
    stack: 5, // false if there should be only one toast at a time or a number representing the maximum number of toasts to be shown at a time
    position: 'bottom-left', // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values
    position: { left : 20, right : 20, top : 20, bottom : 20 }, // bottom-left or bottom-right or bottom-center or top-left or top-right or top-center or mid-center or an object representing the left, right, top, bottom values
    bgColor: '#444',  // Background color of the toast
    textColor: '#eee',  // Text color of the toast
    textAlign: 'left',  // Text alignment i.e. left, right or center
    loader: true,  // Whether to show loader or not. True by default
    loaderBg: '#9EC600',  // Background color of the toast loader
    beforeShow: function () {}, // will be triggered before the toast is shown
    afterShown: function () {}, // will be triggered after the toat has been shown
    beforeHide: function () {}, // will be triggered before the toast gets hidden
    afterHidden: function () {}  // will be triggered after the toast has been hidden
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/background_chatlist"
    android:orientation="vertical" >

    <include
        android:id="@+id/title_layout"
        layout="@layout/activity_title" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/logoff"
            style="@style/about_us_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/weibo" />

        <TextView
            style="@style/about_us_des"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/weibo_des" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="0.5dp"
            android:layout_below="@id/logoff"
            android:background="@color/chat_send_msg" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/otherSex"
            style="@style/about_us_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/qqgroup" />

        <TextView
            style="@style/about_us_des"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/qqgroup_des" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="0.5dp"
            android:layout_below="@id/otherSex"
            android:background="@color/chat_send_msg" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/video_setting"
            style="@style/about_us_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/website" />

        <TextView
            style="@style/about_us_des"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/website_des" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="0.5dp"
            android:layout_below="@id/video_setting"
            android:background="@color/chat_send_msg" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/push_setting"
            style="@style/about_us_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="20dp"
            android:text="@string/weixing" />

        <TextView
            style="@style/about_us_des"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/weixing_des" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="0.5dp"
            android:layout_below="@id/push_setting"
            android:background="@color/chat_send_msg" />
    </RelativeLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
Simulates planetary motion using newtonian physics.

Controls
---------
* 'W', 'A', 'S', 'D' to move camera
* 'R' to reset
* '`' to show/hide debug
* 'Esc' to exit


text:
package org.woehlke.twitterwall.oodm.model;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UserListTest implements DomainObjectMinimalTest {

    private static final Logger log = LoggerFactory.getLogger(UserTest.class);

    @Test
    @Override
    public void test001getUniqueIdTest() throws Exception {

    }

    @Test
    @Override
    public void test002isValidTest() throws Exception {

    }
}


text:
#include <stdlib.h>
#include <string.h>

#include <algorithm>

#define BBCDEBUG_LEVEL 1
#include <bbcat-base/EnhancedFile.h>
#include "ADMXMLGenerator.h"

#include "XMLADMData.h"
#include "RIFFChunk_Definitions.h"

// currently the chna chunk is specified as having either 32 or 2048 entries for tracks
// define CHNA_FIXED_UIDS_LOWER as 0 to disable this behaviour
#define CHNA_FIXED_UIDS_LOWER 0
#define CHNA_FIXED_UIDS_UPPER 2048

BBC_AUDIOTOOLBOX_START

const std::string XMLADMData::DefaultStandardDefinitionsFile = "standarddefinitions.xml";
bool  XMLADMData::defaultebuxmlmode = true;

XMLADMData::XMLADMData() : ADMData(),
                           ebuxmlmode(defaultebuxmlmode)
{
}

XMLADMData::XMLADMData(const XMLADMData& obj) : ADMData(obj),
                                                ebuxmlmode(obj.ebuxmlmode)
{
}

XMLADMData::~XMLADMData()
{
}

/*--------------------------------------------------------------------------------*/
/** Return provider list, creating as necessary
 */
/*--------------------------------------------------------------------------------*/
std::vector<XMLADMData::PROVIDER>& XMLADMData::GetProviderList()
{
  // create here so that this function can be called before this object's static data is constructed
  static std::vector<PROVIDER> _providerlist;
  return _providerlist;
}

/*--------------------------------------------------------------------------------*/
/** Load standard definitions file into ADM
 */
/*--------------------------------------------------------------------------------*/
bool XMLADMData::LoadStandardDefinitions(const std::string& filename)
{
  static const std::string paths[] = {
    "",
    ".",
    BBCAT_AUDIOOBJECTS_DATA_FILES,
  };
  std::string filename2;
  uint_t i;
  bool success = false;

  // delete any existing objects
  Delete();

  for (i = 0; i < NUMBEROF(paths); i++)
  {
    if (filename != "") filename2 = EnhancedFile::catpath(paths[i], filename);
    else                filename2 = EnhancedFile::catpath(paths[i], DefaultStandardDefinitionsFile);    // use default filename if none supplied

    if (EnhancedFile::exists(filename2.c_str()))
    {
      BBCDEBUG("Found standard definitions file '%s' as '%s'", filename.c_str(), filename2.c_str());

      if (ReadXMLFromFile(filename2.c_str()))
      {
        ADMOBJECTS_IT it;

        // set standard def flag on all loaded objects
        for (it = admobjects.begin(); it != admobjects.end(); ++it)
        {
          it->second->SetStandardDefinition();
        }

        success = true;
      }
      else BBCERROR("Failed to read standard definitions file '%s'", filename2.c_str());
      break;
    }
    else BBCDEBUG2(("Standard definitions file '%s' doesn't exist (from '%s' and '%s')", filename2.c_str(), paths[i].c_str(), filename.c_str()));
  }

  if (i == NUMBEROF(paths)) BBCERROR("Failed to find standard definitions file '%s'", filename.c_str());

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Read ADM data from the chna RIFF chunk
 *
 * @param data ptr to chna chunk data
 * @param len length of chna chunk
 *
 * @return true if data read successfully
 */
/*--------------------------------------------------------------------------------*/
bool XMLADMData::SetChna(const uint8_t *data, uint64_t len)
{
  const CHNA_CHUNK& chna = *(const CHNA_CHUNK *)data;
  uint_t maxuids = (uint_t)((len - sizeof(CHNA_CHUNK)) / sizeof(chna.UIDs[0]));   // calculate maximum number of UIDs given chunk length
  std::string terminator;
  bool success = true;

  // create string with a single 0 byte in it to detect terminators
  terminator.push_back(0);

  if (maxuids < chna.UIDCount) BBCERROR("Warning: chna specifies %u UIDs but chunk has only length for %u", (uint_t)chna.UIDCount, maxuids);

  uint16_t i;
  for (i = 0; (i < chna.UIDCount) && (i < maxuids); i++)
  {
    // only handle non-zero track numbers
    if (chna.UIDs[i].TrackNum)
    {
      ADMAudioTrack *track;
      std::string id;

      id.assign(chna.UIDs[i].UID, sizeof(chna.UIDs[i].UID));
      id = id.substr(0, id.find(terminator));

      if ((track = dynamic_cast<ADMAudioTrack *>(Create(ADMAudioTrack::Type, id, ""))) != NULL)
      {
        XMLValue tvalue, pvalue;

        track->SetTrackNum(chna.UIDs[i].TrackNum - 1);

        tvalue.attr = false;
        tvalue.name = ADMAudioTrackFormat::Reference;
        tvalue.value.assign(chna.UIDs[i].TrackRef, sizeof(chna.UIDs[i].TrackRef));
        // trim any zero bytes off the end of the string
        tvalue.value = tvalue.value.substr(0, tvalue.value.find(terminator));
        track->AddValue(tvalue);

        pvalue.attr = false;
        pvalue.name = ADMAudioPackFormat::Reference;
        pvalue.value.assign(chna.UIDs[i].PackRef, sizeof(chna.UIDs[i].PackRef));
        // trim any zero bytes off the end of the string
        pvalue.value = pvalue.value.substr(0, pvalue.value.find(terminator));
        track->AddValue(pvalue);

        track->SetValues();

        BBCDEBUG2(("Track %u/%u: Index %u UID '%s' TrackFormatRef '%s' PackFormatRef '%s'",
                i, (uint_t)tracklist.size(),
                track->GetTrackNum() + 1,
                track->GetID().c_str(),
                tvalue.value.c_str(),
                pvalue.value.c_str()));
      }
      else BBCERROR("Failed to create AudioTrack for UID %u", i);
    }
  }

  SortTracks();

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Read ADM data from the axml RIFF chunk
 *
 * @param data ptr to axml chunk data (MUST be terminated!)
 *
 * @return true if data read successfully
 */
/*--------------------------------------------------------------------------------*/
bool XMLADMData::SetAxml(const char *data)
{
  bool success = false;

  BBCDEBUG3(("Read XML:\n%s", data));

  if (TranslateXML(data))
  {
    Finalise();

    success = true;
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Read ADM data from explicit XML
 *
 * @param data XML data stored as a string
 *
 * @return true if data read successfully
 */
/*--------------------------------------------------------------------------------*/
bool XMLADMData::SetAxml(const std::string& data)
{
  bool success = false;

  BBCDEBUG3(("Read XML:\n%s", data.c_str()));

  if (TranslateXML(data.c_str()))
  {
    Finalise();

    success = true;
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Load CHNA data from file
 *
 * @param filename file containing chna in text form
 *
 * @return true if data read successfully
 */
/*--------------------------------------------------------------------------------*/
bool XMLADMData::ReadChnaFromFile(const std::string& filename)
{
  EnhancedFile fp;
  bool success = false;

  if (fp.fopen(filename.c_str()))
  {
    char buffer[1024];
    int l;

    success = true;

    while (success && ((l = fp.readline(buffer, sizeof(buffer) - 1)) != EOF))
    {
      if (l > 0)
      {
        std::vector<std::string> words;

        SplitString(std::string(buffer), words);

        if (words.size() == 4)
        {
          uint_t tracknum;

          if (Evaluate(words[0], tracknum))
          {
            if (tracknum)
            {
              const std::string& trackuid    = words[1];
              const std::string& trackformat = words[2];
              const std::string& packformat  = words[3];
              ADMAudioTrack *track;
              std::string id;

              if ((track = dynamic_cast<ADMAudioTrack *>(Create(ADMAudioTrack::Type, trackuid, ""))) != NULL)
              {
                XMLValue tvalue, pvalue;

                track->SetTrackNum(tracknum - 1);

                tvalue.attr = false;
                tvalue.name = ADMAudioTrackFormat::Reference;
                tvalue.value = trackformat;
                track->AddValue(tvalue);

                pvalue.attr = false;
                pvalue.name = ADMAudioPackFormat::Reference;
                pvalue.value = packformat;
                track->AddValue(pvalue);

                track->SetValues();

                BBCDEBUG2(("Track %u: Index %u UID '%s' TrackFormatRef '%s' PackFormatRef '%s'",
                        (uint_t)tracklist.size(),
                        track->GetTrackNum() + 1,
                        track->GetID().c_str(),
                        tvalue.value.c_str(),
                        pvalue.value.c_str()));
              }
              else
              {
                BBCERROR("Failed to create AudioTrack for UID %u", tracknum);
                success = false;
              }
            }
          }
          else
          {
            BBCERROR("CHNA line '%s' word 1 ('%s') should be a track number", buffer, words[0].c_str());
            success = false;
          }
        }
        else
        {
          BBCERROR("CHNA line '%s' requires 4 words", buffer);
          success = false;
        }
      }
    }

    fp.fclose();

    if (success) Finalise();
  }

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Load ADM data from file
 *
 * @param filename file containing XML
 *
 * @return true if data read successfully
 */
/*--------------------------------------------------------------------------------*/
bool XMLADMData::ReadXMLFromFile(const std::string& filename)
{
  EnhancedFile fp;
  bool success = false;

  if (fp.fopen(filename.c_str()))
  {
    fp.fseek(0, SEEK_END);
    off_t len = fp.ftell();
    fp.rewind();

    char *buffer;
    if ((buffer = new char[len + 1]) != NULL)
    {
      len = fp.fread(buffer, sizeof(char), len);
      buffer[len] = 0;

      success = SetAxml(buffer);

      delete[] buffer;
    }
    else BBCERROR("Failed to allocate %s chars for file '%s'", StringFrom(len + 1).c_str(), filename.c_str());

    fp.fclose();
  }
  else BBCERROR("Failed to open file '%s' for reading", filename.c_str());

  return success;
}

/*--------------------------------------------------------------------------------*/
/** Read ADM data from the chna and axml RIFF chunks
 *
 * @param chna ptr to chna chunk data
 * @param chnalength length of chna data
 * @param axml ptr to axml chunk data (MUST be terminated like a string)
 *
 * @return true if data read successfully
 */
/*--------------------------------------------------------------------------------*/
bool XMLADMData::Set(const uint8_t *chna, uint64_t chnalength, const char *axml)
{
  return (SetChna(chna, chnalength) && SetAxml(axml));
}

/*--------------------------------------------------------------------------------*/
/** Create chna chunk data
 *
 * @param len reference to length variable to be updated with the size of the chunk
 *
 * @return ptr to chunk data
 */
/*--------------------------------------------------------------------------------*/
uint8_t *XMLADMData::GetChna(uint64_t& len) const
{
  CHNA_CHUNK *p = NULL;
  uint_t nuids = (uint_t)tracklist.size();

#if CHNA_FIXED_UIDS_LOWER > 0
  nuids = (nuids <= CHNA_FIXED_UIDS_LOWER) ? CHNA_FIXED_UIDS_LOWER : CHNA_FIXED_UIDS_UPPER;
#endif

  // calculate size of chna chunk
  len = sizeof(*p) + (uint64_t)nuids * (uint64_t)sizeof(p->UIDs[0]);
  if ((p = (CHNA_CHUNK *)calloc(1, len)) != NULL)
  {
    std::vector<bool> uniquetracks; // list of unique tracks
    uint_t i;

    // allocate maximum number of tracks
    uniquetracks.resize(tracklist.size());

    // populate structure
    p->TrackCount = 0;
    p->UIDCount   = 0;

    for (i = 0; (i < tracklist.size()) && (p->UIDCount < nuids); i++)
    {
      const ADMAudioTrack *track = tracklist[i];
      uint_t tr = track->GetTrackNum();

      // test to see if uniquetracks array needs expanding
      if (tr >= uniquetracks.size()) uniquetracks.resize(tr + 1);

      // if this is a new track (i.e. one not previously used),increment TrackCount
      if (!uniquetracks[tr])
      {
        // set flag
        uniquetracks[tr] = true;
        // increment TrackCount
        p->TrackCount++;
      }

      // set track number (1- based) and UID
      p->UIDs[i].TrackNum = tr + 1;
      strncpy(p->UIDs[i].UID, track->GetID().c_str(), sizeof(p->UIDs[i].UID));

      // set trackformat references
      const ADMAudioTrackFormat *trackref = NULL;
      if (track->GetTrackFormatRefs().size() && ((trackref = track->GetTrackFormatRefs()[0]) != NULL))
      {
        strncpy(p->UIDs[i].TrackRef, trackref->GetID().c_str(), sizeof(p->UIDs[i].TrackRef));
      }

      // set packformat references
      const ADMAudioPackFormat *packref = NULL;
      if (track->GetPackFormatRefs().size() && ((packref = track->GetPackFormatRefs()[0]) != NULL))
      {
        strncpy(p->UIDs[i].PackRef, packref->GetID().c_str(), sizeof(p->UIDs[i].PackRef));
      }

      p->UIDCount++;

      BBCDEBUG2(("Track %u/%u: Index %u UID '%s' TrackFormatRef '%s' PackFormatRef '%s'",
              i, (uint_t)tracklist.size(),
              track->GetTrackNum() + 1,
              track->GetID().c_str(),
              trackref ? trackref->GetID().c_str() : "<none>",
              packref  ? packref->GetID().c_str()  : "<none>"));
    }
  }

  return (uint8_t *)p;
}

/*--------------------------------------------------------------------------------*/
/** Create axml chunk data
 *
 * @param indent indent string to use within XML
 * @param eol end of line string to use within XML
 * @param ind_level initial indentation level
 *
 * @return string containing XML data for axml chunk
 */
/*--------------------------------------------------------------------------------*/
std::string XMLADMData::GetAxml(const std::string& indent, const std::string& eol, uint_t ind_level) const
{
  return ADMXMLGenerator::GetAxml(this, ebuxmlmode, indent, eol, ind_level);
}

/*--------------------------------------------------------------------------------*/
/** Create XML representation of ADM in a data buffer
 *
 * @param buf buffer to store XML in (or NULL to just get the length)
 * @param buflen maximum length of buf (excluding terminator)
 * @param indent indentation for each level of objects
 * @param eol end-of-line string
 * @param level initial indentation level
 *
 * @return total length of XML
 */
/*--------------------------------------------------------------------------------*/
uint64_t XMLADMData::GetAxmlBuffer(uint8_t *buf, uint64_t buflen, const std::string& indent, const std::string& eol, uint_t ind_level) const
{
  return ADMXMLGenerator::GetAxmlBuffer(this, buf, buflen, ebuxmlmode, indent, eol, ind_level);
}

/*--------------------------------------------------------------------------------*/
/** Create an ADM capable of decoding supplied XML as axml chunk
 */
/*--------------------------------------------------------------------------------*/
XMLADMData *XMLADMData::CreateADM(const std::string& standarddefinitionsfile)
{
  const std::vector<PROVIDER>& providerlist = GetProviderList();
  XMLADMData *data = NULL;
  uint_t i;

  for (i = 0; i < providerlist.size(); i++)
  {
    const PROVIDER& provider = providerlist[i];

    if ((data = (*provider.fn)(standarddefinitionsfile, provider.context)) != NULL) break;
  }

  return data;
}

/*--------------------------------------------------------------------------------*/
/** Register a provider for the above
 */
/*--------------------------------------------------------------------------------*/
void XMLADMData::RegisterProvider(CREATOR fn, void *context)
{
  std::vector<PROVIDER>& providerlist = GetProviderList();
  PROVIDER provider = {fn, context};

  providerlist.push_back(provider);
}

/*--------------------------------------------------------------------------------*/
/** Parse XML section
 *
 * @param type object type
 * @param userdata context data
 *
 * @return newly created object
 */
/*--------------------------------------------------------------------------------*/
ADMObject *XMLADMData::Parse(const std::string& type, void *userdata)
{
  ADMHEADER header;
  ADMObject *obj;

  ParseHeader(header, type, userdata);

  if ((obj = Create(type, header.id, header.name)) != NULL)
  {
    ParseValues(obj, userdata);
    PostParse(obj, userdata);

    obj->SetValues();
  }

  return obj;
}

BBC_AUDIOTOOLBOX_END


text:
var allEmbeds = new Array();
var currentEmbedIndex = 0;
function slidesLiveEmbedBox(){
	//Public properties
	var thisInstance = this;
	this.xmlhttp = 5;
	this.presentationID = 38889556;
	this.width = 960;
	this.height = 100;
	this.videoSlideRatio = -1; //-1-100 -1 is balanced
	this.forceLightbox = true;
	this.zoomingOn = true;
	this.startSlide = 1;
	this.bgColor = "#1E1E1E";

	//Private vars
	this.playerContainer = document.createElement('div'),
	this.lightboxShadow = document.createElement('div'),
	this.lightboxClose = document.createElement('div'),
	this.lightboxDisplayed = false,
	this.hasVideo = true,
	this.hasSlides = true,
	this.mediaType = "",
	this.mediaID = "",
	this.isPaid = false,
	this.playerURL = "http://slideslive.com/bundles/player/Player_5_THC.swf",
	//this.playerURL = "http://localhost/SlidesLive/web/bundles/player/Player_5_THC.swf",
	this.presentationJsonApiUrl = "http://slideslive.com/embedjsonapi/",

	this.embedPresentation = function(presentationID, width, videoSlideRatio, forceLightbox, zoomingOn, startSlide) {
		thisInstance.printLog("Embeding presentation"+presentationID);
		if(typeof(presentationID)!=='undefined') thisInstance.presentationID = presentationID;
		if(typeof(width)!=='undefined') thisInstance.width = width;
		if(typeof(videoSlideRatio)!=='undefined') thisInstance.videoSlideRatio = videoSlideRatio;
		if(typeof(forceLightbox)!=='undefined') thisInstance.forceLightbox = forceLightbox;
		if(typeof(zoomingOn)!=='undefined') thisInstance.zoomingOn = zoomingOn;
		if(typeof(startSlide)!=='undefined') thisInstance.startSlide = startSlide;

		thisInstance.createPlayerContainer();
	},

	this.createPlayerContainer = function() {
		thisInstance.printLog("creating container");
		thisInstance.playerContainer.style.width = thisInstance.width+'px';
		thisInstance.playerContainer.style.height = thisInstance.height+'px';
		thisInstance.playerContainer.style.color = "white";
		thisInstance.playerContainer.setAttribute("id", thisInstance.presentationID);
		thisInstance.getPresentationData();

		//Find script tag that called creation
		var scripts = document.getElementsByTagName("script");
		var embedScript = document.getElementById('sle81767');

		//Try to find exact one
		for (var i=0; i<scripts.length; ++i ) {
		  if ( scripts[i].innerHTML.indexOf("embedPresentation("+thisInstance.presentationID) != -1 ) {
			embedScript = scripts[i];
		  }
		}

		embedScript.parentNode.insertBefore(thisInstance.playerContainer, embedScript);
	},

	this.resizePlayerContainer = function(newHeight) {
		if(thisInstance.hasSlides && !thisInstance.hasVideo) newHeight = (parseInt(thisInstance.playerContainer.style.width) * 3) / 4;
		thisInstance.height = newHeight;
		thisInstance.printLog(thisInstance.height);
		thisInstance.playerContainer.style.height = thisInstance.height+"px";
	},

	this.createPlayerHtml = function(scaledWidth, lightboxCode){
		if(typeof(scaledWidth)=='undefined') scaledWidth = thisInstance.width;

		var flashVarString = "hasVideo="+thisInstance.hasVideo+
							"&hasSlides="+thisInstance.hasSlides+
							"&presentationID="+thisInstance.presentationID+
							"&mediaType="+thisInstance.mediaType+
							"&mediaID="+thisInstance.mediaID+
							"&widthScale="+scaledWidth+
							"&isEmbed=true"+
							"&isPaid="+thisInstance.isPaid+
							"&videoSlideRatio="+thisInstance.videoSlideRatio+
							"&zoomingOn="+thisInstance.zoomingOn+
							"&startSlide="+thisInstance.startSlide;
		if(lightboxCode) flashVarString += "&autoplay=true";

		if(thisInstance.bgColor == "transparent" || lightboxCode){
			var colorParameter = "<param name=\"wmode\" value=\"transparent\">";
			var colorEmbed = "wmode=\"transparent\"";
		} else {
			var colorParameter = "<param name=\"bgcolor\" value=\""+thisInstance.bgColor+"\">";
			var colorEmbed = "bgcolor=\""+thisInstance.bgColor+"\"";
		}

		var playerString = "<object type=\"application/x-shockwave-flash\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" width=\"100%\" height=\"100%\">"+
							"<param name=\"movie\" value=\""+thisInstance.playerURL+"\"></param>"+
							"<param name=\"allowFullScreen\" value=\"true\"></param>"+
							"<param name=\"allowscriptaccess\" value=\"always\"></param>"+
							"<param name=\"flashvars\" value=\""+flashVarString+"\"></param>"+
							colorParameter+
    						"<embed src=\""+thisInstance.playerURL+"\" "+colorEmbed+" flashvars=\""+flashVarString+"\" type=\"application/x-shockwave-flash\" width=\"100%\" height=\"100%\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"  allowscriptaccess=\"always\" allowfullscreen=\"true\"></embed>"+
							"</object>";
		return playerString;
	}

	this.getPresentationData = function(){
		if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
			thisInstance.xmlhttp=new XMLHttpRequest();
		} else {// code for IE6, IE5
			thisInstance.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}

		thisInstance.xmlhttp.open("GET",thisInstance.presentationJsonApiUrl+thisInstance.presentationID,true);
		thisInstance.xmlhttp.onreadystatechange=thisInstance.serverResponseProcess;
		thisInstance.xmlhttp.send();
	}

	this.serverResponseProcess = function(){
		if (thisInstance.xmlhttp.readyState==4 && thisInstance.xmlhttp.status==200)
		{
			var json = thisInstance.xmlhttp.responseText;
			var presentations = JSON.parse(json);
			var presentation = presentations[0];
			thisInstance.printLog(json);
			thisInstance.hasVideo = presentation.hasVideo;
			thisInstance.hasSlides = presentation.hasSlides;
			thisInstance.mediaType = presentation.mediaType;
			thisInstance.mediaID = presentation.mediaID;
			thisInstance.isPaid = presentation.isPaid;
		}
		thisInstance.playerContainer.innerHTML = thisInstance.createPlayerHtml();
	}

	this.hideLightBox = function() {
		thisInstance.lightboxDisplayed = false;

		thisInstance.lightboxShadow.style.display = "none";

		//Find script tag that called creation
		var scripts = document.getElementsByTagName("script");
		var embedScript = document.getElementById('sle81767');

		thisInstance.playerContainer.style.width = thisInstance.width+'px';
		thisInstance.playerContainer.style.marginLeft = "0px";
		thisInstance.playerContainer.style.marginRight = "0px";
		thisInstance.playerContainer.innerHTML = thisInstance.createPlayerHtml();

		//Try to find exact one
		for (var i=0; i<scripts.length; ++i ) {
		  if ( scripts[i].innerHTML.indexOf("embedPresentation("+thisInstance.presentationID) != -1 ) {
			embedScript = scripts[i];
		  }
		}

		embedScript.parentNode.insertBefore(thisInstance.playerContainer, embedScript);
	}

	this.displayLightBox = function() {
		console.log("LIGHTBOX DISPLAYYY");
		if(thisInstance.width >= 800 || !thisInstance.forceLightbox || thisInstance.lightboxDisplayed) return false;

		thisInstance.lightboxDisplayed = true;

		document.onkeypress=function(e){
			var e=window.event || e
			if(e.keyCode == 27) thisInstance.hideLightBox();
		}

		//Decide maximum player width according to type of content
		if(thisInstance.hasVideo){
			lbPlayerWidth = Math.round(0.8 * window.innerWidth);
			lbPlayerHeight = 500;
		} else {
			lbPlayerHeight = Math.round(0.9 * window.innerHeight);
			lbPlayerWidth = Math.round((4*lbPlayerHeight) / 3);
			console.log("Audioslideshow, width: "+lbPlayerWidth+ "height: " + lbPlayerHeight );
		}

		thisInstance.lightboxShadow.style.width = "100%";
		thisInstance.lightboxShadow.style.height = "100%";
		thisInstance.lightboxShadow.style.backgroundColor = "#000";
		thisInstance.lightboxShadow.style.backgroundColor = "rgba(0, 0, 0, 0.8)";

		thisInstance.lightboxShadow.style.display = "block";
		thisInstance.lightboxShadow.style.position = "fixed";
		thisInstance.lightboxShadow.style.zIndex = "9999";
		thisInstance.lightboxShadow.style.left = "0px";
		thisInstance.lightboxShadow.style.top = "0px";

		thisInstance.lightboxClose.addEventListener("click",thisInstance.hideLightBox,true);
		thisInstance.lightboxClose.addEventListener("mouseover",thisInstance.lightUpCloseButton);
		thisInstance.lightboxClose.addEventListener("mouseout",thisInstance.lightDownCloseButton);
		thisInstance.lightboxClose.style.width = "50px";
		thisInstance.lightboxClose.style.height = "50px";
		thisInstance.lightboxClose.style.backgroundImage = "url('http://slideslive.com/bundles/close-big.png')";
		thisInstance.lightboxClose.style.backgroundRepeat = "no-repeat";
		thisInstance.lightboxClose.style.backgroundPosition = "50% 15px";
		thisInstance.lightboxClose.style.cursor = "pointer";
		thisInstance.lightboxClose.style.display = "block";
		thisInstance.lightboxClose.style.position = "fixed";
		thisInstance.lightboxClose.style.zIndex = "9999";
		thisInstance.lightboxClose.style.right = "0px";
		thisInstance.lightboxClose.style.top = "0px";

		thisInstance.playerContainer.style.width = lbPlayerWidth+'px';
		thisInstance.playerContainer.style.height = lbPlayerHeight+"px";
		thisInstance.playerContainer.style.marginTop = "50px";
		thisInstance.playerContainer.style.marginLeft = "auto";
		thisInstance.playerContainer.style.marginRight = "auto";

		document.body.appendChild(thisInstance.lightboxShadow);
		thisInstance.lightboxShadow.appendChild(thisInstance.playerContainer);
		thisInstance.lightboxShadow.appendChild(thisInstance.lightboxClose);

		thisInstance.playerContainer.innerHTML = thisInstance.createPlayerHtml(lbPlayerWidth,true);
		//document.body.insertBefore(thisInstance.lightboxShadow, document.body.firstChild);
	}

	this.lightUpCloseButton = function() {
		thisInstance.lightboxClose.style.backgroundPosition = "50% -28px";
	}

	this.lightDownCloseButton = function() {
		thisInstance.lightboxClose.style.backgroundPosition = "50% 15px";
	}

	this.printLog = function(message){
		console.log(message);
	}
};

function createSlidesLiveBox(){
	var tmpSL = new slidesLiveEmbedBox();
	allEmbeds[currentEmbedIndex] = tmpSL;
	currentEmbedIndex++;
	return tmpSL;
}

function resizeEmbedBridge(newHeight, presentationID) {
	for (var i = 0; i < allEmbeds.length; i++) {
		if(allEmbeds[i].presentationID == presentationID) allEmbeds[i].resizePlayerContainer(newHeight);
	}
}

function slFirstPlayBridge(presentationID) {
	console.log("test play fired - "+presentationID);

	for (var i = 0; i < allEmbeds.length; i++) {
		if(allEmbeds[i].presentationID == presentationID) allEmbeds[i].displayLightBox();
	}
}


text:
package cards;

import server.Card;
import server.Game;
import server.Player;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Harvest extends Card {

    @Override
    public String name() {
        return "Harvest";
    }

    @Override
    public Set<Type> types() {
        return types(Type.ACTION);
    }

    @Override
    public int cost() {
        return 5;
    }

    @Override
    public String[] description() {
        return new String[] {"Reveal the_top 4 cards of your_deck, then discard them, <+1$>_per differently_named card_revealed."};
    }

    @Override
    public void onPlay(Player player, Game game) {
        List<Card> revealed = player.takeFromDraw(4);
        if (!revealed.isEmpty()) {
            game.messageAll("revealing and discarding " + Card.htmlList(revealed));
            player.addToDiscard(revealed);
            int numDifferentlyNamed = new HashSet<>(revealed).size();
            plusCoins(player, game, numDifferentlyNamed);
        } else {
            game.message(player, "your deck is empty");
            game.messageOpponents(player, "their deck is empty");
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xmlns:drools="http://drools.org/schema/drools-spring"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
       http://drools.org/schema/drools-spring http://drools.org/schema/drools-spring.xsd">

    <!-- Setup Drools -->
    <drools:grid-node id="node1"/>

    <drools:kbase id="kbase1" node="node1">
        <drools:configuration>
            <drools:mbeans enabled="true"/>
        </drools:configuration>
        <drools:resources>
            <drools:resource type="DRL" source="classpath:testSpring.drl"/>
        </drools:resources>
    </drools:kbase>

    <drools:ksession id="ksession1" type="stateless" name="ksession1" kbase="kbase1" node="node1">
        <!-- Adding a configuration forces drools to use the current classloader (see issue SM-2316) -->
        <drools:configuration />
    </drools:ksession>

    <bean id="droolsHelper" class="org.apache.servicemix.examples.camel.DroolsCommandHelper"/>

    <bean id="personHelper" class="org.apache.servicemix.examples.camel.PersonHelper"/>

    <!-- declare the drools bean here to avoid OSGi classpath issues -->
    <bean id="drools" class="org.drools.camel.component.DroolsComponent"/>

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <route trace="false" id="testRoute">
            <description>
                Example route that will regularly create a random Person and choose an appropriate drink based on the
                drools rules file. After processing, it divides the people into VIPs and regular clients based on the
                drools result.
            </description>
            <from uri="timer:testRoute"/>
            <bean method="createTestPerson" ref="personHelper"/>
            <to uri="drools:node1/ksession1?action=insertBody" id="DrinkChooser">
                <description>valid 'action' values are:
                    'execute' that takes a 'Command' object (default)
                    'insertBody' that inserts the Exchange.in.body, and executes rules
                    'insertMessage' that inserts the Exchange.in (type org.apache.camel.Message), and executes rules
                    'insertExchange' that inserts the Exchange (type org.apache.camel.Exchange), and executes rules
                </description>
            </to>
            <choice>
                <when id="Vip">
                    <simple>${body.isVip}</simple>
                    <log logName="ServeDrink VIP" message="This ${body.name} is a VIP! Give a ${body.getDrink.getDescription} from the house"/>
                </when>
                <otherwise>
                    <log logName="ServeDrink" message="Serve this ${body.name} a ${body.getDrink.getDescription}"/>
                </otherwise>
            </choice>
        </route>
        <route trace="false" id="ruleOnBody">
            <description>This route shows an example of passing (inserting) the Body of the message as a POJO to Drools
                for execution
            </description>
            <from uri="direct://ruleOnBody"/>
            <to uri="drools:node1/ksession1?action=insertBody">
                <description>valid 'action' values are:
                    'execute' that takes a 'Command' object (default)
                    'insertBody' that inserts the Exchange.in.body, and executes rules
                    'insertMessage' that inserts the Exchange.in (type org.apache.camel.Message), and executes rules
                    'insertExchange' that inserts the Exchange (type org.apache.camel.Exchange), and executes rules
                </description>
            </to>
        </route>
        <route trace="false" id="ruleOnCommand">
            <description>This route shows an example of creating a Drools Command wrapping the Body of the message with
                the help of the custom DroolsCommandHelperBean (included in this project), and passing this Drools
                Command to the ruleset for execution.
            </description>
            <from uri="direct://ruleOnCommand"/>
            <bean method="insertAndFireAll" ref="droolsHelper"/>
            <to uri="drools:node1/ksession1?action=execute">
                <description>valid 'action' values are:
                    'execute' that takes a 'Command' object (default)
                    'insertBody' that inserts the Exchange.in.body, and executes rules
                    'insertMessage' that inserts the Exchange.in (type org.apache.camel.Message), and executes rules
                    'insertExchange' that inserts the Exchange (type org.apache.camel.Exchange), and executes rules
                </description>
            </to>
        </route>
    </camelContext>

</beans>


text:
package org.apache.lucene.demo.xmlparser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.StoredDocument;
import org.apache.lucene.queryparser.xml.CorePlusExtensionsParser;
import org.apache.lucene.queryparser.xml.QueryTemplateManager;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.Version;

/**
 * Example servlet that uses the XML queryparser.
 *

 * NOTE: you must provide CSV data in /WEB-INF/data.tsv
 * for the demo to work!
 */
public class FormBasedXmlQueryDemo extends HttpServlet {

  private QueryTemplateManager queryTemplateManager;
  private CorePlusExtensionsParser xmlParser;
  private IndexSearcher searcher;
  private Analyzer analyzer = new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_CURRENT);

  /** for instantiation by the servlet container */
  public FormBasedXmlQueryDemo() {}

  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    try {
      openExampleIndex();

      //load servlet configuration settings
      String xslFile = config.getInitParameter("xslFile");
      String defaultStandardQueryParserField = config.getInitParameter("defaultStandardQueryParserField");

      //Load and cache choice of XSL query template using QueryTemplateManager
      queryTemplateManager = new QueryTemplateManager(
          getServletContext().getResourceAsStream("/WEB-INF/" + xslFile));

      //initialize an XML Query Parser for use by all threads
      xmlParser = new CorePlusExtensionsParser(defaultStandardQueryParserField, analyzer);
    } catch (Exception e) {
      throw new ServletException("Error loading query template", e);
    }
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Take all completed form fields and add to a Properties object
    Properties completedFormFields = new Properties();
    Enumeration<?> pNames = request.getParameterNames();
    while (pNames.hasMoreElements()) {
      String propName = (String) pNames.nextElement();
      String value = request.getParameter(propName);
      if ((value != null) && (value.trim().length() > 0)) {
        completedFormFields.setProperty(propName, value);
      }
    }

    try {
      //Create an XML query by populating template with given user criteria
      org.w3c.dom.Document xmlQuery = queryTemplateManager.getQueryAsDOM(completedFormFields);

      //Parse the XML to produce a Lucene query
      Query query = xmlParser.getQuery(xmlQuery.getDocumentElement());

      //Run the query
      TopDocs topDocs = searcher.search(query, 10);

      //and package the results and forward to JSP
      if (topDocs != null) {
        ScoreDoc[] sd = topDocs.scoreDocs;
        StoredDocument[] results = new StoredDocument[sd.length];
        for (int i = 0; i < results.length; i++) {
          results[i] = searcher.doc(sd[i].doc);
          request.setAttribute("results", results);
        }
      }
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
      dispatcher.forward(request, response);
    }
    catch (Exception e) {
      throw new ServletException("Error processing query", e);
    }
  }

  private void openExampleIndex() throws IOException {
    //Create a RAM-based index from our test data file
    RAMDirectory rd = new RAMDirectory();
    IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
    IndexWriter writer = new IndexWriter(rd, iwConfig);
    InputStream dataIn = getServletContext().getResourceAsStream("/WEB-INF/data.tsv");
    BufferedReader br = new BufferedReader(new InputStreamReader(dataIn, IOUtils.CHARSET_UTF_8));
    String line = br.readLine();
    final FieldType textNoNorms = new FieldType(TextField.TYPE_STORED);
    textNoNorms.setOmitNorms(true);
    while (line != null) {
      line = line.trim();
      if (line.length() > 0) {
        //parse row and create a document
        StringTokenizer st = new StringTokenizer(line, "\t");
        Document doc = new Document();
        doc.add(new Field("location", st.nextToken(), textNoNorms));
        doc.add(new Field("salary", st.nextToken(), textNoNorms));
        doc.add(new Field("type", st.nextToken(), textNoNorms));
        doc.add(new Field("description", st.nextToken(), textNoNorms));
        writer.addDocument(doc);
      }
      line = br.readLine();
    }
    writer.close();

    //open searcher
    // this example never closes it reader!
    IndexReader reader = DirectoryReader.open(rd);
    searcher = new IndexSearcher(reader);
  }
}


text:
/** ------------------------------------------------------------
 * Mail.java
 *
 * Big Cyber City
 *
 * @author wbruschi [ Dec 20, 2008 ]
 * ------------------------------------------------------------
 */
package com.bigcybercity.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * Represents mail in the database
 */

@Entity
@Table(name = "MAIL")
public class Mail {
	long id, fromId, toId;
	String subject, body;
	boolean isRead, delFrom, delTo;
	Date date;

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public long getFromId() {
		return fromId;
	}
	public void setFromId(long fromId) {
		this.fromId = fromId;
	}
	public long getToId() {
		return toId;
	}
	public void setToId(long toId) {
		this.toId = toId;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getBody() {
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}

	@Column(name = "isRead")
	public boolean isRead() {
		return isRead;
	}
	public void setRead(boolean isRead) {
		this.isRead = isRead;
	}
	public boolean isDelFrom() {
		return delFrom;
	}
	public void setDelFrom(boolean delFrom) {
		this.delFrom = delFrom;
	}
	public boolean isDelTo() {
		return delTo;
	}
	public void setDelTo(boolean delTo) {
		this.delTo = delTo;
	}

	@Temporal(TemporalType.TIMESTAMP)
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}

}


text:
package org.openkilda.wfm.topology.flowhs.fsm.create.action;

import static java.lang.String.format;

import org.openkilda.model.Flow;
import org.openkilda.model.PathSegment;
import org.openkilda.model.SwitchId;
import org.openkilda.persistence.PersistenceManager;
import org.openkilda.persistence.repositories.IslRepository;
import org.openkilda.wfm.share.flow.resources.FlowResources;
import org.openkilda.wfm.share.flow.resources.FlowResourcesManager;
import org.openkilda.wfm.topology.flowhs.exception.FlowProcessingException;
import org.openkilda.wfm.topology.flowhs.fsm.common.actions.FlowProcessingAction;
import org.openkilda.wfm.topology.flowhs.fsm.create.FlowCreateContext;
import org.openkilda.wfm.topology.flowhs.fsm.create.FlowCreateFsm;
import org.openkilda.wfm.topology.flowhs.fsm.create.FlowCreateFsm.Event;
import org.openkilda.wfm.topology.flowhs.fsm.create.FlowCreateFsm.State;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;

@Slf4j
public class ResourcesDeallocationAction extends FlowProcessingAction<FlowCreateFsm, State, Event, FlowCreateContext> {
    private final FlowResourcesManager resourcesManager;
    private final IslRepository islRepository;

    public ResourcesDeallocationAction(FlowResourcesManager resourcesManager, PersistenceManager persistenceManager) {
        super(persistenceManager);

        this.resourcesManager = resourcesManager;
        this.islRepository = persistenceManager.getRepositoryFactory().createIslRepository();
    }

    @Override
    protected void perform(State from, State to, Event event, FlowCreateContext context, FlowCreateFsm stateMachine) {
        try {
            transactionManager.doInTransaction(() -> {
                Flow flow = getFlow(stateMachine.getFlowId());
                flow.resetPaths();
            });
        } catch (FlowProcessingException e) {
            stateMachine.saveActionToHistory("Skip resources deallocation",
                    format("Skip resources deallocation. Flow %s has already been deleted: %s",
                            stateMachine.getFlowId(), e.getMessage()));
            return;
        }

        Collection<FlowResources> flowResources = stateMachine.getFlowResources();
        for (FlowResources resources : flowResources) {
            List<PathSegment> removedSegments = new ArrayList<>();

            Stream.of(resources.getForward().getPathId(), resources.getReverse().getPathId())
                    .forEach(pathId ->
                            flowPathRepository.remove(pathId)
                                    .ifPresent(path -> removedSegments.addAll(path.getSegments())));

            updateIslsForSegments(removedSegments);

            transactionManager.doInTransaction(() ->
                    resourcesManager.deallocatePathResources(resources));
        }

        if (!stateMachine.isPathsBeenAllocated()) {
            flowRepository.remove(stateMachine.getFlowId());
        }

        stateMachine.saveActionToHistory("The resources have been deallocated");
    }

    private void updateIslsForSegments(List<PathSegment> pathSegments) {
        pathSegments.forEach(pathSegment ->
                transactionManager.doInTransaction(() -> {
                    updateAvailableBandwidth(pathSegment.getSrcSwitchId(), pathSegment.getSrcPort(),
                            pathSegment.getDestSwitchId(), pathSegment.getDestPort());
                }));
    }

    private void updateAvailableBandwidth(SwitchId srcSwitch, int srcPort, SwitchId dstSwitch, int dstPort) {
        long usedBandwidth = flowPathRepository.getUsedBandwidthBetweenEndpoints(srcSwitch, srcPort,
                dstSwitch, dstPort);
        log.debug("Updating ISL {}_{} - {}_{} with used bandwidth {}", srcSwitch, srcPort, dstSwitch, dstPort,
                usedBandwidth);
        islRepository.updateAvailableBandwidth(srcSwitch, srcPort, dstSwitch, dstPort, usedBandwidth);
    }
}


text:
define( [
	"qunit",
	"jquery",
	"lib/helper"
], function( QUnit, $, helper ) {

return $.extend( helper, {
	drag: function( el, dx, dy ) {

		// This mouseover is to work around a limitation in resizable
		// TODO: fix resizable so handle doesn't require mouseover in order to be used
		$( el ).simulate( "mouseover" ).simulate( "drag", {
			moves: 2,
			dx: dx,
			dy: dy
		} );
	}
} );

} );


text:
/*namespace com.google.zxing.common.reedsolomon {*/

import GenericGF from './GenericGF';
import GenericGFPoly from './GenericGFPoly';

import ReedSolomonException from '../../ReedSolomonException';
import IllegalStateException from '../../IllegalStateException';

/**
 *
Implements Reed-Solomon decoding, as the name implies.

 *
 *
The algorithm will not be explained here, but the following references were helpful
 * in creating this implementation:

 *
 *

 *
Bruce Maggs.
 *
 * "Decoding Reed-Solomon Codes" (see discussion of Forney's Formula)

 *
J.I. Hall.
 * "Chapter 5. Generalized Reed-Solomon Codes"
 * (see discussion of Euclidean algorithm)

 *

 *
 *
Much credit is due to William Rucklidge since portions of this code are an indirect
 * port of his C++ Reed-Solomon implementation.

 *
 * @author Sean Owen
 * @author William Rucklidge
 * @author sanfordsquires
 */
export default class ReedSolomonDecoder {

    public constructor(private field: GenericGF) { }

    /**
     *
Decodes given set of received codewords, which include both data and error-correction
     * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
     * in the input.

     *
     * @param received data and error-correction codewords
     * @param twoS number of error-correction codewords available
     * @throws ReedSolomonException if decoding fails for any reason
     */
    public decode(received: Int32Array, twoS: number /*int*/): void /*throws ReedSolomonException*/ {
        const field = this.field;
        const poly = new GenericGFPoly(field, received);
        const syndromeCoefficients = new Int32Array(twoS);
        let noError: boolean = true;
        for (let i = 0; i < twoS; i++) {
            const evalResult = poly.evaluateAt(field.exp(i + field.getGeneratorBase()));
            syndromeCoefficients[syndromeCoefficients.length - 1 - i] = evalResult;
            if (evalResult !== 0) {
                noError = false;
            }
        }
        if (noError) {
            return;
        }
        const syndrome = new GenericGFPoly(field, syndromeCoefficients);
        const sigmaOmega = this.runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
        const sigma = sigmaOmega[0];
        const omega = sigmaOmega[1];
        const errorLocations = this.findErrorLocations(sigma);
        const errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations);
        for (let i = 0; i < errorLocations.length; i++) {
            const position = received.length - 1 - field.log(errorLocations[i]);
            if (position < 0) {
                throw new ReedSolomonException('Bad error location');
            }
            received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
        }
    }

    private runEuclideanAlgorithm(a: GenericGFPoly, b: GenericGFPoly, R: number /*int*/): GenericGFPoly[] {
        // Assume a's degree is >= b's
        if (a.getDegree() = (R / 2 | 0)) {
            let rLastLast = rLast;
            let tLastLast = tLast;
            rLast = r;
            tLast = t;

            // Divide rLastLast by rLast, with quotient in q and remainder in r
            if (rLast.isZero()) {
                // Oops, Euclidean algorithm already terminated?
                throw new ReedSolomonException('r_{i-1} was zero');
            }
            r = rLastLast;
            let q = field.getZero();
            const denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());
            const dltInverse = field.inverse(denominatorLeadingTerm);
            while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {
                const degreeDiff = r.getDegree() - rLast.getDegree();
                const scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);
                q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
                r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
            }

            t = q.multiply(tLast).addOrSubtract(tLastLast);

            if (r.getDegree() >= rLast.getDegree()) {
                throw new IllegalStateException('Division algorithm failed to reduce polynomial?');
            }
        }

        const sigmaTildeAtZero = t.getCoefficient(0);
        if (sigmaTildeAtZero === 0) {
            throw new ReedSolomonException('sigmaTilde(0) was zero');
        }

        const inverse = field.inverse(sigmaTildeAtZero);
        const sigma = t.multiplyScalar(inverse);
        const omega = r.multiplyScalar(inverse);
        return [sigma, omega];
    }

    private findErrorLocations(errorLocator: GenericGFPoly): Int32Array /*throws ReedSolomonException*/ {
        // This is a direct application of Chien's search
        const numErrors = errorLocator.getDegree();
        if (numErrors === 1) { // shortcut
            return Int32Array.from([errorLocator.getCoefficient(1)]);
        }
        const result = new Int32Array(numErrors);
        let e = 0;
        const field = this.field;
        for (let i = 1; i < field.getSize() && e < numErrors; i++) {
            if (errorLocator.evaluateAt(i) === 0) {
                result[e] = field.inverse(i);
                e++;
            }
        }
        if (e !== numErrors) {
            throw new ReedSolomonException('Error locator degree does not match number of roots');
        }
        return result;
    }

    private findErrorMagnitudes(errorEvaluator: GenericGFPoly, errorLocations: Int32Array): Int32Array {
        // This is directly applying Forney's Formula
        const s = errorLocations.length;
        const result = new Int32Array(s);
        const field = this.field;
        for (let i = 0; i < s; i++) {
            const xiInverse = field.inverse(errorLocations[i]);
            let denominator = 1;
            for (let j = 0; j < s; j++) {
                if (i !== j) {
                    // denominator = field.multiply(denominator,
                    //    GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)))
                    // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
                    // Below is a funny-looking workaround from Steven Parkes
                    const term = field.multiply(errorLocations[j], xiInverse);
                    const termPlus1 = (term & 0x1) === 0 ? term | 1 : term & ~1;
                    denominator = field.multiply(denominator, termPlus1);
                }
            }
            result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse),
                field.inverse(denominator));
            if (field.getGeneratorBase() !== 0) {
                result[i] = field.multiply(result[i], xiInverse);
            }
        }
        return result;
    }

}


text:
package java8.ch02.ex07;

import static org.junit.Assert.*;

import java.util.stream.Stream;

import org.junit.Test;

public class MyMathTest {
	@Test
	public void testIsFinite_1() {
		assertTrue(MyMath.isFinite(Stream.of("foo", "bar")));
	}
	@Test
	public void testIsFinite_2() {
		assertFalse(MyMath.isFinite(Stream.generate(() -> "foo")));
	}
}


text:
<?php

require_once(dirname(__FILE__).'/../../bootstrap/unit.php');

$t = new lime_test(6);

$v1 = new sfValidatorString(array('min_length' => 2, 'trim' => true));

$v = new sfValidatorSchemaFilter('first_name', $v1);

// ->clean()
$t->diag('->clean()');
$t->is($v->clean(array('first_name' => '  foo  ')), array('first_name' => 'foo'), '->clean() executes the embedded validator');

try
{
  $v->clean('string');
  $t->fail('->clean() throws a InvalidArgumentException if the input value is not an array');
}
catch (InvalidArgumentException $e)
{
  $t->pass('->clean() throws a InvalidArgumentException if the input value is not an array');
}

try
{
  $v->clean(null);
  $t->fail('->clean() throws a sfValidatorError if the embedded validator failed');
  $t->skip('', 1);
}
catch (sfValidatorError $e)
{
  $t->pass('->clean() throws a sfValidatorError if the embedded validator failed');
  $t->is($e->getCode(), 'first_name [required]', '->clean() throws a sfValidatorError');
}

try
{
  $v->clean(array('first_name' => 'f'));
  $t->fail('->clean() throws a sfValidatorError if the embedded validator failed');
  $t->skip('', 1);
}
catch (sfValidatorError $e)
{
  $t->pass('->clean() throws a sfValidatorError if the embedded validator failed');
  $t->is($e->getCode(), 'first_name [min_length]', '->clean() throws a sfValidatorError');
}


text: """Package with Melange-specific views."""


text:
'use strict';
moduloUsuarioperfil.controller('UsuarioperfilNewController', ['$scope', '$routeParams', '$location', 'serverService', 'sharedSpaceService',
    function ($scope, $routeParams, $location, serverService, sharedSpaceService) {
        $('#broth_modal_login').css({"display":"none"});
        $scope.id = $routeParams.id;
        $scope.ob = 'usuarioperfil';
        $scope.result = null;
        $scope.title = "Register";
        $scope.icon = "fa-user";
        if (sharedSpaceService.getFase() == 0) {
            $scope.obj = {
              id: 0,
                nombre: "",
                apellido: "",
                email: "",
                password: "",
                direccion:"",
                estado_civil: "",
                ocupacion:"",
                estudio:""
            };
        } else {
            $scope.obj = sharedSpaceService.getObject();
            sharedSpaceService.setFase(0);
        }
        $scope.chooseOne = function (foreignObjectName) {
            sharedSpaceService.setObject($scope.obj);
            sharedSpaceService.setReturnLink('/' + $scope.ob + '/new');
            sharedSpaceService.setFase(1);
            $location.path('/' + foreignObjectName + '/selection/1/10');
        }
        $scope.save = function () {
            console.log("save");
            console.log({json: JSON.stringify(serverService.array_identificarArray($scope.obj))});
            //strValues = serverService.array_identificarArray(thisObject.form_getFormValues(strClass));
            serverService.getDataFromPromise(serverService.promise_setOne($scope.ob, {json: JSON.stringify(serverService.array_identificarArray($scope.obj))})).then(function (data) {
                $scope.result = data;
            });
        };
        $scope.$watch('obj.obj_perfil.id', function () {
            serverService.getDataFromPromise(serverService.promise_getOne('perfil', $scope.obj.obj_perfil.id)).then(function (data2) {
                $scope.obj.obj_perfil = data2.message;
            });
        });
        $scope.back = function () {
            $location.path('#/');

           // window.history.back();
        };
        $scope.close = function () {
           // window.history.back();
            $location.path('#/');

        };
       /* $scope.plist = function () {
            $location.path('/usuario/plist');
        };*/

    }]);


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Classes (Twilio Client for Android)</title>
<meta name="date" content="2015-01-29">
<link rel="stylesheet" type="text/css" href="javadoc-style.css" title="Style">

All Classes

Connection

Connection.State

ConnectionListener

Device

Device.Capability

Device.State

DeviceListener

PresenceEvent

Twilio

Twilio.InitListener


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;

namespace KillrVideo.Statistics {
  ///
  ///  Service that tracks playback statistics for videos
  ///
  public static class StatisticsService
  {
    static readonly string __ServiceName = "killrvideo.statistics.StatisticsService";

    static readonly Marshaller<global::KillrVideo.Statistics.RecordPlaybackStartedRequest> __Marshaller_RecordPlaybackStartedRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Statistics.RecordPlaybackStartedRequest.Parser.ParseFrom);
    static readonly Marshaller<global::KillrVideo.Statistics.RecordPlaybackStartedResponse> __Marshaller_RecordPlaybackStartedResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Statistics.RecordPlaybackStartedResponse.Parser.ParseFrom);
    static readonly Marshaller<global::KillrVideo.Statistics.GetNumberOfPlaysRequest> __Marshaller_GetNumberOfPlaysRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Statistics.GetNumberOfPlaysRequest.Parser.ParseFrom);
    static readonly Marshaller<global::KillrVideo.Statistics.GetNumberOfPlaysResponse> __Marshaller_GetNumberOfPlaysResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::KillrVideo.Statistics.GetNumberOfPlaysResponse.Parser.ParseFrom);

    static readonly Method<global::KillrVideo.Statistics.RecordPlaybackStartedRequest, global::KillrVideo.Statistics.RecordPlaybackStartedResponse> __Method_RecordPlaybackStarted = new Method<global::KillrVideo.Statistics.RecordPlaybackStartedRequest, global::KillrVideo.Statistics.RecordPlaybackStartedResponse>(
        MethodType.Unary,
        __ServiceName,
        "RecordPlaybackStarted",
        __Marshaller_RecordPlaybackStartedRequest,
        __Marshaller_RecordPlaybackStartedResponse);

    static readonly Method<global::KillrVideo.Statistics.GetNumberOfPlaysRequest, global::KillrVideo.Statistics.GetNumberOfPlaysResponse> __Method_GetNumberOfPlays = new Method<global::KillrVideo.Statistics.GetNumberOfPlaysRequest, global::KillrVideo.Statistics.GetNumberOfPlaysResponse>(
        MethodType.Unary,
        __ServiceName,
        "GetNumberOfPlays",
        __Marshaller_GetNumberOfPlaysRequest,
        __Marshaller_GetNumberOfPlaysResponse);

    /// Service descriptor
    public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
    {
      get { return global::KillrVideo.Statistics.StatisticsServiceReflection.Descriptor.Services[0]; }
    }

    /// Base class for server-side implementations of StatisticsService
    public abstract class StatisticsServiceBase
    {
      ///
      ///  Record that playback started for a given video
      ///
      public virtual global::System.Threading.Tasks.Task<global::KillrVideo.Statistics.RecordPlaybackStartedResponse> RecordPlaybackStarted(global::KillrVideo.Statistics.RecordPlaybackStartedRequest request, ServerCallContext context)
      {
        throw new RpcException(new Status(StatusCode.Unimplemented, ""));
      }

      ///
      ///  Get the number of plays for a given video or set of videos
      ///
      public virtual global::System.Threading.Tasks.Task<global::KillrVideo.Statistics.GetNumberOfPlaysResponse> GetNumberOfPlays(global::KillrVideo.Statistics.GetNumberOfPlaysRequest request, ServerCallContext context)
      {
        throw new RpcException(new Status(StatusCode.Unimplemented, ""));
      }

    }

    /// Client for StatisticsService
    public class StatisticsServiceClient : ClientBase<StatisticsServiceClient>
    {
      /// Creates a new client for StatisticsService
      /// <param name="channel">The channel to use to make remote calls.</param>
      public StatisticsServiceClient(Channel channel) : base(channel)
      {
      }
      /// Creates a new client for StatisticsService that uses a custom <c>CallInvoker</c>.
      /// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
      public StatisticsServiceClient(CallInvoker callInvoker) : base(callInvoker)
      {
      }
      /// Protected parameterless constructor to allow creation of test doubles.
      protected StatisticsServiceClient() : base()
      {
      }
      /// Protected constructor to allow creation of configured clients.
      /// <param name="configuration">The client configuration.</param>
      protected StatisticsServiceClient(ClientBaseConfiguration configuration) : base(configuration)
      {
      }

      ///
      ///  Record that playback started for a given video
      ///
      public virtual global::KillrVideo.Statistics.RecordPlaybackStartedResponse RecordPlaybackStarted(global::KillrVideo.Statistics.RecordPlaybackStartedRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return RecordPlaybackStarted(request, new CallOptions(headers, deadline, cancellationToken));
      }
      ///
      ///  Record that playback started for a given video
      ///
      public virtual global::KillrVideo.Statistics.RecordPlaybackStartedResponse RecordPlaybackStarted(global::KillrVideo.Statistics.RecordPlaybackStartedRequest request, CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_RecordPlaybackStarted, null, options, request);
      }
      ///
      ///  Record that playback started for a given video
      ///
      public virtual AsyncUnaryCall<global::KillrVideo.Statistics.RecordPlaybackStartedResponse> RecordPlaybackStartedAsync(global::KillrVideo.Statistics.RecordPlaybackStartedRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return RecordPlaybackStartedAsync(request, new CallOptions(headers, deadline, cancellationToken));
      }
      ///
      ///  Record that playback started for a given video
      ///
      public virtual AsyncUnaryCall<global::KillrVideo.Statistics.RecordPlaybackStartedResponse> RecordPlaybackStartedAsync(global::KillrVideo.Statistics.RecordPlaybackStartedRequest request, CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_RecordPlaybackStarted, null, options, request);
      }
      ///
      ///  Get the number of plays for a given video or set of videos
      ///
      public virtual global::KillrVideo.Statistics.GetNumberOfPlaysResponse GetNumberOfPlays(global::KillrVideo.Statistics.GetNumberOfPlaysRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return GetNumberOfPlays(request, new CallOptions(headers, deadline, cancellationToken));
      }
      ///
      ///  Get the number of plays for a given video or set of videos
      ///
      public virtual global::KillrVideo.Statistics.GetNumberOfPlaysResponse GetNumberOfPlays(global::KillrVideo.Statistics.GetNumberOfPlaysRequest request, CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_GetNumberOfPlays, null, options, request);
      }
      ///
      ///  Get the number of plays for a given video or set of videos
      ///
      public virtual AsyncUnaryCall<global::KillrVideo.Statistics.GetNumberOfPlaysResponse> GetNumberOfPlaysAsync(global::KillrVideo.Statistics.GetNumberOfPlaysRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return GetNumberOfPlaysAsync(request, new CallOptions(headers, deadline, cancellationToken));
      }
      ///
      ///  Get the number of plays for a given video or set of videos
      ///
      public virtual AsyncUnaryCall<global::KillrVideo.Statistics.GetNumberOfPlaysResponse> GetNumberOfPlaysAsync(global::KillrVideo.Statistics.GetNumberOfPlaysRequest request, CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_GetNumberOfPlays, null, options, request);
      }
      protected override StatisticsServiceClient NewInstance(ClientBaseConfiguration configuration)
      {
        return new StatisticsServiceClient(configuration);
      }
    }

    /// Creates service definition that can be registered with a server
    public static ServerServiceDefinition BindService(StatisticsServiceBase serviceImpl)
    {
      return ServerServiceDefinition.CreateBuilder()
          .AddMethod(__Method_RecordPlaybackStarted, serviceImpl.RecordPlaybackStarted)
          .AddMethod(__Method_GetNumberOfPlays, serviceImpl.GetNumberOfPlays).Build();
    }

  }
}
#endregion


text:
namespace blink {
class StorageKey;
}  // namespace blink

namespace leveldb_proto {
class ProtoDatabaseProvider;
}  // namespace leveldb_proto

namespace content {

class BackgroundSyncContext;
class DevToolsBackgroundServicesContext;
class DOMStorageContext;
class FileSystemAccessEntryFactory;
class HostZoomLevelContext;
class HostZoomMap;
class PlatformNotificationContext;
class ServiceWorkerContext;
class ZoomLevelDelegate;

namespace mojom {
class NetworkContext;
}  // namespace mojom

// Fake implementation of StoragePartition.
class TestStoragePartition : public StoragePartition {
 public:
  TestStoragePartition();

  TestStoragePartition(const TestStoragePartition&) = delete;
  TestStoragePartition& operator=(const TestStoragePartition&) = delete;

  ~TestStoragePartition() override;

  void set_path(base::FilePath file_path) { file_path_ = file_path; }
  base::FilePath GetPath() override;

  void set_network_context(network::mojom::NetworkContext* context) {
    network_context_ = context;
  }
  network::mojom::NetworkContext* GetNetworkContext() override;

  scoped_refptr<network::SharedURLLoaderFactory>
  GetURLLoaderFactoryForBrowserProcess() override;

  std::unique_ptr<network::PendingSharedURLLoaderFactory>
  GetURLLoaderFactoryForBrowserProcessIOThread() override;

  void set_cookie_manager_for_browser_process(
      network::mojom::CookieManager* cookie_manager_for_browser_process) {
    cookie_manager_for_browser_process_ = cookie_manager_for_browser_process;
  }
  network::mojom::CookieManager* GetCookieManagerForBrowserProcess() override;

  void CreateTrustTokenQueryAnswerer(
      mojo::PendingReceiver<network::mojom::TrustTokenQueryAnswerer> receiver,
      const url::Origin& top_frame_origin) override;

  mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver>
  CreateURLLoaderNetworkObserverForFrame(int process_id,
                                         int routing_id) override;

  mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver>
  CreateURLLoaderNetworkObserverForNavigationRequest(
      NavigationRequest& navigation_request) override;

  void set_quota_manager(storage::QuotaManager* manager) {
    quota_manager_ = manager;
  }
  storage::QuotaManager* GetQuotaManager() override;

  void set_file_system_context(storage::FileSystemContext* context) {
    file_system_context_ = context;
  }
  storage::FileSystemContext* GetFileSystemContext() override;

  void set_background_sync_context(BackgroundSyncContext* context) {
    background_sync_context_ = context;
  }
  BackgroundSyncContext* GetBackgroundSyncContext() override;

  void set_database_tracker(storage::DatabaseTracker* tracker) {
    database_tracker_ = tracker;
  }
  storage::DatabaseTracker* GetDatabaseTracker() override;

  void set_dom_storage_context(DOMStorageContext* context) {
    dom_storage_context_ = context;
  }
  DOMStorageContext* GetDOMStorageContext() override;

  storage::mojom::LocalStorageControl* GetLocalStorageControl() override;

  storage::mojom::IndexedDBControl& GetIndexedDBControl() override;

  FileSystemAccessEntryFactory* GetFileSystemAccessEntryFactory() override;

  void set_service_worker_context(ServiceWorkerContext* context) {
    service_worker_context_ = context;
  }
  ServiceWorkerContext* GetServiceWorkerContext() override;

  DedicatedWorkerService* GetDedicatedWorkerService() override;

  void set_shared_worker_service(SharedWorkerService* service) {
    shared_worker_service_ = service;
  }
  SharedWorkerService* GetSharedWorkerService() override;

  storage::mojom::CacheStorageControl* GetCacheStorageControl() override;

  void set_generated_code_cache_context(GeneratedCodeCacheContext* context) {
    generated_code_cache_context_ = context;
  }
  GeneratedCodeCacheContext* GetGeneratedCodeCacheContext() override;

  void set_platform_notification_context(PlatformNotificationContext* context) {
    platform_notification_context_ = context;
  }
  PlatformNotificationContext* GetPlatformNotificationContext() override;

  InterestGroupManager* GetInterestGroupManager() override;

  void set_browsing_topics_site_data_manager(
      BrowsingTopicsSiteDataManager* manager) {
    browsing_topics_site_data_manager_ = manager;
  }
  BrowsingTopicsSiteDataManager* GetBrowsingTopicsSiteDataManager() override;

  void set_devtools_background_services_context(
      DevToolsBackgroundServicesContext* context) {
    devtools_background_services_context_ = context;
  }
  DevToolsBackgroundServicesContext* GetDevToolsBackgroundServicesContext()
      override;

  leveldb_proto::ProtoDatabaseProvider* GetProtoDatabaseProvider() override;
  void SetProtoDatabaseProvider(
      std::unique_ptr<leveldb_proto::ProtoDatabaseProvider> proto_db_provider)
      override;
  leveldb_proto::ProtoDatabaseProvider* GetProtoDatabaseProviderForTesting()
      override;

  void set_content_index_context(ContentIndexContext* context) {
    content_index_context_ = context;
  }
  ContentIndexContext* GetContentIndexContext() override;

  NativeIOContext* GetNativeIOContext() override;

  void set_host_zoom_map(HostZoomMap* map) { host_zoom_map_ = map; }
  HostZoomMap* GetHostZoomMap() override;

  void set_host_zoom_level_context(HostZoomLevelContext* context) {
    host_zoom_level_context_ = context;
  }
  HostZoomLevelContext* GetHostZoomLevelContext() override;

  void set_zoom_level_delegate(ZoomLevelDelegate* delegate) {
    zoom_level_delegate_ = delegate;
  }
  ZoomLevelDelegate* GetZoomLevelDelegate() override;

  void ClearDataForOrigin(uint32_t remove_mask,
                          uint32_t quota_storage_remove_mask,
                          const GURL& storage_origin,
                          base::OnceClosure callback) override;

  void ClearData(uint32_t remove_mask,
                 uint32_t quota_storage_remove_mask,
                 const blink::StorageKey& storage_key,
                 const base::Time begin,
                 const base::Time end,
                 base::OnceClosure callback) override;

  void ClearData(uint32_t remove_mask,
                 uint32_t quota_storage_remove_mask,
                 StorageKeyPolicyMatcherFunction storage_key_matcher,
                 network::mojom::CookieDeletionFilterPtr cookie_deletion_filter,
                 bool perform_storage_cleanup,
                 const base::Time begin,
                 const base::Time end,
                 base::OnceClosure callback) override;

  void ClearCodeCaches(
      const base::Time begin,
      const base::Time end,
      const base::RepeatingCallback<bool(const GURL&)>& url_matcher,
      base::OnceClosure callback) override;

  void Flush() override;

  void ResetURLLoaderFactories() override;

  void AddObserver(DataRemovalObserver* observer) override;
  void RemoveObserver(DataRemovalObserver* observer) override;
  int GetDataRemovalObserverCount();

  void ClearBluetoothAllowedDevicesMapForTesting() override;
  void ResetAttributionManagerForTesting(
      base::OnceCallback<void(bool)> callback) override;
  void FlushNetworkInterfaceForTesting() override;
  void WaitForDeletionTasksForTesting() override;
  void WaitForCodeCacheShutdownForTesting() override;
  void SetNetworkContextForTesting(
      mojo::PendingRemote<network::mojom::NetworkContext>
          network_context_remote) override;

  base::WeakPtr<StoragePartition> GetWeakPtr();
  void InvalidateWeakPtrs();

 private:
  base::FilePath file_path_;
  mojo::Remote<network::mojom::NetworkContext> network_context_remote_;
  raw_ptr<network::mojom::NetworkContext> network_context_ = nullptr;
  raw_ptr<network::mojom::CookieManager> cookie_manager_for_browser_process_ =
      nullptr;
  raw_ptr<storage::QuotaManager> quota_manager_ = nullptr;
  raw_ptr<BackgroundSyncContext> background_sync_context_ = nullptr;
  raw_ptr<storage::FileSystemContext> file_system_context_ = nullptr;
  raw_ptr<storage::DatabaseTracker> database_tracker_ = nullptr;
  raw_ptr<DOMStorageContext> dom_storage_context_ = nullptr;
  mojo::Remote<storage::mojom::LocalStorageControl> local_storage_control_;
  mojo::Remote<storage::mojom::IndexedDBControl> indexed_db_control_;
  raw_ptr<ServiceWorkerContext> service_worker_context_ = nullptr;
  raw_ptr<DedicatedWorkerService> dedicated_worker_service_ = nullptr;
  raw_ptr<SharedWorkerService> shared_worker_service_ = nullptr;
  mojo::Remote<storage::mojom::CacheStorageControl> cache_storage_control_;
  raw_ptr<GeneratedCodeCacheContext> generated_code_cache_context_ = nullptr;
  raw_ptr<BrowsingTopicsSiteDataManager> browsing_topics_site_data_manager_ =
      nullptr;
  raw_ptr<PlatformNotificationContext> platform_notification_context_ = nullptr;
  raw_ptr<DevToolsBackgroundServicesContext>
      devtools_background_services_context_ = nullptr;
  raw_ptr<ContentIndexContext> content_index_context_ = nullptr;
  raw_ptr<NativeIOContext> native_io_context_ = nullptr;
  raw_ptr<HostZoomMap> host_zoom_map_ = nullptr;
  raw_ptr<HostZoomLevelContext> host_zoom_level_context_ = nullptr;
  raw_ptr<ZoomLevelDelegate> zoom_level_delegate_ = nullptr;
  int data_removal_observer_count_ = 0;

  // This member must be the last member.
  base::WeakPtrFactory<TestStoragePartition> weak_factory_{this};
};

}  // namespace content

#endif  // CONTENT_PUBLIC_TEST_TEST_STORAGE_PARTITION_H_


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

namespace SleepsCat
{
    class Program
    {
        static void Main(string[] args)
        {
            var holidays = int.Parse(Console.ReadLine());
            var day = 365 - holidays;
            var timeforplay = (day * 63) + (holidays * 127);
            var timediference = Math.Abs(30000 - timeforplay);
            var hours = Math.Abs (timediference / 60);
            var min =Math.Abs (timediference % 60);

            if (timeforplay > 30000)
            {
                Console.WriteLine("Tom will run away");
                Console.WriteLine("{0} hours and {1} minutes more for play", hours, min);
            }
            else
            {
                Console.WriteLine("Tom sleeps well");
                Console.WriteLine("{0} hours and {1} minutes less for play", hours, min);
            }

        }
    }
}