text:
<?xml version="1.0" encoding="UTF-8"?>
<!--  Copyright (C) 2014 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

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

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

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="sip_settings" msgid="7083411056842490982">"Ustawienia dzwonienia przez internet"</string>
    <string name="sip_accounts" msgid="5575635218475814144">"Konta do połączeń przez internet (SIP)"</string>
    <string name="sip_accounts_title" msgid="2082527045326874519">"Konta"</string>
    <string name="sip_receive_calls" msgid="426678617137462173">"Odbieraj połączenia przychodzące"</string>
    <string name="sip_receive_calls_summary" msgid="7390078407518633658">"Skraca czas pracy baterii"</string>
    <string name="sip_call_options_title" msgid="1140346343222696780">"Dzwoń przez internet"</string>
    <string name="sip_call_options_wifi_only_title" msgid="6659725576735517138">"Dzwoń przez internet (tylko Wi-Fi)"</string>
    <string name="sip_call_options_entry_1" msgid="7217659161237099900">"Przy wszystkich połączeniach, gdy sieć transmisji danych jest dostępna"</string>
    <string name="sip_call_options_entry_2" msgid="3432624809972300467">"Tylko internetowe"</string>
    <string name="sip_call_options_entry_3" msgid="1493464396638124047">"Pytaj przy każdym połączeniu"</string>
    <string name="sip_call_options_wifi_only_entry_1" msgid="1358513095551847314">"Wszystkie połączenia"</string>
    <string name="pick_outgoing_call_phone_type" msgid="7140865415705473564">"Połącz"</string>
    <string name="pick_outgoing_sip_phone" msgid="635431914692273175">"Użyj konta do dzwonienia przez internet:"</string>
    <string name="remember_my_choice" msgid="6204557816977242680">"Zawsze używaj do połączeń przez internet"</string>
    <string name="reset_my_choice_hint" msgid="5681276499400166714">"Konto używane domyślnie do dzwonienia przez internet możesz zmienić w sekcji Telefon > Ustawienia > Dzwonienie przez internet > Konta."</string>
    <string name="pstn_phone" msgid="9596332924895028">"Komórkowe połączenie telefoniczne"</string>
    <string name="internet_phone" msgid="4444458244774004247">"Rozmowa internetowa"</string>
    <string name="no_sip_account_found_title" msgid="1930267380483259657">"Brak konta do połączeń przez internet"</string>
    <string name="no_sip_account_found" msgid="2584609532663311723">"Na tym telefonie nie ma jeszcze kont do dzwonienia przez internet. Czy chcesz dodać takie konto teraz?"</string>
    <string name="sip_menu_add" msgid="220996859802365311">"Dodaj"</string>
    <string name="add_sip_account" msgid="800843669753980091">"Dodaj konto"</string>
    <string name="remove_sip_account" msgid="1367664438506503690">"Usuń konto"</string>
    <string name="sip_account_list" msgid="5610858485304821480">"Konta SIP"</string>
    <string name="saving_account" msgid="5336529880235177448">"Zapisuję konto…"</string>
    <string name="removing_account" msgid="5537351356808985756">"Usuwam konto…"</string>
    <string name="sip_menu_save" msgid="7882219814563869225">"Zapisz"</string>
    <string name="sip_menu_discard" msgid="2350421645423888438">"Odrzuć"</string>
    <string name="alert_dialog_close" msgid="1326011828713435134">"Zamknij profil"</string>
    <string name="alert_dialog_ok" msgid="4752048404605388940">"OK"</string>
    <string name="close_profile" msgid="3122414058856309881">"Zamknij"</string>
    <string name="primary_account_summary_with" msgid="3590771303761149724">"Konto podstawowe. <xliff:g id="REGISTRATION_STATUS">%s</xliff:g>"</string>
    <string name="registration_status_checking_status" msgid="6136793741862200337">"Sprawdzam stan..."</string>
    <string name="registration_status_registering" msgid="2677183977796278749">"Rejestruję…"</string>
    <string name="registration_status_still_trying" msgid="7648151061205513458">"Nadal próbuję…"</string>
    <string name="registration_status_not_receiving" msgid="7620333886153361090">"Połączenia nie są odbierane."</string>
    <string name="registration_status_no_data" msgid="2541999976218192413">"Rejestracja konta została zatrzymana, ponieważ nie masz połączenia internetowego."</string>
    <string name="registration_status_no_wifi_data" msgid="9154717387473039546">"Rejestracja konta została zatrzymana, ponieważ nie masz połączenia Wi-Fi."</string>
    <string name="registration_status_not_running" msgid="514205414303796800">"Rejestracja konta nie powiodła się."</string>
    <string name="registration_status_done" msgid="3264961069247314253">"Odbieranie połączeń."</string>
    <string name="registration_status_failed_try_later" msgid="2199970021756384317">"Rejestracja konta nie powiodła się: (<xliff:g id="REGISTRATION_ERROR_MESSAGE">%s</xliff:g>). Spróbujemy ponownie później."</string>
    <string name="registration_status_invalid_credentials" msgid="8406872554323334182">"Rejestracja konta nie powiodła się: nieprawidłowa nazwa użytkownika lub hasło."</string>
    <string name="registration_status_server_unreachable" msgid="7710275557045148634">"Rejestracja konta nie powiodła się: sprawdź nazwę serwera."</string>
    <string name="third_party_account_summary" msgid="9041060473615403041">"To konto jest obecnie używane przez aplikację <xliff:g id="ACCOUNT_OWNER">%s</xliff:g>."</string>
    <string name="sip_edit_title" msgid="1967247832635750410">"Szczegóły konta SIP"</string>
    <string name="sip_edit_new_title" msgid="266414118302574305">"Szczegóły konta SIP"</string>
    <string name="domain_address_title" msgid="1968479941328225423">"Serwer"</string>
    <string name="username_title" msgid="6770064611005663470">"Nazwa użytkownika"</string>
    <string name="password_title" msgid="5289013731515564295">"Hasło"</string>
    <string name="display_name_title" msgid="579241787583079773">"Wyświetlana nazwa"</string>
    <string name="proxy_address_title" msgid="6890163365640631841">"Proxy połączeń wychodzących"</string>
    <string name="port_title" msgid="6693965912656593862">"Numer portu"</string>
    <string name="transport_title" msgid="889155457465372527">"Typ transportu"</string>
    <string name="send_keepalive_title" msgid="599627072150501159">"Utrzymuj połączenie"</string>
    <string name="set_primary_title" msgid="4418523822344363725">"Ustaw jako konto podstawowe"</string>
    <string name="set_primary_summary" msgid="8917913711425551278">"Używane do połączeń wychodzących"</string>
    <string name="advanced_settings" msgid="6622996380747040711">"Ustawienia opcjonalne"</string>
    <string name="auth_username_title" msgid="8262491689004708265">"Nazwa do uwierzytelniania"</string>
    <string name="auth_username_summary" msgid="941160241371436473">"Nazwa użytkownika używana do uwierzytelniania"</string>
    <string name="default_preference_summary" msgid="1979249643719483249">"<Nie ustawiono>"</string>
    <string name="display_name_summary" msgid="7155076491675565407">"<Taka jak nazwa użytkownika>"</string>
    <string name="optional_summary" msgid="2363105560396317624">"<Opcjonalny>"</string>
    <string name="advanced_settings_show" msgid="7838761602853998622">"▷ Dotknij, by pokazać wszystko"</string>
    <string name="advanced_settings_hide" msgid="3480554978705290228">"▽ Dotknij, by ukryć wszystko"</string>
    <string name="empty_alert" msgid="6659484914371384024">"Pole <xliff:g id="INPUT_FIELD_NAME">%s</xliff:g> jest wymagane i nie może pozostać puste."</string>
    <string name="not_a_valid_port" msgid="7931422555587011830">"Numer portu powinien mieć wartość od 1000 do 65 534."</string>
    <string name="no_internet_available_title" msgid="5967612364991972539">"Brak internetu"</string>
    <string name="no_wifi_available_title" msgid="3560623175076099410">"Brak połączenia Wi-Fi"</string>
    <string name="no_internet_available" msgid="3166751740849243568">"Aby zadzwonić przez internet, sprawdź najpierw połączenie internetowe."</string>
    <string name="no_wifi_available" msgid="8786934834522321080">"Aby dzwonić przez internet, musisz połączyć się z siecią Wi-Fi (użyj ustawień w sekcji Sieci zwykłe i bezprzewodowe)."</string>
    <string name="no_voip" msgid="1600568347241920141">"Brak obsługi połączeń przez internet"</string>
    <string name="sip_system_decide" msgid="5577696249416700671">"Automatycznie"</string>
    <string name="sip_always_send_keepalive" msgid="4773022409239823318">"Zawsze wysyłaj"</string>
    <string name="sip_connection_service_label" msgid="9214942431972794760">"Wbudowana funkcja telefonii internetowej"</string>
</resources>


text:
'use strict';

var cluster = require('cluster');
var nWorkers = require('os').cpus().length;

module.exports = function initMaster() {

  for (var i = 0; i < nWorkers; i++) {
    cluster.fork();
  }

  cluster.on('online', function(worker) {
    console.log('Worker ' + worker.id + ' (pid: ' + worker.process.pid + ') is online.');
  });

  cluster.on('exit', function(worker, code, signal) {
    console.log('Worker ' + worker.id + ' (pid: ' + worker.process.pid +
      ') died with code ' + code + ' and signal ' + signal);
  });

};

redpajama_set_name: RedPajamaGithub


text: test


text:
Scorekeeper
===========

Simple score-keeping app for WP8. Basically practice with MVVM and TDD.

Going to include:
* Score keeping for as many players as you can! (Probably will have a limit for practicality sake)
* Score history
* Fast resume


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../../">
  <title data-ice="title">VmsgEngine | videojs-record</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

<meta name="description" content="A video.js plugin for recording audio/video/image files."><meta property="twitter:card" content="summary"><meta property="twitter:title" content="videojs-record"><meta property="twitter:description" content="A video.js plugin for recording audio/video/image files.">

  Home

  Reference
  Source

    <input class="search-input">

CEvent

CRecord

FdefaultKeyHandler

VpluginDefaultOptions

VPlugin

controlsCAnimationDisplay

CCameraButton

CDeviceButton

CPictureInPictureToggle

CRecordCanvas

CRecordIndicator

CRecordToggle

VComponent

VButton

engineCConvertEngine

CRecordEngine

CRecordRTCEngine

FgetAudioEngine

FgetConvertEngine

FgetVideoEngine

FisAudioPluginActive

FgetRecorderMode

VCONVERT_PLUGINS

VFFMPEGJS

VFFMPEGWASM

VTSEBML

VAUDIO_PLUGINS

VLAMEJS

VLIBVORBISJS

VOPUSMEDIARECORDER

VOPUSRECORDER

VRECORDERJS

VRECORDRTC

VRECORD_PLUGINS

VVIDEO_PLUGINS

VVMSG

VWEBMWASM

VANIMATION

VAUDIO_ONLY

VAUDIO_SCREEN

VAUDIO_VIDEO

VIMAGE_ONLY

VSCREEN_ONLY

VVIDEO_ONLY

pluginsCFFmpegWasmEngine

CFFmpegjsEngine

CLamejsEngine

CLibVorbisEngine

COpusMediaRecorderEngine

COpusRecorderEngine

CRecorderjsEngine

CTsEBMLEngine

CVmsgEngine

CWebmWasmEngine

utilsFsetSrcObject

FcompareVersion

FdetectBrowser

FisChrome

FisEdge

FisFirefox

FisOpera

FisSafari

FaddFileInfo

FblobToArrayBuffer

FdownloadBlob

FformatTime

FgetExtension

import VmsgEngine from 'videojs-record/js/plugins/vmsg-plugin.js'

  public
  class

  | source

VmsgEngine

Extends:

Component → RecordEngine → VmsgEngine

Audio-only engine for the vmsg library.

Constructor Summary

Public Constructor

      public

          constructor(player: Player, options: Object)

Creates an instance of this class.

Member Summary

Public Members

      public

          audioContext: *

      public

          audioSourceNode: *

      public

          audioWebAssemblyURL: string

Path to vmsg.wasm WebAssembly script.

      public

          config: {"wasmURL": *}

      public

          debug: boolean

Enables console logging for debugging purposes.

      public

          engine: *

      public

          inputStream: *

      public

          mediaType: *

      public

          pluginLibraryOptions: object

Additional configuration options for the vmsg library.

      public

          processor: *

Method Summary

Public Methods

      public

          destroy()

Destroy engine.

      public

          setup(stream: LocalMediaStream, mediaType: Object, debug: Boolean)

Setup recording engine.

      public

          start()

Start recording.

      public

          stop()

Stop recording.

Private Methods

      private

          onAudioProcess(event: object)

Continuous encoding of audio data.

      private

          onRecordingAvailable()

Inherited Summary

 From class RecordEngine

      public

          recordedData: *

      public

          addFileInfo(fileObj: Blob | File)

Add filename and timestamp to recorded file object.

      public

          destroy()

Destroy engine.

      public

          saveAs(name: Object): void

Show save as dialog in browser so the user can store the recorded
media locally.

      private

          dispose()

Remove any temporary data and references to streams.

      private

          onStopRecording(data: blob)

Invoked when recording is stopped and resulting stream is available.

Public Constructors

    public

    constructor(player: Player, options: Object)

      source

Creates an instance of this class.

Override:
RecordEngine#constructor

Params:

Name	Type	Attribute	Description

      player
      Player

The Player that this class should be attached to.

      options
      Object

optional

The key/value store of player options.

Public Members

    public

    audioContext: *

      source

    public

    audioSourceNode: *

      source

    public

    audioWebAssemblyURL: string

      source

Path to vmsg.wasm WebAssembly script.

    public

    config: {"wasmURL": *}

      source

    public

    debug: boolean

      source

Enables console logging for debugging purposes.

    public

    engine: *

      source

    public

    inputStream: *

      source

    public

    mediaType: *

      source

    public

    pluginLibraryOptions: object

      source

Additional configuration options for the vmsg library.

    public

    processor: *

      source

Public Methods

    public

    destroy()

      source

Destroy engine.

Override:
RecordEngine#destroy

    public

    setup(stream: LocalMediaStream, mediaType: Object, debug: Boolean)

      source

Setup recording engine.

Params:

Name	Type	Attribute	Description

      stream
      LocalMediaStream

Media stream to record.

      mediaType
      Object

Object describing the media type of this
    engine.

      debug
      Boolean

Indicating whether or not debug messages should
    be printed in the console.

    public

    start()

      source

Start recording.

    public

    stop()

      source

Stop recording.

Private Methods

    private

    onAudioProcess(event: object)

      source

Continuous encoding of audio data.

Params:

Name	Type	Attribute	Description

      event
      object

Audio buffer.

    private

    onRecordingAvailable()

      source

  Generated by ESDoc(1.1.0)


text:
contenido-image-uploader
========================

Experimental desktop application for auto-resizing and uploading images to a Contenido backend.

Requirements:

* Python 2
* Python Imaging Library (http://www.pythonware.com/products/pil)
* Python Requests (http://docs.python-requests.org)


text:
using System.Windows.Controls;

namespace Smellyriver.TankInspector.UIComponents
{
    /// <summary>
    /// Interaction logic for LoadingView.xaml
    /// </summary>
    public partial class LoadingView : UserControl
    {

        internal LoadingViewModel ViewModel
        {
            get => this.DataContext as LoadingViewModel;
	        set => this.DataContext = value;
        }

        public LoadingView()
        {
            InitializeComponent();
        }

    }
}


text:
package org.cloudata.core.common.testhelper;

public class FaultException extends RuntimeException {
  private static final long serialVersionUID = -1202349264504659076L;
}


text:
var mySym = Symbol("my sym")

var obj = {
  [mySym]: 22
}
obj[mySym] //: number

obj[Symbol.iterator] = "hello"
obj[Symbol.iterator] //: string


text:
<?php

namespace Drupal\search_api\Plugin\views\field;

use Drupal\Core\Form\FormHelper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\search_api\Plugin\views\EntityFieldRenderer;
use Drupal\search_api\Utility\Utility;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\EntityField;
use Drupal\views\Plugin\views\field\MultiItemsFieldHandlerInterface;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;

/**
 * Displays entity field data.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("search_api_field")
 */
class SearchApiEntityField extends EntityField {

  use SearchApiFieldTrait {
    preRender as traitPreRender;
  }

  /**
   * The parent path of this property.
   *
   * NULL for properties of a result item.
   *
   * @var string|null
   */
  protected $parentPath;

  /**
   * Fallback handler for this field, if Field API rendering should not be used.
   *
   * @var \Drupal\views\Plugin\views\field\FieldHandlerInterface
   */
  protected $fallbackHandler;

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    // Prepare our fallback handler.
    $fallback_handler_id = !empty($this->definition['fallback_handler']) ? $this->definition['fallback_handler'] : 'search_api';
    $this->fallbackHandler = Views::handlerManager('field')
      ->getHandler($options, $fallback_handler_id);
    $options += ['fallback_options' => []];
    $fallback_options = $options['fallback_options'] + $options;
    $this->fallbackHandler->init($view, $display, $fallback_options);

    parent::init($view, $display, $options);
  }

  /**
   * {@inheritdoc}
   */
  public function query($use_groupby = FALSE) {
    // If we're not using Field API field rendering, just use the query()
    // implementation of the fallback handler.
    if (!$this->options['field_rendering']) {
      $this->fallbackHandler->query();
      return;
    }

    // If we do use Field API rendering, we need the entity object for the
    // parent property.
    $parent_path = $this->getParentPath();
    $property_path = $parent_path ? "$parent_path:_object" : '_object';
    $combined_property_path = Utility::createCombinedId($this->getDatasourceId(), $property_path);
    $this->addRetrievedProperty($combined_property_path);
  }

  /**
   * Retrieves the property path of the parent property.
   *
   * @return string|null
   *   The property path of the parent property.
   */
  protected function getParentPath() {
    if (!isset($this->parentPath)) {
      $combined_property_path = $this->getCombinedPropertyPath();
      list(, $property_path) = Utility::splitCombinedId($combined_property_path);
      list($this->parentPath) = Utility::splitPropertyPath($property_path);
    }

    return $this->parentPath;
  }

  /**
   * {@inheritdoc}
   */
  public function defineOptions() {
    $options = parent::defineOptions();

    // Gather the fallback handler's options, but exclude those just inherited
    // from the field plugin base (since they would otherwise be duplicated).
    // To find out which options should be excluded, we take the $options keys
    // from the parent and remove the keys that come directly from the parent.
    $fallback_options = [];
    if (is_callable([$this->fallbackHandler, 'defineOptions'])) {
      $fallback_options = $this->fallbackHandler->defineOptions();
      $parent_keys = $this->getParentOptionKeys();
      $remove_from_fallback = array_diff_key($options, array_flip($parent_keys));
      $fallback_options = array_diff_key($fallback_options, $remove_from_fallback);
    }

    $options['field_rendering'] = ['default' => TRUE];
    $options['fallback_handler'] = ['default' => $this->fallbackHandler->getPluginId()];
    $options['fallback_options'] = ['contains' => $fallback_options];

    return $options;
  }

  /**
   * Retrieves the keys of the options defined by our direct parent.
   *
   * That is, this will exclude all options defined by
   * \Drupal\views\Plugin\views\field\FieldPluginBase, and only include those
   * defined by \Drupal\views\Plugin\views\field\Field.
   *
   * @return string[]
   *   The keys of options directly defined by our parent class.
   */
  protected function getParentOptionKeys() {
    return [
      'multiple_field_settings',
      'click_sort_column',
      'type',
      'field_api_classes',
      'settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    $form['field_rendering'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Use entity field rendering'),
      '#description' => $this->t("If checked, Drupal's built-in field rendering mechanism will be used for rendering this field's values, which requires the entity to be loaded. If unchecked, a type-specific, entity-independent rendering mechanism will be used."),
      '#default_value' => $this->options['field_rendering'],
    ];

    // Wrap the (immediate) parent options in their own field set, to clean up
    // the UI when (un)checking the above checkbox.
    $form['parent_options'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Render settings'),
      '#states' => [
        'visible' => [
          ':input[name="options[field_rendering]"]' => ['checked' => TRUE],
        ],
      ],
    ];

    // Include the parent options form and move all fields that were added by
    // our direct parent (\Drupal\views\Plugin\views\field\Field) to the
    // "parent_options" fieldset.
    parent::buildOptionsForm($form, $form_state);
    $parent_keys = $this->getParentOptionKeys();
    foreach ($parent_keys as $key) {
      if (!empty($form[$key])) {
        $form[$key]['#fieldset'] = 'parent_options';
      }
    }
    // The Core boolean formatter hard-codes the field name to "field_boolean".
    // This breaks the parent class's call of rewriteStatesSelector() for fixing
    // "#states". We therefore apply that behavior again here.
    if (!empty($form['settings'])) {
      FormHelper::rewriteStatesSelector($form['settings'], "fields[field_boolean][settings_edit_form]", 'options');
    }

    // Get the options form for the fallback handler.
    $fallback_form = [];
    $this->fallbackHandler->buildOptionsForm($fallback_form, $form_state);
    // Remove all fields from FieldPluginBase from the fallback form, but leave
    // those in that were only added by our immediate parent,
    // \Drupal\views\Plugin\views\field\Field. (For example, the "type" option
    // is especially prone to conflicts here.) The others come from the plugin
    // base classes and will be identical, so it would be confusing to include
    // them twice.
    $parent_keys[] = '#pre_render';
    $remove_from_fallback = array_diff_key($form, array_flip($parent_keys));
    $fallback_form = array_diff_key($fallback_form, $remove_from_fallback);
    // Fix the "#states" selectors in the fallback form, and put an additional
    // "#states" directive on it to only be visible for the corresponding
    // "field_rendering" setting.
    if ($fallback_form) {
      FormHelper::rewriteStatesSelector($fallback_form, '"options[', '"options[fallback_options][');
      $form['fallback_options'] = $fallback_form;
      $form['fallback_options']['#type'] = 'fieldset';
      $form['fallback_options']['#title'] = $this->t('Render settings');
      $form['fallback_options']['#states']['visible'][':input[name="options[field_rendering]"]'] = ['checked' => FALSE];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function preRender(&$values) {
    if ($this->options['field_rendering']) {
      $this->traitPreRender($values);
      parent::preRender($values);
    }
    else {
      $this->fallbackHandler->preRender($values);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
    if (!$this->options['field_rendering']) {
      return $this->fallbackHandler->render($values);
    }
    return parent::render($values);
  }

  /**
   * {@inheritdoc}
   */
  public function render_item($count, $item) {
    if (!$this->options['field_rendering']) {
      if ($this->fallbackHandler instanceof MultiItemsFieldHandlerInterface) {
        return $this->fallbackHandler->render_item($count, $item);
      }
      return '';
    }
    return parent::render_item($count, $item);
  }

  /**
   * {@inheritdoc}
   */
  protected function getEntityFieldRenderer() {
    if (!isset($this->entityFieldRenderer)) {
      // This can be invoked during field handler initialization in which case
      // view fields are not set yet.
      if (!empty($this->view->field)) {
        foreach ($this->view->field as $field) {
          // An entity field renderer can handle only a single relationship.
          if (isset($field->entityFieldRenderer)) {
            if ($field->entityFieldRenderer instanceof EntityFieldRenderer && $field->entityFieldRenderer->compatibleWithField($this)) {
              $this->entityFieldRenderer = $field->entityFieldRenderer;
              break;
            }
          }
        }
      }
      if (!isset($this->entityFieldRenderer)) {
        $entity_type = $this->entityManager->getDefinition($this->getEntityType());
        $this->entityFieldRenderer = new EntityFieldRenderer($this->view, $this->relationship, $this->languageManager, $entity_type, $this->entityManager);
        $this->entityFieldRenderer->setDatasourceId($this->getDatasourceId());
      }
    }

    return $this->entityFieldRenderer;
  }

  /**
   * {@inheritdoc}
   */
  public function getItems(ResultRow $values) {
    if (!$this->options['field_rendering']) {
      if ($this->fallbackHandler instanceof MultiItemsFieldHandlerInterface) {
        return $this->fallbackHandler->getItems($values);
      }
      return [];
    }

    if ($values->search_api_datasource != $this->getDatasourceId()) {
      return [];
    }

    $parent_path = $this->getParentPath();
    if (empty($values->_relationship_objects[$parent_path])) {
      return [];
    }
    $build = [];
    foreach (array_keys($values->_relationship_objects[$parent_path]) as $i) {
      $this->valueIndex = $i;
      $build[] = parent::getItems($values);
    }
    return $build ? call_user_func_array('array_merge', $build) : [];
  }

  /**
   * {@inheritdoc}
   */
  public function renderItems($items) {
    if (!$this->options['field_rendering']) {
      if ($this->fallbackHandler instanceof MultiItemsFieldHandlerInterface) {
        return $this->fallbackHandler->renderItems($items);
      }
      return '';
    }

    return parent::renderItems($items);
  }

}


text:
layout: page
title: Quinn Black Llc. Trade Fair
date: 2016-05-24
author: Gloria Macdonald
tags: weekly links, java
status: published
summary: Nunc sit amet libero vel lorem.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 03/18/2016
  endDate: 03/19/2016
  ctyhocn: CHAKMHX
  groupCode: QBLTF
published: true
---
Nunc vitae velit dictum, lacinia libero sit amet, efficitur nisi. Cras nec dui purus. Vivamus eget sapien eget justo gravida imperdiet. Nunc tincidunt nulla non justo pellentesque, in tempus nisl posuere. Duis et ligula id elit eleifend egestas id sit amet erat. Aliquam luctus sapien ut mattis pharetra. Maecenas tincidunt pulvinar arcu, nec viverra tellus commodo at. Cras faucibus mi tellus, sit amet consectetur mauris facilisis at. Phasellus sit amet finibus arcu. Praesent eu ligula ultricies, rhoncus mi nec, ultricies felis. Quisque malesuada a leo vel ornare. Vivamus lacinia lectus a diam blandit, non mattis leo posuere. Curabitur tincidunt, nisl rhoncus ultricies rhoncus, erat nibh convallis est, at iaculis velit massa non justo.

1 Duis ut dolor eget nibh convallis porttitor.

Sed vulputate nunc lectus, vel pharetra leo tincidunt vel. In volutpat consectetur ornare. Ut cursus nibh sed cursus condimentum. In hac habitasse platea dictumst. Donec ipsum turpis, feugiat id sollicitudin ut, posuere in turpis. Maecenas porta leo non ante cursus interdum. Aenean dapibus turpis at lorem sagittis sagittis. Cras nec eros lacus. Etiam vitae ultricies lacus. Curabitur sed ligula et turpis accumsan condimentum eu sed odio. Proin fermentum, nisi in semper porttitor, ligula dolor rutrum augue, ut pretium diam dui vel lacus. Cras vitae nisi vel ante feugiat lacinia eget nec mi.


text:
<?php

namespace Vipa\ApiBundle\Tests\Controller;

use Vipa\ApiBundle\Tests\ApiBaseTestCase;
use Symfony\Component\BrowserKit\Cookie;

/**
 * Class AnalyticsRestControllerTest
 * @package Vipa\ApiBundle\Tests\Controller
 */
class AnalyticsRestControllerTest extends ApiBaseTestCase
{
    public function testArticleViewAction()
    {
        $token = $this->getContainer()
            ->get('security.csrf.token_manager')
            ->getToken('article_view');

        $client = $this->client;
        $session = $client->getContainer()->get('session');
        $session->set('_csrf/article_view', $token->getValue());
        $session->save();
        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);

        $client->request(
            'POST',
            '/api/v1/stats/article/1/view',
            [
                'token' => $token,
            ],
            [],
            ['HTTP_ACCEPT' => 'application/json']
        );

        $this->assertStatusCode(200, $client);
    }

    public function testIssueViewAction()
    {
        $token = $this->getContainer()
            ->get('security.csrf.token_manager')
            ->getToken('issue_view');

        $client = $this->client;
        $session = $client->getContainer()->get('session');
        $session->set('_csrf/issue_view', $token->getValue());
        $session->save();
        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);

        $client->request(
            'POST',
            '/api/v1/stats/issue/1/view',
            [
                'token' => $token,
            ],
            [],
            ['HTTP_ACCEPT' => 'application/json']
        );

        $this->assertStatusCode(200, $client);
    }

    public function testJournalViewAction()
    {
        $token = $this->getContainer()
            ->get('security.csrf.token_manager')
            ->getToken('journal_view');

        $client = $this->client;
        $session = $client->getContainer()->get('session');
        $session->set('_csrf/journal_view', $token->getValue());
        $session->save();
        $cookie = new Cookie($session->getName(), $session->getId());
        $this->client->getCookieJar()->set($cookie);

        $client->request(
            'POST',
            '/api/v1/stats/journal/1/view',
            [
                'token' => $token,
            ],
            [],
            ['HTTP_ACCEPT' => 'application/json']
        );

        $this->assertStatusCode(200, $client);
    }
}


text:
"""
Example generation for Py-ART

Generate the rst files for the examples by iterating over the Python
example files.

Files that generate images should state with 'plot'

"""

# This files was adapted from the scikit-learn file of the same name:
# https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/gen_rst.py
#
# The scikit-learn project uses this following License which applies to this
# file.
#
# New BSD License
#
# Copyright (c) 2007-2013 The scikit-learn developers.
# All rights reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   a. Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#   b. Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#   c. Neither the name of the Scikit-learn Developers nor the names of
#      its contributors may be used to endorse or promote products
#      derived from this software without specific prior written
#      permission.
#
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.

from time import time
import os
import re
import shutil
import traceback
import glob
import sys
from StringIO import StringIO
import cPickle
import urllib2
import gzip
import posixpath

try:
    from PIL import Image
except:
    import Image

import matplotlib
matplotlib.use('Agg')

import token
import tokenize
import numpy as np

###############################################################################
# A tee object to redict streams to multiple outputs

class Tee(object):

    def __init__(self, file1, file2):
        self.file1 = file1
        self.file2 = file2

    def write(self, data):
        self.file1.write(data)
        self.file2.write(data)

    def flush(self):
        self.file1.flush()
        self.file2.flush()

###############################################################################
# Documentation link resolver objects

def get_data(url):
    """Helper function to get data over http or from a local file"""
    if url.startswith('http://'):
        resp = urllib2.urlopen(url)
        encoding = resp.headers.dict.get('content-encoding', 'plain')
        data = resp.read()
        if encoding == 'plain':
            pass
        elif encoding == 'gzip':
            data = StringIO(data)
            data = gzip.GzipFile(fileobj=data).read()
        else:
            raise RuntimeError('unknown encoding')
    else:
        with open(url, 'r') as fid:
            data = fid.read()
        fid.close()

    return data

def parse_sphinx_searchindex(searchindex):
    """Parse a Sphinx search index

    Parameters
    ----------
    searchindex : str
        The Sphinx search index (contents of searchindex.js)

    Returns
    -------
    filenames : list of str
        The file names parsed from the search index.
    objects : dict
        The objects parsed from the search index.
    """
    def _select_block(str_in, start_tag, end_tag):
        """Select first block delimited by start_tag and end_tag"""
        start_pos = str_in.find(start_tag)
        if start_pos < 0:
            raise ValueError('start_tag not found')
        depth = 0
        for pos in range(start_pos, len(str_in)):
            if str_in[pos] == start_tag:
                depth += 1
            elif str_in[pos] == end_tag:
                depth -= 1

            if depth == 0:
                break
        sel = str_in[start_pos + 1:pos]
        return sel

    def _parse_dict_recursive(dict_str):
        """Parse a dictionary from the search index"""
        dict_out = dict()
        pos_last = 0
        pos = dict_str.find(':')
        while pos >= 0:
            key = dict_str[pos_last:pos]
            if dict_str[pos + 1] == '[':
                # value is a list
                pos_tmp = dict_str.find(']', pos + 1)
                if pos_tmp < 0:
                    raise RuntimeError('error when parsing dict')
                value = dict_str[pos + 2: pos_tmp].split(',')
                # try to convert elements to int
                for i in range(len(value)):
                    try:
                        value[i] = int(value[i])
                    except ValueError:
                        pass
            elif dict_str[pos + 1] == '{':
                # value is another dictionary
                subdict_str = _select_block(dict_str[pos:], '{', '}')
                value = _parse_dict_recursive(subdict_str)
                pos_tmp = pos + len(subdict_str)
            else:
                raise ValueError('error when parsing dict: unknown elem')

            key = key.strip('"')
            if len(key) > 0:
                dict_out[key] = value

            pos_last = dict_str.find(',', pos_tmp)
            if pos_last < 0:
                break
            pos_last += 1
            pos = dict_str.find(':', pos_last)

        return dict_out

    # parse objects
    query = 'objects:'
    pos = searchindex.find(query)
    if pos < 0:
        raise ValueError('"objects:" not found in search index')

    sel = _select_block(searchindex[pos:], '{', '}')
    objects = _parse_dict_recursive(sel)

    # parse filenames
    query = 'filenames:'
    pos = searchindex.find(query)
    if pos < 0:
        raise ValueError('"filenames:" not found in search index')
    filenames = searchindex[pos + len(query) + 1:]
    filenames = filenames[:filenames.find(']')]
    filenames = [f.strip('"') for f in filenames.split(',')]

    return filenames, objects

class SphinxDocLinkResolver(object):
    """ Resolve documentation links using searchindex.js generated by Sphinx

    Parameters
    ----------
    doc_url : str
        The base URL of the project website.
    searchindex : str
        Filename of searchindex, relative to doc_url.
    extra_modules_test : list of str
        List of extra module names to test.
    relative : bool
        Return relative links (only useful for links to documentation of this
        package).
    """

    def __init__(self, doc_url, searchindex='searchindex.js',
                 extra_modules_test=None, relative=False):
        self.doc_url = doc_url
        self.relative = relative
        self._link_cache = {}

        self.extra_modules_test = extra_modules_test
        self._page_cache = {}
        if doc_url.startswith('http://'):
            if relative:
                raise ValueError('Relative links are only supported for local '
                                 'URLs (doc_url cannot start with "http://)"')
            searchindex_url = doc_url + '/' + searchindex
        else:
            searchindex_url = os.path.join(doc_url, searchindex)

        # detect if we are using relative links on a Windows system
        if os.name.lower() == 'nt' and not doc_url.startswith('http://'):
            if not relative:
                raise ValueError('You have to use relative=True for the local'
                                 'package on a Windows system.')
            self._is_windows = True
        else:
            self._is_windows = False

        # download and initialize the search index
        sindex = get_data(searchindex_url)
        filenames, objects = parse_sphinx_searchindex(sindex)

        self._searchindex = dict(filenames=filenames, objects=objects)

    def _get_link(self, cobj):
        """Get a valid link, False if not found"""

        fname_idx = None
        full_name = cobj['module_short'] + '.' + cobj['name']
        if full_name in self._searchindex['objects']:
            value = self._searchindex['objects'][full_name]
            if isinstance(value, dict):
                value = value[value.keys()[0]]
            fname_idx = value[0]
        elif cobj['module_short'] in self._searchindex['objects']:
            value = self._searchindex['objects'][cobj['module_short']]
            if cobj['name'] in value.keys():
                fname_idx = value[cobj['name']][0]

        if fname_idx is not None:
            fname = self._searchindex['filenames'][fname_idx] + '.html'

            if self._is_windows:
                fname = fname.replace('/', '\\')
                link = os.path.join(self.doc_url, fname)
            else:
                link = posixpath.join(self.doc_url, fname)

            if link in self._page_cache:
                html = self._page_cache[link]
            else:
                html = get_data(link)
                self._page_cache[link] = html

            # test if cobj appears in page
            comb_names = [cobj['module_short'] + '.' + cobj['name']]
            if self.extra_modules_test is not None:
                for mod in self.extra_modules_test:
                    comb_names.append(mod + '.' + cobj['name'])
            url = False
            for comb_name in comb_names:
                if html.find(comb_name) >= 0:
                    url = link + '#' + comb_name
            link = url
        else:
            link = False

        return link

    def resolve(self, cobj, this_url):
        """Resolve the link to the documentation, returns None if not found

        Parameters
        ----------
        cobj : dict
            Dict with information about the "code object" for which we are
            resolving a link.
            cobi['name'] : function or class name (str)
            cobj['module_short'] : shortened module name (str)
            cobj['module'] : module name (str)
        this_url: str
            URL of the current page. Needed to construct relative URLs
            (only used if relative=True in constructor).

        Returns
        -------
        link : str | None
            The link (URL) to the documentation.
        """
        full_name = cobj['module_short'] + '.' + cobj['name']
        link = self._link_cache.get(full_name, None)
        if link is None:
            # we don't have it cached
            link = self._get_link(cobj)
            # cache it for the future
            self._link_cache[full_name] = link

        if link is False or link is None:
            # failed to resolve
            return None

        if self.relative:
            link = os.path.relpath(link, start=this_url)
            if self._is_windows:
                # replace '\' with '/' so it on the web
                link = link.replace('\\', '/')

            # for some reason, the relative link goes one directory too high up
            link = link[3:]

        return link

###############################################################################
rst_template = """

.. _example_%(short_fname)s:

%(docstring)s

**Python source code:** :download:`%(fname)s <%(fname)s>`

.. literalinclude:: %(fname)s
    :lines: %(end_row)s-
    """

plot_rst_template = """

.. _example_%(short_fname)s:

%(docstring)s

%(image_list)s

%(stdout)s

**Python source code:** :download:`%(fname)s <%(fname)s>`

.. literalinclude:: %(fname)s
    :lines: %(end_row)s-

**Total running time of the example:** %(time_elapsed) .2f seconds
    """

# The following strings are used when we have several pictures: we use
# an html div tag that our CSS uses to turn the lists into horizontal
# lists.
HLIST_HEADER = """
.. rst-class:: horizontal

"""

HLIST_IMAGE_TEMPLATE = """
    *

      .. image:: images/%s
            :scale: 47
"""

SINGLE_IMAGE = """
.. image:: images/%s
    :align: center
"""

def extract_docstring(filename, ignore_heading=False):
    """ Extract a module-level docstring, if any
    """
    lines = file(filename).readlines()
    start_row = 0
    if lines[0].startswith('#!'):
        lines.pop(0)
        start_row = 1
    docstring = ''
    first_par = ''
    tokens = tokenize.generate_tokens(iter(lines).next)
    for tok_type, tok_content, _, (erow, _), _ in tokens:
        tok_type = token.tok_name[tok_type]
        if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
            continue
        elif tok_type == 'STRING':
            docstring = eval(tok_content)
            # If the docstring is formatted with several paragraphs, extract
            # the first one:
            paragraphs = '\n'.join(
                line.rstrip() for line
                in docstring.split('\n')).split('\n\n')
            if paragraphs:
                if ignore_heading:
                    if len(paragraphs) > 1:
                        first_par = re.sub('\n', ' ', paragraphs[1])
                        first_par = ((first_par[:95] + '...')
                                     if len(first_par) > 95 else first_par)
                    else:
                        raise ValueError("Docstring not found by gallery",
                                         "Please check your example's layout",
                                         " and make sure it's correct")
                else:
                    first_par = paragraphs[0]

        break
    return docstring, first_par, erow + 1 + start_row

def generate_example_rst(app):
    """ Generate the list of examples, as well as the contents of
        examples.
    """
    root_dir = os.path.join(app.builder.srcdir, 'auto_examples')
    example_dir = os.path.abspath(app.builder.srcdir + '/../../' + 'examples')
    try:
        plot_gallery = eval(app.builder.config.plot_gallery)
    except TypeError:
        plot_gallery = bool(app.builder.config.plot_gallery)
    if not os.path.exists(example_dir):
        os.makedirs(example_dir)
    if not os.path.exists(root_dir):
        os.makedirs(root_dir)

    # we create an index.rst with all examples
    fhindex = file(os.path.join(root_dir, 'index.rst'), 'w')
    fhindex.write("""\

.. raw:: html

    <style type="text/css">

    .figure {
        float: left;
        margin: 10px;
        -webkit-border-radius: 10px; /* Saf3-4, iOS 1-3.2, Android <1.6 */
        -moz-border-radius: 10px; /* FF1-3.6 */
        border-radius: 10px; /* Opera 10.5, IE9, Saf5, Chrome, FF4, iOS 4, Android 2.1+ */
        border: 2px solid #fff;
        background-color: white;
        /* --> Thumbnail image size */
        width: 150px;
        height: 100px;
        -webkit-background-size: 150px 100px; /* Saf3-4 */
        -moz-background-size: 150px 100px; /* FF3.6 */
    }

    .figure img {
        display: inline;
    }

    div.docstringWrapper p.caption {
        display: block;
        -webkit-box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.0);
        -moz-box-shadow: 0px 0px 20px rgba(0, 0, 0, .0); /* FF3.5 - 3.6 */
        box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.0); /* Opera 10.5, IE9, FF4+, Chrome 10+ */
        padding: 0px;
        border: white;
    }

    div.docstringWrapper p {
        display: none;
        background-color: white;
        -webkit-box-shadow: 0px 0px 20px rgba(0, 0, 0, 1.00);
        -moz-box-shadow: 0px 0px 20px rgba(0, 0, 0, 1.00); /* FF3.5 - 3.6 */
        box-shadow: 0px 0px 20px rgba(0, 0, 0, 1.00); /* Opera 10.5, IE9, FF4+, Chrome 10+ */
        padding: 13px;
        margin-top: 0px;
        border-style: solid;
        border-width: 1px;
    }

    </style>

.. raw:: html

        <script type="text/javascript">

        function animateClone(e){
          var position;
          position = $(this).position();
          var clone = $(this).closest('.thumbnailContainer').find('.clonedItem');
          var clone_fig = clone.find('.figure');
          clone.css("left", position.left - 70).css("top", position.top - 70).css("position", "absolute").css("z-index", 1000).css("background-color", "white");

          var cloneImg = clone_fig.find('img');

          clone.show();
          clone.animate({
                height: "270px",
                width: "320px"
            }, 0
          );
          cloneImg.css({
                'max-height': "200px",
                'max-width': "280px"
          });
          cloneImg.animate({
                height: "200px",
                width: "280px"
            }, 0
           );
          clone_fig.css({
               'margin-top': '20px',
          });
          clone_fig.show();
          clone.find('p').css("display", "block");
          clone_fig.css({
               height: "240",
               width: "305px"
          });
          cloneP_height = clone.find('p.caption').height();
          clone_fig.animate({
               height: (200 + cloneP_height)
           }, 0
          );

          clone.bind("mouseleave", function(e){
              clone.animate({
                  height: "100px",
                  width: "150px"
              }, 10, function(){$(this).hide();});
              clone_fig.animate({
                  height: "100px",
                  width: "150px"
              }, 10, function(){$(this).hide();});
          });
        } //end animateClone()

        $(window).load(function () {
            $(".figure").css("z-index", 1);

            $(".docstringWrapper").each(function(i, obj){
                var clone;
                var $obj = $(obj);
                clone = $obj.clone();
                clone.addClass("clonedItem");
                clone.appendTo($obj.closest(".thumbnailContainer"));
                clone.hide();
                $obj.bind("mouseenter", animateClone);
            }); // end each
        }); // end

        </script>

Examples
========

.. _examples-index:
""")
    # Here we don't use an os.walk, but we recurse only twice: flat is
    # better than nested.
    generate_dir_rst('.', fhindex, example_dir, root_dir, plot_gallery)
    for dir in sorted(os.listdir(example_dir)):
        if os.path.isdir(os.path.join(example_dir, dir)):
            generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery)
    fhindex.flush()

def extract_line_count(filename, target_dir):
    # Extract the line count of a file
    example_file = os.path.join(target_dir, filename)
    lines = file(example_file).readlines()
    start_row = 0
    if lines and lines[0].startswith('#!'):
        lines.pop(0)
        start_row = 1
    tokens = tokenize.generate_tokens(lines.__iter__().next)
    check_docstring = True
    erow_docstring = 0
    for tok_type, _, _, (erow, _), _ in tokens:
        tok_type = token.tok_name[tok_type]
        if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
            continue
        elif ((tok_type == 'STRING') and check_docstring):
            erow_docstring = erow
            check_docstring = False
    return erow_docstring+1+start_row, erow+1+start_row

def line_count_sort(file_list, target_dir):
    # Sort the list of examples by line-count
    new_list = filter(lambda x: x.endswith('.py'), file_list)
    unsorted = np.zeros(shape=(len(new_list), 2))
    unsorted = unsorted.astype(np.object)
    for count, exmpl in enumerate(new_list):
        docstr_lines, total_lines = extract_line_count(exmpl, target_dir)
        unsorted[count][1] = total_lines - docstr_lines
        unsorted[count][0] = exmpl
    index = np.lexsort((unsorted[:, 0].astype(np.str),
                        unsorted[:, 1].astype(np.float)))
    if not len(unsorted):
        return []
    return np.array(unsorted[index][:, 0]).tolist()

def generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery):
    """ Generate the rst file for an example directory.
    """
    if not dir == '.':
        target_dir = os.path.join(root_dir, dir)
        src_dir = os.path.join(example_dir, dir)
    else:
        target_dir = root_dir
        src_dir = example_dir
    if not os.path.exists(os.path.join(src_dir, 'README.txt')):
        print(80 * '_')
        print(('Example directory %s does not have a README.txt file' %
               src_dir))
        print('Skipping this directory')
        print(80 * '_')
        return
    fhindex.write("""

%s

""" % file(os.path.join(src_dir, 'README.txt')).read())
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)
    sorted_listdir = line_count_sort(os.listdir(src_dir),
                                     src_dir)
    for fname in sorted_listdir:
        if fname.endswith('py'):
            generate_file_rst(fname, target_dir, src_dir, plot_gallery)
            new_fname = os.path.join(src_dir, fname)
            _, fdocstring, _ = extract_docstring(new_fname, True)
            thumb = os.path.join(dir, 'images', 'thumb', fname[:-3] + '.png')
            link_name = os.path.join(dir, fname).replace(os.path.sep, '_')
            fhindex.write("""

.. raw:: html

    <div class="thumbnailContainer">
        <div class="docstringWrapper">

""")

            fhindex.write('.. figure:: %s\n' % thumb)
            if link_name.startswith('._'):
                link_name = link_name[2:]
            if dir != '.':
                fhindex.write('   :target: ./%s/%s.html\n\n' % (dir,
                                                                fname[:-3]))
            else:
                fhindex.write('   :target: ./%s.html\n\n' % link_name[:-3])
            fhindex.write("""   :ref:`example_%s`

.. raw:: html

    <p>%s
    </p></div>
    </div>

.. toctree::
   :hidden:

   %s/%s

""" % (link_name, fdocstring, dir, fname[:-3]))
    fhindex.write("""
.. raw:: html

    <div style="clear: both"></div>
    """)  # clear at the end of the section

# modules for which we embed links into example code
DOCMODULES = ['pyart', 'matplotlib', 'numpy', 'scipy']

def make_thumbnail(in_fname, out_fname, width, height):
    """Make a thumbnail with the same aspect ratio centered in an
       image with a given width and height
    """
    img = Image.open(in_fname)
    width_in, height_in = img.size
    scale_w = width / float(width_in)
    scale_h = height / float(height_in)

    if height_in * scale_w <= height:
        scale = scale_w
    else:
        scale = scale_h

    width_sc = int(round(scale * width_in))
    height_sc = int(round(scale * height_in))

    # resize the image
    img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

    # insert centered
    thumb = Image.new('RGB', (width, height), (255, 255, 255))
    pos_insert = ((width - width_sc) / 2, (height - height_sc) / 2)
    thumb.paste(img, pos_insert)

    thumb.save(out_fname)

def get_short_module_name(module_name, obj_name):
    """ Get the shortest possible module name """
    parts = module_name.split('.')
    short_name = module_name
    for i in range(len(parts) - 1, 0, -1):
        short_name = '.'.join(parts[:i])
        try:
            exec('from %s import %s' % (short_name, obj_name))
        except ImportError:
            # get the last working module name
            short_name = '.'.join(parts[:(i + 1)])
            break
    return short_name

def generate_file_rst(fname, target_dir, src_dir, plot_gallery):
    """ Generate the rst file for a given example.
    """
    base_image_name = os.path.splitext(fname)[0]
    image_fname = '%s_%%s.png' % base_image_name

    this_template = rst_template
    last_dir = os.path.split(src_dir)[-1]
    # to avoid leading . in file names, and wrong names in links
    if last_dir == '.' or last_dir == 'examples':
        last_dir = ''
    else:
        last_dir += '_'
    short_fname = last_dir + fname
    src_file = os.path.join(src_dir, fname)
    example_file = os.path.join(target_dir, fname)
    shutil.copyfile(src_file, example_file)

    # The following is a list containing all the figure names
    figure_list = []

    image_dir = os.path.join(target_dir, 'images')
    thumb_dir = os.path.join(image_dir, 'thumb')
    if not os.path.exists(image_dir):
        os.makedirs(image_dir)
    if not os.path.exists(thumb_dir):
        os.makedirs(thumb_dir)
    image_path = os.path.join(image_dir, image_fname)
    stdout_path = os.path.join(image_dir,
                               'stdout_%s.txt' % base_image_name)
    time_path = os.path.join(image_dir,
                             'time_%s.txt' % base_image_name)
    thumb_file = os.path.join(thumb_dir, fname[:-3] + '.png')
    time_elapsed = 0
    if plot_gallery and fname.startswith('plot'):
        # generate the plot as png image if file name
        # starts with plot and if it is more recent than an
        # existing image.
        first_image_file = image_path % 1
        if os.path.exists(stdout_path):
            stdout = open(stdout_path).read()
        else:
            stdout = ''
        if os.path.exists(time_path):
            time_elapsed = float(open(time_path).read())

        if not os.path.exists(first_image_file) or \
           os.stat(first_image_file).st_mtime <= os.stat(src_file).st_mtime:
            # We need to execute the code
            print('plotting %s' % fname)
            t0 = time()
            import matplotlib.pyplot as plt
            plt.close('all')
            cwd = os.getcwd()
            try:
                # First CD in the original example dir, so that any file
                # created by the example get created in this directory
                orig_stdout = sys.stdout
                os.chdir(os.path.dirname(src_file))
                my_buffer = StringIO()
                my_stdout = Tee(sys.stdout, my_buffer)
                sys.stdout = my_stdout
                my_globals = {'pl': plt}
                execfile(os.path.basename(src_file), my_globals)
                time_elapsed = time() - t0
                sys.stdout = orig_stdout
                my_stdout = my_buffer.getvalue()

                # get variables so we can later add links to the documentation
                example_code_obj = {}
                for var_name, var in my_globals.iteritems():
                    if not hasattr(var, '__module__'):
                        continue
                    if not isinstance(var.__module__, basestring):
                        continue
                    if var.__module__.split('.')[0] not in DOCMODULES:
                        continue

                    # get the type as a string with other things stripped
                    tstr = str(type(var))
                    tstr = (tstr[tstr.find('\'')
                            + 1:tstr.rfind('\'')].split('.')[-1])
                    # get shortened module name
                    module_short = get_short_module_name(var.__module__,
                                                         tstr)
                    cobj = {'name': tstr, 'module': var.__module__,
                            'module_short': module_short,
                            'obj_type': 'object'}
                    example_code_obj[var_name] = cobj

                # find functions so we can later add links to the documentation
                funregex = re.compile('[\w.]+\(')
                with open(src_file, 'rt') as fid:
                    for line in fid.readlines():
                        if line.startswith('#'):
                            continue
                        for match in funregex.findall(line):
                            fun_name = match[:-1]

                            try:
                                exec('this_fun = %s' % fun_name, my_globals)
                            except Exception as err:
                                # Here, we were not able to execute the
                                # previous statement, either because the
                                # fun_name was not a function but a statement
                                # (print), or because the regexp didn't
                                # catch the whole function name :
                                #    eg:
                                #       X = something().blah()
                                # will work for something, but not blah.

                                continue
                            this_fun = my_globals['this_fun']
                            if not callable(this_fun):
                                continue
                            if not hasattr(this_fun, '__module__'):
                                continue
                            if not isinstance(this_fun.__module__, basestring):
                                continue
                            if (this_fun.__module__.split('.')[0]
                                    not in DOCMODULES):
                                continue

                            # get shortened module name
                            fun_name_short = fun_name.split('.')[-1]
                            module_short = get_short_module_name(
                                this_fun.__module__, fun_name_short)
                            cobj = {'name': fun_name_short,
                                    'module': this_fun.__module__,
                                    'module_short': module_short,
                                    'obj_type': 'function'}
                            example_code_obj[fun_name] = cobj
                fid.close()

                if len(example_code_obj) > 0:
                    # save the dictionary, so we can later add hyperlinks
                    codeobj_fname = example_file[:-3] + '_codeobj.pickle'
                    with open(codeobj_fname, 'wb') as fid:
                        cPickle.dump(example_code_obj, fid,
                                     cPickle.HIGHEST_PROTOCOL)
                    fid.close()

                if '__doc__' in my_globals:
                    # The __doc__ is often printed in the example, we
                    # don't with to echo it
                    my_stdout = my_stdout.replace(
                        my_globals['__doc__'],
                        '')
                my_stdout = my_stdout.strip()
                if my_stdout:
                    stdout = '**Script output**::\n\n  %s\n\n' % (
                        '\n  '.join(my_stdout.split('\n')))
                open(stdout_path, 'w').write(stdout)
                open(time_path, 'w').write('%f' % time_elapsed)
                os.chdir(cwd)

                # In order to save every figure we have two solutions :
                # * iterate from 1 to infinity and call plt.fignum_exists(n)
                #   (this requires the figures to be numbered
                #    incrementally: 1, 2, 3 and not 1, 2, 5)
                # * iterate over [fig_mngr.num for fig_mngr in
                #   matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
                for fig_num in (fig_mngr.num for fig_mngr in
                    matplotlib._pylab_helpers.Gcf.get_all_fig_managers()):
                    # Set the fig_num figure as the current figure as we can't
                    # save a figure that's not the current figure.
                    plt.figure(fig_num)
                    plt.savefig(image_path % fig_num)
                    figure_list.append(image_fname % fig_num)
            except:
                print(80 * '_')
                print('%s is not compiling:' % fname)
                traceback.print_exc()
                print(80 * '_')
            finally:
                os.chdir(cwd)
                sys.stdout = orig_stdout

            print(" - time elapsed : %.2g sec" % time_elapsed)
        else:
            figure_list = [f[len(image_dir):]
                            for f in glob.glob(image_path % '[1-9]')]
                            #for f in glob.glob(image_path % '*')]

        # generate thumb file
        this_template = plot_rst_template
        if os.path.exists(first_image_file):
            make_thumbnail(first_image_file, thumb_file, 400, 280)

    if not os.path.exists(thumb_file):
        # create something to replace the thumbnail
        make_thumbnail('images/no_image.png', thumb_file, 200, 140)

    docstring, short_desc, end_row = extract_docstring(example_file)

    # Depending on whether we have one or more figures, we're using a
    # horizontal list or a single rst call to 'image'.
    if len(figure_list) == 1:
        figure_name = figure_list[0]
        image_list = SINGLE_IMAGE % figure_name.lstrip('/')
    else:
        image_list = HLIST_HEADER
        for figure_name in figure_list:
            image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/')

    f = open(os.path.join(target_dir, fname[:-2] + 'rst'), 'w')
    f.write(this_template % locals())
    f.flush()

def embed_code_links(app, exception):
    """Embed hyperlinks to documentation into example code"""
    try:
        if exception is not None:
            return
        print('Embedding documentation hyperlinks in examples..')

        # Add resolvers for the packages for which we want to show links
        doc_resolvers = {}
        doc_resolvers['pyart'] = SphinxDocLinkResolver(app.builder.outdir,
                                                       relative=True)

        doc_resolvers['matplotlib'] = SphinxDocLinkResolver(
            'http://matplotlib.org')

        doc_resolvers['numpy'] = SphinxDocLinkResolver(
            'http://docs.scipy.org/doc/numpy-1.6.0')

        doc_resolvers['scipy'] = SphinxDocLinkResolver(
            'http://docs.scipy.org/doc/scipy-0.11.0/reference')

        example_dir = os.path.join(app.builder.srcdir, 'auto_examples')
        html_example_dir = os.path.abspath(os.path.join(app.builder.outdir,
                                                        'auto_examples'))

        # patterns for replacement
        link_pattern = '<a href="%s">%s</a>'
        orig_pattern = '<span class="n">%s</span>'
        period = '<span class="o">.</span>'

        for dirpath, _, filenames in os.walk(html_example_dir):
            for fname in filenames:
                print('\tprocessing: %s' % fname)
                full_fname = os.path.join(html_example_dir, dirpath, fname)
                subpath = dirpath[len(html_example_dir) + 1:]
                pickle_fname = os.path.join(example_dir, subpath,
                                            fname[:-5] + '_codeobj.pickle')

                if os.path.exists(pickle_fname):
                    # we have a pickle file with the objects to embed links for
                    with open(pickle_fname, 'rb') as fid:
                        example_code_obj = cPickle.load(fid)
                    fid.close()
                    str_repl = {}
                    # generate replacement strings with the links
                    for name, cobj in example_code_obj.iteritems():
                        this_module = cobj['module'].split('.')[0]

                        if this_module not in doc_resolvers:
                            continue

                        link = doc_resolvers[this_module].resolve(cobj,
                                                                  full_fname)
                        if link is not None:
                            parts = name.split('.')
                            name_html = orig_pattern % parts[0]
                            for part in parts[1:]:
                                name_html += period + orig_pattern % part
                            str_repl[name_html] = link_pattern % (link, name_html)
                    # do the replacement in the html file
                    if len(str_repl) > 0:
                        with open(full_fname, 'rb') as fid:
                            lines_in = fid.readlines()
                        with open(full_fname, 'wb') as fid:
                            for line in lines_in:
                                line = line.decode('utf-8')
                                for name, link in str_repl.iteritems():
                                    line = line.replace(name, link)
                                fid.write(line.encode('utf-8'))
    except urllib2.HTTPError, e:
        print ("The following HTTP Error has occurred:\n")
        print(e.code)
    except urllib2.URLError, e:
        print ("\n...\n"
               "Warning: Embedding the documentation hyperlinks requires "
               "internet access.\nPlease check your network connection.\n"
               "Unable to continue embedding due to a URL Error: \n")
        print(e.args)
    print('[done]')

def setup(app):
    app.connect('builder-inited', generate_example_rst)
    app.add_config_value('plot_gallery', True, 'html')

    # embed links after build is finished
    # XXX disable documentation hyperlinks in examples for now
    #app.connect('build-finished', embed_code_links)

    # Sphinx hack: sphinx copies generated images to the build directory
    #  each time the docs are made.  If the desired image name already
    #  exists, it appends a digit to prevent overwrites.  The problem is,
    #  the directory is never cleared.  This means that each time you build
    #  the docs, the number of images in the directory grows.
    #
    # This question has been asked on the sphinx development list, but there
    #  was no response: http://osdir.com/ml/sphinx-dev/2011-02/msg00123.html
    #
    # The following is a hack that prevents this behavior by clearing the
    #  image build directory each time the docs are built.  If sphinx
    #  changes their layout between versions, this will not work (though
    #  it should probably not cause a crash).  Tested successfully
    #  on Sphinx 1.0.7
    build_image_dir = 'build/html/_images'
    if os.path.exists(build_image_dir):
        filelist = os.listdir(build_image_dir)
        for filename in filelist:
            if filename.endswith('png'):
                os.remove(os.path.join(build_image_dir, filename))


text:
package com.intellij.lang.folding;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.FoldingGroup;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * A variant of {@link FoldingDescriptor} which keeps precalculated value of placeholder text.
 * This makes 'apply' phase of code folding pass (executed in EDT) faster.
 */
public class NamedFoldingDescriptor extends FoldingDescriptor {
  private final String myPlaceholderText;

  public NamedFoldingDescriptor(@NotNull PsiElement e, int start, int end, @Nullable FoldingGroup group, @NotNull String placeholderText) {
    this(e.getNode(), new TextRange(start, end), group, placeholderText);
  }

  public NamedFoldingDescriptor(@NotNull ASTNode node, int start, int end, @Nullable FoldingGroup group, @NotNull String placeholderText) {
    this(node, new TextRange(start, end), group, placeholderText);
  }

  public NamedFoldingDescriptor(@NotNull ASTNode node,
                         @NotNull final TextRange range,
                         @Nullable FoldingGroup group,
                         @NotNull String placeholderText) {
    super(node, range, group);
    myPlaceholderText = placeholderText;
  }

  @Override
  @NotNull
  public String getPlaceholderText() {
    return myPlaceholderText;
  }
}


text:
namespace VSPackage.ScaffolderPackage.Core
{
    using System.Collections.Generic;

    public interface ITemplateProvider
    {
        IEnumerable<TemplateDefinition> TemplateDefinitions { get; }
    }
}


text:
import menu from './menu'

export {
  menu
}


text:
static class Guard
{
    public static void AgainstNullAndEmpty(string value, string argumentName)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentNullException(argumentName);
        }
    }

    public static void AgainstNonExistingFile(string file, string argumentName)
    {
        if (!File.Exists(file))
        {
            throw new ArgumentException($"File does not exist: {file}", argumentName);
        }
    }
}


text:
package org.carrot2.workbench.editors;

import java.util.EventObject;

/**
 * Event holding data related to events on attributes.
 */
@SuppressWarnings("serial")
public class AttributeEvent extends EventObject
{
    /** Attribute key. */
    public final String key;

    /** Attribute value. */
    public final Object value;

    /*
     *
     */
    public AttributeEvent(IAttributeEditor source)
    {
        this(source, source.getAttributeKey(), source.getValue());
    }

    /*
     *
     */
    public AttributeEvent(Object source, String key, Object value)
    {
        super(source);
        this.key = key;
        this.value = value;
    }
}


text:
using System;
using De.Osthus.Ambeth.Log;
using System.Collections.Generic;
using De.Osthus.Ambeth.Util;
using De.Osthus.Ambeth.Ioc.Exceptions;
using De.Osthus.Ambeth.Collections;
using De.Osthus.Ambeth.Exceptions;

namespace De.Osthus.Ambeth.Ioc.Extendable
{
    public class MapExtendableContainer<K, V> : SmartCopyMap<K, Object>, IMapExtendableContainer<K, V>
    {
    	protected readonly bool multiValue;

        protected String message, keyMessage;

        public MapExtendableContainer(String message, String keyMessage) : this(message, keyMessage, false)
        {
            // Intended blank
        }

        public MapExtendableContainer(String message, String keyMessage, bool multiValue)
        {
            ParamChecker.AssertParamNotNull(message, "message");
            ParamChecker.AssertParamNotNull(keyMessage, "keyMessage");
            this.multiValue = multiValue;
            this.message = message;
            this.keyMessage = keyMessage;
        }

        public virtual void Register(V extension, K key)
        {
            ParamChecker.AssertParamNotNull(extension, message);
            ParamChecker.AssertParamNotNull(key, keyMessage);

            Object writeLock = GetWriteLock();
            lock (writeLock)
            {
			    bool putted = false;
			    if (!multiValue)
			    {
				    putted = PutIfNotExists(key, extension);
			    }
			    else
			    {
				    List<V> values = (List<V>) Get(key);
				    if (values == null)
				    {
					    values = new List<V>(1);
					    Put(key, values);
				    }
				    if (!values.Contains(extension))
				    {
					    values.Add(extension);
					    putted = true;
				    }
			    }
			    if (!putted)
			    {
				    throw new ExtendableException("Key '" + keyMessage + "' already added: " + key);
			    }
            }
        }

        public virtual void Unregister(V extension, K key)
        {
            ParamChecker.AssertParamNotNull(extension, message);
            ParamChecker.AssertParamNotNull(key, keyMessage);

            try
            {
                Object writeLock = GetWriteLock();
                lock (writeLock)
                {
                    if (!multiValue)
                    {
                        ParamChecker.AssertTrue(RemoveIfValue(key, extension), message);
                    }
                    else
                    {
                        List<V> values = (List<V>)Get(key);
                        ParamChecker.AssertNotNull(values, message);
                        ParamChecker.AssertTrue(values.Remove(extension), message);
                        if (values.Count == 0)
                        {
                            Remove(key);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw new ExtendableException("Provided extension is not registered at key '" + key + "'. Extension: " + extension);
            }
        }

        public virtual IList<V> GetExtensions(K key)
        {
            ParamChecker.AssertParamNotNull(key, "key");
            Object item = Get(key);
            if (item == null)
            {
                return EmptyList.Empty<V>();
            }
            List<V> list = new List<V>();
            if (!multiValue)
            {
                list.Add((V)item);
            }
            else
            {
                list.AddRange((List<V>)item);
            }
            return list;
        }

        public virtual V GetExtension(K key)
        {
            ParamChecker.AssertParamNotNull(key, "key");
            Object item = Get(key);
            if (item == null)
            {
                return default(V);
            }
            if (!multiValue)
            {
                return (V)item;
            }
            else
            {
                List<V> values = (List<V>)item;
                // unregister removes empty value lists -> at least one entry
                return values[0];
            }
        }

        public ILinkedMap<K, V> GetExtensions()
        {
            LinkedHashMap<K, V> targetMap = new LinkedHashMap<K, V>();
            GetExtensions(targetMap);
            return targetMap;
        }

        public void GetExtensions(IMap<K, V> targetListenerMap)
        {
            foreach (Entry<K, Object> entry in this)
            {
                Object item = entry.Value;
                V extension;
                if (item is V)
                {
                    extension = (V)item;
                }
                else
                {
                    extension = ((List<V>)item)[0];
                }
                targetListenerMap.Put(entry.Key, extension);
            };
        }
    }
}


text:
// **************************************************************************
//Start Finance - An to manage your personal finances.

//Start Finance 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.

//Start Finance 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 Start Finance.If not, see<http://www.gnu.org/licenses/>.
// ***************************************************************************

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
using StartFinance.Models;
using SQLite.Net;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace StartFinance.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class AccountsPage : Page
    {
        SQLiteConnection conn; // adding an SQLite connection
        string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Findata.sqlite");

        public AccountsPage()
        {
            this.InitializeComponent();
            NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
            /// Initializing a database
            conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);

            // Creating table
            Results();
        }

        public void Results()
        {
            // Creating table
            conn.CreateTable<Accounts>();
            var query = conn.Table<Accounts>();
            TransactionList.ItemsSource = query.ToList();
        }
        public string Drafting()
        {
            if(overdraft.IsOn)
            {
                string onn = "ON";
                return onn;
            }
            else
            {
                string off = "OFF";
                return off;
            }
        }

        private async void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // checks if account name is null
                if (AccName.Text.ToString() == "")
                {
                    MessageDialog dialog = new MessageDialog("Amount Name not Entered", "Oops..!");
                    await dialog.ShowAsync();
                }
                else if (AccName.Text.ToString() == "AccountName" || AccName.Text.ToString() == "InitialAmount")
                {
                    MessageDialog variableerror = new MessageDialog("You cannot use this name", "Oops..!");
                }
                else
                {   // Inserts the data
                    conn.Insert(new Accounts()
                    {
                        AccountName = AccName.Text,
                        InitialAmount = Convert.ToDouble(MoneyIn.Text),
                        OverDraft = Drafting()
                    });
                    Results();
                }

            }
            catch (Exception ex)
            {   // Exception to display when amount is invalid or not numbers
                if (ex is FormatException)
                {
                    MessageDialog dialog = new MessageDialog("You forgot to enter the Amount or entered an invalid data", "Oops..!");
                    await dialog.ShowAsync();
                }   // Exception handling when SQLite contraints are violated
                else if (ex is SQLiteException)
                {
                    MessageDialog dialog = new MessageDialog("Account Name already exist, Try Different Name", "Oops..!");
                    await dialog.ShowAsync();
                }
                else
                {
                    /// no idea
                }

            }
        }

        // Clears the fields
        private async void ClearFileds_Click(object sender, RoutedEventArgs e)
        {
            MessageDialog ClearDialog = new MessageDialog("Cleared", "information");
            await ClearDialog.ShowAsync();
        }

        // Displays the data when navigation between pages
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Results();
        }

        private async void DeleteItem_Click(object sender, RoutedEventArgs e)
        {
            MessageDialog ShowConf = new MessageDialog("Deleting this Account will delete all transactions of this account", "Important");
            ShowConf.Commands.Add(new UICommand("Yes, Delete")
            {
                Id = 0
            });
            ShowConf.Commands.Add(new UICommand("Cancel")
            {
                Id = 1
            });
            ShowConf.DefaultCommandIndex = 0;
            ShowConf.CancelCommandIndex = 1;

            var result = await ShowConf.ShowAsync();
            if ((int)result.Id == 0)
            {
                // checks if data is null else inserts
                try
                {
                    string AccountsLabel = ((Accounts)TransactionList.SelectedItem).AccountName;
                    var querydel = conn.Query<Accounts>("DELETE FROM Accounts WHERE AccountName='" + AccountsLabel + "'");
                    Results();
                    conn.CreateTable<Transactions>();
                    var querytable = conn.Query<Transactions>("DELETE FROM Transactions WHERE Account='" + AccountsLabel + "'");
                }
                catch (NullReferenceException)
                {
                    MessageDialog ClearDialog = new MessageDialog("Please select the item to Delete", "Oops..!");
                    await ClearDialog.ShowAsync();
                }
            }
            else
            {
                //
            }
        }
    }
}


text:
// Copyright (c) 2012-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_LEVELDBWRAPPER_H
#define BITCOIN_LEVELDBWRAPPER_H

#include "clientversion.h"
#include "serialize.h"
#include "streams.h"
#include "util.h"
#include "version.h"

#include <boost/filesystem/path.hpp>

#include <leveldb/db.h>
#include <leveldb/write_batch.h>

class leveldb_error : public std::runtime_error
{
public:
    leveldb_error(const std::string& msg) : std::runtime_error(msg) {}
};

void HandleError(const leveldb::Status& status);

/** Batch of changes queued to be written to a CLevelDBWrapper */
class CLevelDBBatch
{
    friend class CLevelDBWrapper;

private:
    leveldb::WriteBatch batch;

public:
    template <typename K, typename V>
    void Write(const K& key, const V& value)
    {
        CDataStream ssKey(SER_DISK, CLIENT_VERSION);
        ssKey.reserve(ssKey.GetSerializeSize(key));
        ssKey << key;
        leveldb::Slice slKey(&ssKey[0], ssKey.size());

        CDataStream ssValue(SER_DISK, CLIENT_VERSION);
        ssValue.reserve(ssValue.GetSerializeSize(value));
        ssValue << value;
        leveldb::Slice slValue(&ssValue[0], ssValue.size());

        batch.Put(slKey, slValue);
    }

    template <typename K>
    void Erase(const K& key)
    {
        CDataStream ssKey(SER_DISK, CLIENT_VERSION);
        ssKey.reserve(ssKey.GetSerializeSize(key));
        ssKey << key;
        leveldb::Slice slKey(&ssKey[0], ssKey.size());

        batch.Delete(slKey);
    }
};

class CLevelDBIterator
{
private:
    leveldb::Iterator *piter;

public:
    CLevelDBIterator(leveldb::Iterator *piterIn) : piter(piterIn) {}
    ~CLevelDBIterator();

    bool Valid();

    void SeekToFirst();
    void SeekToLast();

    template<typename K> void Seek(const K& key) {
        CDataStream ssKey(SER_DISK, CLIENT_VERSION);
        ssKey.reserve(ssKey.GetSerializeSize(key));
        ssKey << key;
        leveldb::Slice slKey(&ssKey[0], ssKey.size());
        piter->Seek(slKey);
    }

    void Next();
    void Prev();

    template<typename K> bool GetKey(K& key) {
        leveldb::Slice slKey = piter->key();
        try {
            CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION);
            ssKey >> key;
        } catch(std::exception &e) {
            return false;
        }
        return true;
    }

    unsigned int GetKeySize() {
        return piter->key().size();
    }

    template<typename V> bool GetValue(V& value) {
        leveldb::Slice slValue = piter->value();
        try {
            CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION);
            ssValue >> value;
        } catch(std::exception &e) {
            return false;
        }
        return true;
    }

    unsigned int GetValueSize() {
        return piter->value().size();
    }

};

class CLevelDBWrapper
{
private:
    //! custom environment this database is using (may be NULL in case of default environment)
    leveldb::Env* penv;

    //! database options used
    leveldb::Options options;

    //! options used when reading from the database
    leveldb::ReadOptions readoptions;

    //! options used when iterating over values of the database
    leveldb::ReadOptions iteroptions;

    //! options used when writing to the database
    leveldb::WriteOptions writeoptions;

    //! options used when sync writing to the database
    leveldb::WriteOptions syncoptions;

    //! the database itself
    leveldb::DB* pdb;

public:
    CLevelDBWrapper(const boost::filesystem::path& path, size_t nCacheSize, bool fMemory = false, bool fWipe = false);
    ~CLevelDBWrapper();

    template <typename K, typename V>
    bool Read(const K& key, V& value) const
    {
        CDataStream ssKey(SER_DISK, CLIENT_VERSION);
        ssKey.reserve(ssKey.GetSerializeSize(key));
        ssKey << key;
        leveldb::Slice slKey(&ssKey[0], ssKey.size());

        std::string strValue;
        leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
        if (!status.ok()) {
            if (status.IsNotFound())
                return false;
            LogPrintf("LevelDB read failure: %s\n", status.ToString());
            HandleError(status);
        }
        try {
            CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);
            ssValue >> value;
        } catch (const std::exception&) {
            return false;
        }
        return true;
    }

    template <typename K, typename V>
    bool Write(const K& key, const V& value, bool fSync = false)
    {
        CLevelDBBatch batch;
        batch.Write(key, value);
        return WriteBatch(batch, fSync);
    }

    template <typename K>
    bool Exists(const K& key) const
    {
        CDataStream ssKey(SER_DISK, CLIENT_VERSION);
        ssKey.reserve(ssKey.GetSerializeSize(key));
        ssKey << key;
        leveldb::Slice slKey(&ssKey[0], ssKey.size());

        std::string strValue;
        leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
        if (!status.ok()) {
            if (status.IsNotFound())
                return false;
            LogPrintf("LevelDB read failure: %s\n", status.ToString());
            HandleError(status);
        }
        return true;
    }

    template <typename K>
    bool Erase(const K& key, bool fSync = false)
    {
        CLevelDBBatch batch;
        batch.Erase(key);
        return WriteBatch(batch, fSync);
    }

    bool WriteBatch(CLevelDBBatch& batch, bool fSync = false);

    // not available for LevelDB; provide for compatibility with BDB
    bool Flush()
    {
        return true;
    }

    bool Sync()
    {
        CLevelDBBatch batch;
        return WriteBatch(batch, true);
    }

    CLevelDBIterator *NewIterator() {
        return new CLevelDBIterator(pdb->NewIterator(iteroptions));
    }

    leveldb::Iterator *NewRawIterator() {
        return pdb->NewIterator(iteroptions);
    }

    /**
     * Return true if the database managed by this class contains no entries.
     */
    bool IsEmpty();
};

#endif // BITCOIN_LEVELDBWRAPPER_H


text:
<?php
namespace app\models\distributor;

use yii\db\ActiveRecord;
use app\models\product\ProductRecord;

class DistributorRecord extends ActiveRecord
{
    private static $distributors = null;

    public static function tableName() {
        return "distributors";
    }

    public function rules() {
        return [
            ['id', 'number'],
            ['name', 'required'],
            ['name', 'unique'],
            ['name', 'string', 'max' => 256],
        ];
    }

    public function getProducts() {
        return $this->hasMany(ProductRecord::className(),
                    [
                        'id' => 'product_id'
                    ]
        );
    }

    public static function getDistributors() {
        if (is_null(self::$distributors)) {
            self::$distributors = self::find()->all();
        }

        return self::$distributors;
    }

}


text:
./gradlew :walle-cli:clean :walle-cli:shadowJar
cp walle-cli/build/libs/walle-cli-all.jar walle-cli/walle-cli-all.jar
# 替换readme中的版本
VERSION_NAME=`grep VERSION_NAME gradle.properties`
VERSION_STRING=`echo $VERSION_NAME | cut -d '=' -f 2`
GROUP=`grep GROUP gradle.properties`
GROUP_STRING=`echo $GROUP | cut -d '=' -f 2`
for file in $(find . -name 'README.md'); do
 sed -i.bak -e "s/\(['\"]\)\(${GROUP_STRING}\):\(.*\):.*\(['\"]\)/\1\2:\3:${VERSION_STRING}\4/g" ${file}
 rm ${file}.bak
done
# 提交
git add .
git commit -m "update cli.jar & readme"
git push origin HEAD
# upload jar & aar
./gradlew clean bintrayUpload -x :app:clean
# git tag
git tag v$VERSION_STRING
git push origin v$VERSION_STRING


text:
package io.sentry;

import io.sentry.util.Objects;
import java.util.HashMap;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Arbitrary data used in {@link SamplingContext} to determine if transaction is going to be
 * sampled.
 */
public final class CustomSamplingContext {
  private final @NotNull Map<String, Object> data = new HashMap<>();

  public void set(final @NotNull String key, final @Nullable Object value) {
    Objects.requireNonNull(key, "key is required");
    this.data.put(key, value);
  }

  public @Nullable Object get(final @NotNull String key) {
    Objects.requireNonNull(key, "key is required");
    return this.data.get(key);
  }

  public @NotNull Map<String, Object> getData() {
    return data;
  }
}