text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for OvfPropertyExport complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="OvfPropertyExport">
 *   <complexContent>
 *     <extension base="{urn:vim25}OvfExport">
 *       <sequence>
 *         <element name="type" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="value" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "OvfPropertyExport", propOrder = {
    "type",
    "value"
})
public class OvfPropertyExport
    extends OvfExport
{

    @XmlElement(required = true)
    protected String type;
    @XmlElement(required = true)
    protected String value;

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        this.type = value;
    }

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace LiteDB
{
    /// <summary>
    /// Service to create a journal file to garantee write operations will be atomic
    /// </summary>
    internal class JournalService
    {
        public const long FINISH_POSITION = BasePage.PAGE_SIZE - 1; // Last byte from header

        private CacheService _cache;
        private ConnectionString _connectionString;

        public JournalService(ConnectionString connectionString, CacheService cache)
        {
            _connectionString = connectionString;
            _cache = cache;
        }

        public void CreateJournalFile(Action action)
        {
            if (!_connectionString.JournalEnabled)
            {
                action();
                return;
            }

            FileStream journal = null;

            // try create journal file in EXCLUSIVE mode
            DiskService.TryExec(_connectionString.Timeout, () =>
            {
                journal = new FileStream(_connectionString.JournalFilename,
                    FileMode.Create, FileAccess.ReadWrite, FileShare.None, BasePage.PAGE_SIZE);
            });

            try
            {
                using (var writer = new BinaryWriter(journal))
                {
                    // first, allocate all journal file
                    var total = (uint)_cache.GetDirtyPages().Count();
                    journal.SetLength(total * BasePage.PAGE_SIZE);

                    // write all dirty pages in sequence on journal file
                    foreach (var page in _cache.GetDirtyPages())
                    {
                        this.WritePageInJournal(writer, page);
                    }

                    // flush all data
                    writer.Flush();

                    // mark header as finish
                    journal.Seek(FINISH_POSITION, SeekOrigin.Begin);

                    writer.Write(true); // mark as TRUE

                    // flush last finish mark
                    writer.Flush();

                    action();
                }

                journal.Dispose();

                File.Delete(_connectionString.JournalFilename);
            }
            catch
            {
                journal.Dispose();
            }
        }

        /// <summary>
        /// Write a page in sequence, not in absolute position
        /// </summary>
        private void WritePageInJournal(BinaryWriter writer, BasePage page)
        {
            // no need position cursor - journal writes in sequence
            var stream = writer.BaseStream;
            var posStart = stream.Position;
            var posEnd = posStart + BasePage.PAGE_SIZE;

            // Write page header
            page.WriteHeader(writer);

            // write content except for empty pages
            if (page.PageType != PageType.Empty)
            {
                page.WriteContent(writer);
            }

            // write with zero non-used page
            writer.Write(new byte[posEnd - stream.Position]);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Bravesheep\CrudifyBundle\Definition\Index;

use Bravesheep\CrudifyBundle\Definition\DefinitionInterface;
use Bravesheep\CrudifyBundle\Definition\Index\Column\ColumnInterface;
use Bravesheep\CrudifyBundle\Exception\ColumnNotFoundException;
use Bravesheep\CrudifyBundle\Query\ModifierInterface;

class IndexDefinition implements IndexDefinitionInterface
{
    /**
     * @var ColumnInterface[]
     */
    private $columns;

    /**
     * @var ColumnInterface
     */
    private $defaultSortColumn;

    /**
     * @var string
     */
    private $defaultSortDirection;

    /**
     * @var string
     */
    private $baseEntity;

    /**
     * @var DefinitionInterface
     */
    private $parent;

    /**
     * @var int
     */
    private $objectsPerPage;

    /**
     * @var string|ModifierInterface
     */
    private $queryModifier;

    public function __construct()
    {
        $this->columns = [];
        $this->defaultSortDirection = self::SORT_ASC;
        $this->objectsPerPage = -1;
    }

    /**
     * {@inheritdoc}
     */
    public function addColumn(ColumnInterface $column)
    {
        $this->columns[] = $column;
        $column->setParent($this);
    }

    /**
     * {@inheritdoc}
     */
    public function getColumns()
    {
        return $this->columns;
    }

    /**
     * {@inheritdoc}
     */
    public function hasColumn($name)
    {
        foreach ($this->columns as $column) {
            if ($column->getName() === $name) {
                return true;
            }
        }
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getColumn($name)
    {
        foreach ($this->columns as $column) {
            if ($column->getName() === $name) {
                return $column;
            }
        }
        throw new ColumnNotFoundException("No column with name '{$name}' found");
    }

    /**
     * @param ColumnInterface $column
     * @param string          $direction
     */
    public function setDefaultSort(ColumnInterface $column, $direction = self::SORT_ASC)
    {
        $this->defaultSortColumn = $column;
        $this->defaultSortDirection = $direction;
        $column->setParent($this);
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultSortColumn()
    {
        return $this->defaultSortColumn;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultSortDirection()
    {
        return $this->defaultSortDirection;
    }

    /**
     * @param string $baseEntity
     * @return $this
     */
    public function setBaseEntity($baseEntity)
    {
        $this->baseEntity = $baseEntity;
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getBaseEntity()
    {
        return $this->baseEntity;
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->columns);
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return count($this->columns);
    }

    /**
     * {@inheritdoc}
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * {@inheritdoc}
     */
    public function setParent(DefinitionInterface $parent)
    {
        $this->parent = $parent;
    }

    /**
     * @param int $objectsPerPage
     * @return $this
     */
    public function setObjectsPerPage($objectsPerPage)
    {
        $this->objectsPerPage = $objectsPerPage;
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getObjectsPerPage()
    {
        return $this->objectsPerPage;
    }

    /**
     * {@inheritdoc}
     */
    public function hasColumnWithField($field)
    {
       return $this->getColumnWithField($field) !== null;
    }

    /**
     * {@inheritdoc}
     */
    public function getColumnWithField($field)
    {
        /** @var ColumnInterface $column */
        foreach ($this as $column) {
            if ($column->getField() === $field) {
                return $column;
            }
        }
        return null;
    }

    /**
     * @param ModifierInterface|string $queryModifier
     * @return $this
     */
    public function setQueryModifier($queryModifier)
    {
        $this->queryModifier = $queryModifier;
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getQueryModifier()
    {
        return $this->queryModifier;
    }

    /**
     * {@inheritdoc}
     */
    public function hasQueryModifier()
    {
        return null !== $this->queryModifier;
    }
}


text:
package org.apache.camel.component.dropbox.dto;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.dropbox.core.DbxEntry;

public class DropboxSearchResult {

    private final List<DbxEntry> found;

    public DropboxSearchResult(List<DbxEntry> found) {
        this.found = new ArrayList<>(found);
    }

    public List<DbxEntry> getFound() {
        return Collections.unmodifiableList(found);
    }

}


text:
#include "config.h"

#include <vector>
#include <algorithm>

#include "pcrepp.hh"
#include "lnav_util.hh"
#include "data_parser.hh"
#include "ansi_scrubber.hh"
#include "log_format.hh"
#include "textview_curses.hh"

using namespace std;

void text_filter::add_line(
        logfile_filter_state &lfs, logfile::const_iterator ll, shared_buffer_ref &line) {
    bool match_state = this->matches(*lfs.tfs_logfile, *ll, line);

    if (!ll->is_continued()) {
        this->end_of_message(lfs);
    }

    this->lf_message_matched = this->lf_message_matched || match_state;
    this->lf_lines_for_message += 1;
}

bookmark_type_t textview_curses::BM_USER("user");
bookmark_type_t textview_curses::BM_PARTITION("partition");
bookmark_type_t textview_curses::BM_SEARCH("search");

string_attr_type textview_curses::SA_ORIGINAL_LINE;
string_attr_type textview_curses::SA_BODY;

textview_curses::textview_curses()
    : tc_sub_source(NULL),
      tc_delegate(NULL),
      tc_searching(false),
      tc_follow_search(false),
      tc_selection_start(-1),
      tc_selection_last(-1),
      tc_selection_cleared(false)
{
    this->set_data_source(this);
}

textview_curses::~textview_curses()
{ }

void textview_curses::reload_data(void)
{
    if (this->tc_sub_source != NULL) {
        this->tc_sub_source->text_update_marks(this->tc_bookmarks);
    }
    this->listview_curses::reload_data();
}

void textview_curses::grep_begin(grep_proc &gp)
{
    this->tc_searching = true;
    this->tc_search_action.invoke(this);

    listview_curses::reload_data();
}

void textview_curses::grep_end(grep_proc &gp)
{
    this->tc_searching = false;
    this->tc_search_action.invoke(this);
}

void textview_curses::grep_match(grep_proc &gp,
                                 grep_line_t line,
                                 int start,
                                 int end)
{
    this->tc_bookmarks[&BM_SEARCH].insert_once(vis_line_t(line));
    if (this->tc_sub_source != NULL) {
        this->tc_sub_source->text_mark(&BM_SEARCH, line, true);
    }

    if (this->get_top() <= line && line <= this->get_bottom()) {
        listview_curses::reload_data();
    }
}

void textview_curses::listview_value_for_row(const listview_curses &lv,
                                             vis_line_t row,
                                             attr_line_t &value_out)
{
    bookmark_vector<vis_line_t> &user_marks = this->tc_bookmarks[&BM_USER];
    bookmark_vector<vis_line_t> &part_marks = this->tc_bookmarks[&BM_PARTITION];
    string_attrs_t &             sa         = value_out.get_attrs();
    string &                     str        = value_out.get_string();
    highlight_map_t::iterator    iter;
    string::iterator             str_iter;

    this->tc_sub_source->text_value_for_line(*this, row, str);
    this->tc_sub_source->text_attrs_for_line(*this, row, sa);

    scrub_ansi_string(str, sa);

    struct line_range body;

    body = find_string_attr_range(sa, &SA_BODY);
    if (body.lr_start == -1) {
        body.lr_start = 0;
        body.lr_end = str.size();
    }

    for (iter = this->tc_highlights.begin();
         iter != this->tc_highlights.end();
         iter++) {
        // XXX testing for '$search' here sucks
        bool internal_hl = iter->first[0] == '$' && iter->first != "$search";
        int off, hcount = 0;
        size_t re_end;

        if (body.lr_end > 8192)
            re_end = 8192;
        else
            re_end = body.lr_end;

        for (off = internal_hl ? body.lr_start : 0; off < (int)str.size(); ) {
            int rc, matches[60];
            rc = pcre_exec(iter->second.h_code,
                           iter->second.h_code_extra,
                           str.c_str(),
                           re_end,
                           off,
                           0,
                           matches,
                           60);
            if (rc > 0) {
                struct line_range lr;

                if (rc == 2) {
                    lr.lr_start = matches[2];
                    lr.lr_end   = matches[3];
                }
                else {
                    lr.lr_start = matches[0];
                    lr.lr_end   = matches[1];
                }

                if (lr.lr_end > lr.lr_start) {
                    sa.push_back(string_attr(
                        lr, &view_curses::VC_STYLE, iter->second.get_attrs(hcount)));
                    hcount++;

                    off = matches[1];
                }
                else {
                    off += 1;
                }
            }
            else {
                off = str.size();
            }
        }
    }

#if 0
    typedef std::map<std::string, view_colors::role_t> key_map_t;
    static key_map_t key_roles;

    data_scanner ds(str);
    data_parser  dp(&ds);

    dp.parse();

    for (list<data_parser::element>::iterator iter = dp.dp_stack.begin();
         iter != dp.dp_stack.end();
         ++iter) {
        view_colors &vc = view_colors::singleton();

        if (iter->e_token == DNT_PAIR) {
            list<data_parser::element>::iterator pair_iter;
            key_map_t::iterator km_iter;
            data_token_t        value_token;
            struct line_range   lr;
            string key;

            value_token =
                iter->e_sub_elements->back().e_sub_elements->front().e_token;
            if (value_token == DT_STRING) {
                continue;
            }

            lr.lr_start = iter->e_capture.c_begin;
            lr.lr_end   = iter->e_capture.c_end;

            key = ds.get_input().get_substr(
                &iter->e_sub_elements->front().e_capture);
            if ((km_iter = key_roles.find(key)) == key_roles.end()) {
                key_roles[key] = vc.next_highlight();
            }
            /* fprintf(stderr, "key = %s\n", key.c_str()); */
            sa[lr].insert(make_string_attr("style",
                                           vc.attrs_for_role(key_roles[key])));

            pair_iter = iter->e_sub_elements->begin();
            ++pair_iter;

            lr.lr_start = pair_iter->e_capture.c_begin;
            lr.lr_end   = pair_iter->e_capture.c_end;
            sa[lr].insert(make_string_attr("style",
                                           COLOR_PAIR(view_colors::VC_WHITE) |
                                           A_BOLD));
        }
    }
#endif

    if (binary_search(user_marks.begin(), user_marks.end(), row)) {
        struct line_range        lr(0);
        string_attrs_t::iterator iter;

        for (iter = sa.begin(); iter != sa.end(); iter++) {
            if (iter->sa_type == &view_curses::VC_STYLE) {
                iter->sa_value.sav_int ^= A_REVERSE;
            }
        }

        sa.push_back(string_attr(lr, &view_curses::VC_STYLE, A_REVERSE));
    }
    else if (binary_search(part_marks.begin(), part_marks.end(), row + 1)) {
        sa.push_back(string_attr(
            line_range(0), &view_curses::VC_STYLE, A_UNDERLINE));
    }
}

bool textview_curses::handle_mouse(mouse_event &me)
{
    unsigned long width;
    vis_line_t height;

    if (this->tc_selection_start == -1 &&
        listview_curses::handle_mouse(me)) {
        return true;
    }

    if (this->tc_delegate != NULL &&
        this->tc_delegate->text_handle_mouse(*this, me)) {
        return true;
    }

    if (me.me_button != BUTTON_LEFT) {
        return false;
    }

    vis_line_t mouse_line(this->get_top() + me.me_y);

    if (mouse_line > this->get_bottom()) {
        mouse_line = this->get_bottom();
    }

    this->get_dimensions(height, width);

    switch (me.me_state) {
    case BUTTON_STATE_PRESSED:
        this->tc_selection_start = mouse_line;
        this->tc_selection_last = vis_line_t(-1);
        this->tc_selection_cleared = false;
        break;
    case BUTTON_STATE_DRAGGED:
        if (me.me_y <= 0) {
            this->shift_top(vis_line_t(-1));
            me.me_y = 0;
            mouse_line = this->get_top();
        }
        if (me.me_y >= height && this->get_top() < this->get_top_for_last_row()) {
            this->shift_top(vis_line_t(1));
            me.me_y = height;
            mouse_line = this->get_bottom();
        }

        if (this->tc_selection_last == mouse_line)
            break;

        if (this->tc_selection_last != -1) {
            this->toggle_user_mark(&textview_curses::BM_USER,
               this->tc_selection_start,
               this->tc_selection_last);
        }
        if (this->tc_selection_start == mouse_line) {
            this->tc_selection_last = vis_line_t(-1);
        }
        else {
            if (!this->tc_selection_cleared) {
                if (this->tc_sub_source != NULL) {
                    this->tc_sub_source->text_clear_marks(&BM_USER);
                }
                this->tc_bookmarks[&BM_USER].clear();

                this->tc_selection_cleared = true;
            }
            this->toggle_user_mark(&BM_USER,
               this->tc_selection_start,
               mouse_line);
            this->tc_selection_last = mouse_line;
        }
        this->reload_data();
        break;
    case BUTTON_STATE_RELEASED:
        this->tc_selection_start = vis_line_t(-1);
        this->tc_selection_last = vis_line_t(-1);
        this->tc_selection_cleared = false;
        break;
    }

    return true;
}


text:
(function(){
	var ns = dragonBones.use("events");
	var Event = ns.Event;

	function FrameEvent(type) {
        FrameEvent.superclass.constructor.call(this, type);
    }
    dragonBones.extends(FrameEvent, Event);

    FrameEvent.ANIMATION_FRAME_EVENT = "animationFrameEvent";
    FrameEvent.BONE_FRAME_EVENT = "boneFrameEvent";

	ns.FrameEvent = FrameEvent;
})();


text:
===========
justeventme
===========

Minimum-Impact Event-Sourcing Library for Django

Quick start
-----------

1. Add "justeventme" to your INSTALLED_APPS setting like this::

    INSTALLED_APPS = [
        ...
        'justeventme',
    ]

2. Run `python manage.py migrate` to create the event models.

3. Start the development server and visit http://127.0.0.1:8000/admin/
   to create a poll (you'll need the Admin app enabled).

4. Visit http://127.0.0.1:8000/admin/ to look at the event stream


text:
<?xml version="1.0" encoding="UTF-8"?>
<workbench progressCount="3" version="2.0">
<workbenchAdvisor/>
<window height="940" width="1200" x="254" y="64">
<fastViewData fastViewLocation="1024"/>
<perspectiveBar>
<itemSize x="160"/>
</perspectiveBar>
<coolbarLayout>
<coolItem id="group.file" itemType="typeGroupMarker"/>
<coolItem id="org.eclipse.ui.workbench.file" itemType="typeToolBarContribution" x="126" y="22"/>
<coolItem id="additions" itemType="typeGroupMarker"/>
<coolItem id="org.eclipse.debug.ui.launchActionSet" itemType="typeToolBarContribution" x="145" y="22"/>
<coolItem id="org.eclipse.search.searchActionSet" itemType="typeToolBarContribution" x="88" y="22"/>
<coolItem id="com.aptana.ui.globalActionSet" itemType="typeToolBarContribution" x="172" y="22"/>
<coolItem id="org.eclipse.ui.edit.text.actionSet.presentation" itemType="typeToolBarContribution" x="84" y="22"/>
<coolItem id="group.nav" itemType="typeGroupMarker"/>
<coolItem id="org.eclipse.ui.workbench.navigate" itemType="typeToolBarContribution" x="99" y="22"/>
<coolItem id="group.editor" itemType="typeGroupMarker"/>
<coolItem id="com.aptana.editor.js" itemType="typePlaceholder" x="-1" y="-1"/>
<coolItem id="com.aptana.editor.html" itemType="typePlaceholder" x="-1" y="-1"/>
<coolItem id="group.help" itemType="typeGroupMarker"/>
<coolItem id="org.eclipse.ui.workbench.help" itemType="typeToolBarContribution" x="-1" y="-1"/>
</coolbarLayout>
<page aggregateWorkingSetId="Aggregate for window 1427128815721" focus="true" label="Workspace - Web">
<editors>
<editorArea activeWorkbook="DefaultEditorWorkbook">
<info part="DefaultEditorWorkbook">
<folder appearance="1" expanded="2">
<presentation id="org.eclipse.ui.presentations.WorkbenchPresentationFactory"/>
</folder>
</info>
</editorArea>
</editors>
<views>
<view id="com.aptana.snippets.ui.views.SnippetsView" partName="Snippets">
<viewState/>
</view>
<view id="com.aptana.terminal.views.terminal" partName="Terminal"/>
<view id="com.aptana.samples.ui.SamplesView" partName="Samples">
<viewState/>
</view>
<view id="org.eclipse.ui.views.ProblemView" partName="Problems">
<viewState PRIMARY_SORT_FIELD="org.eclipse.ui.ide.severityAndDescriptionField" categoryGroup="org.eclipse.ui.ide.severity" markerContentGenerator="org.eclipse.ui.ide.problemsGenerator" partName="Problems">
<columnWidths org.eclipse.ui.ide.locationField="120" org.eclipse.ui.ide.markerType="120" org.eclipse.ui.ide.pathField="160" org.eclipse.ui.ide.resourceField="120" org.eclipse.ui.ide.severityAndDescriptionField="400"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.severityAndDescriptionField"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.resourceField"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.pathField"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.locationField"/>
<visible IMemento.internal.id="org.eclipse.ui.ide.markerType"/>
</viewState>
</view>
<view id="org.eclipse.ui.console.ConsoleView" partName="Console">
<viewState/>
</view>
<view id="org.eclipse.ui.views.ContentOutline" partName="Outline">
<viewState/>
</view>
</views>
<perspectives activePart="org.eclipse.ui.console.ConsoleView" activePerspective="com.aptana.ui.WebPerspective">
<perspective editorAreaTrimState="2" editorAreaVisible="1" fixed="0" version="0.016">
<descriptor class="com.aptana.ui.internal.WebPerspectiveFactory" id="com.aptana.ui.WebPerspective" label="Web"/>
<alwaysOnActionSet id="com.aptana.browser.actionSet"/>
<alwaysOnActionSet id="com.aptana.ruby.debug.ui.RubyDebugActionSet"/>
<alwaysOnActionSet id="org.eclipse.ui.cheatsheets.actionSet"/>
<alwaysOnActionSet id="org.eclipse.search.searchActionSet"/>
<alwaysOnActionSet id="org.eclipse.ui.edit.text.actionSet.convertLineDelimitersTo"/>
<alwaysOnActionSet id="org.eclipse.ui.actionSet.keyBindings"/>
<alwaysOnActionSet id="org.eclipse.ui.actionSet.openFiles"/>
<alwaysOnActionSet id="com.aptana.editor.common.presentation"/>
<alwaysOnActionSet id="org.eclipse.debug.ui.launchActionSet"/>
<alwaysOnActionSet id="org.eclipse.debug.ui.breakpointActionSet"/>
<alwaysOnActionSet id="com.aptana.js.debug.ui.actionSet"/>
<alwaysOnActionSet id="org.eclipse.ui.NavigateActionSet"/>
<alwaysOnActionSet id="org.eclipse.ui.edit.text.actionSet.presentation"/>
<alwaysOnActionSet id="com.aptana.ui.globalActionSet"/>
<alwaysOnActionSet id="com.aptana.terminal.actionSet"/>
<show_view_action id="com.aptana.browser.views.webbrowser"/>
<show_view_action id="com.aptana.explorer.view"/>
<show_view_action id="org.eclipse.ui.navigator.ProjectExplorer"/>
<show_view_action id="com.aptana.ui.io.remoteview"/>
<show_view_action id="org.eclipse.ui.views.ContentOutline"/>
<show_view_action id="com.aptana.samples.ui.SamplesView"/>
<show_view_action id="com.aptana.snippets.ui.views.SnippetsView"/>
<show_view_action id="com.aptana.terminal.views.terminal"/>
<show_view_action id="org.eclipse.ui.console.ConsoleView"/>
<show_view_action id="org.eclipse.pde.runtime.LogView"/>
<show_view_action id="org.eclipse.ui.views.ProblemView"/>
<show_view_action id="org.eclipse.ui.views.TaskList"/>
<show_view_action id="com.aptana.webserver.ui.view"/>
<new_wizard_action id="com.aptana.editor.php.NewPHPProjectWizard"/>
<new_wizard_action id="com.aptana.ui.wizards.NewWebProject"/>
<new_wizard_action id="com.aptana.ruby.core.ui.rubyProjectWizard"/>
<new_wizard_action id="com.aptana.ui.wizards.new.file"/>
<new_wizard_action id="org.eclipse.ui.wizards.new.folder"/>
<new_wizard_action id="org.eclipse.ui.editors.wizards.UntitledTextFileWizard"/>
<new_wizard_action id="org.radrails.rails.ui.projectWizard"/>
<perspective_action id="org.eclipse.debug.ui.DebugPerspective"/>
<hide_toolbar_item_id id="org.eclipse.ui.edit.text.toggleShowSelectedElementOnly"/>
<view id="org.eclipse.ui.console.ConsoleView"/>
<view id="com.aptana.terminal.views.terminal"/>
<view id="org.eclipse.ui.views.ProblemView"/>
<fastViewBars>
<fastViewBar fastViewLocation="1024" id="org.eclipse.ui.internal.ViewStack@1438dbe" orientation="256" selectedTabId="com.aptana.snippets.ui.views.SnippetsView" style="0">
<fastViews>
<view id="org.eclipse.ui.views.ContentOutline" ratio="0.3"/>
<view id="com.aptana.samples.ui.SamplesView" ratio="0.3"/>
<view id="com.aptana.snippets.ui.views.SnippetsView" ratio="0.3"/>
</fastViews>
</fastViewBar>
</fastViewBars>
<layout>
<mainWindow>
<info folder="true" part="left">
<folder appearance="2" expanded="2">
<page content="com.aptana.explorer.view" label="LabelNotFound"/>
<page content="org.eclipse.ui.navigator.ProjectExplorer" label="LabelNotFound"/>
<page content="com.aptana.ui.io.remoteview" label="LabelNotFound"/>
<presentation id="org.eclipse.ui.presentations.WorkbenchPresentationFactory"/>
</folder>
</info>
<info folder="true" part="stickyFolderRight" ratio="0.7495741" ratioLeft="880" ratioRight="294" relationship="2" relative="left">
<folder appearance="2" expanded="2">
<page content="org.eclipse.help.ui.HelpView" label="LabelNotFound"/>
<page content="org.eclipse.ui.internal.introview" label="LabelNotFound"/>
<page content="org.eclipse.ui.cheatsheets.views.CheatSheetView" label="LabelNotFound"/>
</folder>
</info>
<info part="org.eclipse.ui.editorss" ratio="0.2322801" ratioLeft="272" ratioRight="899" relationship="2" relative="left"/>
<info folder="true" part="terminalArea" ratio="0.75" ratioLeft="627" ratioRight="209" relationship="4" relative="org.eclipse.ui.editorss">
<folder activePageID="org.eclipse.ui.console.ConsoleView" appearance="2" expanded="2">
<page content="org.eclipse.ui.console.ConsoleView" label="Console"/>
<page content="com.aptana.terminal.views.terminal" label="Terminal"/>
<page content="org.eclipse.ui.views.ProblemView" label="Problems"/>
<page content="org.eclipse.pde.runtime.LogView" label="LabelNotFound"/>
<page content="org.eclipse.ui.views.TaskList" label="LabelNotFound"/>
<presentation id="org.eclipse.ui.presentations.WorkbenchPresentationFactory">
<part id="0"/>
<part id="1"/>
<part id="2"/>
</presentation>
</folder>
</info>
<info folder="true" part="org.eclipse.ui.internal.ViewStack@1438dbe" ratio="0.75" ratioLeft="627" ratioRight="209" relationship="4" relative="left">
<folder appearance="2" expanded="0">
<page content="org.eclipse.ui.views.ContentOutline" label="LabelNotFound"/>
<page content="com.aptana.samples.ui.SamplesView" label="LabelNotFound"/>
<page content="com.aptana.snippets.ui.views.SnippetsView" label="LabelNotFound"/>
<presentation id="org.eclipse.ui.presentations.WorkbenchPresentationFactory"/>
</folder>
</info>
</mainWindow>
</layout>
</perspective>
</perspectives>
<workingSets/>
<navigationHistory/>
<input factoryID="org.eclipse.ui.internal.model.ResourceFactory" path="/" type="8"/>
</page>
<workbenchWindowAdvisor/>
<actionBarAdvisor/>
<trimLayout>
<trimArea IMemento.internal.id="131072">
<trimItem IMemento.internal.id="org.eclipse.ui.editorss"/>
</trimArea>
<trimArea IMemento.internal.id="128">
<trimItem IMemento.internal.id="org.eclipse.ui.internal.WorkbenchWindow.topBar"/>
</trimArea>
<trimArea IMemento.internal.id="1024">
<trimItem IMemento.internal.id="org.eclise.ui.internal.FastViewBar"/>
<trimItem IMemento.internal.id="org.eclipse.jface.action.StatusLineManager"/>
<trimItem IMemento.internal.id="org.eclipse.ui.internal.progress.ProgressRegion"/>
<trimItem IMemento.internal.id="terminalArea"/>
<trimItem IMemento.internal.id="org.eclipse.ui.internal.ViewStack@1438dbe"/>
</trimArea>
</trimLayout>
</window>
<mruList>
<file factoryID="org.eclipse.ui.part.FileEditorInputFactory" id="com.aptana.editor.js" name="scrollspy.js" tooltip="Fitness-Pal/scrollspy.js">
<persistable path="/Fitness-Pal/scrollspy.js"/>
</file>
<file factoryID="org.eclipse.ui.ide.FileStoreEditorInputFactory" id="com.aptana.editor.html" name="index.html" tooltip="C:\Users\Andria\Documents\New folder\Fitness-Pal\Code\index.html">
<persistable uri="file:/C:/Users/Andria/Documents/New%20folder/Fitness-Pal/Code/index.html"/>
</file>
</mruList>
</workbench>


text:
package foodtruck.session;

import java.math.BigInteger;
import java.security.SecureRandom;

/**
 * @author aviolette
 * @since 6/18/14
 */
class SessionIdentifier {
  private SecureRandom random = new SecureRandom();

  String nextSessionId() {
    return new BigInteger(130, random).toString(32);
  }
}


text:
"""
:mod:`flagtypes` --- SCION flag types
=====================================

For all flags types that are used in multiple parts of the infrastructure.
"""

class FlagBase(object):  # pragma: no cover
    def __init__(self, val_names):
        self._rev = {}
        for val, *names in val_names:
            setattr(self, names[0], val)
            self._rev[val] = names

    def to_str(self, flags):
        ret = []
        for val in sorted(self._rev):
            true, false = self._rev[val]
            if flags & val:
                ret.append(true)
            elif false:
                ret.append(false)
        return "|".join(ret) or "None"

PathSegFlags = FlagBase((
    (1, "SIBRA", "SCION"),
))

InfoOFFlags = FlagBase((
    (1, "CONS_DIR", "NOT_CONS_DIR"),
    (2, "SHORTCUT", ""),
    (4, "PEER_SHORTCUT", ""),
))

HopOFFlags = FlagBase((
    # Used to signal that this HOF is at a cross-over point between segments,
    # and needs special provcessing. Set by the endhost.
    (1, "XOVER", ""),
    # Marks HOFs that aren't used for routing, just for mac verification.
    (2, "VERIFY_ONLY", ""),
))


text:
.. _payloadtype-com.apple.domains:

Domains
=======
:download:`Template </_static/examples/com.apple.domains.mobileconfig>`

This payload defines domains that are under an enterprise's management.

.. contents::

Summary
-------

.. pfmheader:: /_static/manifests/com.apple.domains manifest.plist

Keys
----

.. pfmkey:: EmailDomains /_static/manifests/com.apple.domains manifest.plist
.. pfmkey:: WebDomains /_static/manifests/com.apple.domains manifest.plist
.. pfmkey:: SafariPasswordAutoFillDomains /_static/manifests/com.apple.domains manifest.plist

Links
-----

- `Official Documentation <https://developer.apple.com/library/content/featuredarticles/iPhoneConfigurationProfileRef/Introduction/Introduction.html#//apple_ref/doc/uid/TP40010206-CH1-SW252>`_.


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest release of this document can be found
[here](http://releases.k8s.io/release-1.1/examples/spark/README.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

# Spark example

Following this example, you will create a functional [Apache
Spark](http://spark.apache.org/) cluster using Kubernetes and
[Docker](http://docker.io).

You will setup a Spark master service and a set of Spark workers using Spark's [standalone mode](http://spark.apache.org/docs/latest/spark-standalone.html).

For the impatient expert, jump straight to the [tl;dr](#tldr)
section.

### Sources

The Docker images are heavily based on https://github.com/mattf/docker-spark.
And are curated in https://github.com/kubernetes/application-images/tree/master/spark

## Step Zero: Prerequisites

This example assumes

- You have a Kubernetes cluster installed and running.
- That you have installed the ```kubectl``` command line tool somewhere in your path.
- That a spark-master service which spins up will be automatically discoverable by your kube DNS impl, as 'spark-master'

For details, you can look at the Dockerfiles in the Sources section.

## Step One: Start your Master service

The Master [service](../../docs/user-guide/services.md) is the master service
for a Spark cluster.

Use the
[`examples/spark/spark-master-controller.yaml`](spark-master-controller.yaml)
file to create a
[replication controller](../../docs/user-guide/replication-controller.md)
running the Spark Master service.

```console
$ kubectl create -f examples/spark/spark-master-controller.yaml
replicationcontrollers/spark-master-controller
```

Then, use the
[`examples/spark/spark-master-service.yaml`](spark-master-service.yaml) file to
create a logical service endpoint that Spark workers can use to access the
Master pod.

```console
$ kubectl create -f examples/spark/spark-master-service.yaml
services/spark-master
```

You can then create a service for the Spark Master WebUI:

```console
$ kubectl create -f examples/spark/spark-webui.yaml
services/spark-webui
```

### Check to see if Master is running and accessible

```console
$ kubectl get pods
NAME                            READY     STATUS    RESTARTS   AGE
spark-master-controller-5u0q5   1/1       Running   0          8m
```

Check logs to see the status of the master. (Use the pod retrieved from the previous output.)

```sh
$ kubectl logs spark-master-controller-5u0q5
starting org.apache.spark.deploy.master.Master, logging to /opt/spark-1.5.1-bin-hadoop2.6/sbin/../logs/spark--org.apache.spark.deploy.master.Master-1-spark-master-controller-g0oao.out
Spark Command: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java -cp /opt/spark-1.5.1-bin-hadoop2.6/sbin/../conf/:/opt/spark-1.5.1-bin-hadoop2.6/lib/spark-assembly-1.5.1-hadoop2.6.0.jar:/opt/spark-1.5.1-bin-hadoop2.6/lib/datanucleus-rdbms-3.2.9.jar:/opt/spark-1.5.1-bin-hadoop2.6/lib/datanucleus-core-3.2.10.jar:/opt/spark-1.5.1-bin-hadoop2.6/lib/datanucleus-api-jdo-3.2.6.jar -Xms1g -Xmx1g org.apache.spark.deploy.master.Master --ip spark-master --port 7077 --webui-port 8080
========================================
15/10/27 21:25:05 INFO Master: Registered signal handlers for [TERM, HUP, INT]
15/10/27 21:25:05 INFO SecurityManager: Changing view acls to: root
15/10/27 21:25:05 INFO SecurityManager: Changing modify acls to: root
15/10/27 21:25:05 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(root); users with modify permissions: Set(root)
15/10/27 21:25:06 INFO Slf4jLogger: Slf4jLogger started
15/10/27 21:25:06 INFO Remoting: Starting remoting
15/10/27 21:25:06 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkMaster@spark-master:7077]
15/10/27 21:25:06 INFO Utils: Successfully started service 'sparkMaster' on port 7077.
15/10/27 21:25:07 INFO Master: Starting Spark master at spark://spark-master:7077
15/10/27 21:25:07 INFO Master: Running Spark version 1.5.1
15/10/27 21:25:07 INFO Utils: Successfully started service 'MasterUI' on port 8080.
15/10/27 21:25:07 INFO MasterWebUI: Started MasterWebUI at http://spark-master:8080
15/10/27 21:25:07 INFO Utils: Successfully started service on port 6066.
15/10/27 21:25:07 INFO StandaloneRestServer: Started REST server for submitting applications on port 6066
15/10/27 21:25:07 INFO Master: I have been elected leader! New state: ALIVE
```

After you know the master is running, you can use the [cluster
proxy](../../docs/user-guide/accessing-the-cluster.md#using-kubectl-proxy) to
connect to the Spark WebUI:

```console
kubectl proxy --port=8001
```

At which point the UI will be available at
[http://localhost:8001/api/v1/proxy/namespaces/default/services/spark-webui/](http://localhost:8001/api/v1/proxy/namespaces/default/services/spark-webui/).

## Step Two: Start your Spark workers

The Spark workers do the heavy lifting in a Spark cluster. They
provide execution resources and data cache capabilities for your
program.

The Spark workers need the Master service to be running.

Use the [`examples/spark/spark-worker-controller.yaml`](spark-worker-controller.yaml) file to create a
[replication controller](../../docs/user-guide/replication-controller.md) that manages the worker pods.

```console
$ kubectl create -f examples/spark/spark-worker-controller.yaml
```

### Check to see if the workers are running

If you launched the Spark WebUI, your workers should just appear in the UI when
they're ready. (It may take a little bit to pull the images and launch the
pods.) You can also interrogate the status in the following way:

```console
$ kubectl get pods
NAME                            READY     STATUS    RESTARTS   AGE
spark-master-controller-5u0q5   1/1       Running   0          25m
spark-worker-controller-e8otp   1/1       Running   0          6m
spark-worker-controller-fiivl   1/1       Running   0          6m
spark-worker-controller-ytc7o   1/1       Running   0          6m

$ kubectl logs spark-master-controller-5u0q5
[...]
15/10/26 18:20:14 INFO Master: Registering worker 10.244.1.13:53567 with 2 cores, 6.3 GB RAM
15/10/26 18:20:14 INFO Master: Registering worker 10.244.2.7:46195 with 2 cores, 6.3 GB RAM
15/10/26 18:20:14 INFO Master: Registering worker 10.244.3.8:39926 with 2 cores, 6.3 GB RAM
```

Assuming you still have the `kubectl proxy` running from the previous section,
you should now see the workers in the UI as well. *Note:* The UI will have links
to worker Web UIs. The worker UI links do not work (the links will attempt to
connect to cluster IPs, which Kubernetes won't proxy automatically).

## Step Three: Start the Zeppelin UI to launch jobs on your Spark cluster

The Zeppelin UI pod can be used to launch jobs into the Spark cluster either via
a web notebook frontend or the traditional Spark command line. See
[Zeppelin](https://zeppelin.incubator.apache.org/) and
[Spark architecture](https://spark.apache.org/docs/latest/cluster-overview.html)
for more details.

```console
$ kubectl create -f examples/spark/zeppelin-controller.yaml
replicationcontrollers/zeppelin-controller
```

Zeppelin needs the Master service to be running.

### Check to see if Zeppelin is running

```console
$ kubectl get pods -l component=zeppelin
NAME                        READY     STATUS    RESTARTS   AGE
zeppelin-controller-ja09s   1/1       Running   0          53s
```

## Step Four: Do something with the cluster

Now you have two choices, depending on your predilections. You can do something
graphical with the Spark cluster, or you can stay in the CLI.

### Do something fast with pyspark!

Use the kubectl exec to connect to the Zeppelin driver and run a pipeline.

```console
$ kubectl exec zeppelin-controller-ja09s -it pyspark
Python 2.7.9 (default, Mar  1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /__ / .__/\_,_/_/ /_/\_\   version 1.5.1
      /_/

Using Python version 2.7.9 (default, Mar  1 2015 12:57:24)
SparkContext available as sc, HiveContext available as sqlContext.
>>> sc.textFile("gs://dataflow-samples/shakespeare/*").map(lambda s: len(s.split())).sum()
939193
```

Congratulations, you just counted all of the words in all of the plays of
Shakespeare.

### Do something graphical and shiny!

Take the Zeppelin pod from above and port-forward the WebUI port:

```console
$ kubectl port-forward zeppelin-controller-ja09s 8080:8080
```

This forwards `localhost` 8080 to container port 8080. You can then find
Zeppelin at [https://localhost:8080/](https://localhost:8080/).

Create a "New Notebook". In there, type:

```
%pyspark
print sc.textFile("gs://dataflow-samples/shakespeare/*").map(lambda s: len(s.split())).sum()
```

## Result

You now have services and replication controllers for the Spark master, Spark
workers and Spark driver.  You can take this example to the next step and start
using the Apache Spark cluster you just created, see
[Spark documentation](https://spark.apache.org/documentation.html) for more
information.

## tl;dr

```console
kubectl create -f examples/spark
```

After it's setup:

```console
kubectl get pods # Make sure everything is running
kubectl proxy --port=8001 # Start an application proxy, if you want to see the Spark Master WebUI
kubectl get pods -lcomponent=zeppelin # Get the driver pod to interact with.
```

At which point the Master UI will be available at
[http://localhost:8001/api/v1/proxy/namespaces/default/services/spark-webui/](http://localhost:8001/api/v1/proxy/namespaces/default/services/spark-webui/).

You can either interact with the Spark cluster the traditional `spark-shell` /
`spark-subsubmit` / `pyspark` commands by using `kubectl exec` against the
`zeppelin-controller` pod, or if you want to interact with Zeppelin:

```console
kubectl port-forward zeppelin-controller-abc123 8080:8080 &
```

Then visit [http://localhost:8080/](http://localhost:8080/).

## Known Issues With Spark

* This provides a Spark configuration that is restricted to the cluster network,
  meaning the Spark master is only available as a cluster service. If you need
  to submit jobs using external client other than Zeppelin or `spark-submit` on
  the `zeppelin` pod, you will need to provide a way for your clients to get to
  the
  [`examples/spark/spark-master-service.yaml`](spark-master-service.yaml). See
  [Services](../../docs/user-guide/services.md) for more information.

## Known Issues With Zeppelin

* The Zeppelin pod is large, so it may take a while to pull depending on your
  network. The size of the Zeppelin pod is something we're working on, see issue #17231.

* Zeppelin may take some time (about a minute) on this pipeline the first time
  you run it. It seems to take considerable time to load.

* On GKE, `kubectl port-forward` may not be stable over long periods of time. If
  you see Zeppelin go into `Disconnected` state (there will be a red dot on the
  top right as well), the `port-forward` probably failed and needs to be
  restarted. See #12179.

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/spark/README.md?pixel)]()


text:
"""adjacency_blockgroups.py

Script to compute the adjacency list for the blockgroups in all MSA
"""
import csv
import sys
import itertools
import fiona
from shapely.geometry import shape

csv.field_size_limit(sys.maxsize)

#
# Import list of cities
#
msa = {}
with open('data/names/msa.csv', 'r') as source:
    reader = csv.reader(source, delimiter='\t')
    reader.next()
    for rows in reader:
        msa[rows[0]] = rows[1]

#
# Compute the adjacency list
#
for i,city in enumerate(msa):
    print "Adjacency %s (%s/%s)"%(msa[city], i+1, len(msa))

    ## Import blockgroups
    blocks = {}
    with fiona.open('data/shp/msa/%s/blockgroups.shp'%city, 'r', 'ESRI Shapefile') as source:
        for f in source:
            blocks[f['properties']['BKGPIDFP00']] = shape(f['geometry'])

    ## Compute adjacency list
    adjacency = {b:[] for b in blocks}
    for b0,b1 in itertools.permutations(blocks, 2):
        if blocks[b1].touches(blocks[b0]):
            adjacency[b0].append(b1)

    ## Save data
    with open('extr/adjacency_bg/msa/%s.csv'%city, 'w') as output:
       output.write("BLOCKGROUP FIP\tNEIGHBOURS FIP (list)\n")
       for b0 in adjacency:
           output.write("%s"%b0)
           for b1 in adjacency[b0]:
               output.write("\t%s"%b1)
           output.write("\n")


text:
var gulp    = require('gulp'),
    gutil   = require('gulp-util');
    clean   = require('gulp-clean'),
    jshint  = require('gulp-jshint'),
    uglify  = require('gulp-uglify'),
    stylish = require('jshint-stylish'),
    rename  = require('gulp-rename'),
    colors  = require('colors');

function startExpress() {

    var express = require('express'),
        app     = express();

    app.use(express.static(__dirname + '/test'));
    app.listen(4000);

    console.log('\n[express]'.bold.magenta + ' Server running on port 4000\n');

}

gulp.task('lint', function() {
    console.log('[lint]'.bold.magenta + ' Linting JS files');

    return gulp.src('./src/**/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter(stylish));

});

gulp.task('uglify', ['copy-src'], function() {

    console.log('[uglify]'.bold.magenta + ' Minifying JS files');

    return gulp.src('./src/**/*.js')
        .pipe(uglify({
            preserveComments : 'some',
            outSourceMap     : true
        }))
        .pipe(rename(function (path) {
            path.basename += '.min';
        }))
        .pipe(gulp.dest('dist'));

});

// Clean dist/css folder
gulp.task('clean', function() {

    console.log('[clean]'.bold.magenta + ' Deleting all the files in /dist');

    return gulp.src(['dist'], {read: false})
        .pipe(clean());

});

// Copy dist folder to test folder
gulp.task('copy-src', ['clean'], function () {

    console.log('[copy-src]'.bold.magenta + ' Copying src folder to dist');

    return gulp.src('src/**/*', {base: './src'})
        .pipe(gulp.dest('dist'));

});

// Copy dist folder to test folder
gulp.task('copy-dist', ['uglify'], function () {

    console.log('[copy-dist]'.bold.magenta + ' Copying dist folder to test');

    return gulp.src('dist/**/*', {base: './'})
        .pipe(gulp.dest('test'));

});

// Watch files for changes
gulp.task('watch', function() {

    console.log('[watch]'.bold.magenta + ' Watching JS files for changes');

    gulp.watch('./src/**/*.js', ['lint', 'copy-dist']);

});

// Serve test site
gulp.task('server', ['copy-dist'], function () {

    console.log('[server]'.bold.magenta + ' Starting Express server');

    startExpress();

});

// Build dist files
gulp.task('build', ['copy-dist']);

gulp.task('dev', ['server', 'lint', 'watch']);

gulp.task('test', ['server']);

// Default Task
gulp.task('default', ['lint', 'watch']);


text:
class ArchiveDayIndexPage < Page

  description %{
    To create a day index for an archive, create a child page for the
    archive and assign the "Archive Day Index" page type to it.

    A day index page makes following tags available to you:

    <r:archive:children>...</r:archive:children>
      Grants access to a subset of the children of the archive page
      that match the specific year which the index page is rendering.
  }

  include ArchiveIndexTagsAndMethods
  desc %{
      Grants access to a subset of the children of the archive page
      that match the specific day which the index page is rendering.

      *Usage*:

<r:archive:children>...</r:archive:children>

  }
  tag "archive:children" do |tag|
    year, month, day = $1, $2, $3 if request_uri =~ %r{/(\d{4})/(\d{2})/(\d{2})/?$}
    tag.locals.children = ArchiveFinder.day_finder(parent.children, year, month, day)
    tag.expand
  end

end


text:
<?php

namespace Weserv\Images\Test;

use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
use Weserv\Images\Client;

class ClientTest extends ImagesWeservTestCase
{
    /**
     * @var Client
     */
    private $client;

    /**
     * @var string
     */
    private $tempFile;

    /**
     * @var array
     */
    private $options;

    public function setUp()
    {
        $this->tempFile = tempnam(sys_get_temp_dir(), 'phpunit');
        $this->options = [
            'user_agent' => 'Mozilla/5.0 (compatible; ImageFetcher/6.0; +http://images.weserv.nl/)',
            'connect_timeout' => 5,
            'timeout' => 10,
            'max_image_size' => 0,
            'max_redirects' => 10,
            'allowed_mime_types' => []
        ];
        $this->client = new Client($this->tempFile, $this->options);
    }

    public function tearDown()
    {
        parent::tearDown();
        unlink($this->tempFile);
    }

    public function testCreateInstance(): void
    {
        $this->assertInstanceOf(Client::class, $this->client);
    }

    public function testSetClient(): void
    {
        $client = $this->getMockery(GuzzleClient::class);
        $this->client->setClient($client);
        $this->assertInstanceOf(GuzzleClient::class, $this->client->getClient());
    }

    public function testGetClient(): void
    {
        $this->assertInstanceOf(GuzzleClient::class, $this->client->getClient());
    }

    public function testGetOptions(): void
    {
        $this->assertSame($this->options, $this->client->getOptions());
    }

    /**
     * @expectedException \GuzzleHttp\Exception\RequestException
     */
    public function testInvalidRedirectURI(): void
    {
        $this->client->get('http://test');
    }

    public function testUserAgent(): void
    {
        $mock = new MockHandler([
            new Response(200)
        ]);

        $handler = HandlerStack::create($mock);

        $history = [];
        $handler->push(Middleware::history($history));

        $this->client = new Client($this->tempFile, $this->options, ['handler' => $handler]);
        $this->client->get('image.jpg');

        $this->assertSame($this->options['user_agent'], end($history)['request']->getHeaderLine('User-Agent'));
    }

    public function testTempFile(): void
    {
        $mock = new MockHandler([
            new Response(200)
        ]);

        $handler = HandlerStack::create($mock);

        $this->client = new Client($this->tempFile, $this->options, ['handler' => $handler]);
        $this->client->get('image.jpg');

        $this->assertSame($this->client->getFileName(), $mock->getLastOptions()['sink']);
    }
}


text:
jQuery(document).ready(function($) {

	'use strict';

      var owl = $("#owl-testimonials");

        owl.owlCarousel({

          pagination : true,
          paginationNumbers: false,
          autoPlay: 6000, //Set AutoPlay to 3 seconds
          items : 1, //10 items above 1000px browser width
          itemsDesktop : [1000,1], //5 items between 1000px and 901px
          itemsDesktopSmall : [900,1], // betweem 900px and 601px
          itemsTablet: [600,1], //2 items between 600 and 0
          itemsMobile : false // itemsMobile disabled - inherit from itemsTablet option

      });

        var top_header = $('.parallax-content');
        top_header.css({'background-position':'center center'}); // better use CSS

        $(window).scroll(function () {
        var st = $(this).scrollTop();
        top_header.css({'background-position':'center calc(50% + '+(st*.5)+'px)'});
        });

        $('.counter').each(function() {
          var $this = $(this),
              countTo = $this.attr('data-count');

          $({ countNum: $this.text()}).animate({
            countNum: countTo
          },

          {

            duration: 8000,
            easing:'linear',
            step: function() {
              $this.text(Math.floor(this.countNum));
            },
            complete: function() {
              $this.text(this.countNum);
              //alert('finished');
            }

          });

        });

        $('.tabgroup > div').hide();
        $('.tabgroup > div:first-of-type').show();
        $('.tabs a').click(function(e){
          e.preventDefault();
            var $this = $(this),
            tabgroup = '#'+$this.parents('.tabs').data('tabgroup'),
            others = $this.closest('li').siblings().children('a'),
            target = $this.attr('href');
        others.removeClass('active');
        $this.addClass('active');
        $(tabgroup).children('div').hide();
        $(target).show();

        })

        $(".pop-button").click(function () {
            $(".pop").fadeIn(300);

        });

        $(".pop > span").click(function () {
            $(".pop").fadeOut(300);
        });

        $(window).on("scroll", function() {
            if($(window).scrollTop() > 100) {
                $(".header").addClass("active");
            } else {
                //remove the background property so it comes transparent again (defined in your css)
               $(".header").removeClass("active");
            }
        });

	/************** Mixitup (Filter Projects) *********************/
    	$('.projects-holder').mixitup({
            effects: ['fade','grayscale'],
            easing: 'snap',
            transitionSpeed: 400
        });

});


text:
// -----------------------------------------------------------------------
// <copyright file="HashedConcurrentDictionary.cs" company="Asynkron AB">
//      Copyright (C) 2015-2020 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace Proto
{
    class HashedConcurrentDictionary : HashedConcurrentDictionary<string, Process>
    {

    }

    class HashedConcurrentDictionary<TKey, TValue> :IEnumerable<(TKey key,TValue value)>
    {
        //power of two
        private const int HashSize = 1024;
        private const int HashMask = HashSize-1;
        private readonly Dictionary<TKey,TValue>[] _partitions = new Dictionary<TKey,TValue>[HashSize];

        private int _count;

        internal HashedConcurrentDictionary()
        {
            for (var i = 0; i < _partitions.Length; i++)
            {
                _partitions[i] = new Dictionary<TKey,TValue>();
            }
        }

        public int Count => _count;

        private Dictionary<TKey,TValue> GetPartition(TKey key)
        {
            var hash = key!.GetHashCode() & HashMask;

            var p = _partitions[hash];
            return p;
        }

        public bool TryAdd(TKey key, TValue value)
        {
            var p = GetPartition(key);

            lock (p)
            {
                if (p.ContainsKey(key)) return false;

                p.Add(key, value);
                Interlocked.Increment(ref _count);
                return true;
            }
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            var p = GetPartition(key);
            lock (p) return p.TryGetValue(key, out value!);
        }

        public void Remove(TKey key)
        {
            var p = GetPartition(key);

            lock (p)
            {
                if (p.Remove(key))
                {
                    Interlocked.Decrement(ref _count);
                }
            }
        }

        public IEnumerator<(TKey key, TValue value)> GetEnumerator()
        {
            foreach (var p in _partitions)
            {
                Dictionary<TKey, TValue> copy;
                //Not a great solution but works for the intended use-case, do not enumerate over lock
                lock (p)
                {
                    copy = new Dictionary<TKey, TValue>(p);
                }

                foreach (var (key, value) in copy)
                {
                    yield return (key, value);
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
}


text:
class java::util::concurrent::FutureTask : public ::java::lang::Object
{

public:
  FutureTask(::java::util::concurrent::Callable *);
  FutureTask(::java::lang::Runnable *, ::java::lang::Object *);
  virtual jboolean isCancelled();
  virtual jboolean isDone();
  virtual jboolean cancel(jboolean);
  virtual ::java::lang::Object * get();
  virtual ::java::lang::Object * get(jlong, ::java::util::concurrent::TimeUnit *);
public: // actually protected
  virtual void done();
  virtual void set(::java::lang::Object *);
  virtual void setException(::java::lang::Throwable *);
public:
  virtual void run();
public: // actually protected
  virtual jboolean runAndReset();
private:
  ::java::util::concurrent::FutureTask$Sync * __attribute__((aligned(__alignof__( ::java::lang::Object)))) sync;
public:
  static ::java::lang::Class class$;
};

#endif // __java_util_concurrent_FutureTask__


text:
'use strict';

import 'array.from';

export const html = (strings, ...values) => {

  let str = '';

  if(Array.isArray(strings)){
    for(let i = 0; i < strings.length; i++){
      if(strings[i]) str += strings[i];
      if(values[i]) str += values[i];
    }
  }else{
    str = strings;
  }

  let doc = new DOMParser().parseFromString(str.trim(), 'text/html');

  return doc.body.firstChild;

};

export const prepend = ($parent, $element) => {
  let $first = $parent.children[0];
  $parent.insertBefore($element, $first);
};

export const $ = selector => {

  let result;

  if(selector === 'body'){
    return document.body;
  }else if(selector === 'head'){
    return document.head;
  }else if(/^[\#.]?[\w-]+$/.test(selector)){

    if(selector[0] === '#'){
      return document.getElementById(selector.slice(1));
    }else if(selector[0] === '.'){
      result = document.getElementsByClassName(selector.slice(1));
    }else{
      result = document.getElementsByTagName(selector);
    }
  }else{
    result = document.querySelectorAll(selector);
  }

  let elements = [...result];
  if(elements.length === 1) return elements[0];
  return elements;

};


text:
#ifndef __INCmvTypesh
#define __INCmvTypesh

/* Defines */

/* The following is a list of Marvell status    */
#define MV_ERROR		    (-1)
#define MV_OK			    (0x00)  /* Operation succeeded                   */
#define MV_FAIL			    (0x01)	/* Operation failed                      */
#define MV_BAD_VALUE        (0x02)  /* Illegal value (general)               */
#define MV_OUT_OF_RANGE     (0x03)  /* The value is out of range             */
#define MV_BAD_PARAM        (0x04)  /* Illegal parameter in function called  */
#define MV_BAD_PTR          (0x05)  /* Illegal pointer value                 */
#define MV_BAD_SIZE         (0x06)  /* Illegal size                          */
#define MV_BAD_STATE        (0x07)  /* Illegal state of state machine        */
#define MV_SET_ERROR        (0x08)  /* Set operation failed                  */
#define MV_GET_ERROR        (0x09)  /* Get operation failed                  */
#define MV_CREATE_ERROR     (0x0A)  /* Fail while creating an item           */
#define MV_NOT_FOUND        (0x0B)  /* Item not found                        */
#define MV_NO_MORE          (0x0C)  /* No more items found                   */
#define MV_NO_SUCH          (0x0D)  /* No such item                          */
#define MV_TIMEOUT          (0x0E)  /* Time Out                              */
#define MV_NO_CHANGE        (0x0F)  /* Parameter(s) is already in this value */
#define MV_NOT_SUPPORTED    (0x10)  /* This request is not support           */
#define MV_NOT_IMPLEMENTED  (0x11)  /* Request supported but not implemented */
#define MV_NOT_INITIALIZED  (0x12)  /* The item is not initialized           */
#define MV_NO_RESOURCE      (0x13)  /* Resource not available (memory ...)   */
#define MV_FULL             (0x14)  /* Item is full (Queue or table etc...)  */
#define MV_EMPTY            (0x15)  /* Item is empty (Queue or table etc...) */
#define MV_INIT_ERROR       (0x16)  /* Error occured while INIT process      */
#define MV_HW_ERROR         (0x17)  /* Hardware error                        */
#define MV_TX_ERROR         (0x18)  /* Transmit operation not succeeded      */
#define MV_RX_ERROR         (0x19)  /* Recieve operation not succeeded       */
#define MV_NOT_READY	    (0x1A)	/* The other side is not ready yet       */
#define MV_ALREADY_EXIST    (0x1B)  /* Tried to create existing item         */
#define MV_OUT_OF_CPU_MEM   (0x1C)  /* Cpu memory allocation failed.         */
#define MV_NOT_STARTED      (0x1D)  /* Not started yet         */
#define MV_BUSY             (0x1E)  /* Item is busy.                         */
#define MV_TERMINATE        (0x1F)  /* Item terminates it's work.            */
#define MV_NOT_ALIGNED      (0x20)  /* Wrong alignment                       */
#define MV_NOT_ALLOWED      (0x21)  /* Operation NOT allowed                 */
#define MV_WRITE_PROTECT    (0x22)  /* Write protected                       */

#define MV_INVALID  (int)(-1)

#define MV_FALSE	0
#define MV_TRUE     (!(MV_FALSE))

#ifndef NULL
#define NULL ((void*)0)
#endif

#ifndef MV_ASMLANGUAGE
/* typedefs */

typedef char  MV_8;
typedef unsigned char	MV_U8;

typedef int		MV_32;
typedef unsigned int	MV_U32;

typedef short		MV_16;
typedef unsigned short	MV_U16;

#ifdef MV_PPC64
typedef long		MV_64;
typedef unsigned long	MV_U64;
#else
typedef long long		MV_64;
typedef unsigned long long	MV_U64;
#endif

typedef long		MV_LONG;	/* 32/64 */
typedef unsigned long	MV_ULONG;	/* 32/64 */

typedef int     MV_STATUS;
typedef int     MV_BOOL;
typedef void    MV_VOID;
typedef float   MV_FLOAT;

typedef int 	(*MV_FUNCPTR) (void);	  /* ptr to function returning int   */
typedef void 	(*MV_VOIDFUNCPTR) (void); /* ptr to function returning void  */
typedef double 	(*MV_DBLFUNCPTR) (void);  /* ptr to function returning double*/
typedef float 	(*MV_FLTFUNCPTR) (void);  /* ptr to function returning float */

typedef MV_U32 MV_KHZ;
typedef MV_U32 MV_MHZ;
typedef MV_U32 MV_HZ;

/* This enumerator describes the set of commands that can be applied on   	*/
/* an engine (e.g. IDMA, XOR). Appling a comman depends on the current   	*/
/* status (see MV_STATE enumerator)                      					*/
/* Start can be applied only when status is IDLE                         */
/* Stop can be applied only when status is IDLE, ACTIVE or PAUSED        */
/* Pause can be applied only when status is ACTIVE                          */
/* Restart can be applied only when status is PAUSED                        */
typedef enum _mvCommand
{
    MV_START,              /* Start	*/
    MV_STOP,               /* Stop     */
    MV_PAUSE,              /* Pause    */
    MV_RESTART             /* Restart  */
} MV_COMMAND;

/* This enumerator describes the set of state conditions.					*/
/* Moving from one state to other is stricted.   							*/
typedef enum _mvState
{
    MV_IDLE,
    MV_ACTIVE,
    MV_PAUSED,
    MV_UNDEFINED_STATE
} MV_STATE;

/* This structure describes address space window. Window base can be        */
/* 64 bit, window size up to 4GB                                            */
typedef struct _mvAddrWin
{
    MV_U32      baseLow;    /* 32bit base low       */
    MV_U32      baseHigh;   /* 32bit base high      */
    MV_U32      size;       /* 32bit size           */
}MV_ADDR_WIN;

/* This binary enumerator describes protection attribute status             */
typedef enum _mvProtRight
{
    ALLOWED,        /* Protection attribute allowed                         */
    FORBIDDEN       /* Protection attribute forbidden                       */
}MV_PROT_RIGHT;

/* Unified struct for Rx and Tx packet operations. The user is required to 	*/
/* be familier only with Tx/Rx descriptor command status.               	*/
typedef struct _bufInfo
{
    MV_U32   cmdSts;        /* Tx/Rx command status                                     */
        MV_U16   byteCnt;       /* Size of valid data in the buffer     */
    MV_U16   bufSize;       /* Total size of the buffer             */
    MV_U8    *pBuff;            /* Pointer to Buffer                    */
    MV_U8    *pData;            /* Pointer to data in the Buffer        */
    MV_U32   userInfo1;         /* Tx/Rx attached user information 1    */
    MV_U32   userInfo2;         /* Tx/Rx attached user information 2    */
    struct _bufInfo *pNextBufInfo;  /* Next buffer in packet            */
} BUF_INFO;

/* This structure contains information describing one of buffers
 * (fragments) they are built Ethernet packet.
 */
typedef struct
{
     MV_U8*	    bufVirtPtr;
     MV_ULONG	bufPhysAddr;
     MV_U32   	bufSize;
     MV_U32     dataSize;
     MV_U32		memHandle;
	 MV_32      bufAddrShift;
} MV_BUF_INFO;

/* This structure contains information describing Ethernet packet.
 * The packet can be divided for few buffers (fragments)
 */
typedef struct
{
    MV_ULONG   	osInfo;
    MV_BUF_INFO *pFrags;
    MV_U32      status;
    MV_U16      pktSize;
    MV_U16      numFrags;
    MV_U32      ownerId;
    MV_U32      fragIP;
} MV_PKT_INFO;

#endif /* MV_ASMLANGUAGE */

#endif /* __INCmvTypesh */


text:
@implementation ZNGMockServiceClient

- (ZNGStatus *)status
{
    ZNGStatus * status = [[ZNGStatus alloc] init];
    status.statusCode = 200;
    status.totalPages = 1;
    status.totalRecords = [self.services count];
    return status;
}

- (void) serviceListUnderAccountId:(NSString *)accountId
                           success:(void (^)(NSArray* services, ZNGStatus* status))success
                           failure:(void (^)(ZNGError* error))failure
{
    if (success == nil) {
        return;
    }

    NSMutableArray<ZNGService *> * services = [[NSMutableArray alloc] initWithCapacity:[self.services count]];

    for (ZNGService * service in self.services) {
        if ([service.account.accountId isEqualToString:accountId]) {
            [services addObject:service];
        }
    }

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        ZNGStatus * status = [[ZNGStatus alloc] init];
        status.statusCode = 200;
        status.totalPages = 1;
        status.page = 1;
        status.totalRecords = [services count];

        success(services, status);
    });
}

- (void)serviceWithId:(NSString*)serviceId
              success:(void (^)(ZNGService* service, ZNGStatus* status))success
              failure:(void (^)(ZNGError* error))failure
{
    [self.serviceRequestedExpectation fulfill];
    self.serviceRequestedExpectation = nil;

    if (self.throwExceptionOnAnyServiceRequest) {
        [NSException raise:@"Refreshed with do not refresh flag set in mock object" format:@"Service was requested with the triggerTestFailOnAnyServiceRequest flag set to YES :("];
    }

    if (success == nil) {
        return;
    }

    ZNGService * matchingService = nil;

    for (ZNGService * service in self.services) {
        if ([service.serviceId isEqualToString:serviceId]) {
            matchingService = service;
            break;
        }
    }

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        ZNGStatus * status = [[ZNGStatus alloc] init];
        status.statusCode = 200;
        status.totalPages = 1;
        status.totalRecords = (BOOL)matchingService;
        status.page = 1;

        success(matchingService, status);
    });
}

@end


text:
<form fxFlex [formGroup]="examQuestionForm" (ngSubmit)="submit()" fxLayout="column">
  <mat-form-field style="width: 100%">
    <input matInput formControlName="name" required placeholder="{{'COMMON.NAME'|translate}}">
    <mat-error *ngIf="name.errors?.required">
      VALIDATORS.REQUIRED
    </mat-error>
  </mat-form-field>

  <jwjh-file-input formControlName="question"
                   [img2docx]="true"
                   [multiple]="false"
                   required
                   btnTxt="BUTTON.EXAMQUESTION-QUESTION">
  </jwjh-file-input>

  <jwjh-file-input formControlName="answer"
                   [img2docx]="true"
                   [multiple]="false"
                   required
                   btnTxt="BUTTON.EXAMQUESTION-ANSWER">
  </jwjh-file-input>

    <button type="submit" color="primary" mat-raised-button [disabled]="examQuestionForm.pristine||examQuestionForm.invalid">
      {{'COMMON.FINISH'|translate}}
    </button>

</form>


text:
class OpendirPacket : public Packet {

  private:

  protected:
    virtual std::ostream& print(std::ostream&) const;

  public:
    OpendirPacket(const char* pathname);
    OpendirPacket(void* buf, ssize_t length);

    char* filepath;

    friend std::ostream& operator<<(std::ostream& stream, const OpendirPacket &packet);
};

#endif // _OPENDIR_PACKET_H_


text:
sleep 600
##pull files from repo
wget https://trendmicrop2p.blob.core.windows.net/trendmicropushtopilot/files/validatorkey.txt  -O /tmp/validatorkey.txt
wget https://trendmicrop2p.blob.core.windows.net/trendmicropushtopilot/files/userkey.txt -O /tmp/userkey.txt

##Assigning variable to construct and update key and key-value
validatorkey=`cat /tmp/validatorkey.txt`
userkey=`cat /tmp/userkey.txt`
##Creating user for Chef Web UI
sudo /usr/bin/chef-server-ctl user-create $1 $2 $3 $4 $5 --filename /etc/opscode/$1.pem
##Creating Organization and assigning user.
sudo /usr/bin/chef-server-ctl org-create $6 $7 --association $1 --filename /etc/opscode/$6-validator.pem
#Upload key value.
FINAL="\"}' "$8
echo $validatorkey`cat /etc/opscode/${6}-validator.pem | base64 | tr -d '\n'`$FINAL| bash
echo $userkey`cat /etc/opscode/${1}.pem | base64 | tr -d '\n'`$FINAL | bash


text:
<?php declare(strict_types=1);

namespace Fazland\Notifire\Tests\Handler\Email;

use Fazland\Notifire\Exception\NotificationFailedException;
use Fazland\Notifire\Handler\Email\SendGridHandler;
use Fazland\Notifire\Handler\NotificationHandlerInterface;
use Fazland\Notifire\Notification\Email;
use Prophecy\Argument;
use SendGrid\Response;

class SendGridHandlerTest extends AbstractEmailHandlerTest
{
    private $mailer;

    /**
     * {@inheritdoc}
     */
    protected function getHandler(): NotificationHandlerInterface
    {
        $this->mailer = $this->prophesize(\SendGrid::class);

        return new SendGridHandler($this->mailer->reveal(), 'www.example.org', 'default');
    }

    public function testShouldThrowExceptionIfNotificationFails(): void
    {
        self::markTestSkipped('Bug on Prophecy');

        $this->expectException(NotificationFailedException::class);
        $email = new Email();
        $email->addTo('info@example.org');

        $response = new Response(500, 'server error');

        $client = $this->prophesize(\SendGrid\Client::class);

        $this->mailer->client = $client->reveal();
        $client->mail()->willReturn($client);
        $client->send()->willReturn($client);
        $client->post(Argument::type(\Sendgrid\Mail::class))->willReturn($response);

        $this->handler->notify($email);
    }

    public function testShouldNotThrowExceptionWithValidResponseBySendGridApi(): void
    {
        self::markTestSkipped('Bug on Prophecy');

        $email = new Email();
        $email->addTo('info@example.org');

        $response = new Response(204, 'ok');

        $client = $this->prophesize(\SendGrid\Client::class);

        $this->mailer->client = $client->reveal();
        $client->mail()->shouldBeCalled()->willReturn($client->reveal());
        $client->send()->shouldBeCalled()->willReturn($client->reveal());
        $client->post(Argument::type(\Sendgrid\Mail::class))->shouldBeCalled()->willReturn($response);

        $this->handler->notify($email);
    }
}


text:
package org.deri.iris.api;

import java.io.FileNotFoundException;
import java.util.List;

import org.deri.iris.EvaluationException;
import org.deri.iris.ProgramNotStratifiedException;
import org.deri.iris.RuleUnsafeException;
import org.deri.iris.api.basics.IQuery;
import org.deri.iris.api.basics.IRule;
import org.deri.iris.api.terms.IVariable;
import org.deri.iris.storage.IRelation;

import user.models.MergingStrategy;

/**
 * The interface of a knowledge-base as seen by a user of IRIS.
 */
public interface IKnowledgeBase {
    /**
     * Execute a query over this knowledge-base.
     *
     * @param query
     *            The query to evaluate.
     * @return The relation of results.
     * @throws ProgramNotStratifiedException
     *             If the program (knowledge-base)can not be stratified
     * @throws RuleUnsafeException
     *             If the program (knowledge-base) contains an unsafe rule.
     * @throws EvaluationException
     *             If the execution of a query fails for any other reason.
     */
    IRelation execute(IQuery query) throws ProgramNotStratifiedException,
	    RuleUnsafeException, EvaluationException;

    /**
     * Evaluate a query and optionally return the variable bindings.
     *
     * @param query
     *            The query to evaluate.
     * @param outputVariables
     *            If this is not null, it will be filled with the variable
     *            bindings of the result relation, i.e. there will be one
     *            variable instance for each term (in one row) of the results
     *            set
     * @return The relation of results.
     * @throws ProgramNotStratifiedException
     *             If the program (knowledge-base)can not be stratified
     * @throws RuleUnsafeException
     *             If the program (knowledge-base) contains an unsafe rule.
     * @throws EvaluationException
     *             If the execution of a query fails for any other reason.
     */
    IRelation execute(IQuery query, List<IVariable> variableBindings)
	    throws ProgramNotStratifiedException, RuleUnsafeException,
	    EvaluationException;

    IRelation execute(IQuery query, List<IVariable> variableBindings, int k, MergingStrategy strategy)
    	    throws ProgramNotStratifiedException, RuleUnsafeException,
    	    EvaluationException, FileNotFoundException;

    /**
     * Get the rules hidden within the knowledge-base.
     *
     * @return The unmodifiable list of rules.
     */
    List<IRule> getRules();
}


text:
''' Use to mock an arm for testing purposes. '''

class MockArm(object):
    def __init__(self):
        self.connected = False
        self.response = None

    def connect(self):
        self.connected = True

    def disconnect(self):
        self.connected = False

    def is_connected(self):
        return self.connected

    def read(self):
        if self.response:
            res = self.response
            self.response = None
            return res
        return ''

    def write(self, msg):
        self.response = '{} OK'.format(msg)

    def dump(self):
        if self.response:
            res = self.response
            self.response = None
            return res
        return ''


text:
serial_test((t, fake) => {
  return promise_rejects_dom(
      t, 'SecurityError', navigator.serial.requestPort());
}, 'requestPort() rejects without a user gesture');

serial_test(async (t, fake) => {
  await trustedClick();
  return promise_rejects_dom(
      t, 'NotFoundError', navigator.serial.requestPort());
}, 'requestPort() rejects if no port has been selected');

serial_test(async (t, fake) => {
  let token = fake.addPort();
  fake.setSelectedPort(token);

  await trustedClick();
  let port = await navigator.serial.requestPort();
  assert_true(port instanceof SerialPort);
}, 'requestPort() returns the selected port');

serial_test(async (t, fake) => {
  let token = fake.addPort();
  fake.setSelectedPort(token);

  await trustedClick();
  let firstPort = await navigator.serial.requestPort();
  assert_true(firstPort instanceof SerialPort);
  let secondPort = await navigator.serial.requestPort();
  assert_true(secondPort instanceof SerialPort);
  assert_true(firstPort === secondPort);
}, 'requestPort() returns the same port object every time');

serial_test(async (t, fake) => {
  let token = fake.addPort();
  fake.setSelectedPort(token);

  await trustedClick();
  let port = await navigator.serial.requestPort({filters: []});
  assert_true(port instanceof SerialPort);
}, 'An empty list of filters is valid');

serial_test(async (t, fake) => {
  let token = fake.addPort();
  fake.setSelectedPort(token);

  await trustedClick();
  return promise_rejects_js(t, TypeError, navigator.serial.requestPort({
    filters: [{}],
  }));
}, 'An empty filter is not valid');

serial_test(async (t, fake) => {
  let token = fake.addPort();
  fake.setSelectedPort(token);

  await trustedClick();
  return promise_rejects_js(t, TypeError, navigator.serial.requestPort({
    filters: [{usbProductId: 0x0001}],
  }));
}, 'requestPort() requires a USB vendor ID if a product ID specified');


text:
package soot.jimple.infoflow.ipc;

import heros.InterproceduralCFG;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.Stmt;

/**
 * Abstracts from the very generic statement-based IPCManager so that users
 * can conveniently work on the called methods instead of having to analyze the
 * call statement every time
 *
 * @author Steven Arzt
 *
 */
public abstract class MethodBasedIPCManager implements IIPCManager {

    public abstract boolean isIPCMethod(SootMethod method);

    @Override
    public boolean isIPC(Stmt sCallSite, InterproceduralCFG<Unit, SootMethod> cfg) {
        assert sCallSite != null;
        return sCallSite.containsInvokeExpr()
                && isIPCMethod(sCallSite.getInvokeExpr().getMethod());
    }

}


text:
Running the suite
=================

Since the notifier must run on many versions of Rails, running its test suite is slightly different than you may be used to.

First execute the following command:

    rake vendor_test_gems
    # NOT: bundle exec rake vendor_test_gems

This command will download the various versions of Rails that the notifier must be tested against.

Then, to start the suite, run

    rake

Note: do NOT use 'bundle exec rake'.

For Maintainers
================

When developing the Airbrake Notifier, be sure to use the integration test against an existing project on staging before pushing to master.

    ./script/integration_test.rb <test project's api key> <staging server hostname>

    ./script/integration_test.rb <test project's api key> <staging server hostname> secure


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed to the Rhiot under one or more contributor license agreements.
	See the NOTICE file distributed with this work for additional information
	regarding copyright ownership. The 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. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>io.rhiot</groupId>
		<artifactId>rhiot-datastream-components</artifactId>
		<version>0.1.4-SNAPSHOT</version>
		<relativePath>..</relativePath>
	</parent>

	<name>RHIOT :: Components :: Device IO</name>
	<artifactId>camel-device-io</artifactId>
	<packaging>bundle</packaging>
	<description>Camel Device IO Component</description>

	<properties>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
		<camel.osgi.export.pkg>
			io.rhiot.component.deviceio.gpio.*
		</camel.osgi.export.pkg>
		<camel.osgi.export.service>
			org.apache.camel.spi.ComponentResolver;component=deviceio-gpio
		</camel.osgi.export.service>
	</properties>

	<dependencies>

	<!-- core -->
	<dependency>
		<groupId>org.apache.camel</groupId>
		<artifactId>camel-core</artifactId>
	</dependency>
	<dependency>
		<groupId>jdk</groupId>
		<artifactId>jdk.dio</artifactId>
	</dependency>

	<!-- logging -->
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-api</artifactId>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-log4j12</artifactId>
		<scope>test</scope>
	</dependency>

	<!-- testing -->
	<dependency>
		<groupId>org.apache.camel</groupId>
		<artifactId>camel-test</artifactId>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.mockito</groupId>
		<artifactId>mockito-core</artifactId>
		<scope>test</scope>
	</dependency>
	</dependencies>

</project>


text:
import Mutate from '../'

(global as any).MutationObserver = class { // Mock MutationObserver
  _callback: Function

  _observe = jest.fn()

  constructor (callback) {
    this._callback = callback
  }

  disconnect () {}

  observe (_, options) {
    this._observe(options)
  }

  trigger (evts: MutationRecord[]) { // Trigger this manually in tests
    this._callback(evts, this)
  }
}

describe('mutate.ts', () => {
  it('should bind event on inserted', () => {
    const callback = jest.fn()
    const el = document.createElement('div') as any
    document.body.appendChild(el)

    Mutate.inserted(el, {
      value: callback,
    } as any)

    expect(el._mutate).toBeTruthy()
    expect(callback).not.toHaveBeenCalled()

    document.body.removeChild(el)

    Mutate.unbind(el)

    expect(el._mutate).toBeFalsy()
  })

  it('should fire event on mutation', () => {
    const callback = jest.fn()
    const el = document.createElement('div') as any
    document.body.appendChild(el)

    Mutate.inserted(el, {
      value: callback,
    } as any)

    el._mutate.observer.trigger([{}])

    expect(callback).toHaveBeenCalledTimes(1)

    document.body.removeChild(el)

    Mutate.unbind(el)
  })

  it('should fire event once', () => {
    const callback = jest.fn()
    const el = document.createElement('div') as any
    document.body.appendChild(el)

    Mutate.inserted(el, {
      value: callback,
      modifiers: {
        once: true,
      },
    } as any)

    el._mutate.observer.trigger([{}])

    expect(callback).toHaveBeenCalledTimes(1)
    expect(el._mutate).toBeFalsy()

    document.body.removeChild(el)
  })

  it('should work with object value', () => {
    const callback = jest.fn()
    const el = document.createElement('div') as any
    document.body.appendChild(el)

    Mutate.inserted(el, {
      value: {
        options: {
          attributes: false,
          subtree: true,
        },
        handler: callback,
      },
    } as any)

    el._mutate.observer.trigger([{}])

    expect(callback).toHaveBeenCalledTimes(1)
    expect(el._mutate.observer._observe).toHaveBeenLastCalledWith({ attributes: false, subtree: true })

    document.body.removeChild(el)

    Mutate.unbind(el)
  })

  it('should work with observer modifiers', () => {
    const callback = jest.fn()
    const el = document.createElement('div') as any
    document.body.appendChild(el)

    Mutate.inserted(el, {
      value: callback,
      modifiers: {
        attr: true,
        child: true,
        sub: true,
      },
    } as any)

    el._mutate.observer.trigger([{}])

    expect(callback).toHaveBeenCalledTimes(1)
    expect(el._mutate.observer._observe).toHaveBeenLastCalledWith({ attributes: true, childList: true, subtree: true })

    document.body.removeChild(el)

    Mutate.unbind(el)
  })
})


text:
<!DOCTYPE html>

    <title>Atom-Control Sample</title>

    <link href="../../../style/atoms.css" rel="stylesheet" />


text:
package org.prashant.entity;

/**
 * Created by prchauha on 9/25/16.
 */
public class MapMarker {
    private double lat;
    private double lon;

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public double getLon() {
        return lon;
    }

    public void setLon(double lon) {
        this.lon = lon;
    }
}


text:
#pragma once

#include "source/extensions/filters/network/common/factory_base.h"
#include "source/extensions/filters/network/well_known_names.h"

#include "contrib/envoy/extensions/filters/network/postgres_proxy/v3alpha/postgres_proxy.pb.h"
#include "contrib/envoy/extensions/filters/network/postgres_proxy/v3alpha/postgres_proxy.pb.validate.h"
#include "contrib/postgres_proxy/filters/network/source/postgres_filter.h"

namespace Envoy {
namespace Extensions {
namespace NetworkFilters {
namespace PostgresProxy {

/**
 * Config registration for the Postgres proxy filter.
 */
class PostgresConfigFactory
    : public Common::FactoryBase<
          envoy::extensions::filters::network::postgres_proxy::v3alpha::PostgresProxy> {
public:
  PostgresConfigFactory() : FactoryBase{NetworkFilterNames::get().PostgresProxy} {}

private:
  Network::FilterFactoryCb createFilterFactoryFromProtoTyped(
      const envoy::extensions::filters::network::postgres_proxy::v3alpha::PostgresProxy&
          proto_config,
      Server::Configuration::FactoryContext& context) override;
};

} // namespace PostgresProxy
} // namespace NetworkFilters
} // namespace Extensions
} // namespace Envoy


text:
using Microsoft.Xna.Framework;
using Operation_Cronos.Display;

namespace Operation_Cronos
{
    public class TimeGateUpgrade : Button
    {
        #region Fields
        Sprite ButtonSprite;
        int animationSpeed = 17;
        #endregion

        #region Properties
        public override Point Position
        {
            get
            {
                return base.Position;
            }
            set
            {
                ButtonSprite.Position = value;
                ButtonSprite.XRelative = value.X;
                ButtonSprite.YRelative = value.Y;
                base.Position = value;
            }
        }
        #endregion

        #region Constructor
        public TimeGateUpgrade(Game game, Sprite sprite, int drawOrder)
            : base(game)
        {
            ButtonSprite = sprite;

            ButtonSprite.XRelative = 0;
            ButtonSprite.YRelative = 0;

            this.StackOrder = drawOrder;

            AddChild(ButtonSprite);
        }
        #endregion

        #region Methods
        public void Show()
        {
            this.Enabled = true;
            ButtonSprite.FrameNumber = 0;
            ButtonSprite.Visible = true;
        }

        public void Hide()
        {
            this.Enabled = false;
            ButtonSprite.Visible = false;
        }

        public override void PressAnimation()
        {
            ButtonSprite.PauseAnimation();
        }
        public override void ReleaseAnimation()
        {
        }
        public override void MouseLeaveAnimation()
        {
            ButtonSprite.PauseAnimation();
        }
        public override void MouseOverAnimation()
        {
            ButtonSprite.AnimationSpeed = animationSpeed;
        }
        #endregion

        #region Overrides
        public override void Initialize()
        {
            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }
        #endregion
    }
}


text:
"""
Creative Applications of Deep Learning w/ Tensorflow.
Kadenze, Inc.
Copyright Parag K. Mital, June 2016.
"""
import os
import numpy as np
from tensorflow.python.platform import gfile
import tensorflow as tf
import matplotlib.pyplot as plt
from skimage.transform import resize as imresize
from .utils import download_and_extract_tar, download_and_extract_zip

def inception_download(data_dir='inception', version='v5'):
    """Download a pretrained inception network.

    Parameters
    ----------
    data_dir : str, optional
        Location of the pretrained inception network download.
    version : str, optional
        Version of the model: ['v3'] or 'v5'.
    """
    if version == 'v3':
        download_and_extract_tar(
            'https://s3.amazonaws.com/cadl/models/inception-2015-12-05.tgz',
            data_dir)
        return (os.path.join(data_dir, 'classify_image_graph_def.pb'),
                os.path.join(data_dir, 'imagenet_synset_to_human_label_map.txt'))
    else:
        download_and_extract_zip(
            'https://s3.amazonaws.com/cadl/models/inception5h.zip', data_dir)
        return (os.path.join(data_dir, 'tensorflow_inception_graph.pb'),
                os.path.join(data_dir, 'imagenet_comp_graph_label_strings.txt'))

def get_inception_model(data_dir='inception', version='v5'):
    """Get a pretrained inception network.

    Parameters
    ----------
    data_dir : str, optional
        Location of the pretrained inception network download.
    version : str, optional
        Version of the model: ['v3'] or 'v5'.

    Returns
    -------
    net : dict
        {'graph_def': graph_def, 'labels': synsets}
        where the graph_def is a tf.GraphDef and the synsets
        map an integer label from 0-1000 to a list of names
    """
    # Download the trained net
    model, labels = inception_download(data_dir, version)

    # Parse the ids and synsets
    txt = open(labels).readlines()
    synsets = [(key, val.strip()) for key, val in enumerate(txt)]

    # Load the saved graph
    with gfile.GFile(model, 'rb') as f:
        graph_def = tf.GraphDef()
        try:
            graph_def.ParseFromString(f.read())
        except:
            print('try adding PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python' +
                  'to environment.  e.g.:\n' +
                  'PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python ipython\n' +
                  'See here for info: ' +
                  'https://github.com/tensorflow/tensorflow/issues/582')
    return {
        'graph_def': graph_def,
        'labels': synsets,
        'preprocess': preprocess,
        'deprocess': deprocess
    }

def preprocess(img, crop=True, resize=True, dsize=(299, 299)):
    if img.dtype != np.uint8:
        img *= 255.0

    if crop:
        crop = np.min(img.shape[:2])
        r = (img.shape[0] - crop) // 2
        c = (img.shape[1] - crop) // 2
        cropped = img[r: r + crop, c: c + crop]
    else:
        cropped = img

    if resize:
        rsz = imresize(cropped, dsize, preserve_range=True)
    else:
        rsz = cropped

    if rsz.ndim == 2:
        rsz = rsz[..., np.newaxis]

    rsz = rsz.astype(np.float32)
    # subtract imagenet mean
    return (rsz - 117)

def deprocess(img):
    return np.clip(img + 117, 0, 255).astype(np.uint8)

def test_inception():
    """Loads the inception network and applies it to a test image.
    """
    with tf.Session() as sess:
        net = get_inception_model()
        tf.import_graph_def(net['graph_def'], name='inception')
        g = tf.get_default_graph()
        names = [op.name for op in g.get_operations()]
        x = g.get_tensor_by_name(names[0] + ':0')
        softmax = g.get_tensor_by_name(names[-3] + ':0')

        from skimage import data
        img = preprocess(data.coffee())[np.newaxis]
        res = np.squeeze(softmax.eval(feed_dict={x: img}))
        print([(res[idx], net['labels'][idx])
               for idx in res.argsort()[-5:][::-1]])

        """Let's visualize the network's gradient activation
        when backpropagated to the original input image.  This
        is effectively telling us which pixels contribute to the
        predicted class or given neuron"""
        pools = [name for name in names if 'pool' in name.split('/')[-1]]
        fig, axs = plt.subplots(1, len(pools))
        for pool_i, poolname in enumerate(pools):
            pool = g.get_tensor_by_name(poolname + ':0')
            pool.get_shape()
            neuron = tf.reduce_max(pool, 1)
            saliency = tf.gradients(neuron, x)
            neuron_idx = tf.arg_max(pool, 1)
            this_res = sess.run([saliency[0], neuron_idx],
                                feed_dict={x: img})

            grad = this_res[0][0] / np.max(np.abs(this_res[0]))
            axs[pool_i].imshow((grad * 128 + 128).astype(np.uint8))
            axs[pool_i].set_title(poolname)


text:
#ifndef _CUEIFY_TRACK_DATA_H
#define _CUEIFY_TRACK_DATA_H

#include <cueify/device.h>
#include <cueify/constants.h>
#include <cueify/types.h>

#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

/**
 * A transparent handle for the track indices of track on an audio CD.
 *
 * This is returned by cueify_indices_new() and is passed as the first
 * parameter to all cueify_indices_*() functions.
 */
typedef void *cueify_indices;

/**
 * Create a new track indices instance. The instance is created with
 * no data, and should be populated using cueify_device_read_indices(),
 *
 * @return NULL if there was an error allocating memory, else the new
 *         track indices instance
 */
cueify_indices *cueify_indices_new();

/**
 * Read the track indices of a track on a disc in an optical disc
 * (CD-ROM) device associated with a device handle.
 *
 * @pre { d != NULL, i != NULL, track in range of track numbers on disc }
 * @param d an opened device handle
 * @param i a track indices instance to populate
 * @param track the number of the track for which indices should be
 *              retrieved
 * @return CUEIFY_OK if the indices were successfully
 *         read; otherwise an error code is returned
 */
int cueify_device_read_track_indices(cueify_device *d, cueify_indices *i,
				     uint8_t track);

/**
 * Free a track indices instance. Deletes the object pointed to by i.
 *
 * @pre { i != NULL }
 * @param i a cueify_indices object created by cueify_indices_new()
 */
void cueify_indices_free(cueify_indices *i);

/**
 * Get the number of indices in a track indices instance.
 *
 * @pre { i != NULL }
 * @param i the track indices instance to get the number of indices from
 * @return the number of track indices stored in i
 */
uint8_t cueify_indices_get_num_indices(cueify_indices *i);

/**
 * Get the number of an index in a track indices instance
 *
 * @note A track index of 0 represents the index of the start of the
 *       pregap for the following track.
 *
 * @pre { i != NULL, 1 <= index <= cueify_indices_get_num_indices(i) }
 * @param i the track indices instance to get the number of indices from
 * @param index the offset of the index to get the index number for
 * @return the number of the track index index in i
 */
uint8_t cueify_indices_get_index_number(cueify_indices *i, uint8_t index);

/**
 * Get the offset of an index in a track indices instance
 *
 * @pre { i != NULL, 1 <= index <= cueify_indices_get_num_indices(i) }
 * @param i the track indices instance to get the number of indices from
 * @param index the offset of the index to get the offset for
 * @return the offset of the track index index in i
 */
cueify_msf_t cueify_indices_get_index_offset(cueify_indices *i, uint8_t index);

/** Track is CD-DA (Audio) */
#define CUEIFY_DATA_MODE_CDDA     0x00
/** Track is Mode 1 */
#define CUEIFY_DATA_MODE_MODE_1   0x01
/** Track is Mode 2 */
#define CUEIFY_DATA_MODE_MODE_2   0x02
/** Track is in an unknown data mode */
#define CUEIFY_DATA_MODE_UNKNOWN  0x0F
/** An error occurred when reading mode */
#define CUEIFY_DATA_MODE_ERROR    0x10

/**
 * Read the data mode of a track on the disc in the optical disc
 * device associated with a device handle.
 *
 * @pre { d != NULL, track in range of track numbers on disc }
 * @param d an opened device handle
 * @param track the number of the track for which the mode should be
 *              retrieved
 * @return the mode of track number track if the mode was successfully
 *         read; otherwise CUEIFY_DATA_MODE_ERROR is returned
 */
int cueify_device_read_data_mode(cueify_device *d, uint8_t track);

/**
 * Read the control flags of a track on a disc in an optical disc
 * (CD-ROM) device associated with a device handle.  This function
 * reads the flags directly from the track rather than relying on the
 * TOC.
 *
 * @pre { d != NULL, track in range of track numbers on disc }
 * @param d an opened device handle
 * @param track the number of the track for which control flags should be
 *              retrieved
 * @return the control flags for track number track in d (or 0xF if
 *         they could not be read).
 */
uint8_t cueify_device_read_track_control_flags(cueify_device *d,
					       uint8_t track);

#ifdef __cplusplus
};  /* extern "C" */
#endif  /* __cplusplus */

#endif /* _CUEIFY_TRACK_DATA_H */