text:
import { spyElementPrototype } from 'rc-util/lib/test/domHook';
import React from 'react';
import Popconfirm from '..';
import mountTest from '../../../tests/shared/mountTest';
import rtlTest from '../../../tests/shared/rtlTest';
import { render, fireEvent, act, waitFakeTimer } from '../../../tests/utils';
import Button from '../../button';

describe('Popconfirm', () => {
  mountTest(Popconfirm);
  rtlTest(Popconfirm);

  const eventObject = expect.objectContaining({
    target: expect.anything(),
    preventDefault: expect.any(Function),
  });

  beforeAll(() => {
    spyElementPrototype(HTMLElement, 'offsetParent', {
      get: () => ({}),
    });
  });

  beforeEach(() => {
    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.clearAllTimers();
    jest.useRealTimers();
  });

  it('should popup Popconfirm dialog', () => {
    const onOpenChange = jest.fn();

    const wrapper = render(
      <Popconfirm
        title={Are you sure delete this task?}
        okText="Yes"
        cancelText="No"
        mouseEnterDelay={0}
        mouseLeaveDelay={0}
        onOpenChange={onOpenChange}
      >
        Delete
      </Popconfirm>,
    );

    const triggerNode = wrapper.container.querySelectorAll('span')[0];
    fireEvent.click(triggerNode);
    expect(onOpenChange).toHaveBeenLastCalledWith(true, undefined);
    expect(wrapper.container.querySelectorAll('.popconfirm-test').length).toBe(1);

    fireEvent.click(triggerNode);
    expect(onOpenChange).toHaveBeenLastCalledWith(false, undefined);
  });

  it('should show overlay when trigger is clicked', async () => {
    const popconfirm = render(
      <Popconfirm title="code">
        show me your code
      </Popconfirm>,
    );

    expect(popconfirm.container.querySelector('.ant-popover')).toBe(null);

    const triggerNode = popconfirm.container.querySelectorAll('span')[0];
    fireEvent.click(triggerNode);

    await waitFakeTimer(100);

    expect(popconfirm.container.querySelector('.ant-popover')).not.toBeNull();
    expect(popconfirm.container.querySelector('.ant-popover')?.className).toContain(
      'ant-popover-placement-top',
    );
    expect(popconfirm.container.querySelector('.ant-popover')?.innerHTML).toMatchSnapshot();
    expect(popconfirm.container.querySelector('.ant-popover')?.innerHTML).toMatchSnapshot();
  });

  it('shows content for render functions', async () => {
    const makeRenderFunction = (content: string) => () => content;

    const popconfirm = render(
      <Popconfirm title={makeRenderFunction('some-title')}>
        show me your code
      </Popconfirm>,
    );

    expect(popconfirm.container.querySelector('.ant-popover')).toBe(null);

    const triggerNode = popconfirm.container.querySelectorAll('span')[0];
    fireEvent.click(triggerNode);
    await waitFakeTimer(100);

    expect(popconfirm.container.querySelector('.ant-popover')).not.toBe(null);
    expect(popconfirm.container.querySelector('.ant-popover')?.innerHTML).toContain('some-title');
    expect(popconfirm.container.querySelector('.ant-popover')?.innerHTML).toMatchSnapshot();
  });

  it('should be controlled by open', () => {
    jest.useFakeTimers();
    const popconfirm = render(
      <Popconfirm title="code">
        show me your code
      </Popconfirm>,
    );

    expect(popconfirm.container.querySelector('.ant-popover')).toBe(null);
    popconfirm.rerender(
      <Popconfirm title="code" open>
        show me your code
      </Popconfirm>,
    );

    expect(popconfirm.container.querySelector('.ant-popover')).not.toBe(null);
    expect(popconfirm.container.querySelector('.ant-popover')?.className).not.toContain(
      'ant-popover-hidden',
    );

    popconfirm.rerender(
      <Popconfirm title="code" open={false}>
        show me your code
      </Popconfirm>,
    );
    act(() => {
      jest.runAllTimers();
    });
    expect(popconfirm.container.querySelector('.ant-popover')).not.toBe(null);
    jest.useRealTimers();
  });

  it('should trigger onConfirm and onCancel', async () => {
    const confirm = jest.fn();
    const cancel = jest.fn();
    const onOpenChange = jest.fn((_, e) => {
      e?.persist?.();
    });
    const popconfirm = render(
      <Popconfirm title="code" onConfirm={confirm} onCancel={cancel} onOpenChange={onOpenChange}>
        show me your code
      </Popconfirm>,
    );
    const triggerNode = popconfirm.container.querySelector('span')!;
    fireEvent.click(triggerNode);
    await waitFakeTimer();

    fireEvent.click(popconfirm.container.querySelector('.ant-btn-primary')!);
    expect(confirm).toHaveBeenCalled();
    expect(onOpenChange).toHaveBeenLastCalledWith(false, eventObject);

    fireEvent.click(triggerNode);
    await waitFakeTimer();

    fireEvent.click(popconfirm.container.querySelector('.ant-btn')!);
    expect(cancel).toHaveBeenCalled();
    expect(onOpenChange).toHaveBeenLastCalledWith(false, eventObject);
  });

  it('should support onConfirm to return Promise', async () => {
    const confirm = () =>
      new Promise(res => {
        setTimeout(res, 300);
      });
    const onOpenChange = jest.fn((_, e) => {
      e?.persist?.();
    });
    const popconfirm = render(
      <Popconfirm title="code" onConfirm={confirm} onOpenChange={onOpenChange}>
        show me your code
      </Popconfirm>,
    );

    const triggerNode = popconfirm.container.querySelectorAll('span')[0];
    fireEvent.click(triggerNode);
    expect(onOpenChange).toHaveBeenCalledTimes(1);

    fireEvent.click(popconfirm.container.querySelectorAll('.ant-btn')[0]);
    await waitFakeTimer();
    expect(onOpenChange).toHaveBeenCalledWith(false, eventObject);
  });

  it('should support customize icon', () => {
    const popconfirm = render(
      <Popconfirm title="code" icon={custom-icon}>
        show me your code
      </Popconfirm>,
    );

    const triggerNode = popconfirm.container.querySelectorAll('span')[0];
    fireEvent.click(triggerNode);
    expect(popconfirm.container.querySelectorAll('.customize-icon').length).toBe(1);
  });

  it('should prefixCls correctly', () => {
    const btnPrefixCls = 'custom-btn';
    const wrapper = render(
      <Popconfirm
        open
        title="x"
        prefixCls="custom-popconfirm"
        okButtonProps={{ prefixCls: btnPrefixCls }}
        cancelButtonProps={{ prefixCls: btnPrefixCls }}
      >
        show me your code
      </Popconfirm>,
    );

    expect(wrapper.container.querySelectorAll('.custom-popconfirm').length).toBeGreaterThan(0);
    expect(wrapper.container.querySelectorAll('.custom-btn').length).toBeGreaterThan(0);
  });

  it('should support defaultOpen', () => {
    const wrapper = render(
      <Popconfirm title="code" defaultOpen>
        show me your code
      </Popconfirm>,
    );
    expect(wrapper.container.querySelector('.ant-popover')).toBeTruthy();
  });

  it('should not open in disabled', () => {
    const wrapper = render(
      <Popconfirm title="code" disabled>
        click me
      </Popconfirm>,
    );
    const triggerNode = wrapper.container.querySelectorAll('span')[0];
    fireEvent.click(triggerNode);
    expect(wrapper.container.querySelector('.ant-popover')).toBeFalsy();
  });

  it('should be closed by pressing ESC', () => {
    const onOpenChange = jest.fn((_, e) => {
      e?.persist?.();
    });
    const wrapper = render(
      <Popconfirm title="title" mouseEnterDelay={0} mouseLeaveDelay={0} onOpenChange={onOpenChange}>
        Delete
      </Popconfirm>,
    );
    const triggerNode = wrapper.container.querySelectorAll('span')[0];
    fireEvent.click(triggerNode);
    expect(onOpenChange).toHaveBeenLastCalledWith(true, undefined);
    fireEvent.keyDown(triggerNode, { key: 'Escape', keyCode: 27 });
    expect(onOpenChange).toHaveBeenLastCalledWith(false, eventObject);
  });

  it('should not warn memory leaking if setState in async callback', async () => {
    const error = jest.spyOn(console, 'error').mockImplementation(() => {});

    const Test = () => {
      const [show, setShow] = React.useState(true);

      if (show) {
        return (
          <Popconfirm
            title="will unmount"
            onConfirm={() =>
              new Promise(resolve => {
                setTimeout(() => {
                  setShow(false);
                  resolve(true);
                }, 300);
              })
            }
          >
            <Button className="clickTarget">Test</Button>
          </Popconfirm>
        );
      }
      return <Button>Unmounted</Button>;
    };

    const { container } = render(

        <Test />

,
    );

    expect(container.textContent).toEqual('Test');

    fireEvent.click(container.querySelector('.clickTarget')!);
    fireEvent.click(container.querySelector('.ant-btn-primary')!);

    await waitFakeTimer(500);
    // expect(container.textContent).toEqual('Unmounted');
    expect(error).not.toHaveBeenCalled();
  });
});


text:
class CreateListings < ActiveRecord::Migration
  def change
    create_table :listings do |t|
      t.string :title, null: false
      t.text :description, null: false
      t.references :user, index: true, foreign_key: true, null: false
      t.datetime :start_time, null: false
      t.datetime :end_time, null: false
      t.string :condition, null: false
      t.boolean :completed, default: false

      t.timestamps null: false
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.tazine.io.socket.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * NonBlockingTimeServer
 *
 * @author frank
 * @date 2017/10/31
 */
public class NonBlockingTimeServer implements Runnable {

    private Selector selector;

    private ServerSocketChannel serverSocketChannel;

    private volatile boolean stop = false;

    /**
     * 初始化多路复用器,绑定监听端口
     *
     * @param port
     */
    public NonBlockingTimeServer(int port) {
        try {
            selector = Selector.open();
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("The time server started on port:" + port);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()) {
                    key = it.next();
                    it.remove();

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void handleInput(SelectionKey key) throws IOException {
        if (key.isValid()) {
            if (key.isAcceptable()) {
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel socketChannel = ssc.accept();
                socketChannel.configureBlocking(false);
                socketChannel.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel socketChannel = (SocketChannel) key.channel();
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = socketChannel.read(readBuffer);
                if (readBytes > 0) {
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("The time server receive order:" + body);
                    String currentTime = new Date(System.currentTimeMillis()).toString();
                    doWrite(socketChannel, currentTime);
                } else {
                    key.cancel();
                    socketChannel.close();
                }
            }
        }
    }

    private void doWrite(SocketChannel socketChannel, String response) throws IOException {
        if (null != response && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            socketChannel.write(writeBuffer);
        }
    }
}


text:
require File.dirname(__FILE__) + '/spec_helper'
require 'nanite'

class WebDocumentImporter
  include Nanite::Actor
  expose :import, :cancel

  def import
    1
  end
  def cancel
    0
  end
  def continue
    1
  end
end

module Actors
  class ComedyActor
    include Nanite::Actor
    expose :fun_tricks
    def fun_tricks
      :rabbit_in_the_hat
    end
  end
end

describe Nanite::Actor do

  describe ".expose" do
    it "should single expose method only once" do
      3.times { WebDocumentImporter.expose(:continue) }
      WebDocumentImporter.provides_for("webfiles").should == ["/webfiles/import", "/webfiles/cancel", "/webfiles/continue"]
    end
  end

  describe ".default_prefix" do
    it "is calculated as default prefix as const path of class name" do
      Actors::ComedyActor.default_prefix.should == "actors/comedy_actor"
      WebDocumentImporter.default_prefix.should == "web_document_importer"
    end
  end

  describe ".provides_for(prefix)" do
    before :each do
      @provides = Actors::ComedyActor.provides_for("money")
    end
    it "returns an array" do
      @provides.should be_kind_of(Array)
    end

    it "maps exposed service methods to prefix" do
      @provides.should == ["/money/fun_tricks"]
      wdi_provides = WebDocumentImporter.provides_for("webfiles")
      wdi_provides.should include("/webfiles/import")
      wdi_provides.should include("/webfiles/cancel")
    end
  end
end


text:
namespace app_list {

namespace {

const int kMinMouseWheelToSwitchPage = 20;
const int kMinScrollToSwitchPage = 20;
const int kMinHorizVelocityToSwitchPage = 800;

const double kFinishTransitionThreshold = 0.33;

}  // namespace

ContentsView::ContentsView(AppListMainView* app_list_main_view)
    : search_results_view_(NULL),
      start_page_view_(NULL),
      app_list_main_view_(app_list_main_view),
      contents_switcher_view_(NULL),
      view_model_(new views::ViewModel) {
  pagination_model_.AddObserver(this);
}

ContentsView::~ContentsView() {
  pagination_model_.RemoveObserver(this);
}

void ContentsView::InitNamedPages(AppListModel* model,
                                  AppListViewDelegate* view_delegate) {
  DCHECK(model);

  if (app_list::switches::IsExperimentalAppListEnabled()) {
    start_page_view_ = new StartPageView(app_list_main_view_, view_delegate);
    AddLauncherPage(
        start_page_view_, IDR_APP_LIST_SEARCH_ICON, NAMED_PAGE_START);
  } else {
    search_results_view_ =
        new SearchResultListView(app_list_main_view_, view_delegate);
    AddLauncherPage(search_results_view_, 0, NAMED_PAGE_SEARCH_RESULTS);
    search_results_view_->SetResults(model->results());
  }

  apps_container_view_ = new AppsContainerView(app_list_main_view_, model);
  int apps_page_index = AddLauncherPage(
      apps_container_view_, IDR_APP_LIST_APPS_ICON, NAMED_PAGE_APPS);

  pagination_model_.SelectPage(apps_page_index, false);
}

void ContentsView::CancelDrag() {
  if (apps_container_view_->apps_grid_view()->has_dragged_view())
    apps_container_view_->apps_grid_view()->EndDrag(true);
  if (apps_container_view_->app_list_folder_view()
          ->items_grid_view()
          ->has_dragged_view()) {
    apps_container_view_->app_list_folder_view()->items_grid_view()->EndDrag(
        true);
  }
}

void ContentsView::SetDragAndDropHostOfCurrentAppList(
    ApplicationDragAndDropHost* drag_and_drop_host) {
  apps_container_view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host);
}

void ContentsView::SetActivePage(int page_index) {
  if (GetActivePageIndex() == page_index)
    return;

  SetActivePageInternal(page_index, false);
}

int ContentsView::GetActivePageIndex() const {
  // The active page is changed at the beginning of an animation, not the end.
  return pagination_model_.SelectedTargetPage();
}

bool ContentsView::IsNamedPageActive(NamedPage named_page) const {
  std::map<NamedPage, int>::const_iterator it =
      named_page_to_view_.find(named_page);
  if (it == named_page_to_view_.end())
    return false;
  return it->second == GetActivePageIndex();
}

int ContentsView::GetPageIndexForNamedPage(NamedPage named_page) const {
  // Find the index of the view corresponding to the given named_page.
  std::map<NamedPage, int>::const_iterator it =
      named_page_to_view_.find(named_page);
  // GetPageIndexForNamedPage should never be called on a named_page that does
  // not have a corresponding view.
  DCHECK(it != named_page_to_view_.end());
  return it->second;
}

int ContentsView::NumLauncherPages() const {
  return pagination_model_.total_pages();
}

void ContentsView::SetActivePageInternal(int page_index,
                                         bool show_search_results) {
  // Start animating to the new page.
  pagination_model_.SelectPage(page_index, true);
  ActivePageChanged(show_search_results);
}

void ContentsView::ActivePageChanged(bool show_search_results) {
  // TODO(xiyuan): Highlight default match instead of the first.
  if (IsNamedPageActive(NAMED_PAGE_SEARCH_RESULTS) &&
      search_results_view_->visible()) {
    search_results_view_->SetSelectedIndex(0);
  }
  if (search_results_view_)
    search_results_view_->UpdateAutoLaunchState();

  if (IsNamedPageActive(NAMED_PAGE_START)) {
    if (show_search_results)
      start_page_view_->ShowSearchResults();
    else
      start_page_view_->Reset();
  }

  // Notify parent AppListMainView of the page change.
  app_list_main_view_->UpdateSearchBoxVisibility();
}

void ContentsView::ShowSearchResults(bool show) {
  NamedPage new_named_page = show ? NAMED_PAGE_SEARCH_RESULTS : NAMED_PAGE_APPS;
  if (app_list::switches::IsExperimentalAppListEnabled())
    new_named_page = NAMED_PAGE_START;

  SetActivePageInternal(GetPageIndexForNamedPage(new_named_page), show);
}

bool ContentsView::IsShowingSearchResults() const {
  return app_list::switches::IsExperimentalAppListEnabled()
             ? IsNamedPageActive(NAMED_PAGE_START) &&
                   start_page_view_->IsShowingSearchResults()
             : IsNamedPageActive(NAMED_PAGE_SEARCH_RESULTS);
}

void ContentsView::UpdatePageBounds() {
  gfx::Rect rect(GetContentsBounds());
  if (rect.IsEmpty())
    return;

  // The bounds calculations will potentially be mid-transition (depending on
  // the state of the PaginationModel).
  int current_page = std::max(0, pagination_model_.selected_page());
  int target_page = current_page;
  double progress = 1;
  if (pagination_model_.has_transition()) {
    const PaginationModel::Transition& transition =
        pagination_model_.transition();
    if (pagination_model_.is_valid_page(transition.target_page)) {
      target_page = transition.target_page;
      progress = transition.progress;
    }
  }

  gfx::Rect incoming_target(rect);
  gfx::Rect outgoing_target(rect);
  int dir = target_page > current_page ? -1 : 1;

  if (app_list::switches::IsExperimentalAppListEnabled()) {
    // The experimental app list transitions horizontally.
    int page_width = rect.width();
    int transition_offset = progress * page_width * dir;

    outgoing_target.set_x(transition_offset);
    incoming_target.set_x(dir < 0 ? transition_offset + page_width
                                  : transition_offset - page_width);
  } else {
    // The normal app list transitions vertically.
    int page_height = rect.height();
    int transition_offset = progress * page_height * dir;

    outgoing_target.set_y(transition_offset);
    incoming_target.set_y(dir < 0 ? transition_offset + page_height
                                  : transition_offset - page_height);
  }

  view_model_->view_at(current_page)->SetBoundsRect(outgoing_target);
  view_model_->view_at(target_page)->SetBoundsRect(incoming_target);
}

PaginationModel* ContentsView::GetAppsPaginationModel() {
  return apps_container_view_->apps_grid_view()->pagination_model();
}

void ContentsView::ShowFolderContent(AppListFolderItem* item) {
  apps_container_view_->ShowActiveFolder(item);
}

void ContentsView::Prerender() {
  const int selected_page =
      std::max(0, GetAppsPaginationModel()->selected_page());
  apps_container_view_->apps_grid_view()->Prerender(selected_page);
}

views::View* ContentsView::GetPageView(int index) {
  return view_model_->view_at(index);
}

void ContentsView::AddBlankPageForTesting() {
  AddLauncherPage(new views::View, 0);
}

int ContentsView::AddLauncherPage(views::View* view, int resource_id) {
  int page_index = view_model_->view_size();
  AddChildView(view);
  view_model_->Add(view, page_index);
  pagination_model_.SetTotalPages(view_model_->view_size());
  if (contents_switcher_view_)
    contents_switcher_view_->AddSwitcherButton(resource_id, page_index);
  return page_index;
}

int ContentsView::AddLauncherPage(views::View* view,
                                  int resource_id,
                                  NamedPage named_page) {
  int page_index = AddLauncherPage(view, resource_id);
  named_page_to_view_.insert(std::pair<NamedPage, int>(named_page, page_index));
  return page_index;
}

gfx::Size ContentsView::GetPreferredSize() const {
  const gfx::Size container_size =
      apps_container_view_->apps_grid_view()->GetPreferredSize();
  const gfx::Size results_size = search_results_view_
                                     ? search_results_view_->GetPreferredSize()
                                     : gfx::Size();

  int width = std::max(container_size.width(), results_size.width());
  int height = std::max(container_size.height(), results_size.height());
  return gfx::Size(width, height);
}

void ContentsView::Layout() {
  // Immediately finish all current animations.
  pagination_model_.FinishAnimation();

  // Move the current view onto the screen, and all other views off screen to
  // the left. (Since we are not animating, we don't need to be careful about
  // which side we place the off-screen views onto.)
  gfx::Rect rect(GetContentsBounds());
  if (rect.IsEmpty())
    return;

  gfx::Rect offscreen_target(rect);
  offscreen_target.set_x(-rect.width());

  for (int i = 0; i < view_model_->view_size(); ++i) {
    view_model_->view_at(i)->SetBoundsRect(
        i == pagination_model_.SelectedTargetPage() ? rect : offscreen_target);
  }
}

bool ContentsView::OnKeyPressed(const ui::KeyEvent& event) {
  return view_model_->view_at(GetActivePageIndex())->OnKeyPressed(event);
}

bool ContentsView::OnMouseWheel(const ui::MouseWheelEvent& event) {
  if (!IsNamedPageActive(NAMED_PAGE_APPS))
    return false;

  int offset;
  if (abs(event.x_offset()) > abs(event.y_offset()))
    offset = event.x_offset();
  else
    offset = event.y_offset();

  if (abs(offset) > kMinMouseWheelToSwitchPage) {
    if (!GetAppsPaginationModel()->has_transition()) {
      GetAppsPaginationModel()->SelectPageRelative(offset > 0 ? -1 : 1, true);
    }
    return true;
  }

  return false;
}

void ContentsView::TotalPagesChanged() {
}

void ContentsView::SelectedPageChanged(int old_selected, int new_selected) {
}

void ContentsView::TransitionStarted() {
}

void ContentsView::TransitionChanged() {
  UpdatePageBounds();
}

void ContentsView::OnGestureEvent(ui::GestureEvent* event) {
  if (!IsNamedPageActive(NAMED_PAGE_APPS))
    return;

  switch (event->type()) {
    case ui::ET_GESTURE_SCROLL_BEGIN:
      GetAppsPaginationModel()->StartScroll();
      event->SetHandled();
      return;
    case ui::ET_GESTURE_SCROLL_UPDATE:
      // event->details.scroll_x() > 0 means moving contents to right. That is,
      // transitioning to previous page.
      GetAppsPaginationModel()->UpdateScroll(event->details().scroll_x() /
                                             GetContentsBounds().width());
      event->SetHandled();
      return;
    case ui::ET_GESTURE_SCROLL_END:
      GetAppsPaginationModel()->EndScroll(
          GetAppsPaginationModel()->transition().progress <
          kFinishTransitionThreshold);
      event->SetHandled();
      return;
    case ui::ET_SCROLL_FLING_START: {
      GetAppsPaginationModel()->EndScroll(true);
      if (fabs(event->details().velocity_x()) > kMinHorizVelocityToSwitchPage) {
        GetAppsPaginationModel()->SelectPageRelative(
            event->details().velocity_x() < 0 ? 1 : -1, true);
      }
      event->SetHandled();
      return;
    }
    default:
      break;
  }
}

void ContentsView::OnScrollEvent(ui::ScrollEvent* event) {
  if (!IsNamedPageActive(NAMED_PAGE_APPS) ||
      event->type() == ui::ET_SCROLL_FLING_CANCEL) {
    return;
  }

  float offset;
  if (std::abs(event->x_offset()) > std::abs(event->y_offset()))
    offset = event->x_offset();
  else
    offset = event->y_offset();

  if (std::abs(offset) > kMinScrollToSwitchPage) {
    if (!GetAppsPaginationModel()->has_transition()) {
      GetAppsPaginationModel()->SelectPageRelative(offset > 0 ? -1 : 1, true);
    }
    event->SetHandled();
    event->StopPropagation();
  }
}

}  // namespace app_list


text:
<?php

class Controller_Entry extends Controller_Template
{

	public function action_index()
	{
		$data["subnav"] = array('index'=> 'active' );

                $data['entries'] = Model_Entry::find('all');

		$this->template->title = 'Entry » Index';
		$this->template->content = View::forge('entry/index', $data);
	}

	public function action_view($id = null)
	{
		$data["subnav"] = array('view'=> 'active' );

                is_null($id) and Response::redirect('entry');

                if (!$data['entry'] = Model_Entry::find($id))
                {
                    Session::set_flash('error', 'Could not find entry #' . $id);
                    Response::redirect('entry');
                }

                $this->template->title = 'Entry » View';
		$this->template->content = View::forge('entry/view', $data);
	}

}


text:
var util = require('util'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    dbconf = require('./dbconf');

    dburl = dbconf.db;

// 调通测试
// exports.dburl = dbconf.db;

// 连接数据库
exports.connect = function(callback) {
    mongoose.connect(dburl);
};

// 断开数据库
exports.disconnect = function(callback) {
    mongoose.disconnect(callback);
};

// 定义对象模型,可以对应为关系型数据库的表项
var TodoScheme = new Schema({
    title:String,
    finished:{type:Boolean,default:false},
    post_date:{type:Date,default:Date.now}
});

// 访问对象模型
mongoose.model('Todo', TodoScheme);
var Todo = mongoose.model('Todo');

// 添加
exports.add = function(title,callback) {
    var newTodo = new Todo();
    newTodo.title = title;
    newTodo.save(function(err){
        if(err){
            util.log("FATAL"+err);
            callback(err);
        }else{
            callback(null);
        }
    });

};

// 删除
exports.delete = function(id, callback) {
    exports.findTodoById(id, function(err, doc) {
        if (err)
            callback(err);
        else {
            util.log(util.inspect(doc));
            doc.remove();
            callback(null);
        }
    });
};

// 修改
exports.editTitle = function(id, title, callback) {
    exports.findTodoById(id, function(err, doc) {
        if (err)
            callback(err);
        else {
            doc.post_date = new Date();
            doc.title = title;
            doc.save(function(err) {
                if (err) {
                    util.log('FATAL '+ err);
                    callback(err);
                } else
                    callback(null);
            });
        }
    });
};

// 结束修改
exports.editFinished = function(id, finished, callback) {
    exports.findTodoById(id, function(err, doc) {
        if (err)
            callback(err);
        else {
            doc.post_date = new Date();
            doc.finished = finished;
            doc.save(function(err) {
                if (err) {
                    util.log('FATAL '+ err);
                    callback(err);
                } else
                    callback(null);
            });
        }
    });
};

// 获取所有表项
exports.allTodos = function(callback) {
    Todo.find({}, callback);
};

exports.forAll = function(doEach, done) {
    Todo.find({}, function(err, docs) {
        if (err) {
            util.log('FATAL '+ err);
            done(err, null);
        }
        docs.forEach(function(doc) {
            doEach(null, doc);
        });
        done(null);
    });
};

// 查询定位具体内容
var findTodoById = exports.findTodoById = function(id,callback){
    Todo.findOne({_id:id},function(err,doc){
        if (err) {
            util.log('FATAL '+ err);
            callback(err, null);
        }
        callback(null, doc);
    });
};


text:
FlagIconSass
---

This project integrates [https://github.com/lipis/flag-icon-css](https://github.com/lipis/flag-icon-css) in a Ruby Gem but only the sass version.

**THIS GEM IS IN EARLY BETA STATE SO USE AT YOUR OWN RISK**

### Installation

In your Gemfile include:

```ruby
gem 'flag-icon-sass'
```

And then execute:

```sh
bundle install
```

Import the FlagIconSass styles in your `app/assets/stylesheets/application.scss`.

```scss
@import "flag-icon-sass";
```

#### Plain usage

In your view:

```html
<span class="flag-icon flag-icon-it"></span>
```

```html
<span class="flag-icon flag-icon-it flag-icon-squared"></span>
```

#### Rails Helper usage

In your view:

```ruby
flag_icon(:it)
# => <span class="flag-icon flag-icon-it"></span>
```

```ruby
flag_icon(:it, true)
# => <span class="flag-icon flag-icon-it flag-icon-squared"></span>
```

```ruby
flag_icon(:it, id: 'my-flag', class: 'strong')
# => <span id="my-flag" class="flag-icon flag-icon-it flag-icon-squared strong"></span>
```

### Thanks

* [https://github.com/lipis/flag-icon-css](https://github.com/lipis/flag-icon-css) for flags-icon-css
* [font-awesome-sass gem](https://github.com/FortAwesome/font-awesome-sass) for inspiration
* [bootstrap-sass gem](https://github.com/twbs/bootstrap-sass) for inspiration


text:
package uk.jamierocks.atlauncher.api.psp;

import static uk.jamierocks.atlauncher.api.ATLauncherAPI.GSON;

import uk.jamierocks.atlauncher.api.ATLauncherAPI;
import uk.jamierocks.atlauncher.api.model.PackModel;
import uk.jamierocks.atlauncher.api.response.Response;

import java.io.IOException;
import java.io.InputStreamReader;

public class PspPacks {

    public static Response<PackModel[]> getPublic(String apiKey) {
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(ATLauncherAPI.makeRequest("/psp/packs/full/public/", "GET", apiKey));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return GSON.fromJson(reader, PacksResponse.class);
    }

    public static Response<PackModel[]> getSemiPublic(String apiKey) {
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(ATLauncherAPI.makeRequest("/psp/packs/full/semipublic/", "GET", apiKey));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return GSON.fromJson(reader, PacksResponse.class);
    }

    public static Response<PackModel[]> getPrivate(String apiKey) {
        InputStreamReader reader = null;
        try {
            reader = new InputStreamReader(ATLauncherAPI.makeRequest("/psp/packs/full/private/", "GET", apiKey));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return GSON.fromJson(reader, PacksResponse.class);
    }

    private class PacksResponse extends Response<PackModel[]> {

    }
}


text:
import {
  FETCH_USER_FILTERS_SUCCESS,
  UPDATE_FILTER_CONDITIONS,
  SET_PAGE_LOADING,
} from './constants';
import { launchesFiltersReducer, launchesFiltersReadyReducer, pageLoadingReducer } from './reducer';

describe('filter reducer', () => {
  describe('launchesFiltersReducer', () => {
    test('should return old state on unknown action', () => {
      const oldState = [{ id: 0 }];
      expect(
        launchesFiltersReducer(oldState, {
          type: 'test',
        }),
      ).toBe(oldState);
    });

    test('should update entities in filter on UPDATE_FILTER_CONDITIONS', () => {
      const oldState = [
        {
          id: '0',
          conditions: [
            {
              value: 'foo',
            },
          ],
        },
        {
          id: '1',
          conditions: [
            {
              value: 'bar',
            },
          ],
        },
      ];
      const newState = launchesFiltersReducer(oldState, {
        type: UPDATE_FILTER_CONDITIONS,
        payload: {
          filterId: '1',
          conditions: [
            {
              value: 'baz',
            },
          ],
        },
      });
      expect(newState).toEqual([
        {
          id: '0',
          conditions: [
            {
              value: 'foo',
            },
          ],
        },
        {
          id: '1',
          conditions: [
            {
              value: 'baz',
            },
          ],
        },
      ]);
    });
  });

  describe('launchesFiltersReadyReducer', () => {
    test('should return old state on unknown action', () => {
      const oldState = true;
      expect(
        launchesFiltersReadyReducer(oldState, {
          type: 'unknownAction',
        }),
      ).toBe(oldState);
    });

    test('should return true on FETCH_USER_FILTERS_SUCCESS action', () => {
      expect(launchesFiltersReadyReducer(false, { type: FETCH_USER_FILTERS_SUCCESS })).toBe(true);
    });
  });

  describe('pageLoadingReducer', () => {
    test('should return initial state', () => {
      expect(pageLoadingReducer(undefined, {})).toBe(false);
    });

    test('should return old state on unknown action', () => {
      const oldState = false;
      expect(pageLoadingReducer(oldState, { type: 'foo' })).toBe(oldState);
    });

    test('should handle SET_PAGE_LOADING', () => {
      const payload = true;
      const newState = pageLoadingReducer(SET_PAGE_LOADING, {
        type: SET_PAGE_LOADING,
        payload,
      });
      expect(newState).toEqual(payload);
    });
  });
});


text:
<!DOCTYPE HTML>

    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="0; url=https://www.seqstat.com/">

    <title>Page Redirection</title>

    If you are not redirected automatically, follow this link to example.


text:
//
// Created by Mingqiu Wang on 1/22/16.
//

#ifndef SIMDNA_DATASTRUCTURE_H
#define SIMDNA_DATASTRUCTURE_H

#include <stdio.h>
#include <iostream>
#include <unordered_map>
#include <vector>

#include "../lib/Vector3D.h"
#include "Configure.h"

/*
 * ID of each nucleotide residue {strand No., base No.}
 *
 *     default constructor assigns both strand and base number as -1
 *     therefore if there exists a base number as -1, meaning there is not such base or it hasn't defined
 * */
class ID {
    int _strandID;
    int _baseID;
public:

    ID() : _strandID{-1}, _baseID{-1} {}
    ID(int s, int b) : _strandID{s}, _baseID{b} {}

    int strandID() const { return _strandID; }
    int baseID() const { return _baseID; }

    bool operator<(const ID &rhs) const {
        return _strandID < rhs._strandID || (rhs._strandID >= _strandID && _baseID < rhs._baseID);
    }
    bool operator==(const ID &other) const {
        return (_strandID == other._strandID && _baseID == other._baseID);
    }

};

std::ostream& operator<<(std::ostream& os, const ID &idnum);

struct IDHasher {
    int operator()(const ID& k) const {
        return ((std::hash<int>()(k.strandID())
                 ^ (std::hash<int>()(k.baseID()) << 1)^(std::hash<int>()(k.baseID()) << 1)) >> 1);
    }
};

struct pairhash {
public:
    template <typename T, typename U>
    std::size_t operator()(const std::pair<T, U> &x) const
    {
        return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
    }
};

/*
 * Nucleotide information (ID, pair residue ID, coordinate, etc..)
 *
 * */
class Nucleotide {
    ID _id;
    Vector3Dd _coordinate;
    ID _pairID;
    bool _isDS; // false if pair residue doesn't exist, _pairID == {-1, -1}
    bool _isBreak; // whether this residue belongs to axial discontinuity

public:
    Nucleotide() {}
    Nucleotide(const ID &IDnum, const Vector3Dd &coor, const ID &comID, bool isBreak) :
            _id{IDnum}, _pairID{comID}, _coordinate{coor},
            _isDS{ !((comID.strandID() == -1) && (comID.baseID() == -1))},
            _isBreak{ isBreak } {}

    const ID &id() const {return _id;}
    const ID &pairID() const {return _pairID;}
    const Vector3Dd &coordinate() const {return _coordinate;}
    bool withPair() const {return _isDS;}
    bool isDiscont() const { return _isBreak;}

};

/*
 * Axial discontinuity
 * A base pair belong to axial discontinuity
 * Type A: Neighbor to another discontinuity not by a crossover
 * Type B: Neighbor to another discontinuity by a crossover
 * Single: doesn't have pair
 *
 * For example: (assume all "=" duplex, "-" single strand)
 * ==i=c======a=b======d
 *            | |      |
 * k-j=e======f=g======h
 * a, b, f, and g are both type A and B; d and h are type B; i, j and c are type A; k is single
 * */
class AxialDiscontinuity {

    bool _typeA;
    bool _typeB;
    bool _single;
    std::pair<ID, ID> _ids;

public:

    AxialDiscontinuity() : _typeA(false), _typeB(false), _single(false) {}
    AxialDiscontinuity(const std::pair<ID, ID> &_ids) :
            _ids(_ids), _typeA(false), _typeB(false), _single(false) {}
    AxialDiscontinuity(const std::pair<ID, ID> &_ids, bool _typeA, bool _typeB, bool _single) :
            _typeA(_typeA), _typeB(_typeB), _single(_single), _ids(_ids) {}

    bool is_typeA() const { return _typeA; }
    void set_typeA(bool _typeA) { AxialDiscontinuity::_typeA = _typeA; }
    bool is_typeB() const { return _typeB; }
    void set_typeB(bool _typeB) { AxialDiscontinuity::_typeB = _typeB; }
    bool is_single() const { return _single; }
    const std::pair<ID, ID> &get_ids() const { return _ids; }

    static bool similar(const AxialDiscontinuity &a, const AxialDiscontinuity &b) {
        return a.is_typeA()==b.is_typeA()&&a.is_typeB()==b.is_typeB()&&
                a.is_single()==b.is_single();
    }
};

std::ostream& operator<<(std::ostream& os, const AxialDiscontinuity & hbp);

/*
 * Basic unit used in the simulation
 *
 * */
class Node {
    int _num;
    int _type; // 3 types
    std::vector<std::pair<ID,ID>> _ids;
    double _mass;
    Vector3Dd _position;
    double _vdWradii;
    bool _inHJ; // whether in a Holliday junction

public:

    Node() {}
    Node(int _type, const std::vector<std::pair<ID, ID>> &_ids,
         double _mass, const Vector3Dd &_position,
         double _vdWradii) : _type(_type), _ids(_ids), _mass(_mass),
                             _position(_position), _vdWradii(_vdWradii) {}

    void set_num(int _num) { Node::_num = _num; }
    int get_num() const { return _num; }
    int get_type() const { return _type; }
    void set_type(int _type) { Node::_type = _type; }
    const std::vector<std::pair<ID, ID>> &get_ids() const { return _ids; }
    void set_ids(const std::vector<std::pair<ID, ID>> &_ids) { Node::_ids = _ids; }
    double get_mass() const { return _mass; }
    void set_mass(double _mass) { Node::_mass = _mass; }
    const Vector3Dd &get_position() const { return _position; }
    void set_position(const Vector3Dd &_position) { Node::_position = _position; }
    double get_vdWradii() const { return _vdWradii; }
    void set_vdWradii(double _vdWradii) { Node::_vdWradii = _vdWradii; }
    bool is_inHJ() const { return _inHJ; }
    void set_inHJ(bool _inHJ) { Node::_inHJ = _inHJ; }
};

/*
 * Basic unit used in the simulation
 *
 *
 * */
class Edge {
    std::pair<int, int> _endsNode;
    std::pair<int, int> _types;
    std::pair<ID, ID> _endsHB;

    bool _ds; // whether is double strand
    bool _crossover; // whether is a crossover
    bool _isHJ; // whether is a Holliday junction
    bool _isStackJunc; // whether is in stacked junctions
    std::vector<std::pair<ID,ID>> _ids;
    double _stretchConstant;

public:
    Edge() {}
    Edge(const std::pair<int, int> &_endsNode, const std::pair<int, int> &_types,
         const std::pair<ID, ID> &_endsHB, bool _crossover,
         const std::vector<std::pair<ID, ID>> &_ids)
            : _endsNode(_endsNode), _types(_types), _endsHB(_endsHB), _crossover(_crossover),
              _ids(_ids), _isHJ(false), _isStackJunc(false)
    {
        _ds = _crossover ? _types.first == 1 && _types.second == 1 : _types.first != 3 && _types.second != 3;
        _stretchConstant = _ds ? STRETCH_DS : STRETCH_SS;
    }
    Edge(const std::pair<int, int> &_endsNode) // initialize stack only
            : _endsNode(_endsNode), _types({2,2}), _endsHB({ID{}, ID{}}), _ds(true), _crossover(false),
               _isHJ(false), _isStackJunc(true), _ids({}), _stretchConstant(STRETCH_SS/100) {}

    size_t length() const { return _ids.size(); }
    double get_stretchConstant() const { return _stretchConstant; }
    const std::pair<int, int> &get_endsNode() const { return _endsNode; }
    void set_endsNode(const std::pair<int, int> &_endsNode) { Edge::_endsNode = _endsNode; }
    const std::pair<int, int> &get_types() const { return _types; }
    void set_types(const std::pair<int, int> &_types) { Edge::_types = _types; }
    const std::pair<ID, ID> &get_endsHB() const { return _endsHB; }
    bool is_ds() const { return _ds; }
    bool is_crossover() const { return _crossover; }
    const std::vector<std::pair<ID, ID>> &get_ids() const { return _ids; }
    bool is_isHJ() const { return _isHJ; }
    void set_isHJ(bool _isHJ) { Edge::_isHJ = _isHJ; }
    bool is_isStackJunc() const { return _isStackJunc; }
};

/**
 * Maps ID with an arbitrary class, i.e., Edge, Node, etc.
 *      where Typename T is the type of the arbitrary class,
 *      all index starts from 1.
 */
template<typename T>
class Index {
    std::unordered_map<int, T> _member;
    std::unordered_map<ID, int, IDHasher> _index;
    int _size;

public:

    Index() : _size(0) {}

    int &findIndexFromID(ID id) {return _index[id];}
    T &findTypeFromIndex(int index) {return _member[index];}
    T &findTypeFromID(ID id) { return _member[_index[id]];}

    int size() {return _size;}
    const std::unordered_map<int, T> &member() const { return _member;}
    std::unordered_map<int, T> &updateMember() { return _member;}
    const std::unordered_map<ID, int, IDHasher> &index() const { return _index;}

    int idExists(ID id) const {
        // if id exists, return the index No., otherwise 0
        std::unordered_map<ID, int, IDHasher>::const_iterator a = _index.find(id);
        if ( a == _index.end()) return 0;
        else return a->second;
    }

    friend class AxialDiscons;
    friend class Nodes;
    friend class Edges;

};

class AxialDiscons : public Index<AxialDiscontinuity> {

public:
    void insert(std::pair<ID, ID> basePair, bool a, bool b, bool c) {
        auto index = this->idExists(basePair.first);
        if (index) {
            if (a) _member[index].set_typeA(true);
            if (b) _member[index].set_typeB(true);
        }
        else {
            ++_size;
            _member[_size] = AxialDiscontinuity{basePair, a, b, c};
            if (basePair.first.baseID()!=-1) _index[basePair.first] = _size;
            if (basePair.second.baseID()!=-1) _index[basePair.second] = _size;
        }
    }
};

class Nodes : public Index<Node> {
public:
    void insert(Node nd);
    int insertVir(Node nd);
};

class Edges : public Index<Edge> {
    std::unordered_map<std::pair<int, int>, int, pairhash> _indexEdge;
public:
    void insert(Edge eg) {
        ++_size;
        _member[_size] = eg;
        _indexEdge[eg.get_endsNode()] = _size;
        for (const auto &item : eg.get_ids()) {
            if (item.first.baseID() != -1) _index[item.first] = _size;
            if (item.second.baseID() != -1) _index[item.second] = _size;
        }
    }
    const Edge &findEdgeFromEnds(int a, int b) const {

        auto v = _indexEdge.find({a, b});
        if ( v == _indexEdge.end()) return _member.at(_indexEdge.at({b, a}));
        else return _member.at(v->second);

    }

};

class OrigamiGraph {
    Nodes _nodes;
    Edges _edges;
    std::vector<std::vector<int>> _origamiGraph;
    int _numHJ; // how many Holliday junctions
    std::vector<Edge> _HJ;
    std::vector<Edge> _crossovers;

public:

    void resizeGraph() { _origamiGraph.resize(_nodes.size()+1); }
    void insertNode(Node nd) { _nodes.insert(nd); }
    int insertVir(Node nd) { return _nodes.insertVir(nd);  }
    void insertEdge(Edge eg, int c1, int c2);
    bool findEdge(int id1, int id2) const;
    int findNodeType(ID id);
    int findNodeType(int a);
    int findNodeNum(ID id);
    const std::vector<std::pair<ID, ID>> &findIDsfromIndex(int a);
    const std::vector<std::vector<int>>& showGraph() const { return _origamiGraph; }
    int howManyNodes() { return _nodes.size();}
    Vector3Dd nodeCenter(int a) { return _nodes.findTypeFromIndex(a).get_position();}
    const Edges &get_edges() const { return _edges; }
    const Nodes &get_nodes() const { return _nodes; }
    const std::vector<Edge> &get_HJ() const { return _HJ; }
    const std::vector<Edge> &get_crossovers() const { return _crossovers; }
    const std::vector<int> connectFrom(int a) const { return _origamiGraph[a]; }
    void repCon(int a, int b, int c);

    int howMany4Ways() const { return _numHJ; }
    const Edge &findEdgeFromEnds(int a, int b) const {
        return _edges.findEdgeFromEnds(a, b);
    }
    const Node &findNodeFromNum(int a) { return _nodes.findTypeFromIndex(a);}

    void printAllNodes() {
        for (auto && item :_nodes.member())
            for (auto && item1 : item.second.get_ids())
                std::cout << item1.first << "\t" << item1.second << std::endl;
    }

/*
 * Find all Holliday junctions, complete _nodes and _edges
 * */
    void findHollidayJ();

};

class VirtualSite {
    int virNum;
    Vector3Dd coordinate;
    int end1;
    int end2;
    double weight1;
    double weight2;

public:
    VirtualSite(int virNum, const Vector3Dd &coordinate, int end1, int end2, double weight1, double weight2) : virNum(
            virNum), coordinate(coordinate), end1(end1), end2(end2), weight1(weight1), weight2(weight2) { }

    double getWeight2() const { return weight2; }
    int getVirNum() const { return virNum; }
    const Vector3Dd &getCoordinate() const { return coordinate; }
    int getEnd1() const { return end1; }
    int getEnd2() const { return end2; }
    double getWeight1() const { return weight1; }
};
#endif //SIMDNA_DATASTRUCTURE_H


text:
function love.conf(t)
	-- Love settings
	t.title = "Forest"	        -- The title of the window the game is in (string)
	t.author = "Josh Bothun"    -- The author of the game (string)
	t.identity = nil            -- The name of the save directory (string)
	t.version = 0.7             -- The LÖVE version this game was made for (number)
	t.console = false           -- Attach a console (boolean, Windows only)
	t.release = false           -- Enable release mode (boolean)
    t.screen.width = 1024       -- The window width (number)
    t.screen.height = 768       -- The window height (number)
    t.screen.fullscreen = false -- Enable fullscreen (boolean)
    t.screen.vsync = false      -- Enable vertical sync (boolean)
    t.screen.fsaa = 0           -- The number of FSAA-buffers (number)

	-- Modules
	t.modules.joystick = true   -- Enable the joystick module (boolean)
	t.modules.audio = true      -- Enable the audio module (boolean)
	t.modules.keyboard = true   -- Enable the keyboard module (boolean)
	t.modules.event = true      -- Enable the event module (boolean)
	t.modules.image = true      -- Enable the image module (boolean)
	t.modules.graphics = true   -- Enable the graphics module (boolean)
	t.modules.timer = true      -- Enable the timer module (boolean)
	t.modules.mouse = true      -- Enable the mouse module (boolean)
	t.modules.sound = true      -- Enable the sound module (boolean)
	t.modules.physics = false   -- Enable the physics module (boolean)

	-- Custom
	DEBUG = true
	VERSION = '0.0.3'
end


text:
import { Component } from '@angular/core';

import { OSW_NAVIGATION_DIRECTIVES } from '@osw/navigation/navigation';
import { OSW_TABLE_DIRECTIVES } from '@osw/table/table';
import { Cell, CellComponent } from '@osw/table/cell.component';

@Component({
	selector: 'epi-list',
	template: `
		<osw-navigation [isTranslucent]="true" [title]="title">
			<template osw-navigation-view>
				<osw-table [tableStyle]="'default'">
					<osw-table-list>
						<template osw-table-list-content>
							<osw-table-cell *ngFor="let cell of cells" [cell]="cell">
								{{cell.content}}
							</osw-table-cell>
						</template>
					</osw-table-list>
				</osw-table>
			</template>
		<osw-navigation>
	`,
	directives: [
		OSW_NAVIGATION_DIRECTIVES,
		OSW_TABLE_DIRECTIVES,
		CellComponent
	]
})
export class EpiListComponent {
	title: string = "List";

	cells: Cell[];

	constructor() {
		this.cells = [
			new Cell("My item 0"),
			new Cell("My item 1"),
			new Cell("My item 2"),
			new Cell("My item 3"),
			new Cell("My item 4"),
			new Cell("My item 5"),
			new Cell("My item 6"),
			new Cell("My item 7"),
			new Cell("My item 8"),
			new Cell("My item 9"),
			new Cell("My item 10"),
			new Cell("My item 11"),
		];
	}

}


text:
<project>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>chapter_002</artifactId>
    <version>2.0</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>ru.job4j</groupId>
        <artifactId>junior</artifactId>
        <version>2.0</version>
    </parent>

<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-checkstyle-plugin</artifactId>
			<version>2.17</version>
			<executions>
				<execution>
					<id>validate</id>
					<phase>validate</phase>
					<configuration>
						<configLocation>checkstyle.xml</configLocation>
						<encoding>UTF-8</encoding>
						<consoleOutput>true</consoleOutput>
						<failsOnError>true</failsOnError>
						<includeTestSourceDirectory>true</includeTestSourceDirectory>
					</configuration>
					<goals>
					<goal>check</goal>
					</goals>
				</execution>
			</executions>
		</plugin>
	</plugins>
    <extensions>
        <extension>
            <groupId>org.apache.maven.wagon</groupId>
            <artifactId>wagon-ssh</artifactId>
            <version>1.0-beta-7</version>
        </extension>
    </extensions>
</build>

</project>


text:
@interface GameScene : CCNode <CCTargetedTouchDelegate>
{
	CCLayer* blockLayer;
	//CCLayer *controlsLayer;

	NSString *touchedColor;

	NSArray* colors;
	NSMutableArray* blocks;
	NSMutableArray* touchedBlocks;
    NSMutableArray* touchedBlockColumns;

    NSMutableArray* traceLine;
    NSMutableArray* outlines;

    int totalScore;
    float score;
    int multiplier;

    int energyTotal;
    int myEnergy;

    int barWidth; //size of window should be calculated off png

    float bossAttack;
    float bossAttackFreq;
    float bossSuperAttack;
    float bossSuperAttackFreq;
    float attackCount;

    CCSprite* pauseButton;
    CCSprite* energyBar;
    float energyBarMovement;

    BOOL touchHappening;

    CCLabelBMFont* totalScoreLabel;
    CCLabelBMFont* multiplierLabel;
    CCLabelBMFont* scoreLabel;

    NSArray* test;

    enum blockPosition
    {
        doesNotTouch = 0,
        topLeft = 1,
        top = 2,
        topRight = 3,
        right = 4,
        bottomRight = 5,
        bottom = 6,
        bottomLeft = 7,
        left = 8
    };
}

@property int numOfGridRows;
@property int numOfGridCols;
@property int blockCount;
@property float offSetX,offSetY;

+(id) scene;

@end


text:
package com.adobe.acs.commons.workflow.bulk.execution.impl;

import com.adobe.acs.commons.workflow.bulk.execution.BulkWorkflowEngine;
import com.day.cq.commons.jcr.JcrConstants;
import com.day.cq.wcm.api.NameConstants;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.resource.AbstractResourceVisitor;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.jcr.resource.api.JcrResourceConstants;

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

public class ConfigResourceVisitor extends AbstractResourceVisitor {

    private static final String BULK_WORKFLOW_MANAGER_PAGE_FOLDER_PATH = "/etc/acs-commons/bulk-workflow-manager";
    private static final String NT_PAGE_CONTENT = "cq:PageContent";
    private static final String[] ACCEPTED_PRIMARY_TYPES = new String[]{NameConstants.NT_PAGE, NT_PAGE_CONTENT};
    private List<Resource> configurations = new ArrayList<Resource>();

    public final List<Resource> getConfigs() {
        return this.configurations;
    }

    @Override
    public final void accept(final Resource resource) {
        // Only accept the Root folder and cq:Page and cq:PageContent nodes; All other structures are uninteresting
        // to this functionality and may be very large
        if (StringUtils.startsWith(resource.getPath(), BULK_WORKFLOW_MANAGER_PAGE_FOLDER_PATH)) {
            final ValueMap properties = resource.adaptTo(ValueMap.class);
            final String primaryType = properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class);

            if (BULK_WORKFLOW_MANAGER_PAGE_FOLDER_PATH.equals(resource.getPath())
                    || ArrayUtils.contains(ACCEPTED_PRIMARY_TYPES, primaryType)) {
                super.accept(resource);
            }
        }
    }

    @Override
    protected void visit(final Resource resource) {
        final ValueMap properties = resource.adaptTo(ValueMap.class);

        // Ensure jcr:primaryType = cq:PageContent and
        // that the sling:resourceType is that of Bulk Workflow Manager Page
        if (NT_PAGE_CONTENT.equals(properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class))
                && StringUtils.equals(BulkWorkflowEngine.SLING_RESOURCE_TYPE,
                    properties.get(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, String.class))) {
            this.configurations.add(resource);
        }
    }
}


text:
<?php

/**
 * Get info of root device
 *
 * @phpstub
 *
 * @param resource $root_device
 *
 * @return array Return array wich contains the information of the root device (like location, url, udn and etc).
 */
function gupnp_device_info_get($root_device)
{
}


text:
package com.twitter.finagle.http.filter

import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.util.Future

/**
 * Validate request filter:
 *   400 Bad Request if the parameters are invalid.
 */
@deprecated("Being removed due to its limited utility", "2017-01-11")
class ValidateRequestFilter[REQUEST <: Request]
  extends SimpleFilter[REQUEST, Response] {

  def apply(request: REQUEST, service: Service[REQUEST, Response]): Future[Response] = {
    if (request.params.isValid) service(request)
    else Future.value(Response(request.version, Status.BadRequest))
  }
}

@deprecated("Being removed due to its limited utility", "2017-01-11")
object ValidateRequestFilter extends ValidateRequestFilter[Request]


text:
Gesmew.config do |config|
  # Example:
  # Uncomment to stop tracking inventory levels in the application
  # config.track_inventory_levels = false
end

Gesmew.user_class = <%= (options[:user_class].blank? ? "Gesmew::LegacyUser" : options[:user_class]).inspect %>


text:
CKEDITOR.plugins.setLang( 'preview', 'af', {
	preview: 'Voorbeeld'
});


text:
package fr.delcey.cinereminday.cloud_code_manager.beans;

/**
 * Created by Nino on 15/03/2017.
 */

public class CinedayCode {

    private String mCode;
    private boolean mAvailable;

    @SuppressWarnings("unused")
    public CinedayCode() { // Needed for Firebase deserialization

    }

    public CinedayCode(String code) {
        this.mCode = code;
        this.mAvailable = true;
    }

    public String getCode() {
        return mCode;
    }

    public void setCode(String code) {
        mCode = code;
    }

    public boolean isAvailable() {
        return mAvailable;
    }

    public void setAvailable(boolean available) {
        mAvailable = available;
    }

    @Override
    public String toString() {
        return "CinedayCode{" +
            "code='" + mCode + '\'' +
            ", available=" + mAvailable +
            '}';
    }
}


text:
/*
Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.6
Version: 2.0.0
Author: Sean Ngu
Website: http://www.seantheme.com/color-admin-v2.0/admin/angularjs/
    ----------------------------
        APPS CONTENT TABLE
    ----------------------------

    01. Handle Scrollbar

    02. Handle Sidebar - Menu
    03. Handle Sidebar - Mobile View Toggle
    04. Handle Sidebar - Minify / Expand
    05. Handle Page Load - Fade in
    06. Handle Panel - Remove / Reload / Collapse / Expand
    07. Handle Panel - Draggable
    08. Handle Tooltip & Popover Activation
    09. Handle Scroll to Top Button Activation

    10. Handle Theme & Page Structure Configuration
    11. Handle Theme Panel Expand
    12. Handle After Page Load Add Class Function - added in V1.2

    13. Handle Save Panel Position Function - added in V1.5
    14. Handle Draggable Panel Local Storage Function - added in V1.5
    15. Handle Reset Local Storage - added in V1.5

    16. Handle IE Full Height Page Compatibility - added in V1.6
    17. Handle Unlimited Nav Tabs - added in V1.6

    18. Handle Mobile Sidebar Scrolling Feature - added in V1.7

    19. Handle Top Menu - Unlimited Top Menu Render - added in V1.9
    20. Handle Top Menu - Sub Menu Toggle - added in V1.9
    21. Handle Top Menu - Mobile Sub Menu Toggle - added in V1.9
    22. Handle Top Menu - Mobile Top Menu Toggle - added in V1.9
    23. Handle Clear Sidebar Selection & Hide Mobile Menu - added in V1.9

    Application Controller
*/

/* 01. Handle Scrollbar
------------------------------------------------ */
var handleSlimScroll = function() {
    "use strict";
    $('[data-scrollbar=true]').each( function() {
        generateSlimScroll($(this));
    });
};
var generateSlimScroll = function(element) {
    if ($(element).attr('data-init')) {
        return;
    }
    var dataHeight = $(element).attr('data-height');
        dataHeight = (!dataHeight) ? $(element).height() : dataHeight;

    var scrollBarOption = {
        height: dataHeight,
        alwaysVisible: true
    };
    if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        $(element).css('height', dataHeight);
        $(element).css('overflow-x','scroll');
    } else {
        $(element).slimScroll(scrollBarOption);
    }
    $(element).attr('data-init', true);
};

/* 02. Handle Sidebar - Menu
------------------------------------------------ */
var handleSidebarMenu = function() {
    "use strict";
    $('.sidebar .nav > .has-sub > a').click(function() {
        var target = $(this).next('.sub-menu');
        var otherMenu = '.sidebar .nav > li.has-sub > .sub-menu';

        if ($('.page-sidebar-minified').length === 0) {
            $(otherMenu).not(target).slideUp(250, function() {
                $(this).closest('li').removeClass('expand');
            });
            $(target).slideToggle(250, function() {
                var targetLi = $(this).closest('li');
                if ($(targetLi).hasClass('expand')) {
                    $(targetLi).removeClass('expand');
                } else {
                    $(targetLi).addClass('expand');
                }
            });
        }
    });
    $('.sidebar .nav > .has-sub .sub-menu li.has-sub > a').click(function() {
        if ($('.page-sidebar-minified').length === 0) {
            var target = $(this).next('.sub-menu');
            $(target).slideToggle(250);
        }
    });
};

/* 03. Handle Sidebar - Mobile View Toggle
------------------------------------------------ */
var handleMobileSidebarToggle = function() {
    var sidebarProgress = false;
    $('.sidebar').bind('click touchstart', function(e) {
        if ($(e.target).closest('.sidebar').length !== 0) {
            sidebarProgress = true;
        } else {
            sidebarProgress = false;
            e.stopPropagation();
        }
    });

    $(document).bind('click touchstart', function(e) {
        if ($(e.target).closest('.sidebar').length === 0) {
            sidebarProgress = false;
        }
        if (!e.isPropagationStopped() && sidebarProgress !== true) {
            if ($('#page-container').hasClass('page-sidebar-toggled')) {
                sidebarProgress = true;
                $('#page-container').removeClass('page-sidebar-toggled');
            }
            if ($(window).width() <= 767) {
                if ($('#page-container').hasClass('page-right-sidebar-toggled')) {
                    sidebarProgress = true;
                    $('#page-container').removeClass('page-right-sidebar-toggled');
                }
            }
        }
    });

    $('[data-click=right-sidebar-toggled]').click(function(e) {
        e.stopPropagation();
        var targetContainer = '#page-container';
        var targetClass = 'page-right-sidebar-collapsed';
            targetClass = ($(window).width() < 979) ? 'page-right-sidebar-toggled' : targetClass;
        if ($(targetContainer).hasClass(targetClass)) {
            $(targetContainer).removeClass(targetClass);
        } else if (sidebarProgress !== true) {
            $(targetContainer).addClass(targetClass);
        } else {
            sidebarProgress = false;
        }
        if ($(window).width() < 480) {
            $('#page-container').removeClass('page-sidebar-toggled');
        }
        $(window).trigger('resize');
    });

    $('[data-click=sidebar-toggled]').click(function(e) {
        e.stopPropagation();
        var sidebarClass = 'page-sidebar-toggled';
        var targetContainer = '#page-container';

        if ($(targetContainer).hasClass(sidebarClass)) {
            $(targetContainer).removeClass(sidebarClass);
        } else if (sidebarProgress !== true) {
            $(targetContainer).addClass(sidebarClass);
        } else {
            sidebarProgress = false;
        }
        if ($(window).width() < 480) {
            $('#page-container').removeClass('page-right-sidebar-toggled');
        }
    });
};

/* 04. Handle Sidebar - Minify / Expand
------------------------------------------------ */
var handleSidebarMinify = function() {
    $('[data-click=sidebar-minify]').click(function(e) {
        e.preventDefault();
        var sidebarClass = 'page-sidebar-minified';
        var targetContainer = '#page-container';
        $('#sidebar [data-scrollbar="true"]').css('margin-top','0');
        $('#sidebar [data-scrollbar="true"]').removeAttr('data-init');
        $('#sidebar [data-scrollbar=true]').stop();
        if ($(targetContainer).hasClass(sidebarClass)) {
            $(targetContainer).removeClass(sidebarClass);
            if ($(targetContainer).hasClass('page-sidebar-fixed')) {
                if ($('#sidebar .slimScrollDiv').length !== 0) {
                    $('#sidebar [data-scrollbar="true"]').slimScroll({destroy: true});
                    $('#sidebar [data-scrollbar="true"]').removeAttr('style');
                }
                generateSlimScroll($('#sidebar [data-scrollbar="true"]'));
                $('#sidebar [data-scrollbar=true]').trigger('mouseover');
            } else if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
                if ($('#sidebar .slimScrollDiv').length !== 0) {
                    $('#sidebar [data-scrollbar="true"]').slimScroll({destroy: true});
                    $('#sidebar [data-scrollbar="true"]').removeAttr('style');
                }
                generateSlimScroll($('#sidebar [data-scrollbar="true"]'));
            }
        } else {
            $(targetContainer).addClass(sidebarClass);

            if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
                if ($(targetContainer).hasClass('page-sidebar-fixed')) {
                    $('#sidebar [data-scrollbar="true"]').slimScroll({destroy: true});
                    $('#sidebar [data-scrollbar="true"]').removeAttr('style');
                }
                $('#sidebar [data-scrollbar=true]').trigger('mouseover');
            } else {
                $('#sidebar [data-scrollbar="true"]').css('margin-top','0');
                $('#sidebar [data-scrollbar="true"]').css('overflow', 'visible');
            }
        }
        $(window).trigger('resize');
    });
};

/* 05. Handle Page Load - Fade in
------------------------------------------------ */
var handlePageContentView = function() {
    "use strict";
    $.when($('#page-loader').addClass('hide')).done(function() {
        $('#page-container').addClass('in');
    });
};

/* 06. Handle Panel - Remove / Reload / Collapse / Expand
------------------------------------------------ */
var panelActionRunning = false;
var handlePanelAction = function() {
    "use strict";

    if (panelActionRunning) {
        return false;
    }
    panelActionRunning = true;

    // remove
    $(document).on('hover', '[data-click=panel-remove]', function(e) {
        $(this).tooltip({
            title: 'Remove',
            placement: 'bottom',
            trigger: 'hover',
            container: 'body'
        });
        $(this).tooltip('show');
    });
    $(document).on('click', '[data-click=panel-remove]', function(e) {
        e.preventDefault();
        $(this).tooltip('destroy');
        $(this).closest('.panel').remove();
    });

    // collapse
    $(document).on('hover', '[data-click=panel-collapse]', function(e) {
        $(this).tooltip({
            title: 'Collapse / Expand',
            placement: 'bottom',
            trigger: 'hover',
            container: 'body'
        });
        $(this).tooltip('show');
    });
    $(document).on('click', '[data-click=panel-collapse]', function(e) {
        e.preventDefault();
        $(this).closest('.panel').find('.panel-body').slideToggle();
    });

    // reload
    $(document).on('hover', '[data-click=panel-reload]', function(e) {
        $(this).tooltip({
            title: 'Reload',
            placement: 'bottom',
            trigger: 'hover',
            container: 'body'
        });
        $(this).tooltip('show');
    });
    $(document).on('click', '[data-click=panel-reload]', function(e) {
        e.preventDefault();
        var target = $(this).closest('.panel');
        if (!$(target).hasClass('panel-loading')) {
            var targetBody = $(target).find('.panel-body');
            var spinnerHtml = '

';
            $(target).addClass('panel-loading');
            $(targetBody).prepend(spinnerHtml);
            setTimeout(function() {
                $(target).removeClass('panel-loading');
                $(target).find('.panel-loader').remove();
            }, 2000);
        }
    });

    // expand
    $(document).on('hover', '[data-click=panel-expand]', function(e) {
        $(this).tooltip({
            title: 'Expand / Compress',
            placement: 'bottom',
            trigger: 'hover',
            container: 'body'
        });
        $(this).tooltip('show');
    });
    $(document).on('click', '[data-click=panel-expand]', function(e) {
        e.preventDefault();
        var target = $(this).closest('.panel');
        var targetBody = $(target).find('.panel-body');
        var targetTop = 40;
        if ($(targetBody).length !== 0) {
            var targetOffsetTop = $(target).offset().top;
            var targetBodyOffsetTop = $(targetBody).offset().top;
            targetTop = targetBodyOffsetTop - targetOffsetTop;
        }

        if ($('body').hasClass('panel-expand') && $(target).hasClass('panel-expand')) {
            $('body, .panel').removeClass('panel-expand');
            $('.panel').removeAttr('style');
            $(targetBody).removeAttr('style');
        } else {
            $('body').addClass('panel-expand');
            $(this).closest('.panel').addClass('panel-expand');

            if ($(targetBody).length !== 0 && targetTop != 40) {
                var finalHeight = 40;
                $(target).find(' > *').each(function() {
                    var targetClass = $(this).attr('class');

                    if (targetClass != 'panel-heading' && targetClass != 'panel-body') {
                        finalHeight += $(this).height() + 30;
                    }
                });
                if (finalHeight != 40) {
                    $(targetBody).css('top', finalHeight + 'px');
                }
            }
        }
        $(window).trigger('resize');
    });
};

/* 07. Handle Panel - Draggable
------------------------------------------------ */
var handleDraggablePanel = function() {
    "use strict";
    var target = $('.panel').parent('[class*=col]');
    var targetHandle = '.panel-heading';
    var connectedTarget = '.row > [class*=col]';

    $(target).sortable({
        handle: targetHandle,
        connectWith: connectedTarget,
        stop: function(event, ui) {
            ui.item.find('.panel-title').append('');
            handleSavePanelPosition(ui.item);
        }
    });
};

/* 08. Handle Tooltip & Popover Activation
------------------------------------------------ */
var handelTooltipPopoverActivation = function() {
    "use strict";
    $('[data-toggle=tooltip]').tooltip();
    $('[data-toggle=popover]').popover();
};

/* 09. Handle Scroll to Top Button Activation
------------------------------------------------ */
var handleScrollToTopButton = function() {
    "use strict";
    $(document).scroll( function() {
        var totalScroll = $(document).scrollTop();

        if (totalScroll >= 200) {
            $('[data-click=scroll-top]').addClass('in');
        } else {
            $('[data-click=scroll-top]').removeClass('in');
        }
    });

    $('[data-click=scroll-top]').click(function(e) {
        e.preventDefault();
        $('html, body').animate({
            scrollTop: $("body").offset().top
        }, 500);
    });
};

/* 10. Handle Theme & Page Structure Configuration - added in V1.2
------------------------------------------------ */
var handleThemePageStructureControl = function() {
    // COOKIE - Theme File Setting
    if ($.cookie && $.cookie('theme')) {
        if ($('.theme-list').length !== 0) {
            $('.theme-list [data-theme]').closest('li').removeClass('active');
            $('.theme-list [data-theme="'+ $.cookie('theme') +'"]').closest('li').addClass('active');
        }
        var cssFileSrc = 'assets/css/theme/' + $.cookie('theme') + '.css';
        $('#theme').attr('href', cssFileSrc);
    }

    // COOKIE - Sidebar Styling Setting
    if ($.cookie && $.cookie('sidebar-styling')) {
        if ($('.sidebar').length !== 0 && $.cookie('sidebar-styling') == 'grid') {
            $('.sidebar').addClass('sidebar-grid');
            $('[name=sidebar-styling] option[value="2"]').prop('selected', true);
        }
    }

    // COOKIE - Header Setting
    if ($.cookie && $.cookie('header-styling')) {
        if ($('.header').length !== 0 && $.cookie('header-styling') == 'navbar-inverse') {
            $('.header').addClass('navbar-inverse');
            $('[name=header-styling] option[value="2"]').prop('selected', true);
        }
    }

    // COOKIE - Gradient Setting
    if ($.cookie && $.cookie('content-gradient')) {
        if ($('#page-container').length !== 0 && $.cookie('content-gradient') == 'enabled') {
            $('#page-container').addClass('gradient-enabled');
            $('[name=content-gradient] option[value="2"]').prop('selected', true);
        }
    }

    // COOKIE - Content Styling Setting
    if ($.cookie && $.cookie('content-styling')) {
        if ($('body').length !== 0 && $.cookie('content-styling') == 'black') {
            $('body').addClass('flat-black');
            $('[name=content-styling] option[value="2"]').prop('selected', true);
        }
    }

    // THEME - theme selection
    $('.theme-list [data-theme]').click(function() {
        var cssFileSrc = 'assets/css/theme/' + $(this).attr('data-theme') + '.css';
        $('#theme').attr('href', cssFileSrc);
        $('.theme-list [data-theme]').not(this).closest('li').removeClass('active');
        $(this).closest('li').addClass('active');
        $.cookie('theme', $(this).attr('data-theme'));
    });

    // HEADER - inverse or default
    $('.theme-panel [name=header-styling]').on('change', function() {
        var targetClassAdd = ($(this).val() == 1) ? 'navbar-default' : 'navbar-inverse';
        var targetClassRemove = ($(this).val() == 1) ? 'navbar-inverse' : 'navbar-default';
        $('#header').removeClass(targetClassRemove).addClass(targetClassAdd);
        $.cookie('header-styling',targetClassAdd);
    });

    // SIDEBAR - grid or default
    $('.theme-panel [name=sidebar-styling]').on('change', function() {
        if ($(this).val() == 2) {
            $('#sidebar').addClass('sidebar-grid');
            $.cookie('sidebar-styling', 'grid');
        } else {
            $('#sidebar').removeClass('sidebar-grid');
            $.cookie('sidebar-styling', 'default');
        }
    });

    // CONTENT - gradient enabled or disabled
    $('.theme-panel [name=content-gradient]').on('change', function() {
        if ($(this).val() == 2) {
            $('#page-container').addClass('gradient-enabled');
            $.cookie('content-gradient', 'enabled');
        } else {
            $('#page-container').removeClass('gradient-enabled');
            $.cookie('content-gradient', 'disabled');
        }
    });

    // CONTENT - default or black
    $(document).on('change', '.theme-panel [name=content-styling]', function() {
        if ($(this).val() == 2) {
            $('body').addClass('flat-black');
            $.cookie('content-styling', 'black');
        } else {
            $('body').removeClass('flat-black');
            $.cookie('content-styling', 'default');
        }
    });

    // SIDEBAR - fixed or default
    $(document).on('change', '.theme-panel [name=sidebar-fixed]', function() {
        if ($(this).val() == 1) {
            if ($('.theme-panel [name=header-fixed]').val() == 2) {
                alert('Default Header with Fixed Sidebar option is not supported. Proceed with Fixed Header with Fixed Sidebar.');
                $('.theme-panel [name=header-fixed] option[value="1"]').prop('selected', true);
                $('#header').addClass('navbar-fixed-top');
                $('#page-container').addClass('page-header-fixed');
            }
            $('#page-container').addClass('page-sidebar-fixed');
            if (!$('#page-container').hasClass('page-sidebar-minified')) {
                generateSlimScroll($('.sidebar [data-scrollbar="true"]'));
            }
        } else {
            $('#page-container').removeClass('page-sidebar-fixed');
            if ($('.sidebar .slimScrollDiv').length !== 0) {
                if ($(window).width() <= 979) {
                    $('.sidebar').each(function() {
                        if (!($('#page-container').hasClass('page-with-two-sidebar') && $(this).hasClass('sidebar-right'))) {
                            $(this).find('.slimScrollBar').remove();
                            $(this).find('.slimScrollRail').remove();
                            $(this).find('[data-scrollbar="true"]').removeAttr('style');
                            var targetElement = $(this).find('[data-scrollbar="true"]').parent();
                            var targetHtml = $(targetElement).html();
                            $(targetElement).replaceWith(targetHtml);
                        }
                    });
                } else if ($(window).width() > 979) {
                    $('.sidebar [data-scrollbar="true"]').slimScroll({destroy: true});
                    $('.sidebar [data-scrollbar="true"]').removeAttr('style');
                }
            }
            if ($('#page-container .sidebar-bg').length === 0) {
                $('#page-container').append('

');
            }
        }
    });

    // HEADER - fixed or default
    $(document).on('change', '.theme-panel [name=header-fixed]', function() {
        if ($(this).val() == 1) {
            $('#header').addClass('navbar-fixed-top');
            $('#page-container').addClass('page-header-fixed');
            $.cookie('header-fixed', true);
        } else {
            if ($('.theme-panel [name=sidebar-fixed]').val() == 1) {
                alert('Default Header with Fixed Sidebar option is not supported. Proceed with Default Header with Default Sidebar.');
                $('.theme-panel [name=sidebar-fixed] option[value="2"]').prop('selected', true);
                $('#page-container').removeClass('page-sidebar-fixed');
                if ($('#page-container .sidebar-bg').length === 0) {
                    $('#page-container').append('

');
                }
            }
            $('#header').removeClass('navbar-fixed-top');
            $('#page-container').removeClass('page-header-fixed');
            $.cookie('header-fixed', false);
        }
    });
};

/* 11. Handle Theme Panel Expand - added in V1.2
------------------------------------------------ */
var handleThemePanelExpand = function() {
    $(document).on('click', '[data-click="theme-panel-expand"]', function() {
        var targetContainer = '.theme-panel';
        var targetClass = 'active';
        if ($(targetContainer).hasClass(targetClass)) {
            $(targetContainer).removeClass(targetClass);
        } else {
            $(targetContainer).addClass(targetClass);
        }
    });
};

/* 12. Handle After Page Load Add Class Function - added in V1.2
------------------------------------------------ */
var handleAfterPageLoadAddClass = function() {
    if ($('[data-pageload-addclass]').length !== 0) {
        $(window).load(function() {
            $('[data-pageload-addclass]').each(function() {
                var targetClass = $(this).attr('data-pageload-addclass');
                $(this).addClass(targetClass);
            });
        });
    }
};

/* 13. Handle Save Panel Position Function - added in V1.5
------------------------------------------------ */
var handleSavePanelPosition = function(element) {
    "use strict";
    if ($('.ui-sortable').length !== 0) {
        var newValue = [];
        var index = 0;
        $.when($('.ui-sortable').each(function() {
            var panelSortableElement = $(this).find('[data-sortable-id]');
            if (panelSortableElement.length !== 0) {
                var columnValue = [];
                $(panelSortableElement).each(function() {
                    var targetSortId = $(this).attr('data-sortable-id');
                    columnValue.push({id: targetSortId});
                });
                newValue.push(columnValue);
            } else {
                newValue.push([]);
            }
            index++;
        })).done(function() {
            var targetPage = window.location.href;
                targetPage = targetPage.split('?');
                targetPage = targetPage[0];
            localStorage.setItem(targetPage, JSON.stringify(newValue));
            $(element).find('[data-id="title-spinner"]').delay(500).fadeOut(500, function() {
                $(this).remove();
            });
        });
    }
};

/* 14. Handle Draggable Panel Local Storage Function - added in V1.5
------------------------------------------------ */
var handleLocalStorage = function() {
    "use strict";
    if (typeof(Storage) !== 'undefined' && typeof(localStorage) !== 'undefined') {
        var targetPage = window.location.href;
            targetPage = targetPage.split('?');
            targetPage = targetPage[0];
        var panelPositionData = localStorage.getItem(targetPage);

        if (panelPositionData) {
            panelPositionData = JSON.parse(panelPositionData);
            var i = 0;
            $('.panel').parent('[class*="col-"]').each(function() {
                var storageData = panelPositionData[i];
                var targetColumn = $(this);
                if (storageData) {
                    $.each(storageData, function(index, data) {
                        var targetId = $('[data-sortable-id="'+ data.id +'"]').not('[data-init="true"]');
                        if ($(targetId).length !== 0) {
                            var targetHtml = $(targetId).clone();
                            $(targetId).remove();
                            $(targetColumn).append(targetHtml);
                            $('[data-sortable-id="'+ data.id +'"]').attr('data-init','true');
                        }
                    });
                }
                i++;
            });
        }
    } else {
        alert('Your browser is not supported with the local storage');
    }
};

/* 15. Handle Reset Local Storage - added in V1.5
------------------------------------------------ */
var handleResetLocalStorage = function() {
    "use strict";
    $(document).on('click', '[data-click=reset-local-storage]', function(e) {
        e.preventDefault();

        var targetModalHtml = ''+
        '
'+
        '
'+
        '
'+
        '
'+
        '                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>'+
        '
 Reset Local Storage Confirmation
'+
        '
'+
        '
'+
        '
Would you like to RESET all your saved widgets and clear Local Storage?
'+
        '
'+
        '
'+
        '                 No'+
        '                 Yes'+
        '
'+
        '
'+
        '
'+
        '
';

        $('body').append(targetModalHtml);
        $('[data-modal-id="reset-local-storage-confirmation"]').modal('show');
    });
    $(document).on('hidden.bs.modal', '[data-modal-id="reset-local-storage-confirmation"]', function(e) {
        $('[data-modal-id="reset-local-storage-confirmation"]').remove();
    });
    $(document).on('click', '[data-click=confirm-reset-local-storage]', function(e) {
        e.preventDefault();
        var localStorageName = window.location.href;
            localStorageName = localStorageName.split('?');
            localStorageName = localStorageName[0];
        localStorage.removeItem(localStorageName);

        location.reload();
    });
};

/* 16. Handle IE Full Height Page Compatibility - added in V1.6
------------------------------------------------ */
var handleIEFullHeightContent = function() {
    var userAgent = window.navigator.userAgent;
    var msie = userAgent.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        $('.vertical-box-row [data-scrollbar="true"][data-height="100%"]').each(function() {
            var targetRow = $(this).closest('.vertical-box-row');
            var targetHeight = $(targetRow).height();
            $(targetRow).find('.vertical-box-cell').height(targetHeight);
        });
    }
};

/* 17. Handle Unlimited Nav Tabs - added in V1.6
------------------------------------------------ */
var handleUnlimitedTabsRender = function() {

    // function handle tab overflow scroll width
    function handleTabOverflowScrollWidth(obj, animationSpeed) {
        var marginLeft = parseInt($(obj).css('margin-left'));
        var viewWidth = $(obj).width();
        var prevWidth = $(obj).find('li.active').width();
        var speed = (animationSpeed > -1) ? animationSpeed : 150;
        var fullWidth = 0;

        $(obj).find('li.active').prevAll().each(function() {
            prevWidth += $(this).width();
        });

        $(obj).find('li').each(function() {
            fullWidth += $(this).width();
        });

        if (prevWidth >= viewWidth) {
            var finalScrollWidth = prevWidth - viewWidth;
            if (fullWidth != prevWidth) {
                finalScrollWidth += 40;
            }
            $(obj).find('.nav.nav-tabs').animate({ marginLeft: '-' + finalScrollWidth + 'px'}, speed);
        }

        if (prevWidth != fullWidth && fullWidth >= viewWidth) {
            $(obj).addClass('overflow-right');
        } else {
            $(obj).removeClass('overflow-right');
        }

        if (prevWidth >= viewWidth && fullWidth >= viewWidth) {
            $(obj).addClass('overflow-left');
        } else {
            $(obj).removeClass('overflow-left');
        }
    }

    // function handle tab button action - next / prev
    function handleTabButtonAction(element, direction) {
        var obj = $(element).closest('.tab-overflow');
        var marginLeft = parseInt($(obj).find('.nav.nav-tabs').css('margin-left'));
        var containerWidth = $(obj).width();
        var totalWidth = 0;
        var finalScrollWidth = 0;

        $(obj).find('li').each(function() {
            if (!$(this).hasClass('next-button') && !$(this).hasClass('prev-button')) {
                totalWidth += $(this).width();
            }
        });

        switch (direction) {
            case 'next':
                var widthLeft = totalWidth + marginLeft - containerWidth;
                if (widthLeft <= containerWidth) {
                    finalScrollWidth = widthLeft - marginLeft;
                    setTimeout(function() {
                        $(obj).removeClass('overflow-right');
                    }, 150);
                } else {
                    finalScrollWidth = containerWidth - marginLeft - 80;
                }

                if (finalScrollWidth != 0) {
                    $(obj).find('.nav.nav-tabs').animate({ marginLeft: '-' + finalScrollWidth + 'px'}, 150, function() {
                        $(obj).addClass('overflow-left');
                    });
                }
                break;
            case 'prev':
                var widthLeft = -marginLeft;

                if (widthLeft <= containerWidth) {
                    $(obj).removeClass('overflow-left');
                    finalScrollWidth = 0;
                } else {
                    finalScrollWidth = widthLeft - containerWidth + 80;
                }
                $(obj).find('.nav.nav-tabs').animate({ marginLeft: '-' + finalScrollWidth + 'px'}, 150, function() {
                    $(obj).addClass('overflow-right');
                });
                break;
        }
    }

    // handle page load active tab focus
    function handlePageLoadTabFocus() {
        $('.tab-overflow').each(function() {
            var targetWidth = $(this).width();
            var targetInnerWidth = 0;
            var targetTab = $(this);
            var scrollWidth = targetWidth;

            $(targetTab).find('li').each(function() {
                var targetLi = $(this);
                targetInnerWidth += $(targetLi).width();

                if ($(targetLi).hasClass('active') && targetInnerWidth > targetWidth) {
                    scrollWidth -= targetInnerWidth;
                }
            });

            handleTabOverflowScrollWidth(this, 0);
        });
    }

    // handle tab next button click action
    $('[data-click="next-tab"]').click(function(e) {
        e.preventDefault();
        handleTabButtonAction(this,'next');
    });

    // handle tab prev button click action
    $('[data-click="prev-tab"]').click(function(e) {
        e.preventDefault();
        handleTabButtonAction(this,'prev');

    });

    // handle unlimited tabs responsive setting
    $(window).resize(function() {
        $('.tab-overflow .nav.nav-tabs').removeAttr('style');
        handlePageLoadTabFocus();
    });

    handlePageLoadTabFocus();
};

/* 18. Handle Mobile Sidebar Scrolling Feature - added in V1.7
------------------------------------------------ */
var handleMobileSidebar = function() {
    "use strict";
    if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        if ($('#page-container').hasClass('page-sidebar-minified')) {
            $('#sidebar [data-scrollbar="true"]').css('overflow', 'visible');
            $('.page-sidebar-minified #sidebar [data-scrollbar="true"]').slimScroll({destroy: true});
            $('.page-sidebar-minified #sidebar [data-scrollbar="true"]').removeAttr('style');
            $('.page-sidebar-minified #sidebar [data-scrollbar=true]').trigger('mouseover');
        }
    }

    var oriTouch = 0;
    $('.page-sidebar-minified .sidebar [data-scrollbar=true] a').bind('touchstart', function(e) {
        var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
        var touchVertical = touch.pageY;
        oriTouch = touchVertical - parseInt($(this).closest('[data-scrollbar=true]').css('margin-top'));
    });

    $('.page-sidebar-minified .sidebar [data-scrollbar=true] a').bind('touchmove',function(e){
        e.preventDefault();
        if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
            var touchVertical = touch.pageY;
            var elementTop = touchVertical - oriTouch;

            $(this).closest('[data-scrollbar=true]').css('margin-top', elementTop + 'px');
        }
    });

    $('.page-sidebar-minified .sidebar [data-scrollbar=true] a').bind('touchend', function(e) {
        var targetScrollBar = $(this).closest('[data-scrollbar=true]');
        var windowHeight = $(window).height();
        var sidebarTopPosition = parseInt($('#sidebar').css('padding-top'));
        var sidebarContainerHeight = $('#sidebar').height();
        oriTouch = $(targetScrollBar).css('margin-top');

        var sidebarHeight = sidebarTopPosition;
        $('.sidebar').not('.sidebar-right').find('.nav').each(function() {
            sidebarHeight += $(this).height();
        });
        var finalHeight = -parseInt(oriTouch) + $('.sidebar').height();
        if (finalHeight >= sidebarHeight && windowHeight <= sidebarHeight && sidebarContainerHeight <= sidebarHeight) {
            var finalMargin = windowHeight - sidebarHeight - 20;
            $(targetScrollBar).animate({marginTop: finalMargin + 'px'});
        } else if (parseInt(oriTouch) >= 0 || sidebarContainerHeight >= sidebarHeight) {
            $(targetScrollBar).animate({marginTop: '0px'});
        } else {
            finalMargin = oriTouch;
            $(targetScrollBar).animate({marginTop: finalMargin + 'px'});
        }
    });
};

/* 19. Handle Top Menu - Unlimited Top Menu Render - added in V1.9
------------------------------------------------ */
var handleUnlimitedTopMenuRender = function() {
    "use strict";
    // function handle menu button action - next / prev
    function handleMenuButtonAction(element, direction) {
        var obj = $(element).closest('.nav');
        var marginLeft = parseInt($(obj).css('margin-left'));
        var containerWidth = $('.top-menu').width() - 88;
        var totalWidth = 0;
        var finalScrollWidth = 0;

        $(obj).find('li').each(function() {
            if (!$(this).hasClass('menu-control')) {
                totalWidth += $(this).width();
            }
        });

        switch (direction) {
            case 'next':
                var widthLeft = totalWidth + marginLeft - containerWidth;
                if (widthLeft <= containerWidth) {
                    finalScrollWidth = widthLeft - marginLeft + 128;
                    setTimeout(function() {
                        $(obj).find('.menu-control.menu-control-right').removeClass('show');
                    }, 150);
                } else {
                    finalScrollWidth = containerWidth - marginLeft - 128;
                }

                if (finalScrollWidth != 0) {
                    $(obj).animate({ marginLeft: '-' + finalScrollWidth + 'px'}, 150, function() {
                        $(obj).find('.menu-control.menu-control-left').addClass('show');
                    });
                }
                break;
            case 'prev':
                var widthLeft = -marginLeft;

                if (widthLeft <= containerWidth) {
                    $(obj).find('.menu-control.menu-control-left').removeClass('show');
                    finalScrollWidth = 0;
                } else {
                    finalScrollWidth = widthLeft - containerWidth + 88;
                }
                $(obj).animate({ marginLeft: '-' + finalScrollWidth + 'px'}, 150, function() {
                    $(obj).find('.menu-control.menu-control-right').addClass('show');
                });
                break;
        }
    }

    // handle page load active menu focus
    function handlePageLoadMenuFocus() {
        var targetMenu = $('.top-menu .nav');
        var targetList = $('.top-menu .nav > li');
        var targetActiveList = $('.top-menu .nav > li.active');
        var targetContainer = $('.top-menu');

        var marginLeft = parseInt($(targetMenu).css('margin-left'));
        var viewWidth = $(targetContainer).width() - 128;
        var prevWidth = $('.top-menu .nav > li.active').width();
        var speed = 0;
        var fullWidth = 0;

        $(targetActiveList).prevAll().each(function() {
            prevWidth += $(this).width();
        });

        $(targetList).each(function() {
            if (!$(this).hasClass('menu-control')) {
                fullWidth += $(this).width();
            }
        });

        if (prevWidth >= viewWidth) {
            var finalScrollWidth = prevWidth - viewWidth + 128;
            $(targetMenu).animate({ marginLeft: '-' + finalScrollWidth + 'px'}, speed);
        }

        if (prevWidth != fullWidth && fullWidth >= viewWidth) {
            $(targetMenu).find('.menu-control.menu-control-right').addClass('show');
        } else {
            $(targetMenu).find('.menu-control.menu-control-right').removeClass('show');
        }

        if (prevWidth >= viewWidth && fullWidth >= viewWidth) {
            $(targetMenu).find('.menu-control.menu-control-left').addClass('show');
        } else {
            $(targetMenu).find('.menu-control.menu-control-left').removeClass('show');
        }
    }

    // handle menu next button click action
    $('[data-click="next-menu"]').click(function(e) {
        e.preventDefault();
        handleMenuButtonAction(this,'next');
    });

    // handle menu prev button click action
    $('[data-click="prev-menu"]').click(function(e) {
        e.preventDefault();
        handleMenuButtonAction(this,'prev');

    });

    // handle unlimited menu responsive setting
    $(window).resize(function() {
        $('.top-menu .nav').removeAttr('style');
        handlePageLoadMenuFocus();
    });

    handlePageLoadMenuFocus();
};

/* 20. Handle Top Menu - Sub Menu Toggle - added in V1.9
------------------------------------------------ */
var handleTopMenuSubMenu = function() {
    "use strict";
    $('.top-menu .sub-menu .has-sub > a').click(function() {
        var target = $(this).closest('li').find('.sub-menu').first();
        var otherMenu = $(this).closest('ul').find('.sub-menu').not(target);
        $(otherMenu).not(target).slideUp(250, function() {
            $(this).closest('li').removeClass('expand');
        });
        $(target).slideToggle(250, function() {
            var targetLi = $(this).closest('li');
            if ($(targetLi).hasClass('expand')) {
                $(targetLi).removeClass('expand');
            } else {
                $(targetLi).addClass('expand');
            }
        });
    });
};

/* 21. Handle Top Menu - Mobile Sub Menu Toggle - added in V1.9
------------------------------------------------ */
var handleMobileTopMenuSubMenu = function() {
    "use strict";
    $('.top-menu .nav > li.has-sub > a').click(function() {
        if ($(window).width() <= 767) {
            var target = $(this).closest('li').find('.sub-menu').first();
            var otherMenu = $(this).closest('ul').find('.sub-menu').not(target);
            $(otherMenu).not(target).slideUp(250, function() {
                $(this).closest('li').removeClass('expand');
            });
            $(target).slideToggle(250, function() {
                var targetLi = $(this).closest('li');
                if ($(targetLi).hasClass('expand')) {
                    $(targetLi).removeClass('expand');
                } else {
                    $(targetLi).addClass('expand');
                }
            });
        }
    });
};

/* 22. Handle Top Menu - Mobile Top Menu Toggle - added in V1.9
------------------------------------------------ */
var handleTopMenuMobileToggle = function() {
    "use strict";
    $('[data-click="top-menu-toggled"]').click(function() {
        $('.top-menu').slideToggle(250);
    });
};

/* 23. Handle Clear Sidebar Selection & Hide Mobile Menu - added in V1.9
------------------------------------------------ */
var handleClearSidebarSelection = function() {
    $('.sidebar .nav > li, .sidebar .nav .sub-menu').removeClass('expand').removeAttr('style');
};
var handleClearSidebarMobileSelection = function() {
    $('#page-container').removeClass('page-sidebar-toggled');
};

/* Application Controller
------------------------------------------------ */
var App = function () {
	"use strict";

	return {
		init: function () {
		    this.initLocalStorage();
		    this.initSidebar();
		    this.initTopMenu();
		    this.initPageLoad();
		    this.initComponent();
		    this.initThemePanel();
		},
		initSidebar: function() {
			handleSidebarMenu();
			handleMobileSidebarToggle();
			handleSidebarMinify();
			handleMobileSidebar();
		},
		initSidebarSelection: function() {
		    handleClearSidebarSelection();
		},
		initSidebarMobileSelection: function() {
		    handleClearSidebarMobileSelection();
		},
		initTopMenu: function() {
			handleUnlimitedTopMenuRender();
			handleTopMenuSubMenu();
			handleMobileTopMenuSubMenu();
			handleTopMenuMobileToggle();
		},
		initPageLoad: function() {
			handlePageContentView();
		},
		initComponent: function() {
			handleDraggablePanel();
			handleIEFullHeightContent();
			handleSlimScroll();
			handleUnlimitedTabsRender();
			handlePanelAction();
			handelTooltipPopoverActivation();
			handleScrollToTopButton();
			handleAfterPageLoadAddClass();
		},
		initLocalStorage: function() {
		    handleLocalStorage();
		},
		initThemePanel: function() {
			handleThemePageStructureControl();
			handleThemePanelExpand();
		    handleResetLocalStorage();
		},
		scrollTop: function() {
            $('html, body').animate({
                scrollTop: $('body').offset().top
            }, 0);
		}
  };
}();