text:
package org.noorganization.instalist.presenter.implementation;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import org.noorganization.instalist.model.Tag;
import org.noorganization.instalist.presenter.ITagController;
import org.noorganization.instalist.presenter.event.Change;
import org.noorganization.instalist.presenter.event.TagChangedMessage;
import org.noorganization.instalist.provider.internal.TagProvider;

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

import de.greenrobot.event.EventBus;

public class TagController implements ITagController {

    private static TagController mInstance;

    private EventBus mBus;
    private ContentResolver mResolver;

    private TagController(Context _context) {
        mBus = EventBus.getDefault();
        mResolver = _context.getContentResolver();
    }

    static ITagController getInstance(Context _context) {
        if (mInstance == null) {
            mInstance = new TagController(_context);
        }
        return mInstance;
    }

    @Override
    public Tag createTag(String _title) {
        if (_title == null) {
            return null;
        }
        Cursor tagCursor = mResolver.query(Uri.parse(TagProvider.MULTIPLE_TAG_CONTENT_URI), Tag.COLUMN.ALL_COLUMNS, Tag.COLUMN.NAME + "= ?", new String[]{_title}, null, null);
        if (tagCursor == null || tagCursor.getCount() > 0) {
            if (tagCursor != null) {
                tagCursor.close();
            }
            return null;
        }

        tagCursor.close();

        Tag tag = new Tag(_title);
        Uri tagUri = mResolver.insert(Uri.parse(TagProvider.MULTIPLE_TAG_CONTENT_URI), tag.toContentValues());
        // insertion went wrong
        if (tagUri == null) {
            return null;
        }
        tag.mUUID = tagUri.getLastPathSegment();
        mBus.post(new TagChangedMessage(Change.CREATED, tag));
        return tag;
    }

    @Override
    public Tag renameTag(Tag _toRename, String _newTitle) {
        if (_toRename == null) {
            return null;
        }
        if (_toRename.mName.equals(_newTitle)) {
            return _toRename;
        }

        Tag toChange = findById(_toRename.mUUID);
        if (toChange == null || _newTitle == null) {
            return _toRename;
        }

        // check if name was changed
        Cursor cursor = mResolver.query(Uri.parse(TagProvider.MULTIPLE_TAG_CONTENT_URI),
                Tag.COLUMN.ALL_COLUMNS, Tag.COLUMN.NAME + "=? AND " + Tag.COLUMN.ID + " <> ?",
                new String[]{_newTitle, _toRename.mUUID},
                null);
        if (cursor == null || cursor.getCount() > 0) {
            if (cursor != null) {
                cursor.close();
            }
            return _toRename;
        }
        cursor.close();

        toChange.mName = _newTitle;
        int updatedRows = mResolver.update(Uri.parse(TagProvider.SINGLE_TAG_CONTENT_URI.replace("*", toChange.mUUID)), toChange.toContentValues(), null, null);

        if (updatedRows == 0) {
            return _toRename;
        }

        mBus.post(new TagChangedMessage(Change.CHANGED, toChange));
        return toChange;
    }

    @Override
    public void removeTag(Tag _toRemove) {
        if (_toRemove == null) {
            return;
        }
        /*
        List<TaggedProduct> taggedProducts = Select.from(TaggedProduct.class).
                where(Condition.prop(TaggedProduct.ATTR_TAG).eq(_toRemove.getId())).list();
        IProductController productController = ControllerFactory.getProductController();
        for (TaggedProduct toNotify : taggedProducts) {
            productController.removeTagFromProduct(toNotify.mProduct, toNotify.mTag);
        }
        */
        int removedRows = mResolver.delete(Uri.parse(TagProvider.SINGLE_TAG_CONTENT_URI.replace("*", _toRemove.mUUID)), null, null);
        if (removedRows == 0) {
            return;
        }

        mBus.post(new TagChangedMessage(Change.DELETED, _toRemove));
    }

    @Override
    public Tag findById(String _uuid) {
        Cursor cursor = mResolver.query(Uri.parse(TagProvider.SINGLE_TAG_CONTENT_URI.replace("*", _uuid)), Tag.COLUMN.ALL_COLUMNS, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            if (cursor != null) {
                cursor.close();
            }
            return null;
        }
        cursor.moveToFirst();
        Tag tag = new Tag();
        tag.mUUID = cursor.getString(cursor.getColumnIndex(Tag.COLUMN.ID));
        tag.mName = cursor.getString(cursor.getColumnIndex(Tag.COLUMN.NAME));
        cursor.close();
        return tag;
    }

    @Override
    public Tag findByName(String _name) {
        Cursor cursor = mResolver.query(Uri.parse(TagProvider.MULTIPLE_TAG_CONTENT_URI),
                Tag.COLUMN.ALL_COLUMNS,
                Tag.COLUMN.NAME + "=?",
                new String[]{_name}, null);
        if (cursor == null || cursor.getCount() == 0) {
            if (cursor != null) {
                cursor.close();
            }
            return null;
        }
        cursor.moveToFirst();
        Tag tag = new Tag();
        tag.mUUID = cursor.getString(cursor.getColumnIndex(Tag.COLUMN.ID));
        tag.mName = cursor.getString(cursor.getColumnIndex(Tag.COLUMN.NAME));
        cursor.close();
        return tag;
    }

    @Override
    public List<Tag> listAll() {
        Cursor tagCursor = mResolver.query(
                Uri.parse(TagProvider.MULTIPLE_TAG_CONTENT_URI),
                Tag.COLUMN.ALL_COLUMNS,
                null, null, null);
        if (tagCursor == null) {
            Log.e(getClass().getCanonicalName(), "Querying for tags failed. " +
                    "Returning error.");
            return null;
        }
        ArrayList<Tag> rtn = new ArrayList<>(tagCursor.getCount());

        try {
            while (tagCursor.moveToNext()) {
                Tag tag = new Tag();
                tag.mUUID = tagCursor.getString(tagCursor.getColumnIndex(Tag.COLUMN.ID));
                tag.mName = tagCursor.getString(tagCursor.getColumnIndex(Tag.COLUMN.NAME));
                rtn.add(tag);
            }
        } finally {
            tagCursor.close();
        }
        return rtn;
    }
}


text:
module HalfAndHalf

  class Variant
    attr_accessor :name, :experiment

    def initialize(args={})
      @result = args[:result]
      @name = args[:name] || default_name
      @experiment = args[:experiment]
    end

    def default_name
      raise NotImplementedError
    end

    def control?
      raise NotImplementedError
    end

    def treatment?
      raise NotImplementedError
    end

    def call(*args)
      if @result.respond_to?(:call)
        @result.call(*args)
      else
        @result
      end
    end

    def events
      experiment.events.map do |name|
        HalfAndHalf::Event.new(
          name: name,
          variant: self
        )
      end
    end

    def get_event(name)
      events.find do |event|
        event.name.to_sym == name.to_sym
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
Wsus-client CHANGELOG
==============
This file is used to list changes made in each version of the wsus-client cookbook.

1.2.0 (2015-08-07)
------------------
- [PR 17](https://github.com/criteo-cookbooks/wsus-client/pull/14) - Speed up LWRP by searching updates only once
- [PR 15](https://github.com/criteo-cookbooks/wsus-client/pull/15) - Log more information before downloading and installing updates

1.1.0 (2015-06-18)
------------------
- Expose new wsus_client_update LWRP to synchronously download or install updates
- [PR 9](https://github.com/criteo-cookbooks/wsus-client/pull/9) - Fix the client-side detection
- [PR 11](https://github.com/criteo-cookbooks/wsus-client/pull/11) - Allow string values for automatic_update_behavior and schedule_install_day
- Add chefspec and rspec tests!

1.0.1 (2015-06-03)
------------------
- Fix README.md for chef supermarket

1.0.0 (2015-06-03)
------------------
- Workaround foodcritic false positive
- Rename attribute `disable_windows_update_acces` to `disable_windows_update_access`
- Explicitly set attribute value of `detection_frequency` to 22 hours
- Force WU detection on configuration change
- Complete README.md

0.1.3 (2015-01-29)
------------------
- Fail chef run on guard failure
- Configure basic rake tasks and travis build

0.1.2 (2014-09-15)
------------------
-  Fix update script guard condition

0.1.1 (2014-09-15)
------------------
- Add windows supports in metadata

0.1.0 (2014-08-27)
------------------
- Initial release of wsus-client
- Client recipes do nothing on non-windows platform
- Add client recipes that configures automatic updates and initiates download and install


text:
/**
 * @fileoverview generator:ts_migration_exports_shim.ts
 * original_file:third_party/javascript/node_modules/tsickle/test_files/ts_migration_exports_shim.no_externs/correct_default_shorthand.ts
 * pintomodule absent in original_file
 */
goog.module('project.CorrectDefaultShorthand');
goog.module.declareLegacyNamespace();
var mainModule = goog.require('test_files.ts_migration_exports_shim.no_externs.correct_default_shorthand');
exports = mainModule.MyDefaultType;


text:
package poussecafe.processing;

public class ThreadAssignment {

    public ThreadAssignment(int threadId) {
        this.threadId = threadId;
    }

    private int threadId;

    public int threadId() {
        return threadId;
    }

    private int queuedGroups;

    public void queueGroup() {
        ++queuedGroups;
    }

    public void unqueueGroup() {
        --queuedGroups;
    }

    public boolean noGroupsQueued() {
        return queuedGroups == 0;
    }

    public int queuedGroups() {
        return queuedGroups;
    }
}


text:
import play.api._
import play.api.mvc._

import play.api.Logger
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits.defaultContext

object Global extends WithFilters() {

}


text:
BEGIN_INANITY_AUDIO

SdlDevice::SdlDevice(ptr<SdlSystem> system, uint32_t samplesPerSecond, uint8_t channelsCount)
: system(system)
{
  BEGIN_TRY();

  SDL_AudioSpec spec, actualSpec;
  SDL_zero(spec);
  spec.freq = samplesPerSecond;
  spec.format = AUDIO_F32;
  spec.channels = channelsCount;
  spec.samples = 4096;
  spec.callback = &SdlDevice::StaticCallback;
  spec.userdata = this;

  deviceId = SDL_OpenAudioDevice(nullptr, 0, &spec, &actualSpec, 0);
  if(!deviceId)
    THROW_SECONDARY("Can't open audio device", Platform::Sdl::Error());

  SDL_PauseAudioDevice(deviceId, 0);

  END_TRY("Can't create SDL audio device");
}

SdlDevice::~SdlDevice()
{
  SDL_CloseAudioDevice(deviceId);
}

void SdlDevice::StaticCallback(void* userdata, uint8_t* stream, int len)
{
  ((SdlDevice*)userdata)->Callback((Math::vec2*)stream, len / (sizeof(float) * 2));
}

void SdlDevice::Callback(Math::vec2* data, size_t count)
{
  std::fill(data, data + count, Math::vec2());
  for(auto player : players)
  {
    player->Read(data, count);
  }
}

void SdlDevice::RegisterPlayer(SdlPlayer* player)
{
  players.insert(player);
}

void SdlDevice::UnregisterPlayer(SdlPlayer* player)
{
  players.erase(player);
}

ptr<Sound> SdlDevice::CreateBufferedSound(ptr<Source> source)
{
  return NEW(SdlSound(this, source));
}

ptr<Sound> SdlDevice::CreateStreamedSound(ptr<Source> source)
{
  return NEW(SdlSound(this, source));
}

void SdlDevice::SetListenerPosition(const Math::vec3& position)
{
  // not implemented
}

void SdlDevice::SetListenerOrientation(const Math::vec3& forward, const Math::vec3& up)
{
  // not implemented
}

void SdlDevice::SetListenerVelocity(const Math::vec3& velocity)
{
  // not implemented
}

END_INANITY_AUDIO


text:
<?php

/* guestbook_add_action.php Starter file Revision 6 10-21-15 10:00 am

Requirements:
a) Please do not remove any of my comments in this code. I need them for grading.
b) Type code for only one step at a time, then run it in your browser to test it before moving to the next step.
Some of the code will not display any output, but you still need to test it to be sure there are no error messages.
Trouble-shooting is very difficult if many steps are entered at once. Do not ask me for help with your code if you are
not testing one step at a time!

==========================================================================================================
PLEASE DO NOT ATTEMPT TO WORK THROUGH THIS FILE WITHOUT FOLLOWING MY INSTRUCTIONS IN ASSIGNMENT 5, PART 2.
I HAVE A SPECIFIC SERIES OF STEPS I WOULD LIKE YOU TO FOLLOW.
==========================================================================================================

*/

// HEADER

// 1. Update the Header information below (all 3 lines).

/*
File Name: guestbook_add_action.php
Date: 10/09/2015
Programmer: Keith Murphy
*/

// ==========================================================
// VARIABLES

include_once "includes/php_header.php";

$styles_page = "home.css";
$heading = "Contact Us";
$missing_count = 0;

// ==========================================================
// FUNCTIONS

include_once "includes/cas225_functions.php";

// =======================================
// HTML HEADER ?>

<?php include_once "includes/html_header.php" ?>

<?php

// FUNCTION CALLS

// -- CHECK EACH FIELD FOR MISSING DATA

check_submitted("name", "text", $missing_count);

check_submitted("email", "text", $missing_count);

check_submitted("comment", "textarea", $missing_count);

check_submitted("mail", "checkbox", $missing_count);

// 4a. Enter your function call for count_errors below this comment. There should be only one line of code.

count_errors($missing_count);

// Below this point is your our old code for checking for missing data.
// Notice that you had more code, and it did less -- it didn't track how many fields were missing.
// Once you create the functions and call them, please delete the $counter line and the 'if' blocks in this section.

// -- SANITIZE FIELDS (REMOVE DANGEROUS CHARACTERS) -- text boxes and textarea only

sanitize("name", "text", $_POST["name"]);

sanitize("email", "text", $_POST["email"]);

sanitize("comment", "textarea", $_POST["comment"]);

// Below this point is your our old code for checking for sanitizing the data.
// Notice that you had a lot more code, and it did less -- we didn't escape quote marks in the previous version.
// Once you create the functions and call them, please delete the old code in this section.

// -- DISPLAY OUTPUT

echo "
You submitted the following information:
";
echo "
";

display_data("name", "text", $_POST["name"]);

display_data("email", "text", $_POST["email"]);

display_data("comment", "textarea", $_POST["comment"]);

display_data("mail", "checkbox", $_POST["mail"]);

echo "
"; // close #formData

?>

Return to Form

<?php include_once "includes/footer.php"; ?>


text:
class Album < ActiveRecord::Base
  has_many :tracks
  belongs_to :artist
end


text:
/*************************************************************************/
/*                                                                       */
/*                  Language Technologies Institute                      */
/*                     Carnegie Mellon University                        */
/*                        Copyright (c) 2001                             */
/*                        All Rights Reserved.                           */
/*                                                                       */
/*  Permission is hereby granted, free of charge, to use and distribute  */
/*  this software and its documentation without restriction, including   */
/*  without limitation the rights to use, copy, modify, merge, publish,  */
/*  distribute, sublicense, and/or sell copies of this work, and to      */
/*  permit persons to whom this work is furnished to do so, subject to   */
/*  the following conditions:                                            */
/*   1. The code must retain the above copyright notice, this list of    */
/*      conditions and the following disclaimer.                         */
/*   2. Any modifications must be clearly marked as such.                */
/*   3. Original authors' names are not deleted.                         */
/*   4. The authors' names are not used to endorse or promote products   */
/*      derived from this software without specific prior written        */
/*      permission.                                                      */
/*                                                                       */
/*  CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK         */
/*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING      */
/*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT   */
/*  SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE      */
/*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    */
/*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   */
/*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          */
/*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       */
/*  THIS SOFTWARE.                                                       */
/*                                                                       */
/*************************************************************************/
/*             Author:  Alan W Black (awb@cs.cmu.edu)                    */
/*               Date:  August 2000                                      */
/*************************************************************************/
/*                                                                       */
/*  Converts ascii shorts to ascii mulaw                                 */
/*                                                                       */
/*************************************************************************/
#include <stdio.h>
#include "cst_wave.h"

int main(int argc, char **argv)
{
    int s;

    while (scanf("%d\n",&s) != EOF)
	printf("%d\n",(int)cst_short_to_ulaw(s));

    return 0;
}


text:
    <meta charset="utf-8">
    <title>A fullscreen Peepers client</title>

      Peepers URL
      <input id="imgSource" name="imgSource" type="text" value="http://"/>
      <button onclick="updateImageSource(this, event)">Start</button>

Press Esc to toggle controls.

        See instructions if you're
        having problems.


text:
package annis.gui.controlpanel;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.vaadin.data.Container;
import com.vaadin.data.Property;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.data.util.ItemSorter;
import com.vaadin.ui.AbstractSelect;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.ProgressBar;

import annis.gui.AnnisUI;
import annis.gui.components.HelpButton;
import annis.gui.objects.QueryUIState;
import annis.libgui.Background;
import annis.libgui.Helper;
import annis.service.objects.CorpusConfig;
import annis.service.objects.CorpusConfigMap;
import annis.service.objects.OrderType;
import annis.service.objects.SegmentationList;

/**
 *
 * @author Thomas Krause <krauseto@hu-berlin.de>
 * @author Benjamin Weißenfels <b.pixeldrama@gmail.com>
 */
public class SearchOptionsPanel extends FormLayout
{

  public static final String NULL_SEGMENTATION_VALUE = "tokens (default)";

  public static final String KEY_DEFAULT_CONTEXT_SEGMENTATION = "default-context-segmentation";

  public static final String KEY_DEFAULT_BASE_TEXT_SEGMENTATION = "default-base-text-segmentation";

  public static final String KEY_MAX_CONTEXT_LEFT = "max-context-left";

  public static final String KEY_MAX_CONTEXT_RIGHT = "max-context-right";

  public static final String KEY_CONTEXT_STEPS = "context-steps";

  public static final String KEY_DEFAULT_CONTEXT = "default-context";

  public static final String KEY_RESULT_PER_PAGE = "results-per-page";

  public static final String DEFAULT_CONFIG = "default-config";

  public static final int DEFAULT_CONTEXT = 5;
  public static final int DEFAULT_CONTEXT_STEPS = 5;
  public static final int DEFAULT_MAX_CONTEXT = 20;

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

  private final ComboBox cbLeftContext;

  private final ComboBox cbRightContext;

  private final ComboBox cbResultsPerPage;

  private final ComboBox cbSegmentation;
  private final HelpButton segmentationHelp;

  private final ComboBox cbOrder;

  // TODO: make this configurable
  private static final List<Integer> PREDEFINED_PAGE_SIZES = ImmutableList.of(
    1, 2, 5, 10, 20, 25
  );

  public static final List<Integer> PREDEFINED_CONTEXTS = ImmutableList.of(
    0, 1, 2, 5, 10, 20
  );

  private final ProgressBar pbLoadConfig;

  private final BeanItemContainer<OrderType> orderContainer
    = new BeanItemContainer<>(OrderType.class,
      Lists.newArrayList(OrderType.values()));
  private final IndexedContainer contextContainerLeft = new IndexedContainer();
  private final IndexedContainer contextContainerRight = new IndexedContainer();
  private final IndexedContainer segmentationContainer = new IndexedContainer();
  private final IndexedContainer resultsPerPageContainer = new IndexedContainer();

  private final AtomicInteger maxLeftContext = new AtomicInteger(Integer.MAX_VALUE);
  private final AtomicInteger maxRightContext = new AtomicInteger(Integer.MAX_VALUE);

  private boolean updateStateFromConfig = true;

  private QueryUIState state;

  public SearchOptionsPanel()
  {
    setWidth("100%");
    setHeight("-1px");

    pbLoadConfig = new ProgressBar();
    pbLoadConfig.setIndeterminate(true);
    pbLoadConfig.setCaption("Loading search options...");
    addComponent(pbLoadConfig);

    cbLeftContext = new ComboBox("Left Context", contextContainerLeft);
    cbRightContext = new ComboBox("Right Context", contextContainerRight);
    cbResultsPerPage = new ComboBox("Results Per Page", resultsPerPageContainer);

    cbLeftContext.setNullSelectionAllowed(false);
    cbRightContext.setNullSelectionAllowed(false);
    cbResultsPerPage.setNullSelectionAllowed(false);

    cbLeftContext.setNewItemsAllowed(true);
    cbRightContext.setNewItemsAllowed(true);
    cbResultsPerPage.setNewItemsAllowed(true);

    cbLeftContext.setTextInputAllowed(true);
    cbRightContext.setTextInputAllowed(true);
    cbResultsPerPage.setTextInputAllowed(true);

    cbLeftContext.setImmediate(true);
    cbRightContext.setImmediate(true);
    cbResultsPerPage.setImmediate(true);

    cbSegmentation = new ComboBox("Show context in", segmentationContainer);

    cbSegmentation.setTextInputAllowed(false);
    cbSegmentation.setNullSelectionAllowed(true);
    cbSegmentation.setNewItemsAllowed(true);
    cbSegmentation.setNullSelectionItemId(NULL_SEGMENTATION_VALUE);
    cbSegmentation.addItem(NULL_SEGMENTATION_VALUE);

    cbSegmentation.setDescription(
      "If corpora with multiple "
      + "context definitions are selected, a list of available context units will be "
      + "displayed. By default context is calculated in 'tokens' "
      + "(e.g. 5 minimal units to the left and right of a search result). "
      + "Some corpora might offer further context definitions, e.g. in "
      + "syllables, word forms belonging to different speakers, normalized or "
      + "diplomatic segmentations of a manuscript, etc.");

    segmentationHelp = new HelpButton<Object>(cbSegmentation);

    cbOrder = new ComboBox("Order", orderContainer);
    cbOrder.setNewItemsAllowed(false);
    cbOrder.setNullSelectionAllowed(false);
    cbOrder.setImmediate(true);

    cbLeftContext.setVisible(false);
    cbRightContext.setVisible(false);
    cbResultsPerPage.setVisible(false);
    cbOrder.setVisible(false);
    segmentationHelp.setVisible(false);

    addComponent(cbLeftContext);
    addComponent(cbRightContext);

    addComponent(segmentationHelp);
    addComponent(cbResultsPerPage);
    addComponent(cbOrder);

  }

  @Override
  public void attach()
  {
    super.attach();

    contextContainerLeft.setItemSorter(new IntegerIDSorter());
    contextContainerRight.setItemSorter(new IntegerIDSorter());
    resultsPerPageContainer.setItemSorter(new IntegerIDSorter());

    resultsPerPageContainer.removeAllItems();
    for(Integer i :PREDEFINED_PAGE_SIZES)
    {
      resultsPerPageContainer.addItem(i);
    }

    if (getUI() instanceof AnnisUI)
    {
      AnnisUI ui = (AnnisUI) getUI();

      state = ui.getQueryState();

      Background.run(new CorpusConfigUpdater(ui, state.getSelectedCorpora().getValue(), false));

      cbLeftContext.setNewItemHandler(new CustomContext(maxLeftContext, contextContainerLeft,
        state.getLeftContext()));
      cbRightContext.setNewItemHandler(new CustomContext(maxRightContext, contextContainerRight,
        state.getRightContext()));
      cbResultsPerPage.setNewItemHandler(new CustomResultSize(resultsPerPageContainer, state.getLimit()));

      cbLeftContext.setPropertyDataSource(state.getLeftContext());
      cbRightContext.setPropertyDataSource(state.getRightContext());
      cbResultsPerPage.setPropertyDataSource(state.getLimit());
      cbSegmentation.setPropertyDataSource(state.getContextSegmentation());

      orderContainer.removeAllItems();
      for(OrderType t : OrderType.values())
      {
        orderContainer.addItem(t);
      }
      cbOrder.setPropertyDataSource(state.getOrder());

    }
  }

  public void updateSearchPanelConfigurationInBackground(
    final Set<String> corpora, final AnnisUI ui)
  {
    setLoadingState(true);
    // remove custom adjustments
    contextContainerLeft.removeAllItems();
    contextContainerRight.removeAllItems();
    cbSegmentation.removeAllItems();

    // reload the config in the background
    Background.run(new CorpusConfigUpdater(ui, corpora, true));
  }

  private static Integer getInteger(String key, CorpusConfig config)
  {
    String s = config.getConfig(key);
    if(s != null)
    {
      return Integer.parseInt(s);
    }
    return null;
  }

  private static List<String> getSegmentationNamesFromService(
    Set<String> corpora)
  {
    List<String> segNames = new ArrayList<>();
    WebResource service = Helper.getAnnisWebResource();
    if (service != null)
    {
      for (String corpus : corpora)
      {
        try
        {
          SegmentationList segList
            = service.path("query").path("corpora").path(Helper.encodeJersey(
                corpus))
            .path("segmentation-names")
            .get(SegmentationList.class);
          segNames.addAll(segList.getSegmentatioNames());
        }
        catch (UniformInterfaceException ex)
        {
          if (ex.getResponse().getStatus() == 403)
          {
            log.debug(
              "Did not have access rights to query segmentation names for corpus",
              ex);
          }
          else
          {
            log.warn("Could not query segmentation names for corpus", ex);
          }
        }
      }

    }

    return segNames;
  }

  private void updateSegmentations(String segment,
    List<String> segNames, boolean updateValue)
  {

    cbSegmentation.setNullSelectionItemId(NULL_SEGMENTATION_VALUE);
    cbSegmentation.addItem(NULL_SEGMENTATION_VALUE);

    if ("tok".equalsIgnoreCase(segment))
    {
      if(state != null && updateValue)
      {
        state.getContextSegmentation().setValue(null);
      }
    }
    else if (segment != null)
    {
      cbSegmentation.addItem(segment);
      if(state != null && updateValue)
      {
        cbSegmentation.setValue(segment);
      }
    }

    if (segNames != null && !segNames.isEmpty())
    {
      for (String s : segNames)
      {
        if (!s.equalsIgnoreCase(segment))
        {
          cbSegmentation.addItem(s);
        }
      }
    }
  }

  /**
   * If all values of a specific corpus property have the same value, this value
   * is returned, otherwise the value of the default configuration is choosen.
   *
   * @param key The property key.
   * @param corpora Specifies the selected corpora.
   * @return A value defined in the copurs.properties file or in the
   * admin-service.properties
   */
  private String mergeConfigValue(String key, Set<String> corpora,
    CorpusConfigMap corpusConfigurations)
  {
    Set<String> values = new TreeSet<>();
    for(String corpus : corpora)
    {
      CorpusConfig config = corpusConfigurations.get(corpus);
      if(config != null)
      {
        String v = config.getConfig(key);
        if(v != null)
        {
          values.add(v);
        }
      }
    }
    if(values.size() > 1 || values.isEmpty())
    {
      // fallback to the default values
      CorpusConfig defaultConfig = corpusConfigurations.get(DEFAULT_CONFIG);
      if(defaultConfig != null && defaultConfig.containsKey(key))
      {
        return defaultConfig.getConfig(key);
      }
    }

      // ok, just return the first value as a fallback of the fallback
    if(!values.isEmpty())
    {
      return values.iterator().next();
    }

    return null;
  }

  /**
   * Builds a single config for selection of one or muliple corpora.
   *
   * @param corpora Specifies the combination of corpora, for which the config
   * is calculated.
   * @param corpusConfigurations  A map containg the known corpus configurations.
   * @return A new config which takes into account the segementation of all
   * selected corpora.
   */
  private CorpusConfig mergeConfigs(Set<String> corpora,
    CorpusConfigMap corpusConfigurations)
  {
    CorpusConfig corpusConfig = new CorpusConfig();

    // calculate the left and right context.
    String leftCtx = mergeConfigValue(KEY_MAX_CONTEXT_LEFT, corpora,
      corpusConfigurations);
    String rightCtx = mergeConfigValue(KEY_MAX_CONTEXT_RIGHT,
      corpora, corpusConfigurations);
    corpusConfig.setConfig(KEY_MAX_CONTEXT_LEFT, leftCtx);
    corpusConfig.setConfig(KEY_MAX_CONTEXT_RIGHT, rightCtx);

    // calculate the default-context
    corpusConfig.setConfig(KEY_CONTEXT_STEPS, mergeConfigValue(
      KEY_CONTEXT_STEPS, corpora, corpusConfigurations));
    corpusConfig.setConfig(KEY_DEFAULT_CONTEXT, mergeConfigValue(
      KEY_DEFAULT_CONTEXT, corpora, corpusConfigurations));

    // get the results per page
    corpusConfig.setConfig(KEY_RESULT_PER_PAGE, mergeConfigValue(
      KEY_RESULT_PER_PAGE, corpora, corpusConfigurations));

    corpusConfig.setConfig(KEY_DEFAULT_CONTEXT_SEGMENTATION, checkSegments(
      KEY_DEFAULT_CONTEXT_SEGMENTATION, corpora, corpusConfigurations));

    corpusConfig.setConfig(KEY_DEFAULT_BASE_TEXT_SEGMENTATION, checkSegments(
      KEY_DEFAULT_BASE_TEXT_SEGMENTATION, corpora, corpusConfigurations));

    return corpusConfig;
  }

  /**
   * Checks, if all selected corpora have the same default segmentation layer.
   * If not the tok layer is taken, because every corpus has this one.
   *
   * @param key the key for the segementation config, must be
   * {@link #KEY_DEFAULT_BASE_TEXT_SEGMENTATION} or
   * {@link #KEY_DEFAULT_CONTEXT_SEGMENTATION}.
   * @param corpora the corpora which has to be checked.
   * @return "tok" or a segment which is defined in all corpora.
   */
  private String checkSegments(String key, Set<String> corpora, CorpusConfigMap corpusConfigurations)
  {
    String segmentation = null;
    for (String corpus : corpora)
    {

      CorpusConfig c = null;

      if (corpusConfigurations.containsConfig(corpus))
      {
        c = corpusConfigurations.get(corpus);
      }
      else
      {
        c = corpusConfigurations.get(DEFAULT_CONFIG);
      }

      // do nothing if not even default config is set
      if (c == null)
      {
        continue;
      }

      String tmpSegment = c.getConfig(key);

      /**
       * If no segment is set in the corpus config use always the tok segment.
       */
      if (tmpSegment == null)
      {
        return corpusConfigurations.get(DEFAULT_CONFIG).getConfig(key);
      }

      if (segmentation == null)
      {
        segmentation = tmpSegment;
        continue;
      }

      if (!segmentation.equals(tmpSegment)) // return the default config
      {
        return corpusConfigurations.get(DEFAULT_CONFIG).getConfig(key);
      }
    }

    if (segmentation == null)
    {
      return corpusConfigurations.get(DEFAULT_CONFIG).getConfig(key);
    }
    else
    {
      return segmentation;
    }
  }

  /**
   * Updates context combo boxes.
   *
   * @param c the container, which is updated.
   * @param maxCtx the larges context values until context steps are calculated.
   * @param ctxSteps the step range.
   * @param keepCustomValues If this is true all custom values are kept.
   */
  private void updateContext(Container c ,int maxCtx, int ctxSteps, boolean keepCustomValues)
  {

    if(!keepCustomValues)
    {
      c.removeAllItems();
    }

    for (Integer i : PREDEFINED_CONTEXTS)
    {
      if (i < maxCtx)
      {
        c.addItem(i);
      }
    }

    for (int step = ctxSteps; step < maxCtx; step += ctxSteps)
    {
      c.addItem(step);
    }

    c.addItem(maxCtx);

  }

  private void setLoadingState(boolean isLoading)
  {
    pbLoadConfig.setVisible(isLoading);

    cbLeftContext.setVisible(!isLoading);
    cbRightContext.setVisible(!isLoading);
    cbResultsPerPage.setVisible(!isLoading);
    cbOrder.setVisible(!isLoading);
    segmentationHelp.setVisible(!isLoading);
  }

  public boolean isUpdateStateFromConfig()
  {
    return updateStateFromConfig;
  }

  public void setUpdateStateFromConfig(boolean updateStateFromConfig)
  {
    this.updateStateFromConfig = updateStateFromConfig;
  }

  private static class CustomResultSize implements AbstractSelect.NewItemHandler
  {
    private final IndexedContainer container;
    private final Property<Integer> prop;

    public CustomResultSize(IndexedContainer container, Property<Integer> prop)
    {
      this.container = container;
      this.prop = prop;
    }

    @Override
    public void addNewItem(String resultPerPage)
    {
      try
      {
        int i = Integer.parseInt((String) resultPerPage);

        if (i < 1)
        {
          throw new IllegalArgumentException(
            "result number has to be a positive number greater or equal than 1");
        }
        container.addItem(i);
        container.sort(null, null);
        prop.setValue(i);
      }
      catch (NumberFormatException ex)
      {
        Notification.show("invalid result per page input",
          "Please enter valid numbers [0-9]",
          Notification.Type.WARNING_MESSAGE);
      }
      catch (IllegalArgumentException ex)
      {
        Notification.show("invalid result per page input",
          ex.getMessage(), Notification.Type.WARNING_MESSAGE);
      }

    }
  }

  private class CorpusConfigUpdater implements Runnable
  {

    private final AnnisUI ui;
    private final Set<String> corpora;
    private final QueryUIState state;
    private final boolean corpusSelectionChanged;

    public CorpusConfigUpdater(AnnisUI ui, Set<String> corpora, boolean corpusSelectionChanged)
    {
      this.ui = ui;
      this.state = ui.getQueryState();
      this.corpora = corpora;
      this.corpusSelectionChanged = corpusSelectionChanged;
    }

    @Override
    public void run()
    {
      final List<String> segmentations = getSegmentationNamesFromService(corpora);

      final Set<String> corporaWithDefault = new TreeSet<>(corpora);
      corporaWithDefault.add(DEFAULT_CONFIG);

      final CorpusConfigMap corpusConfigs = new CorpusConfigMap();
      for(String c : corporaWithDefault)
      {
        corpusConfigs.put(c, ui.getCorpusConfigWithCache(c));
      }

      // if there are not any defaults create them
      if (!corpusConfigs.containsConfig(DEFAULT_CONFIG))
      {
        CorpusConfig defaultConfig = new CorpusConfig();
        defaultConfig.setConfig(KEY_MAX_CONTEXT_LEFT, "" + DEFAULT_MAX_CONTEXT);
        defaultConfig.setConfig(KEY_MAX_CONTEXT_RIGHT, "" + DEFAULT_MAX_CONTEXT);
        defaultConfig.setConfig(KEY_CONTEXT_STEPS, "" + DEFAULT_CONTEXT_STEPS);
        defaultConfig.setConfig(KEY_RESULT_PER_PAGE, "10");
        defaultConfig.setConfig(KEY_DEFAULT_CONTEXT, "" + DEFAULT_CONTEXT);
        defaultConfig.setConfig(KEY_DEFAULT_CONTEXT_SEGMENTATION, "tok");
        defaultConfig.setConfig(KEY_DEFAULT_BASE_TEXT_SEGMENTATION, "tok");
        corpusConfigs.put(DEFAULT_CONFIG, defaultConfig);
      }

      // update GUI
      ui.access(new Runnable()
      {

        @Override
        public void run()
        {
          setLoadingState(false);

          CorpusConfig c = mergeConfigs(corpora, corpusConfigs);

          Integer resultsPerPage = getInteger(KEY_RESULT_PER_PAGE, c);
          Integer leftCtx = getInteger(KEY_MAX_CONTEXT_LEFT, c);
          if(leftCtx != null)
          {
            maxLeftContext.set(leftCtx);
          }

          Integer rightCtx = getInteger(KEY_MAX_CONTEXT_RIGHT, c);
          if(rightCtx != null)
          {
            maxRightContext.set(rightCtx);
          }
          Integer defaultCtx = getInteger(KEY_DEFAULT_CONTEXT, c);

          Integer ctxSteps = getInteger(KEY_CONTEXT_STEPS, c);
          String segment = c.getConfig(KEY_DEFAULT_CONTEXT_SEGMENTATION);

          updateContext(contextContainerLeft, leftCtx == null ? DEFAULT_CONTEXT : leftCtx,
            ctxSteps == null ? DEFAULT_CONTEXT_STEPS : ctxSteps, true);
          updateContext(contextContainerRight, rightCtx == null ? DEFAULT_CONTEXT : rightCtx,
            ctxSteps == null ? DEFAULT_CONTEXT_STEPS : ctxSteps, true);
          if (defaultCtx != null && updateStateFromConfig && corpusSelectionChanged)
          {
            state.getLeftContext().setValue(defaultCtx);
            state.getRightContext().setValue(defaultCtx);
          }
          updateSegmentations(segment, segmentations, updateStateFromConfig && !corpora.isEmpty());
          if(resultsPerPage != null && updateStateFromConfig && corpusSelectionChanged)
          {
            state.getLimit().setValue(resultsPerPage);
          }
          // reset if corpus selection has changed
          if(corpusSelectionChanged)
          {
            updateStateFromConfig = true;
          }
        }

      });
    }

  }

  private static class CustomContext implements AbstractSelect.NewItemHandler
  {
    private final AtomicInteger maxCtx;
    private final IndexedContainer container;
    private final Property<Integer> prop;

    public CustomContext(AtomicInteger maxCtx,IndexedContainer container,
      Property<Integer> prop)
    {
      this.maxCtx = maxCtx;
      this.container = container;
      this.prop = prop;
    }

    @Override
    public void addNewItem(String context)
    {
      try
      {
        int i = Integer.parseInt((String) context);

        if (i < 0)
        {
          throw new IllegalArgumentException(
            "context has to be a positive number or 0");
        }

        if (i > maxCtx.get())
        {
          throw new IllegalArgumentException(
            "The context is greater than, than the max value defined in the corpus property file.");
        }

        // everything ok, add the value
        container.addItem(i);
        container.sort(null, null);
        prop.setValue(i);
      }
      catch (NumberFormatException ex)
      {
        Notification.show("invalid context input",
          "Please enter valid numbers [0-9]",
          Notification.Type.WARNING_MESSAGE);
      }
      catch (IllegalArgumentException ex)
      {
        Notification.show("invalid context input",
          ex.getMessage(),
          Notification.Type.WARNING_MESSAGE);
      }

    }
  }

  public static class IntegerIDSorter implements ItemSorter
  {

    @Override
    public void setSortProperties(Container.Sortable container,
      Object[] propertyId, boolean[] ascending)
    {
      // does nothing
    }

    @Override
    public int compare(Object itemId1, Object itemId2)
    {
      if(itemId1 instanceof Integer && itemId2 instanceof Integer)
      {
        return Integer.compare((Integer) itemId1, (Integer) itemId2);
      }
      return 0;
    }

  }

}


text:
<?php
/**
 * Created by mr.xcray in the name of magic
 *
 * Date: 21.02.14
 * Time: 3:36
 */
namespace X;

define("__XDIR__", dirname(__FILE__) . DIRECTORY_SEPARATOR);

function registerAutoloader($namespaceName, $rootDirectory){

  if (substr($rootDirectory, -1)!=DIRECTORY_SEPARATOR){
    $rootDirectory.=DIRECTORY_SEPARATOR;
  }

  spl_autoload_register( function($className) use(&$namespaceName, &$rootDirectory){
    $namespaceNameLen = strlen($namespaceName);
    if (substr($className, 0, $namespaceNameLen+1) !== $namespaceName."\\"){
      return;
    }
    $classFullName = (string)str_replace('\\', DIRECTORY_SEPARATOR, substr($className, $namespaceNameLen+1));

    if (file_exists( $rootDirectory . $classFullName . '.php')){
      include ( $rootDirectory . $classFullName . '.php');
    }
  });
}

registerAutoloader("X", __XDIR__);
\X\registerAutoloader("Typograf", __XDIR__.'3rdparty/Typograf/');
\X\registerAutoloader("Phois", __XDIR__.'3rdparty/Phois/');
\X\registerAutoloader("Parsedown", __XDIR__.'3rdparty/Parsedown/');
\X\registerAutoloader("Clickatell", __XDIR__.'3rdparty/Clickatell/');
\X\registerAutoloader("Afi", __XDIR__.'3rdparty/Afigenius/');
\X\registerAutoloader("Snoop", __XDIR__.'3rdparty/Snoop/');
\X\registerAutoloader("Barzo\\Password", __XDIR__.'3rdparty/PasswordGenerator/');
\X\registerAutoloader("Longman\\TelegramBot", __XDIR__.'3rdparty/telegram-bot/');
\X\registerAutoloader("Skype", __XDIR__.'3rdparty/Skype/');
\X\registerAutoloader("ClickMeeting", __XDIR__.'3rdparty/Clickmeeting/');
\X\registerAutoloader("Piwik", __XDIR__.'3rdparty/Piwik/');
\X\registerAutoloader("Skype", __XDIR__.'3rdparty/Skype/');
\X\registerAutoloader("GuzzleHttp", __XDIR__.'3rdparty/GuzzleHttp/');
\X\registerAutoloader("Psr", __XDIR__.'3rdparty/Psr/');
\X\registerAutoloader("Symfony", __XDIR__.'3rdparty/Symfony/');
\X\registerAutoloader("Threads", __XDIR__.'3rdparty/Threads/');
\X\registerAutoloader("JeroenDesloovere\\VCard", __XDIR__.'3rdparty/VCard/');
\X\registerAutoloader("Behat\\Transliterator", __XDIR__.'3rdparty/Behat/Transliterator/');

require_once(__XDIR__ . '3rdparty/GuzzleHttp/functions.php');
require_once(__XDIR__ . '3rdparty/GuzzleHttp/Promise/functions.php');
require_once(__XDIR__ . '3rdparty/GuzzleHttp/Psr7/functions.php');
require_once(__XDIR__ . '3rdparty/Imagine/Autoloader.php');
\Imagine_Autoloader::register();

require_once(__XDIR__.'3rdparty/dompdf/autoload.inc.php');
require_once(__XDIR__.'3rdparty/PHPExcel/PHPExcel.php');
require_once(__XDIR__.'3rdparty/PHPSQLParser/PHPSQLParser.php');
require_once(__XDIR__.'3rdparty/PHPSQLParser/PHPSQLCreator.php');
require_once(__XDIR__.'3rdparty/PHPMailer/PHPMailerAutoload.php');
require_once(__XDIR__.'3rdparty/Mobile-Detect/Mobile_Detect.php');
require_once(__XDIR__.'3rdparty/Dropbox/autoload.php');

X::isOk();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>Processing Embedded SQL Programs</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.0.5 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="ECPG - Embedded SQL in C"
HREF="ecpg.html"><LINK
REL="PREVIOUS"
TITLE="Preprocessor directives"
HREF="ecpg-preproc.html"><LINK
REL="NEXT"
TITLE="Library Functions"
HREF="ecpg-library.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2011-09-22T22:21:03">

PostgreSQL 9.0.5 Documentation

Prev	Fast Backward	Chapter 33. ECPG - Embedded <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> in C	Fast Forward	Next

33.13. Processing Embedded SQL Programs

   Now that you have an idea how to form embedded SQL C programs, you
   probably want to know how to compile them.  Before compiling you
   run the file through the embedded <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
>
   <ACRONYM
CLASS="ACRONYM"
>C</ACRONYM
> preprocessor, which converts the
   <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> statements you used to special function
   calls.  After compiling, you must link with a special library that
   contains the needed functions. These functions fetch information
   from the arguments, perform the <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> command using
   the libpq interface, and put the result
   in the arguments specified for output.

   The preprocessor program is called <TT
CLASS="FILENAME"
>ecpg</TT
> and is
   included in a normal PostgreSQL installation.
   Embedded SQL programs are typically named with an extension
   <TT
CLASS="FILENAME"
>.pgc</TT
>.  If you have a program file called
   <TT
CLASS="FILENAME"
>prog1.pgc</TT
>, you can preprocess it by simply
   calling:

ecpg prog1.pgc

   This will create a file called <TT
CLASS="FILENAME"
>prog1.c</TT
>.  If
   your input files do not follow the suggested naming pattern, you
   can specify the output file explicitly using the
   <TT
CLASS="OPTION"
>-o</TT
> option.

   The preprocessed file can be compiled normally, for example:

cc -c prog1.c

   The generated C source files include header files from the
   PostgreSQL installation, so if you installed
   PostgreSQL in a location that is not searched by
   default, you have to add an option such as
   <TT
CLASS="LITERAL"
>-I/usr/local/pgsql/include</TT
> to the compilation
   command line.

   To link an embedded SQL program, you need to include the
   <TT
CLASS="FILENAME"
>libecpg</TT
> library, like so:

cc -o myprog prog1.o prog2.o ... -lecpg

   Again, you might have to add an option like
   <TT
CLASS="LITERAL"
>-L/usr/local/pgsql/lib</TT
> to that command line.

   If you manage the build process of a larger project using
   make, it might be convenient to include
   the following implicit rule to your makefiles:

ECPG = ecpg

%.c: %.pgc
        $(ECPG) $<

   The complete syntax of the <TT
CLASS="COMMAND"
>ecpg</TT
> command is
   detailed in ecpg.

   The ecpg library is thread-safe by
   default.  However, you might need to use some threading
   command-line options to compile your client code.

Prev	Home	Next

Preprocessor directives	Up	Library Functions


text:
package j2se.jfreechart.barchart;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

/**
 * This demonstration shows a 3D bar chart with item labels displayed.
 *
 */
public class BarChart3DDemo3 extends ApplicationFrame {

    /**
     * Creates a new demo.
     *
     * @param title  the frame title.
     */
    public BarChart3DDemo3(final String title) {

        super(title);

        final CategoryDataset dataset = createDataset();
        final JFreeChart chart = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);

    }

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    *
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    /**
     * Creates a sample dataset.
     *
     * @return a sample dataset.
     */
   private CategoryDataset createDataset() {

        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(25.0, "Series 1", "Category 1");
        dataset.addValue(34.0, "Series 1", "Category 2");
        dataset.addValue(19.0, "Series 2", "Category 1");
        dataset.addValue(29.0, "Series 2", "Category 2");
        dataset.addValue(41.0, "Series 3", "Category 1");
        dataset.addValue(33.0, "Series 3", "Category 2");
        return dataset;

    }

    /**
     * Creates a chart.
     *
     * @param dataset  the dataset.
     *
     * @return The chart.
     */
    private JFreeChart createChart(final CategoryDataset dataset) {

        final JFreeChart chart = ChartFactory.createBarChart3D(
            "3D Bar Chart Demo",      // chart title
            "Category",               // domain axis label
            "Value",                  // range axis label
            dataset,                  // data
            PlotOrientation.VERTICAL, // orientation
            true,                     // include legend
            true,                     // tooltips
            false                     // urls
        );

        final CategoryPlot plot = chart.getCategoryPlot();
        final CategoryAxis axis = plot.getDomainAxis();
        axis.setCategoryLabelPositions(
            CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 8.0)
        );

        final CategoryItemRenderer renderer = plot.getRenderer();
        renderer.setItemLabelsVisible(true);
        final BarRenderer r = (BarRenderer) renderer;
        r.setMaximumBarWidth(0.05);

        return chart;

    }

    /**
     * Starting point for the demonstration application.
     *
     * @param args  ignored.
     */
    public static void main(final String[] args) {

        final BarChart3DDemo3 demo = new BarChart3DDemo3("3D Bar Chart Demo 3");
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);

    }

}


text:
`npm install angular2-viewport --save`

```typescript
import { ViewportModule } from 'angular2-viewport';

@NgModule({
	imports: [
		...
		ViewportModule
	], ...
})
export class AppModule {}
```

## Directives

### In View `[vp-in-view]`
-------------------------------------------

Emits an event when element is in viewport

#### *__Usage:__*

```html
<div (vp-in-view)="handlerFunction()"></div>
```

#### *__Options:__*
```html
<div (vp-in-view)="handlerFunction()" [vp-in-view-config]="{infinite: true, margin: 300}"></div>
```
| Property               | Type    | Default | Description                                             |
|:-----------------------|---------|---------|---------------------------------------------------------|
|**margin**              | number  | 0       | shortcut for 'marginHorizontal' & 'marginVertical'      |
|**marginHorizontal**    | number  | 0       | shortcut for 'marginLeft' & 'marginRight'               |
|**marginVertical**      | number  | 0       | shortcut for 'marginTop' & 'marginBottom'               |
|**marginTop**           | number  | 0       | Offset for calculation of top positon of the element    |
|**marginBottom**        | number  | 0       | Offset for calculation of bottom positon of the element |
|**marginLeft**          | number  | 0       | Offset for calculation of left positon of the element   |
|**marginRight**         | number  | 0       | Offset for calculation of right positon of the element  |
|**infinite**            | boolean | false   | Emit event on every enter to the viewport or only once  |

_______________________________________________

### Scrollable Content `[vp-scrollable-content]` (helper)
-------------------------------------------

Mark a scrollable element for triggering detection of **'in-view'** directives and emitting scroll events of **'ScrollService'**

#### *__Usage:__*

```html
<div vp-scrollable-content></div>
```

#### *__Dynamic Child:__*
If the scrolling target will be created dynamically, specify a selector for getting the target when view rendered
```html
<ion-scroll vp-scrollable-content=".scroll-content"></ion-scroll>
```
_______________________________________________

## Services
### ScrollService
-------------------------------------------

#### *__Usage:__*

```typescript
import { ScrollService } from 'angular2-viewport';

@Component({
	selector: 'a-component'
})
export class AComponent {

	constructor(scrollService: ScrollService) {
			scrollService.onScrollEnd.subscribe(e => {
				console.log('Yayy! Scrolling is ended');
			});
	}
```

#### *__Properties:__*
> **onScrollStart: Observable\<Event>**
> Emits when the scrolling is started on bound targets

> **onScrollEnd: Observable\<Event>**
> Emits when the scrolling is finished on bound targets

> **onScroll: Observable\<Event>**
> Throttled Scroll Event of bound targets

#### *__Methods:__*
> **bind(target: EventTarget): Function**
> Binds its listener to the event target to trigger checking position of in-view directive or for emiting its scroll events
> Returns the unbinding function

> **unbind(target: EventTarget):void**
> Removes its listener from the target

### TriggerService (helper)
-------------------------------------------

#### *__Usage:__*

```typescript
import { TriggerService } from 'angular2-viewport';

@Component({
	selector: 'a-component'
})
export class AComponent {

	constructor(triggerService: TriggerService) {
			...
	}
```

#### *__Methods:__*
> **bind(obs: Observable\<any>):Subscription**
> Bind an observable to trigger manually the detection of in-view directives


text:
package org.cqback.runtime.context;

/**
 * Created by pragone
 * Created on 30/12/2015 at 12:21 PM
 *
 * @author Paolo Ragone <pragone@ebay.com>
 */
public interface CommitListener {
    public void committed(CommitableExecutionContext commitableExecutionContext);
}


text:
package src;

// triangle.java
// evaluates triangular numbers
// to run this program: C>java TriangleApp
import java.io.*; // for I/O
////////////////////////////////////////////////////////////////
class knapSack
{
    static int theNumber;
    public static void main(String[] args) throws IOException
    {
        System.out.print("Enter a number: ");
        System.out.flush();
        theNumber = getInt();
        int theAnswer = triangle(theNumber);
        System.out.println("Triangle="+theAnswer);
    } // end main()
    //-------------------------------------------------------------
    public static int triangle(int n)
    {
        if(n==1)
            return 1;
        else
            return( n + triangle(n-1) );
    }
    //-------------------------------------------------------------
    public static String getString() throws IOException
    {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String s = br.readLine();
        return s;
    }
//-------------------------------------------------------------
    //-
    public static int getInt() throws IOException
    {
        String s = getString();
        return Integer.parseInt(s);
    }
//-------------------------------------------------------------
    //-
} // end class TriangleApp


text:
using namespace std;

std::string utFormatString(const char format[], ...);

void utCommaSeparatedToStringVector(const std::string & commaSeparatedString, std::vector<std::string> & outputStringVector);

std::string utGetTokenInStream(istream & stream, int maxLength, char delimiter);
bool utVerifyTokenInStream(istream & stream, char delimiter, std::string token);

int utGetIntInStream(istream & stream);
float utGetFloatInStream(istream & stream);
bool utGetBoolInStream(istream & stream);
mlVector2D utGetVector2DInStream(istream & stream);
mlVector3D utGetVector3DInStream(istream & stream);
mlQuaternion utGetQuaternionInStream(istream & stream);

void utPutLabelInStream(ostream & stream, const std::string & label);
void utPutStringInStream(ostream & stream, const std::string & label, const std::string & value);
void utPutIntInStream(ostream & stream, const std::string & label, int value);
void utPutBoolInStream(ostream & stream, const std::string & label, bool value);
void utPutFloatInStream(ostream & stream, const std::string & label, mlFloat value);
void utPutVector2DInStream(ostream & stream, const std::string & label, const mlVector2D & value);
void utPutVector3DInStream(ostream & stream, const std::string & label, const mlVector3D & value);
void utPutQuaternionInStream(ostream & stream, const std::string & label, const mlQuaternion & value);

#endif // UT_STRING_H


text:
package nl.knaw.dans.rs.aggregator.sync;

import nl.knaw.dans.rs.aggregator.http.ResourceReader;
import nl.knaw.dans.rs.aggregator.http.Result;
import nl.knaw.dans.rs.aggregator.syncore.ResourceManager;
import nl.knaw.dans.rs.aggregator.syncore.VerificationStatus;
import nl.knaw.dans.rs.aggregator.util.FileCleaner;
import nl.knaw.dans.rs.aggregator.util.HashUtil;
import nl.knaw.dans.rs.aggregator.syncore.PathFinder;
import nl.knaw.dans.rs.aggregator.util.ZonedDateTimeUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.security.NoSuchAlgorithmException;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Set;

/**
 * Created on 2017-04-28 12:56.
 */
public class FsResourceManager implements ResourceManager {

  private static Logger logger = LoggerFactory.getLogger(FsResourceManager.class);

  private PathFinder pathFinder;
  private ResourceReader resourceReader;
  private CloseableHttpClient httpClient;

  private PathFinder getPathFinder() {
    if (pathFinder == null) throw new IllegalStateException("Missing PathFinder. No PathFinder was set.");
    return pathFinder;
  }

  public void setPathFinder(PathFinder pathFinder) {
    this.pathFinder = pathFinder;
  }

  private CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
      httpClient = HttpClients.createDefault();
    }
    return httpClient;
  }

  public FsResourceManager withHttpClient(CloseableHttpClient httpClient) {
    this.httpClient = httpClient;
    return this;
  }

  private ResourceReader getResourceReader() {
    if (resourceReader == null) {
      resourceReader = new ResourceReader(getHttpClient());
    }
    return resourceReader;
  }

  public FsResourceManager withResourceReader(ResourceReader resourceReader) {
    this.resourceReader = resourceReader;
    return this;
  }

  @Override
  public boolean exists(@Nonnull URI normalizedURI) {
    return getPathFinder().findResourceFilePath(normalizedURI).exists();
  }

  @Override
  public VerificationStatus verifyHash(@Nonnull URI normalizedURI, @Nonnull String algorithm, @Nonnull String hash) {
    VerificationStatus status = VerificationStatus.not_verified;
    try {
      String localHash = HashUtil.computeHash(algorithm,
        new FileInputStream(getPathFinder().findResourceFilePath(normalizedURI)));
      if (hash.equalsIgnoreCase(localHash)) {
        status = VerificationStatus.verification_success;
        //logger.debug("Verified {} hash of {}.", algorithm, normalizedURI);
      } else {
        status = VerificationStatus.verification_failure;
        logger.info("Hash failure. algorithm={}, remote={}, local={}, uri={}",
          algorithm, hash, localHash, normalizedURI);
      }
    } catch (NoSuchAlgorithmException e) {
      status = VerificationStatus.verification_error;
      logger.error("Unknown hash algorithm: '{}': {}", algorithm, normalizedURI, e);
    } catch (IOException e) {
      status = VerificationStatus.verification_error;
      logger.error("Exception while computing hash: {}", normalizedURI, e);
    }
    return status;
  }

  @Override
  public VerificationStatus verifyLastModified(@Nonnull URI normalizedURI, @Nonnull ZonedDateTime lastModified) {
    VerificationStatus status = VerificationStatus.not_verified;
    long localLm = getPathFinder().findResourceFilePath(normalizedURI).lastModified();
    long remoteLm = ZonedDateTimeUtil.toLong(lastModified);
    if (remoteLm == localLm) {
      status = VerificationStatus.verification_success;
      //logger.debug("Verified Last-modified of {}", normalizedURI);
    } else {
      status = VerificationStatus.verification_failure;
      logger.info("Last-modified not equal. remote={} ({}), local={} ({}), uri={}",
        remoteLm, new Date(remoteLm),
        localLm, new Date(localLm), normalizedURI);
    }
    return status;
  }

  @Override
  public VerificationStatus verifySize(@Nonnull URI normalizedURI, long size) {
    VerificationStatus status = VerificationStatus.not_verified;
    long localSize = getPathFinder().findResourceFilePath(normalizedURI).length();
    if (size == localSize) {
      status = VerificationStatus.verification_success;
      //logger.debug("Verified Length of {}", normalizedURI);
    } else {
      status = VerificationStatus.verification_failure;
      logger.info("Length not equal. remote={}, local={}, uri={}", size, localSize, normalizedURI);
    }
    return status;
  }

  @Override
  public boolean keepOnly(@Nonnull Set<URI> normalizedURIs) {
    Set<File> fileSet = getPathFinder().findResourceFilePaths(normalizedURIs);
    FileCleaner fileCleaner = new FileCleaner(fileSet);
    File resourceDirectory = getPathFinder().getResourceDirectory();
    if (!resourceDirectory.exists()) return true;
    try {
      Files.walkFileTree(getPathFinder().getResourceDirectory().toPath(), fileCleaner);
    } catch (IOException e) {
      throw new RuntimeException("Could not clear resource directory for " + getPathFinder().getCapabilityListUri(), e);
    }
    return true;
  }

  @Override
  public boolean keep(@Nonnull URI normalizedURI) {
    File resourcePath = getPathFinder().findResourceFilePath(normalizedURI);
    logger.debug("Remain {} --> {}", normalizedURI, resourcePath);
    return true;
  }

  @Override
  public boolean create(@Nonnull URI normalizedURI) {
    return download(normalizedURI);
  }

  @Override
  public boolean update(@Nonnull URI normalizedURI) {
    return download(normalizedURI);
  }

  @Override
  public boolean delete(@Nonnull URI normalizedURI) {
    File resourcePath = getPathFinder().findResourceFilePath(normalizedURI);
    boolean deleted = resourcePath.delete();
    if (deleted) logger.debug("Deleted {} --> {}", normalizedURI, resourcePath);
    return true;
  }

  private boolean download(@Nonnull URI normalizedURI) {
    boolean downloaded = false;
    File resourcePath = getPathFinder().findResourceFilePath(normalizedURI);
    Result<File> result = getResourceReader().read(normalizedURI, resourcePath);
    if (result.getContent().isPresent()) {
      downloaded = true;
      logger.debug("Downloaded {} --> {}", normalizedURI, resourcePath);
    } else {
      logger.warn("Failed download of {}: ", normalizedURI, result.lastError());
    }
    return downloaded;
  }
}


text:
package com.google.cloud.apigeeregistry.v1.samples;

// [START apigeeregistry_v1_generated_Registry_CreateApiVersion_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.apigeeregistry.v1.ApiName;
import com.google.cloud.apigeeregistry.v1.ApiVersion;
import com.google.cloud.apigeeregistry.v1.CreateApiVersionRequest;
import com.google.cloud.apigeeregistry.v1.RegistryClient;

public class AsyncCreateApiVersion {

  public static void main(String[] args) throws Exception {
    asyncCreateApiVersion();
  }

  public static void asyncCreateApiVersion() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (RegistryClient registryClient = RegistryClient.create()) {
      CreateApiVersionRequest request =
          CreateApiVersionRequest.newBuilder()
              .setParent(ApiName.of("[PROJECT]", "[LOCATION]", "[API]").toString())
              .setApiVersion(ApiVersion.newBuilder().build())
              .setApiVersionId("apiVersionId1678816025")
              .build();
      ApiFuture<ApiVersion> future = registryClient.createApiVersionCallable().futureCall(request);
      // Do something.
      ApiVersion response = future.get();
    }
  }
}
// [END apigeeregistry_v1_generated_Registry_CreateApiVersion_async]


text:
confirm() {
  read -r -p "$1 [y/n] " response
  case $response in
    [yY][eE][sS]|[yY])
      return 0;;
    *)
      return 1;;
  esac
}

### Check passed arguments and initialse variables for command execution ###

# Get the absolute path to the parent directory and the name of this script.
pushd $( dirname $0 ) > /dev/null
BASENAME=$( basename $0)
DIRNAME=$( pwd -P )
popd > /dev/null

# All assets needed by this script are found in a dedicated directory.
ASSETS_DIR=${DIRNAME}/assets/${BASENAME%.*}

# Define the base directory, where all managed projects are stored.
[[ -z ${PROJECTS_BASEDIR} ]] && PROJECTS_BASEDIR=${HOME}/projects

# Define source and name for the script that starts the project Terimnal.
if [ $( uname ) == "Darwin" ]; then
  [[ -z ${PROJECTS_TERMINAL_CMD_TEMPLATE} ]] && PROJECTS_TERMINAL_CMD_TEMPLATE=${ASSETS_DIR}/mac-terminal.command
  [[ -z ${PROJECTS_TERMINAL_CMD_FILE_NAME} ]] && PROJECTS_TERMINAL_CMD_FILE_NAME=_terminal.command
else
  [[ -z ${PROJECTS_TERMINAL_CMD_TEMPLATE} ]] && PROJECTS_TERMINAL_CMD_TEMPLATE="UNSUPPORTED_OS"
  [[ -z ${PROJECTS_TERMINAL_CMD_FILE_NAME} ]] && TERMINAL_START_SCRIPT_NAME=_terminal.sh
fi

# Set help and usage texts.
USAGE="${BASENAME} [-c project-name | -h | -l] [-b basedir] [-t terminal-start-script-file-name] [-T terminal-start-script-template]"
USAGE_TEXT="usage: ${USAGE}"
MAN_TEXT="
NAME
  ${BASENAME} -- manages projects.

SYNOPSIS
  ${USAGE}

DESCRIPTION
  Manages projects on a development workstation. Each project is stored in a
  directory below '~/projects'. It:
   - can define project-specific settings (environment variables, aliases, etc.)
   - has its own history
   - has its own Terminal start script
   - can start the Terminal using a profile (on Mac)

  To provide a Mac Terminal profile that should be used for a project Terminal,
  create a profile in the settings of the Terminal application and export it to
  a file that is replaced in project directory or on of its parent directories.

  The options are as follows:

  -b basedir
      Overwrites the base directory, where all managed projects are stored. The
      default base directory is '~/projects'. It can also be overwritten using
      the environment variable 'PROJECTS_BASEDIR'.

  -c project-name
      Create a new project with the given name. This option will create a
      directory with the given project name as sub directory of '~/projects' and
      place a '.projectrc' file and a Terminal start script in the new project
      directory.

  -h
      Print this help.

  -l
      Print a list of all projects.

  -t terminal-start-script-file-name
      Overwrites the name of the script that starts the Terminal for a project.
      The default name is '_terminal.command' on Mac and '_terminal.sh' on other
      enviornments. The name of the start script can also be overwritten using
      the environment variable 'PROJECTS_TERMINAL_CMD_FILE_NAME'.

  -T terminal-start-script-template
      Overwrites the template for the script that starts the Terminal for a
      project. The default file is '${ASSETS_DIR}/mac-terminal.command'
      for Mac. Support for other enviornments is currently not implemented. The
      name of the start script can also be overwritten using the environment
      variable 'PROJECTS_TERMINAL_CMD_TEMPLATE'.
"

# Pass the option arguments to variables.
while getopts "b:c:hlt:T:" OPTFLAG; do
  case "${OPTFLAG}" in

    # Main (command) arguments
    c) NEW_PROJECT=${OPTARG};;
    h) PRINT_HELP=true;;
    l) PRINT_LIST=true;;

    # Overwritable arguments
    b) PROJECTS_BASEDIR=${OPTARG};;
    t) PROJECTS_TERMINAL_CMD_FILE_NAME=${OPTARG};;
    T) PROJECTS_TERMINAL_CMD_TEMPLATE=${OPTARG};;

    # Unknown arguments
    ?) echo "${USAGE_TEXT}" >&2
       exit 1;;
  esac
done

# Ensure that exactly one of the main command arguments is specified.
NUM_COMMAND_ARGS=0
[[ -n ${NEW_PROJECT} ]] && NUM_COMMAND_ARGS=$( expr ${NUM_COMMAND_ARGS} + 1 )
[[ -n ${PRINT_HELP} ]] && NUM_COMMAND_ARGS=$( expr ${NUM_COMMAND_ARGS} + 1 )
[[ -n ${PRINT_LIST} ]] && NUM_COMMAND_ARGS=$( expr ${NUM_COMMAND_ARGS} + 1 )
if [[ "${NUM_COMMAND_ARGS}" != "1" ]]; then
  echo "Please specify exactly one of the arguments [-c | -h | -l]" >&2
  echo "${USAGE_TEXT}" >&2
  exit 1
fi

# Print the help text.
if [ "${PRINT_HELP}" == "true" ]; then
  echo "${MAN_TEXT}"
  exit 0
fi

# Check if there's an existsing command file - if a target file name is specified.
if [[ -n "${PROJECTS_TERMINAL_CMD_FILE_NAME}" && ! -f "${PROJECTS_TERMINAL_CMD_TEMPLATE}" ]]; then
  echo "Terminal start script template ${PROJECTS_TERMINAL_CMD_TEMPLATE} not found." >&2
  echo "Did You provide a custom template path that doesn't exist?" >&2
  echo "Otherwise Your operating system ($( uname )) may not be supported so far. In this case Your pull request may help ..." >&2
  exit 1
fi

### Check prerequisites ###

# The RC file for projects settings initialsation must have been sourced.
# Assumption: It has been sourced, when PROJECTS_RCFILE is defined.
if [ -z ${PROJECTS_RCFILE} ]; then
  echo "Project environments require ${ASSETS_DIR}/rcfile to be sourced."
  if [ "${SHELL}" == $( which zsh ) ]; then
    RCFILE="${HOME}/.zshrc"
  else
    RCFILE="${HOME}/.profile"
  fi
  if confirm "Should 'source ${ASSETS_DIR}/rcfile' be added to ${RCFILE}?"; then
    echo "" >> ${RCFILE}
    echo "# Source the RC file that sets the custom environment for each project." >> ${RCFILE}
    echo "source ${ASSETS_DIR}/rcfile" >> ${RCFILE}
    source ${ASSETS_DIR}/rcfile
    echo "Added and executed 'source ${ASSETS_DIR}/rcfile' to ${RCFILE}"
  else
    echo "Aborting. Please add 'source ${ASSETS_DIR}/rcfile' to Your Terminal startup files!" >&2
    exit 1
  fi
fi

### Print list of projects ###
if [ "${PRINT_LIST}" == "true" ]; then

  # Use the project source scripts to identify the projects.
  find ${PROJECTS_BASEDIR} -name "${PROJECTS_RCFILE}" -maxdepth 5 | sed "s:${PROJECTS_BASEDIR}/::g" | sed "s:/[^/]*$::g"

fi

### Create new project ###
if [ -n "${NEW_PROJECT}" ]; then

  # Create the project directory
  NEW_PROJECT_DIR=${PROJECTS_BASEDIR}/${NEW_PROJECT}
  if [ ! -e "${NEW_PROJECT_DIR}" ]; then
    mkdir -p "${NEW_PROJECT_DIR}"
    echo "Created project directory ${NEW_PROJECT_DIR}"
  elif [ ! -d "${NEW_PROJECT_DIR}" ]; then
    echo "${PROJECTS_BASEDIR}/${NEW_PROJECT} already exists but isn't a directory" >&2
    exit 1
  fi

  # Create project source script.
  if [ ! -f "${NEW_PROJECT_DIR}/${PROJECTS_RCFILE}" ]; then
    echo "# RC file for project ${NEW_PROJECT}" > "${NEW_PROJECT_DIR}/${PROJECTS_RCFILE}"
    echo "Created project source script ${NEW_PROJECT_DIR}/${PROJECTS_RCFILE}"
  fi

  # Copy the Terminal start script to the project directory - if the target file name is specified.
  if [[ -n "${PROJECTS_TERMINAL_CMD_FILE_NAME}" && ! -f "${NEW_PROJECT_DIR}/${PROJECTS_TERMINAL_CMD_FILE_NAME}" ]]; then
    cp "${PROJECTS_TERMINAL_CMD_TEMPLATE}" "${NEW_PROJECT_DIR}/${PROJECTS_TERMINAL_CMD_FILE_NAME}"
    echo "Created project Terminal start script ${NEW_PROJECT_DIR}/${PROJECTS_TERMINAL_CMD_FILE_NAME}"
  fi

fi


text:
export const MENTION_NOT_FOUND = 1;
export const MENTION_FOUND = 2;


text:
                        UI Elements

Notifications

Getting started

For Your Information - FYI

Breaking convention again, we have inctroduced a notification system which variates based on the type and level of importance of the message. Thanks to this, an alert by the side of your screen would easily catch your attention.

VIA senior product manage

 for UI/UX at REVOX

Pages notification

Notifications provide alerts and related information for pages Framework.As an important part of pages user interface, we made a tool for much easier visualizations

Alert

Individual alerts will be visible and depending on the level of its importance, will have dedicated colours and sized indicating specified scenarios.

Robust and lightweight

CSS3 powered transitions and animations for greater user experience.

Select a notification style

                            Notification Bar
                            Bouncy Flip
                            Circle Notification
                            Simple Alert

Notification Bar

Awesome Loading Circle Animation

Highly Customizable, Change radius, Add Content Change X , Y Axis, Change svg animation

Bouncy Flip

Awesome Loading Circle Animation

Highly Customizable, Change radius, Add Content Change X , Y Axis, Change svg animation

Circle Notification

Awesome Loading Circle Animation

Highly Customizable, Change radius, Add Content Change X , Y Axis, Change svg animation

Simple Alert

Simple alert

Highly Customizable, Change radius, Add Content Change X , Y Axis, Change svg animation

                            <form role="form" name="notificationForm" novalidate>

                                    Message
                                    <input type="text" ng-model="notification.message" class="form-control notification-message" placeholder="Type your message here" value="This notification looks so perfect!" required>

                                <select class="cs-select cs-skin-slide notification-type" ng-model="notification.color" cs-select>
                                    <option value="info">Info</option>
                                    <option value="warning">Warning</option>
                                    <option value="success">Success</option>
                                    <option value="danger">Danger</option>
                                    <option value="default">Default</option>
                                </select>
                                <button class="btn btn-success show-notification" ng-click="showNotification()" ng-disabled="notificationForm.$invalid">Show</button>
                            </form>

Select Position

Simple alerts

Where ever you are we'll keep you notified and up to date!

Alerts help to gain user attention and give feedback for proccessed task. These alerts are built with different background and borders to show.

VIA senior product manage

 for UI/UX at REVOX

                                <button class="close" data-dismiss="alert"></button>
                                Danger: The daily report has failed

                                <button class="close" data-dismiss="alert"></button>
                                Warning: Bandwidth limit exceeded

                                <button class="close" data-dismiss="alert"></button>
                                Success: The page has been added.

                                <button class="close" data-dismiss="alert"></button>
                                Info: You have 198 messages

Descriptive alerts

Alerts can be multilined. Feel free to include any HTML inside your alerts

Meeting rescheduled

                                <button class="close" data-dismiss="alert"></button>

The STG Meeting has been resheduled to the following date : 2014-12-17

Please complete the attendance form to confirm your attendance

Alert with link

You can also use a link to show more information about the notification. Use the .alert-link utility class to quickly provide matching colored links within any alert.

Your data limit has exceeded

                                <button class="close" data-dismiss="alert"></button>

See all now

Bordered alerts

By default all Pages alerts are borderless. To add a border, simply append the class .bordered

Info: You have 198 messages

                                <button class="close" data-dismiss="alert"></button>

Simple labels

A label, with optional background colors. Use the
                                    labelclass to create a label

                                DEFAULT
                                VIEW
                                HOLD
                                ALERT
                                SUCCESS
                                SOLD

Badge
                                    Variations

A Badge, with optional background colors. Use the
                                    badgeclass to create a Badge

                                2
                                8
                                12
                                300
                                25
                                5

Tooltips

Tooltips can be a helpful way to provide information to visitors without creating clutter in a design. Tooltip plugin let's you transform native tooltip's into customizable overlays. You can adjust their content, position and appearance.

                            <button title="" data-toggle="tooltip" class="btn btn-default tip m-b-5 m-r-5" type="button" data-original-title="Up here!" ui-jq="tooltip">Top</button>
                            <button data-placement="right" title="" data-toggle="tooltip" class="btn btn-default tip m-b-5 m-r-5" type="button" data-original-title="Hello there!" ui-jq="tooltip">Right</button>
                            <button data-placement="bottom" title="" data-toggle="tooltip" class="btn btn-default tip m-b-5 m-r-5" type="button" data-original-title="Look down!" ui-jq="tooltip">Down</button>
                            <button data-placement="left" title="" data-toggle="tooltip" class="btn btn-default tip m-b-5 m-r-5" type="button" data-original-title="Over here!" ui-jq="tooltip">Left</button>


text:
require 'uri'
require 'chef/config'

# Helper functions for Push Jobs cookbook
module PushJobsHelper
  def self.package_file(url = 'http://www.opscode.com/chef/install.sh')
    uri = ::URI.parse(::URI.unescape(url))
    package_file = File.basename(uri.path)
    package_file
  end

  def self.config_path
    ::File.join(config_dir, 'push-jobs-client.rb')
  end

  def self.config_dir
    Chef::Config.platform_specific_path('/etc/chef')
  end
end


text:
<?php

namespace Haverkamp87\MessageBundle\Command;

use Doctrine\ORM\EntityManager;
use Haverkamp87\LanguageBundle\Entity\Language;
use Haverkamp87\Library\Validator\EmailAddress;
use Haverkamp87\Library\Validator\Name;
use Haverkamp87\MessageBundle\Entity\MessageTemplate;
use Haverkamp87\MessageBundle\Entity\MessageTemplateCode;
use Haverkamp87\MessageBundle\Entity\MessageTemplateField;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class CreateMessageTemplateCommand
 * @package Haverkamp87\MessageBundle\Command
 */
class CreateMessageTemplateCommand extends ContainerAwareCommand
{

	protected function configure()
	{
		$this
			->setName('haverkamp87_message:create_message_template')
			->setDescription('Create a new message template')
			->addArgument('name', InputArgument::REQUIRED)
			->addArgument('messageTemplateCode', InputArgument::REQUIRED, 'The MessageTemplateCode name')
			->addArgument('messageTemplateFields', InputArgument::REQUIRED, 'A MessageTemplateFields JSON array')
			->addArgument('language', InputArgument::REQUIRED, 'The Language ISO code')
			->addArgument('subject', InputArgument::REQUIRED)
			->addArgument('from', InputArgument::REQUIRED, 'Email address')
			->addArgument('src', InputArgument::REQUIRED, 'The template file source');
	}

	/**
	 * @param InputInterface $input
	 * @param OutputInterface $output
	 * @return void
	 */
	protected function execute(InputInterface $input, OutputInterface $output)
	{
		/**
		 * @var EntityManager $entityManager
		 */
		$entityManager = $this->getContainer()
			->get('doctrine')
			->getManager();

		/**
		 * @var string $name
		 */
		$name = $input->getArgument('name');

		// validate name argument
		if (!Name::isValid($name)) {
			$output->writeln('<error>Argument \'name\' is invalid.</error>');
			return;
		}

		/**
		 * @var MessageTemplateCode $messageTemplateCode
		 */
		$messageTemplateCodeRepository = $entityManager->getRepository('Haverkamp87MessageBundle:MessageTemplateCode');
		$messageTemplateCode = $messageTemplateCodeRepository->findOneBy(array(
			'name' => $input->getArgument('messageTemplateCode'),
		));

		// validate messageTemplateCode argument
		if (!$messageTemplateCode instanceof MessageTemplateCode) {
			$output->writeln('<error>Argument \'messageTemplateCode\' is invalid.</error>');
			return;
		}

		/**
		 * @var MessageTemplateField[] $messageTemplateFields
		 */
		$messageTemplateFields = $input->getArgument('messageTemplateFields');

		// validate messageTemplateFields argument
		if (!is_array($messageTemplateFields = json_decode($messageTemplateFields))) {
			$output->writeln('<error>Argument \'messageTemplateFields\' is invalid.</error>');
			return;
		}

		// check if the given messageTemplateFields exists
		$messageTemplateFieldRepository = $entityManager->getRepository('Haverkamp87MessageBundle:MessageTemplateField');
		foreach ($messageTemplateFields as $name) {
			$messageTemplateField = $messageTemplateFieldRepository->findOneBy(array(
				'name' => $name,
			));

			if (!$messageTemplateField instanceof MessageTemplateField) {
				$output->writeln('<notice>MessageTemplateField \'' . $name . '\' not found.</notice>');
			}
		}

		// get the message template fields
		$messageTemplateFields = $messageTemplateFieldRepository->findBy(array(
			'name' => $messageTemplateFields,
		));

		/**
		 * @var Language $language
		 */
		$languageRepository = $entityManager->getRepository('Haverkamp87LanguageBundle:Language');
		$language = $languageRepository->findOneBy(array(
			'iso' => $input->getArgument('language'),
		));

		// validate language argument
		if (!$language instanceof Language) {
			$output->writeln('<error>Argument \'language\' is invalid.</error>');
			return;
		}

		/**
		 * @var string $subject
		 */
		$subject = $input->getArgument('subject');

		// @todo: validate subject argument

		/**
		 * @var string $from
		 */
		$from = $input->getArgument('from');

		// validate from argument
		if (!EmailAddress::isValid($from)) {
			$output->writeln('<error>Argument \'from\' is invalid.</error>');
			return;
		}

		/**
		 * @var string $src
		 */
		$src = $input->getArgument('src');

		// validate src argument
		if (!$this->getContainer()
			->get('templating')
			->exists($src)
		) {
			$output->writeln('<error>Argument \'src\' is invalid.</error>');
			return;
		}

		// check if the message template exist
		$messageTemplateRepository = $entityManager->getRepository('Haverkamp87MessageBundle:MessageTemplate');
		$messageTemplate = $messageTemplateRepository->findOneBy(array(
			'messageTemplateCode' => $messageTemplateCode,
			'language' => $language,
		));

		// add a new message template
		if (!$messageTemplate instanceof MessageTemplate) {
			$messageTemplate = new MessageTemplate();
			$messageTemplate->setName($name);
			$messageTemplate->setMessageTemplateCode($messageTemplateCode);
			$messageTemplate->setMessageTemplateFields($messageTemplateFields);
			$messageTemplate->setLanguage($language);
			$messageTemplate->setSubject($subject);
			$messageTemplate->setFrom($from);
			$messageTemplate->setSrc($src);
			$messageTemplate->setActive(true);

			$entityManager->persist($messageTemplate);
			$entityManager->flush();

			$output->writeln('<info>New message template created.</info>');
		} else {
			$output->writeln('<info>Message template already exists.</info>');
		}
	}

}


text:
package com.huawei.push.messaging;

import com.huawei.push.util.IgnoreSSLUtils;
import com.huawei.push.util.ValidatorUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/** Configurable HCM options. */
public class HuaweiOption {
    private static final Logger logger = LoggerFactory.getLogger(HuaweiOption.class);

    private final HuaweiCredential credential;
    private final CloseableHttpClient httpClient;
    private final ThreadManager threadManager;

    private HuaweiOption(HuaweiOption.Builder builder) {
        ValidatorUtils.checkArgument(builder.credential != null, "HuaweiOption must be initialized with setCredential()");
        this.credential = builder.credential;

        ValidatorUtils.checkArgument(builder.httpClient != null, "HuaweiOption must be initialized with a non-null httpClient");
        this.httpClient = builder.httpClient;

        ValidatorUtils.checkArgument(builder.threadManager != null, "HuaweiOption must be initialized with a non-null threadManager");
        this.threadManager = builder.threadManager;
    }

    /**
     * Returns a instance of HuaweiCredential used for refreshing token.
     *
     * @return A HuaweiCredential instance.
     */
    public HuaweiCredential getCredential() {
        return credential;
    }

    /**
     * Returns a instance of httpclient used for sending http request.
     *
     * @return A httpclient instance.
     */
    public CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    public ThreadManager getThreadManager() {
        return threadManager;
    }

    /**
     * Builder for constructing {@link HuaweiOption}.
     */
    public static Builder builder() {
        return new Builder();
    }

    public static final class Builder {
        private HuaweiCredential credential;
        private CloseableHttpClient httpClient;

        {
            try {
                httpClient = IgnoreSSLUtils.createClient();
            } catch (KeyManagementException | NoSuchAlgorithmException e) {
                logger.debug("Fail to create httpClient for sending message", e);
            }
        }

        private ThreadManager threadManager = HuaweiThreadManager.DEFAULT_THREAD_MANAGER;

        public Builder() {}

        public Builder setCredential(HuaweiCredential credential) {
            this.credential = credential;
            return this;
        }

        public Builder setHttpClient(CloseableHttpClient httpClient) {
            this.httpClient = httpClient;
            return this;
        }

        public Builder setThreadManager(ThreadManager threadManager) {
            this.threadManager = threadManager;
            return this;
        }

        public HuaweiOption build() {
            return new HuaweiOption(this);
        }
    }
}


text:
package org.switchyard.component.test.mixins.transaction;

import com.arjuna.ats.jta.common.JTAEnvironmentBean;

/**
 * Helper interface which lets abstract {@link JTAEnvironmentBean} lookup.
 */
public interface TransactionMixInParticipant {

    /**
     * Locates Arjuna environment bean, if null value is returned then
     * TransactionMixIn will continue looking it in next participant. If all
     * participants will return null value then default JTAEnvironmentBean will
     * be used.
     *
     * @return Instance of environment bean or null.
     * @throws Throwable In case of failure to look up.
     */
    JTAEnvironmentBean locateEnvironmentBean() throws Throwable;

}


text:
(function () {
    'use strict';
    CPM.namespace('nodes');

    (function (nodes, core) {

        nodes.profile = nodes.profile || new core.LocalProfile('composum.nodes');

    })(CPM.nodes, CPM.core);

})();


text:
package me.normanmaurer.niosmtp.delivery.lmtp;

import java.io.ByteArrayInputStream;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

import me.normanmaurer.niosmtp.SMTPClientFuture;
import me.normanmaurer.niosmtp.core.SMTPMessageImpl;
import me.normanmaurer.niosmtp.delivery.AbstractSMTPSClientTest;
import me.normanmaurer.niosmtp.delivery.AssertCheck;
import me.normanmaurer.niosmtp.delivery.AsyncAssertCheck;
import me.normanmaurer.niosmtp.delivery.BogusSslContextFactory;
import me.normanmaurer.niosmtp.delivery.DeliveryRecipientStatus;
import me.normanmaurer.niosmtp.delivery.LMTPDeliveryAgent;
import me.normanmaurer.niosmtp.delivery.MockLogger;
import me.normanmaurer.niosmtp.delivery.SMTPDeliveryAgent;
import me.normanmaurer.niosmtp.delivery.SMTPDeliveryEnvelope;
import me.normanmaurer.niosmtp.delivery.impl.SMTPDeliveryAgentConfigImpl;
import me.normanmaurer.niosmtp.delivery.impl.SMTPDeliveryEnvelopeImpl;
import me.normanmaurer.niosmtp.delivery.lmtp.AbstractLMTPClientTest.RejectOneRecipientAfterDataAssertCheck;
import me.normanmaurer.niosmtp.transport.FutureResult;
import me.normanmaurer.niosmtp.transport.SMTPClientTransport;
import me.normanmaurer.niosmtp.util.TestUtils;

import org.apache.james.protocols.api.Encryption;
import org.apache.james.protocols.api.handler.WiringException;
import org.apache.james.protocols.netty.NettyServer;
import org.apache.james.protocols.lmtp.LMTPConfigurationImpl;
import org.apache.james.protocols.lmtp.LMTPProtocolHandlerChain;
import org.apache.james.protocols.lmtp.hook.DeliverToRecipientHook;
import org.apache.james.protocols.smtp.MailEnvelope;
import org.apache.james.protocols.smtp.SMTPProtocol;
import org.apache.james.protocols.smtp.SMTPSession;
import org.apache.james.protocols.smtp.hook.Hook;
import org.apache.james.protocols.smtp.hook.HookResult;
import org.apache.james.protocols.smtp.hook.HookReturnCode;
import org.apache.james.protocols.smtp.hook.SimpleHook;
import org.apache.james.protocols.smtp.MailAddress;
import org.junit.Test;

public abstract class AbstractLMTPSClientTest extends AbstractSMTPSClientTest{

    @Override
    protected NettyServer create(Hook hook) throws WiringException {
        if (hook instanceof SimpleHook) {
            hook = new SimpleHookAdapter((SimpleHook)hook);
        }
        LMTPProtocolHandlerChain chain = new LMTPProtocolHandlerChain(hook);

        return new NettyServer(new SMTPProtocol(chain, new LMTPConfigurationImpl(), new MockLogger()), Encryption.createTls(BogusSslContextFactory.getServerContext()));

    }

    @Override
    protected SMTPClientTransport createSMTPClient() {
        return createFactory().createSMTPS(BogusSslContextFactory.getClientContext());
    }

    @Override
    protected SMTPDeliveryAgent createAgent(SMTPClientTransport transport) {
        return new LMTPDeliveryAgent(transport);
    }

    @Test
    public void testRejectOneRecipientAfterData() throws Exception {
        checkRejectOneRecipientAfterData(new RejectOneRecipientAfterDataAssertCheck());
    }

    @Test
    public void testRejectOneRecipientAfterDataNonBlocking() throws Exception {
        checkRejectOneRecipientAfterData(new AsyncAssertCheck(new RejectOneRecipientAfterDataAssertCheck()));
    }

    private void checkRejectOneRecipientAfterData(AssertCheck check) throws Exception {
        int port = TestUtils.getFreePort();

        NettyServer smtpServer = create(new DeliverToRecipientHook() {

            @Override
            public HookResult deliver(SMTPSession session, MailAddress address, MailEnvelope env) {
                if (address.toString().equals("to@example.com")) {
                    return new HookResult(HookReturnCode.DENY);
                }
                return new HookResult(HookReturnCode.OK);
            }
        });

        smtpServer.setListenAddresses(new InetSocketAddress(port));

        smtpServer.bind();

        SMTPClientTransport transport = createSMTPClient();
        SMTPDeliveryAgent c = createAgent(transport);

        try {
            SMTPDeliveryAgentConfigImpl conf = createConfig();
            SMTPDeliveryEnvelope transaction = new SMTPDeliveryEnvelopeImpl("from@example.com", Arrays.asList(new String[] {"to@example.com", "to2@example.com", "to3@example.com"}), new SMTPMessageImpl(new ByteArrayInputStream("msg".getBytes())));

            SMTPClientFuture<Collection<FutureResult<Iterator<DeliveryRecipientStatus>>>> future = c.deliver(new InetSocketAddress(port), conf,transaction);
            check.onSMTPClientFuture(future);

        } finally {
            smtpServer.unbind();
            transport.destroy();
        }

    }
}


text:
import { RouteRecordRaw } from 'vue-router';

export const routeDashAccountChatCommands: RouteRecordRaw = {
	name: 'dash.account.chat-commands',
	path: 'chat-commands',
	component: () => import('./RouteDashAccountChatCommands.vue'),
};


text:
/*globals describe, beforeEach, afterEach, it*/
import sinon        from 'sinon';
import should       from 'should';
import uncapitalise from '../../../server/middleware/uncapitalise';

should.equal(true, true);

describe('Middleware :: Uncapitalise', () => {
  let sandbox;
  let res;
  let req;
  let next;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();

    res = sinon.spy();
    req = sinon.spy();
    next = sinon.spy();
  });

  afterEach(() => {
    sandbox.restore();
  });

  describe('A signup or reset request', () => {
    it('does nothing if there are no capital letters', (done) => {
      req.path = '/sagedesk/signup';
      uncapitalise(req, res, next);

      next.calledOnce.should.be.true();
      done();
    });

    it('redirects to the lower case slug if there are capital letters', (done) => {
      req.path = '/sagedesk/SignUP';
      req.url = 'http://localhost' + req.path;
      res = {
        redirect: sinon.spy(),
        set: sinon.spy()
      };

      uncapitalise(req, res, next);

      next.called.should.be.false();
      res.redirect.calledOnce.should.be.true();
      res.redirect.calledWith(301, 'http://localhost/sagedesk/signup').should.be.true();
      done();
    });
  });

  describe('An API request', () => {
    it('does nothing if there are no capital letters', (done) => {
      req.path = '/sagedesk/api/v0.1';
      uncapitalise(req, res, next);

      next.calledOnce.should.be.true();
      done();
    });

    it('redirects to the lower case slug if there are capital letters', (done) => {
      req.path = '/sagedesk/api/v0.1/ASDfJ';
      req.url = 'http://localhost' + req.path;
      res = {
        redirect: sinon.spy(),
        set: sinon.spy()
      };

      uncapitalise(req, res, next);

      next.called.should.be.false();
      res.redirect.calledOnce.should.be.true();
      res.redirect.calledWith(301, 'http://localhost/sagedesk/api/v0.1/asdfj').should.be.true();
      done();
    });
  });

  describe('Any other request', () => {
    it('does nothing if there are no capital letters', (done) => {
      req.path = '/this-is-my-a-ticket-url';
      uncapitalise(req, res, next);

      next.calledOnce.should.be.true();
      done();
    });

    it('redirects to the lower case slug if there are capital letters', function (done) {
      req.path = '/THis-iS-a-TICKet-URl';
      req.url = 'http://localhost' + req.path;
      res = {
        redirect: sinon.spy(),
        set: sinon.spy()
      };

      uncapitalise(req, res, next);

      next.called.should.be.false();
      res.redirect.calledOnce.should.be.true();
      res.redirect.calledWith(301, 'http://localhost/this-is-a-ticket-url').should.be.true();
      done();
    });
  });
});


text:
package org.apache.polygene.api.composite;

import java.lang.reflect.Method;
import org.apache.polygene.api.common.AppliesToFilter;

/**
 * Filter Default Interface Methods to apply a generic fragment.
 */
public class DefaultMethodsFilter
    implements AppliesToFilter
{
    @Override
    public boolean appliesTo( Method method, Class<?> mixin, Class<?> compositeType, Class<?> modifierClass )
    {
        return method.isDefault();
    }
}


text:
<?php
// © copyright XRL Team, 2012. All rights reserved.
/*
    This file is part of XRL.

    XRL is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    XRL is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with XRL.  If not, see <http://www.gnu.org/licenses/>.
*/

interface XRL_RequestFactoryInterface
{
    public function createRequest($method, array $params);
}


text:
class SynergyController < ActionController::Base
  protect_from_forgery

  before_filter :set_locale
  before_filter :set_announcement, unless: :admin?
  before_filter :assign_text
  before_filter :assign_page_photo

  protected

  def set_locale
    unless admin?
      I18n.locale = params[:locale] || I18n.default_locale
    else
      I18n.locale = :en
    end
  end

  def default_url_options(options = {})
    {locale: params[:locale]}
  end

  def set_announcement
    @announcement = Announcement
      .available_in(I18n.locale)
      .first
      .try(:decorate)
  end

  def admin?
    self.class.name =~ /admin/i
  end

  private

  def assign_text
    @text = Text.find("#{params[:controller]}/#{params[:action]}").try(:decorate)
  end

  def assign_page_photo
    @page_photo = PagePhoto.find("#{params[:controller]}/#{params[:action]}")
  rescue NameError
  end

  # Go to the application after signing out from the admin interface (Devise)
  def after_sign_out_path_for(*)
    "/"
  end

  # Disable strong_parameters inside the admin interface (Inherited Resources)
  def permitted_params
    params.permit!
  end
end