text:
BOOST_AUTO_TEST_SUITE( lib_ThreadStructure )

BOOST_AUTO_TEST_SUITE( newTicket )

BOOST_AUTO_TEST_CASE( FirstTicket )
{
  BOOST_TEST_CHECKPOINT("Generates tickets from 1.");
  ThreadStructure::newTicket();
  BOOST_REQUIRE( ThreadStructure::myTicket() >= 1  );
}
BOOST_AUTO_TEST_CASE( TicketType )
{
  BOOST_TEST_CHECKPOINT("Ticket type should be uint64_t");
  BOOST_REQUIRE( typeid( ThreadStructure::myTicket() ) == typeid( uint64_t ) );
}
BOOST_AUTO_TEST_CASE( IncrementTicket )
{
  BOOST_TEST_CHECKPOINT("Tickets increment by 1.");
  for(uint64_t i=0;i< 10000;i++){
    ThreadStructure::newTicket();
    BOOST_REQUIRE_EQUAL( ThreadStructure::myTicket() , i+2  );
  }
}
BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( ContextID )
BOOST_AUTO_TEST_CASE( PushPop )
{
  for(uint32_t n=1;n<=10000;n++){
    //std::ostringstream oss;
    //oss<<"context"<<n;
    ThreadStructure::pushContext( n );
  }
  BOOST_REQUIRE_EQUAL( ThreadStructure::getCurrentContext() , (uint32_t)10000 );
  for(int n=1;n<=10000;n++){
    ThreadStructure::popContext();
  }
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE( TransitionValidity )
BOOST_AUTO_TEST_CASE( TestValid )
{

}
BOOST_AUTO_TEST_CASE( TestInValid )
{

}
BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()


text:
<!doctype html>

    <title>Code coverage report for javascripts/explore/explore.jsx</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      All files / javascripts/explore explore.jsx

        0%
        Statements
        0/186

        0%
        Branches
        0/51

        0%
        Functions
        0/43

        0%
        Lines
        0/181

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376

// Javascript for the explorer page
// Init explorer view -> load vis dependencies -> read data (from dynamic html) -> render slice
// nb: to add a new vis, you must also add a Python fn in viz.py
//
// js
const $ = window.$ = require('jquery');
const px = require('./../modules/caravel.js');
const showModal = require('./../modules/utils.js').showModal;
const jQuery = window.jQuery = require('jquery'); // eslint-disable-line

import React from 'react';
import ReactDOM from 'react-dom';
import QueryAndSaveBtns from './components/QueryAndSaveBtns.jsx';
import ExploreActionButtons from './components/ExploreActionButtons.jsx';

require('jquery-ui');
$.widget.bridge('uitooltip', $.ui.tooltip); // Shutting down jq-ui tooltips
require('bootstrap');

require('./../caravel-select2.js');

// css
require('../../vendor/pygments.css');
require('../../stylesheets/explore.css');

let slice;

const getPanelClass = function (fieldPrefix) {
  return (fieldPrefix === 'flt' ? 'filter' : 'having') + '_panel';
};

function prepForm() {
  // Assigning the right id to form elements in filters
  const fixId = function ($filter, fieldPrefix, i) {
    $filter.attr('id', function () {
      return fieldPrefix + '_' + i;
    });

    ['col', 'op', 'eq'].forEach(function (fieldMiddle) {
      const fieldName = fieldPrefix + '_' + fieldMiddle;
      $filter.find('[id^=' + fieldName + '_]')
          .attr('id', function () {
            return fieldName + '_' + i;
          })
          .attr('name', function () {
            return fieldName + '_' + i;
          });
    });
  };

  ['flt', 'having'].forEach(function (fieldPrefix) {
    let i = 1;
    $('#' + getPanelClass(fieldPrefix) + ' #filters > div').each(function () {
      fixId($(this), fieldPrefix, i);
      i++;
    });
  });
}

function query(forceUpdate, pushState) {
  let force = forceUpdate;
  if (force === undefined) {
    force = false;
  }
  $('.query-and-save button').attr('disabled', 'disabled');
  if (force) {  // Don't hide the alert message when the page is just loaded
    $('div.alert').remove();
  }
  $('#is_cached').hide();
  prepForm();

  if (pushState !== false) {
    // update the url after prepForm() fix the field ids
    history.pushState({}, document.title, slice.querystring());
  }
  slice.render(force);
}

function saveSlice() {
  const action = $('input[name=rdo_save]:checked').val();
  if (action === 'saveas') {
    const sliceName = $('input[name=new_slice_name]').val();
    if (sliceName === '') {
      showModal({
        title: 'Error',
        body: 'You must pick a name for the new slice',
      });
      return;
    }
    document.getElementById('slice_name').value = sliceName;
  }
  const addToDash = $('input[name=addToDash]:checked').val();
  if (addToDash === 'existing' && $('#save_to_dashboard_id').val() === '') {
    showModal({
      title: 'Error',
      body: 'You must pick an existing dashboard',
    });
    return;
  } else if (addToDash === 'new' && $('input[name=new_dashboard_name]').val() === '') {
    showModal({
      title: 'Error',
      body: 'Please enter a name for the new dashboard',
    });
    return;
  }
  $('#action').val(action);
  prepForm();
  $('#query').submit();
}

function initExploreView() {
  function getCollapsedFieldsets() {
    let collapsedFieldsets = $('#collapsedFieldsets').val();

    if (collapsedFieldsets !== undefined && collapsedFieldsets !== '') {
      collapsedFieldsets = collapsedFieldsets.split('||');
    } else {
      collapsedFieldsets = [];
    }
    return collapsedFieldsets;
  }

  function toggleFieldset(legend, animation) {
    const parent = legend.parent();
    const fieldset = parent.find('.legend_label').text();
    const collapsedFieldsets = getCollapsedFieldsets();
    let index;

    if (parent.hasClass('collapsed')) {
      if (animation) {
        parent.find('.panel-body').slideDown();
      } else {
        parent.find('.panel-body').show();
      }
      parent.removeClass('collapsed');
      parent.find('span.collapser').text('[-]');

      // removing from array, js is overcomplicated
      index = collapsedFieldsets.indexOf(fieldset);
      if (index !== -1) {
        collapsedFieldsets.splice(index, 1);
      }
    } else { // not collapsed
      if (animation) {
        parent.find('.panel-body').slideUp();
      } else {
        parent.find('.panel-body').hide();
      }

      parent.addClass('collapsed');
      parent.find('span.collapser').text('[+]');
      index = collapsedFieldsets.indexOf(fieldset);
      if (index === -1 && fieldset !== '' && fieldset !== undefined) {
        collapsedFieldsets.push(fieldset);
      }
    }

    $('#collapsedFieldsets').val(collapsedFieldsets.join('||'));
  }

  px.initFavStars();

  $('#viz_type').change(function () {
    $('#query').submit();
  });

  $('#datasource_id').change(function () {
    window.location = $(this).find('option:selected').attr('url');
  });

  const collapsedFieldsets = getCollapsedFieldsets();
  for (let i = 0; i < collapsedFieldsets.length; i++) {
    toggleFieldset($('legend:contains("' + collapsedFieldsets[i] + '")'), false);
  }
  function formatViz(viz) {
    const url = `/static/assets/images/viz_thumbnails/${viz.id}.png`;
    const noImg = '/static/assets/images/noimg.png';
    return $(
      `<img class="viz-thumb-option" src="${url}" onerror="this.src='${noImg}';">` +
      `<span>${viz.text}</span>`
    );
  }

  $('.select2').select2({
    dropdownAutoWidth: true,
  });
  $('.select2Sortable').select2({
    dropdownAutoWidth: true,
  });
  $('.select2-with-images').select2({
    dropdownAutoWidth: true,
    dropdownCssClass: 'bigdrop',
    formatResult: formatViz,
  });
  $('.select2Sortable').select2Sortable({
    bindOrder: 'sortableStop',
  });
  $('form').show();
  $('[data-toggle="tooltip"]').tooltip({ container: 'body' });
  $('.ui-helper-hidden-accessible').remove(); // jQuery-ui 1.11+ creates a div for every tooltip

  function addFilter(i, fieldPrefix) {
    const cp = $('#' + fieldPrefix + '0').clone();
    $(cp).appendTo('#' + getPanelClass(fieldPrefix) + ' #filters');
    $(cp).show();
    if (i !== undefined) {
      $(cp).find('#' + fieldPrefix + '_eq_0').val(px.getParam(fieldPrefix + '_eq_' + i));
      $(cp).find('#' + fieldPrefix + '_op_0').val(px.getParam(fieldPrefix + '_op_' + i));
      $(cp).find('#' + fieldPrefix + '_col_0').val(px.getParam(fieldPrefix + '_col_' + i));
    }
    $(cp).find('select').select2();
    $(cp).find('.remove').click(function () {
      $(this)
      .parent()
      .parent()
      .remove();
    });
  }

  function setFilters() {
    ['flt', 'having'].forEach(function (prefix) {
      for (let i = 1; i < 10; i++) {
        const col = px.getParam(prefix + '_col_' + i);
        if (col !== '') {
          addFilter(i, prefix);
        }
      }
    });
  }
  setFilters();

  $(window).bind('popstate', function () {
    // Browser back button
    const returnLocation = history.location || document.location;
    // Could do something more lightweight here, but we're not optimizing
    // for the use of the back button anyways
    returnLocation.reload();
  });

  $('#filter_panel #plus').click(function () {
    addFilter(undefined, 'flt');
  });
  $('#having_panel #plus').click(function () {
    addFilter(undefined, 'having');
  });

  function createChoices(term, data) {
    const filtered = $(data).filter(function () {
      return this.text.localeCompare(term) === 0;
    });
    if (filtered.length === 0) {
      return {
        id: term,
        text: term,
      };
    }
    return {};
  }

  function initSelectionToValue(element, callback) {
    callback({
      id: element.val(),
      text: element.val(),
    });
  }

  $('.select2_freeform').each(function () {
    const parent = $(this).parent();
    const name = $(this).attr('name');
    const l = [];
    let selected = '';
    for (let i = 0; i < this.options.length; i++) {
      l.push({
        id: this.options[i].value,
        text: this.options[i].text,
      });
      if (this.options[i].selected) {
        selected = this.options[i].value;
      }
    }
    parent.append(
      `<input class="${$(this).attr('class')}" ` +
      `name="${name}" type="text" value="${selected}">`
    );
    $(`input[name='${name}']`).select2({
      createSearchChoice: createChoices,
      initSelection: initSelectionToValue,
      dropdownAutoWidth: true,
      multiple: false,
      data: l,
    });
    $(this).remove();
  });

  function prepSaveDialog() {
    const setButtonsState = function () {
      const addToDash = $('input[name=addToDash]:checked').val();
      if (addToDash === 'existing' || addToDash === 'new') {
        $('.gotodash').removeAttr('disabled');
      } else {
        $('.gotodash').prop('disabled', true);
      }
    };
    const url = '/dashboardmodelviewasync/api/read?_flt_0_owners=' + $('#userid').val();
    $.get(url, function (data) {
      const choices = [];
      for (let i = 0; i < data.pks.length; i++) {
        choices.push({ id: data.pks[i], text: data.result[i].dashboard_title });
      }
      $('#save_to_dashboard_id').select2({
        data: choices,
        dropdownAutoWidth: true,
      }).on('select2-selecting', function () {
        $('#addToDash_existing').prop('checked', true);
        setButtonsState();
      });
    });

    $('input[name=addToDash]').change(setButtonsState);
    $("input[name='new_dashboard_name']").on('focus', function () {
      $('#add_to_new_dash').prop('checked', true);
      setButtonsState();
    });
    $("input[name='new_slice_name']").on('focus', function () {
      $('#save_as_new').prop('checked', true);
      setButtonsState();
    });

    $('#btn_modal_save').on('click', () => saveSlice());

    $('#btn_modal_save_goto_dash').click(() => {
      document.getElementById('goto_dash').value = 'true';
      saveSlice();
    });
  }
  prepSaveDialog();
}

function initComponents() {
  const queryAndSaveBtnsEl = document.getElementById('js-query-and-save-btns');
  ReactDOM.render(
    <QueryAndSaveBtns
      canAdd={queryAndSaveBtnsEl.getAttribute('data-can-add')}
      onQuery={() => query(true)}
    />,
    queryAndSaveBtnsEl
  );

  const exploreActionsEl = document.getElementById('js-explore-actions');
  ReactDOM.render(
    <ExploreActionButtons
      canDownload={exploreActionsEl.getAttribute('data-can-download')}
      slice={slice}
    />,
    exploreActionsEl
  );
}

$(document).ready(function () {
  const data = $('.slice').data('slice');

  initExploreView();

  slice = px.Slice(data);

  $('.slice').data('slice', slice);

  // call vis render method, which issues ajax
  // calls render on the slice for the first time
  query(false, false);

  slice.bindResizeToWindowResize();

  initComponents();
});

  Code coverage
  generated by istanbul at Mon Sep 26 2016 23:09:10 GMT+0800 (CST)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
     <!-- Dialeto do Banco de dados -->
    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <!-- Driver do Banco de dados -->
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <!-- Url de conexão do Banco de dados
        localhost: indica que´o banco e dados está na própria máquina.
        5432: porta de acesso ao banco de dados
        teste: nome do banco/esquema -->
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/exemplo</property>
    <!-- Usuario do banco de dados-->
    <property name="hibernate.connection.username">root</property>
    <!-- senha do banco de dados-->
    <property name="hibernate.connection.password">root</property>
    <!-- Mostra a consulta SQL no console -->
    <property name="show_sql">true</property>
    <!-- Mostra a consulta formatada -->
    <property name="format_sql">true</property>

    <!-- Mapeamento da classe que será persistida pelo hibernate -->
    <mapping class="br.exemplo.hibernate.entidade.Produto"/>
  </session-factory>
</hibernate-configuration>


text:
using System;

namespace SharpRemote.Hosting.OutOfProcess
{
	/// <summary>
	/// A <see cref="IFailureHandler"/> implementation that doesn't tolerate any kind of failure and
	/// immediately stops the <see cref="OutOfProcessSilo"/>.
	/// </summary>
	public sealed class ZeroFailureToleranceStrategy
		: IFailureHandler
	{
		/// <summary>
		/// This event is fired when <see cref="OnResolutionFailed"/> is called.
		/// </summary>
		public event Action OnResolutionFailedEvent;

		/// <inheritdoc />
		public Decision? OnStartFailure(int numSuccessiveFailures, Exception hostProcessException, out TimeSpan waitTime)
		{
			waitTime = TimeSpan.Zero;
			return Decision.Stop;
		}

		/// <inheritdoc />
		public Decision? OnFailure(Failure failure)
		{
			return Decision.Stop;
		}

		/// <inheritdoc />
		public void OnResolutionFailed(Failure failure, Decision decision, Exception exception)
		{
			var fn = OnResolutionFailedEvent;
			fn?.Invoke();
		}

		/// <inheritdoc />
		public void OnResolutionFinished(Failure failure, Decision decision, Resolution resolution)
		{

		}
	}
}


text:
#ifndef ResourceFetcher_h
#define ResourceFetcher_h

#include "core/loader/ResourceLoaderHost.h"
#include "core/loader/cache/CachePolicy.h"
#include "core/loader/cache/FetchInitiatorInfo.h"
#include "core/loader/cache/FetchRequest.h"
#include "core/loader/cache/Resource.h"
#include "core/loader/cache/ResourcePtr.h"
#include "core/platform/Timer.h"
#include "wtf/Deque.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/ListHashSet.h"
#include "wtf/text/StringHash.h"

namespace WebCore {

class CSSStyleSheetResource;
class DocumentResource;
class FontResource;
class ImageResource;
class RawResource;
class ScriptResource;
class ShaderResource;
class TextTrackResource;
class XSLStyleSheetResource;
class Document;
class DocumentLoader;
class Frame;
class FrameLoader;
class ImageLoader;
class KURL;
class ResourceTimingInfo;

// The ResourceFetcher provides a per-context interface to the MemoryCache
// and enforces a bunch of security checks and rules for resource revalidation.
// Its lifetime is roughly per-DocumentLoader, in that it is generally created
// in the DocumentLoader constructor and loses its ability to generate network
// requests when the DocumentLoader is destroyed. Documents also hold a
// RefPtr<ResourceFetcher> for their lifetime (and will create one if they
// are initialized without a Frame), so a Document can keep a ResourceFetcher
// alive past detach if scripts still reference the Document.
class ResourceFetcher : public RefCounted<ResourceFetcher>, public ResourceLoaderHost {
    WTF_MAKE_NONCOPYABLE(ResourceFetcher); WTF_MAKE_FAST_ALLOCATED;
friend class ImageLoader;
friend class ResourceCacheValidationSuppressor;

public:
    static PassRefPtr<ResourceFetcher> create(DocumentLoader* documentLoader) { return adoptRef(new ResourceFetcher(documentLoader)); }
    virtual ~ResourceFetcher();

    using RefCounted<ResourceFetcher>::ref;
    using RefCounted<ResourceFetcher>::deref;

    ResourcePtr<ImageResource> requestImage(FetchRequest&);
    ResourcePtr<CSSStyleSheetResource> requestCSSStyleSheet(FetchRequest&);
    ResourcePtr<CSSStyleSheetResource> requestUserCSSStyleSheet(FetchRequest&);
    ResourcePtr<ScriptResource> requestScript(FetchRequest&);
    ResourcePtr<FontResource> requestFont(FetchRequest&);
    ResourcePtr<RawResource> requestRawResource(FetchRequest&);
    ResourcePtr<RawResource> requestMainResource(FetchRequest&);
    ResourcePtr<DocumentResource> requestSVGDocument(FetchRequest&);
    ResourcePtr<XSLStyleSheetResource> requestXSLStyleSheet(FetchRequest&);
    ResourcePtr<Resource> requestLinkResource(Resource::Type, FetchRequest&);
    ResourcePtr<TextTrackResource> requestTextTrack(FetchRequest&);
    ResourcePtr<ShaderResource> requestShader(FetchRequest&);
    ResourcePtr<RawResource> requestImport(FetchRequest&);

    // Logs an access denied message to the console for the specified URL.
    void printAccessDeniedMessage(const KURL&) const;

    Resource* cachedResource(const String& url) const;
    Resource* cachedResource(const KURL&) const;

    typedef HashMap<String, ResourcePtr<Resource> > DocumentResourceMap;
    const DocumentResourceMap& allResources() const { return m_documentResources; }

    bool autoLoadImages() const { return m_autoLoadImages; }
    void setAutoLoadImages(bool);

    void setImagesEnabled(bool);

    bool shouldDeferImageLoad(const KURL&) const;

    CachePolicy cachePolicy(Resource::Type) const;

    Frame* frame() const; // Can be null
    Document* document() const { return m_document; } // Can be null
    void setDocument(Document* document) { m_document = document; }

    DocumentLoader* documentLoader() const { return m_documentLoader; }
    void clearDocumentLoader() { m_documentLoader = 0; }

    void garbageCollectDocumentResources();

    int requestCount() const { return m_requestCount; }

    bool isPreloaded(const String& urlString) const;
    void clearPreloads();
    void clearPendingPreloads();
    void preload(Resource::Type, FetchRequest&, const String& charset);
    void checkForPendingPreloads();
    void printPreloadStats();
    bool canRequest(Resource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload = false);
    bool canAccess(Resource*);

    // ResourceLoaderHost
    virtual void incrementRequestCount(const Resource*) OVERRIDE;
    virtual void decrementRequestCount(const Resource*) OVERRIDE;
    virtual void didLoadResource(Resource*) OVERRIDE;
    virtual void redirectReceived(Resource*, const ResourceResponse&) OVERRIDE;
    virtual void didFinishLoading(const Resource*, double finishTime, const ResourceLoaderOptions&) OVERRIDE;
    virtual void didChangeLoadingPriority(const Resource*, ResourceLoadPriority) OVERRIDE;
    virtual void didFailLoading(const Resource*, const ResourceError&, const ResourceLoaderOptions&) OVERRIDE;
    virtual void willSendRequest(const Resource*, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) OVERRIDE;
    virtual void didReceiveResponse(const Resource*, const ResourceResponse&, const ResourceLoaderOptions&) OVERRIDE;
    virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) OVERRIDE;
    virtual void subresourceLoaderFinishedLoadingOnePart(ResourceLoader*) OVERRIDE;
    virtual void didInitializeResourceLoader(ResourceLoader*) OVERRIDE;
    virtual void willTerminateResourceLoader(ResourceLoader*) OVERRIDE;
    virtual void willStartLoadingResource(ResourceRequest&) OVERRIDE;
    virtual bool defersLoading() const OVERRIDE;
    virtual bool isLoadedBy(ResourceLoaderHost*) const OVERRIDE;
    virtual bool shouldRequest(Resource*, const ResourceRequest&, const ResourceLoaderOptions&) OVERRIDE;
    virtual void refResourceLoaderHost() OVERRIDE;
    virtual void derefResourceLoaderHost() OVERRIDE;

    static const ResourceLoaderOptions& defaultResourceOptions();
private:

    explicit ResourceFetcher(DocumentLoader*);

    FrameLoader* frameLoader();
    bool shouldLoadNewResource() const;

    ResourcePtr<Resource> requestResource(Resource::Type, FetchRequest&);
    ResourcePtr<Resource> revalidateResource(const FetchRequest&, Resource*);
    ResourcePtr<Resource> loadResource(Resource::Type, FetchRequest&, const String& charset);
    void preCacheDataURIImage(const FetchRequest&);
    void storeResourceTimingInitiatorInformation(const ResourcePtr<Resource>&, const FetchRequest&);
    void requestPreload(Resource::Type, FetchRequest&, const String& charset);

    enum RevalidationPolicy { Use, Revalidate, Reload, Load };
    RevalidationPolicy determineRevalidationPolicy(Resource::Type, ResourceRequest&, bool forPreload, Resource* existingResource, FetchRequest::DeferOption) const;

    void determineTargetType(ResourceRequest&, Resource::Type);
    ResourceRequestCachePolicy resourceRequestCachePolicy(const ResourceRequest&, Resource::Type);
    void addAdditionalRequestHeaders(ResourceRequest&, Resource::Type);

    void notifyLoadedFromMemoryCache(Resource*);
    bool checkInsecureContent(Resource::Type, const KURL&) const;

    void garbageCollectDocumentResourcesTimerFired(Timer<ResourceFetcher>*);
    void performPostLoadActions();

    bool clientDefersImage(const KURL&) const;
    void reloadImagesIfNotDeferred();

    HashSet<String> m_validatedURLs;
    mutable DocumentResourceMap m_documentResources;
    Document* m_document;
    DocumentLoader* m_documentLoader;

    int m_requestCount;

    OwnPtr<ListHashSet<Resource*> > m_preloads;
    struct PendingPreload {
        Resource::Type m_type;
        FetchRequest m_request;
        String m_charset;
    };
    Deque<PendingPreload> m_pendingPreloads;

    Timer<ResourceFetcher> m_garbageCollectDocumentResourcesTimer;

    typedef HashMap<Resource*, RefPtr<ResourceTimingInfo> > ResourceTimingInfoMap;
    ResourceTimingInfoMap m_resourceTimingInfoMap;

    // 29 bits left
    bool m_autoLoadImages : 1;
    bool m_imagesEnabled : 1;
    bool m_allowStaleResources : 1;
};

class ResourceCacheValidationSuppressor {
    WTF_MAKE_NONCOPYABLE(ResourceCacheValidationSuppressor);
    WTF_MAKE_FAST_ALLOCATED;
public:
    ResourceCacheValidationSuppressor(ResourceFetcher* loader)
        : m_loader(loader)
        , m_previousState(false)
    {
        if (m_loader) {
            m_previousState = m_loader->m_allowStaleResources;
            m_loader->m_allowStaleResources = true;
        }
    }
    ~ResourceCacheValidationSuppressor()
    {
        if (m_loader)
            m_loader->m_allowStaleResources = m_previousState;
    }
private:
    ResourceFetcher* m_loader;
    bool m_previousState;
};

} // namespace WebCore

#endif


text:
extern NSString *const JWTAlgorithmNameHS256;
extern NSString *const JWTAlgorithmNameHS384;
extern NSString *const JWTAlgorithmNameHS512;

@interface JWTAlgorithmHSBase : NSObject <JWTAlgorithm>

@property (assign, nonatomic, readonly) size_t ccSHANumberDigestLength;
@property (assign, nonatomic, readonly) uint32_t ccHmacAlgSHANumber;

@end

@interface JWTAlgorithmHSBase (Create)

+ (instancetype)algorithm256;
+ (instancetype)algorithm384;
+ (instancetype)algorithm512;

@end


text:
package org.activiti.rest.conf;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;

@Configuration
@PropertySources({
  @PropertySource(value = "classpath:db.properties", ignoreResourceNotFound = true),
  @PropertySource(value = "classpath:engine.properties", ignoreResourceNotFound = true)
  })
@ComponentScan(basePackages = { "org.activiti.rest.conf" })
@ImportResource({ "classpath:activiti-custom-context.xml" })
public class ApplicationConfiguration {

}


text:
export interface DialogActionsClasses {
  root: string;
  spacing: string;
}

declare const dialogActionsClasses: DialogActionsClasses;

export function getDialogActionsUtilityClass(slot: string): string;

export default dialogActionsClasses;


text:
A lightning talk contest will happen on the 2nd of July at 5:30pm in front of the whole audience!

#IMPORTANT: this is only for attendees so you will need a ticket to the conference! You can still get one [here](https://eventlama.com/#/events/reacteurope/tickets).

What's in a lightning? You will have 5 minutes to demo a project of yours or a project you have contributed to, the only requirement is that it must be open source and related to react.js.

**All** lightnings speakers will get awesome prizes as described [here](https://medium.com/@patcito/our-reacteurope-lightning-talks-contest-prizes-61c786e28864).

#How to proceed to submit a lightning#

##Just fork it##

 1. Fork this repository.
 2. Create a directory and name it something such as "my-awesome-lightning" (no spaces).
 3. In that directory, add a proposal.yaml, you can find a [template here](https://github.com/react-europe/cfp-lightnings-2015/blob/master/lightning-sample/proposal.yaml). If there is another speaker, add a Speaker2 key using the same format.
 4. Add a picture of yourself to the dir called speaker1.jpg of size 200x200 (this will be used on the site), if there is another speaker, the file should be named speaker2.jpg and be incremented for each additional speakers.
 5. Commit and create a pull-request to this repo, selected lightnings will be merge into master.
 6. If you want to submit more than one lightning, create a new branch and do a pull request for each branch.
 7. Want to have more chances to get your lightning accepted? Add a link to a youtube video in the past_experience field where you would advertise your talk to attendees so we can re-use the video as promotional material on the conference website (idea from EmberConf :).

You have until Wednesday June 3rd 23:59 UTC+0 to send a proposal
We will announce selected lightnings by Friday June 5th, 2015.

Good luck and thanks for participating!

Follow us on [twitter](https://twitter.com/reacteurope) and [facebook](https://www.facebook.com/ReactEurope).
Don't miss our ticket sale, get a push notification from either our [pushbullet channel](https://www.pushbullet.com/channel?tag=reacteurope) or [YO account](http://www.justyo.co/REACTEUROPE/).


text:
FOSS License Exception
==========================================

What is the FOSS License Exception?
------------------------------------------
This Free and Open Source Software ("FOSS") License Exception allows developers of FOSS Projects to include *Patented NTRU Algorithms and/or NTRU reference code ("NTRU")* with their FOSS Projects. NTRU is licensed pursuant to version 2 (or later) of the General Public License ("GPL"), or under commercial license. This exception permits distribution of NTRU, licensed under GPL, with a developer's FOSS Project licensed under the terms of another FOSS license listed below, even though such other FOSS license may be incompatible with the GPL.

This FOSS License Exception, along with the GPL licensing of NTRU, is an irrevocable grant by Security Innovation, Inc. and cannot be withdrawn by Security Innovation, Inc, and/or any future owners of the Patented NTRU Algorithms.

1. **Definitions.**

    "Derivative Work" means a derivative work, as defined under applicable copyright law, formed entirely from the GPLed NTRU and one or more FOSS Projects.

    "FOSS Project" means a free and open source software product distributed subject to a license listed in the section below titled "FOSS License List."

    "FOSS Notice" means a notice placed by Security Innovation, Inc. in the NTRU Crypto Library Repository ("ntru-crypto") stating that NTRU may be distributed under Security Innovation's FOSS License Exception. As of December 4th 2013, this repository is hosted on github at https://github.com/NTRUOpenSourceProject/ntru-crypto

    "Independent Work" means portions of the Derivative Work that are not derived from the GPLed NTRU and can reasonably be considered independent and separate works.

    "GPLed NTRU" means NTRU, distributed under the GPL v2 or higher.

2.  **A FOSS Project developer ("you" or "your")** may distribute a Derivative Work provided that you and the Derivative Work meet all of the following conditions:

  a. You obey the GPL in all respects for the GPLed NTRU and all portions (including modifications) of the GPLed NTRU included in the Derivative Work (provided that this condition does not apply to Independent Works);

  b. The Derivative Work does not include any work licensed under the GPL other than the GPLed NTRU;

  c. You distribute Independent Works subject to a license listed in the section below titled "FOSS License List";

  d. You distribute Independent Works in object code or executable form with the complete corresponding machine-readable source code on the same medium and under the same FOSS license applying to the object code or executable forms;

  e. All works that are aggregated with the GPLed NTRU or the Derivative Work on a medium or volume of storage are not derivative works of the GPLed NTRU, Derivative Work or FOSS Project, and must reasonably be considered independent and separate works.

  f. You distribute a copy of this FOSS License Exception with your Derivative Work.

3. **Security Innovation, Inc. reserves all rights** not expressly granted in these terms and conditions. If all of the above conditions are not met, then this FOSS License Exception does not apply to you or your Derivative Work.

FOSS License List
------------------

            License Name

            Version(s)/Copyright Date

            Release Early

            Certified Software

            Academic Free License

            2.0

            Apache Software License

            1.0/1.1/2.0

            Apple Public Source License

            2.0

            Artistic license

            From Perl 5.8.0

            BSD license

            "July 22 1999"

            Common Development and Distribution License (CDDL)

            1.0

            Common Public License

            1.0

            Eclipse Public License

            1.0

            European Union Public License (EUPL)1

            1.1

            GNU Affero General Public License (AGPL)

            3.0

            GNU Library or "Lesser" General Public License (LGPL)

            2.0/2.1/3.0

            GNU General Public License (GPL)

            3.0

            IBM Public License

            1.0

            Jabber Open Source License

            1.0

            MIT License (As listed in file MIT-License.txt)

            -

            Mozilla Public License (MPL)

            1.0/1.1

            Open Software License

            2.0

            OpenSSL license (with original SSLeay license)

            "2003" ("1998")

            PHP License

            3.0/3.01

            Python license (CNRI Python License)

            -

            Python Software Foundation License

            2.1.1

            Sleepycat License

            "1999"

            University of Illinois/NCSA Open Source License

            -

            W3C License

            "2001"

            X11 License

            "2001"

            Zlib/libpng License

            -

            Zope Public License

            2.0

FAQ
----

*Q:* Are the NTRU patents covered under the FOSS exception

*A:* Yes, the NTRU patents are covered by the FOSS exception

*Q:* What are the benefits of the FOSS license exception

*A:* The FOSS License Exception permits use of the GPL-licensed patents and source code
with software applications licensed under certain other FOSS licenses without causing the entire derivative work to be subject to the GPL.

*Q:* Is a commercial license still required for proprietary 'for resale' applications

*A:* Yes, if you create a derivative work for resale that is not open source you must acquire a commercial license from Security Innovation


text:
require 'forwardable'

module Svent

  class Event
    extend Forwardable
    def_delegators :@list, :delete, :each, :push, :length, :[]=, :[]

    attr_reader :name
    attr_reader :info

    def initialize(name, info)
      @list = []
      @name = name
      @info = info
    end

    def reverse
      event = Event.new(@name, @info)
      event.instance_variable_set(:@list, @list.reverse)
      event
    end

  end

end


text:
// Copyright 2009-2013 Matvei Stefarov <me@matvei.org>
using System;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
using JetBrains.Annotations;

namespace fCraft
{

    /// <summary> Class dedicated to solving Mono compatibility issues </summary>
    public static class MonoCompat
    {

        /// <summary> Whether the current filesystem is case-sensitive. </summary>
        public static bool IsCaseSensitive { get; private set; }

        /// <summary> Whether we are currently running under Mono. </summary>
        public static bool IsMono { get; private set; }

        /// <summary> Whether Mono's generational GC is available. </summary>
        public static bool IsSGenCapable { get; private set; }

        /// <summary> Full Mono version string. May be null if we are running a REALLY old version. </summary>
        public static string MonoVersionString { get; private set; }

        /// <summary> Mono version number. May be null if we are running a REALLY old version. </summary>
        public static Version MonoVersion { get; private set; }

        /// <summary> Whether we are under a Windows OS (under either .NET or Mono). </summary>
        public static bool IsWindows { get; private set; }

        private const string UnsupportedMessage = "Your Mono version is not supported. Update to at least Mono 2.6+ (recommended 2.10+)";
        private static readonly Regex VersionRegex = new Regex(@"^(\d)+\.(\d+)\.(\d)\D");

        private const BindingFlags MonoMethodFlags = BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding;

        static MonoCompat()
        {
            Type monoRuntimeType = typeof(object).Assembly.GetType("Mono.Runtime");

            if (monoRuntimeType != null)
            {
                IsMono = true;
                MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod("GetDisplayName", MonoMethodFlags, null, Type.EmptyTypes, null);

                if (getDisplayNameMethod != null)
                {
                    MonoVersionString = (string)getDisplayNameMethod.Invoke(null, null);

                    try
                    {
                        Match versionMatch = VersionRegex.Match(MonoVersionString);
                        int major = Int32.Parse(versionMatch.Groups[1].Value);
                        int minor = Int32.Parse(versionMatch.Groups[2].Value);
                        int revision = Int32.Parse(versionMatch.Groups[3].Value);
                        MonoVersion = new Version(major, minor, revision);
                        IsSGenCapable = (major == 2 && minor >= 8);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(UnsupportedMessage, ex);
                    }

                    if (MonoVersion.Major < 2 && MonoVersion.Major < 6)
                    {
                        throw new Exception(UnsupportedMessage);
                    }
                }
                else
                {
                    throw new Exception(UnsupportedMessage);
                }
            }

            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.MacOSX:
                case PlatformID.Unix:
                    IsMono = true;
                    IsWindows = false;
                    break;

                default:
                    IsWindows = true;
                    break;
            }

            IsCaseSensitive = !IsWindows;
        }

        /// <summary> Starts a .NET process, using Mono if necessary. </summary>
        /// <param name="assemblyLocation"> .NET executable path. </param>
        /// <param name="assemblyArgs"> Arguments to pass to the executable. </param>
        /// <param name="detachIfMono"> If true, new process will be detached under Mono. </param>
        /// <returns>Process object</returns>
        public static Process StartDotNetProcess([NotNull] string assemblyLocation, [NotNull] string assemblyArgs, bool detachIfMono)
        {
            if (assemblyLocation == null)
                throw new ArgumentNullException("assemblyLocation");
            if (assemblyArgs == null)
                throw new ArgumentNullException("assemblyArgs");
            string binaryName, args;
            if (IsMono)
            {
                if (IsSGenCapable)
                {
                    binaryName = "mono-sgen";
                }
                else
                {
                    binaryName = "mono";
                }
                args = "\"" + assemblyLocation + "\"";
                if (!String.IsNullOrEmpty(assemblyArgs))
                {
                    args += " " + assemblyArgs;
                }
                if (detachIfMono)
                {
                    args += " &";
                }
            }
            else
            {
                binaryName = assemblyLocation;
                args = assemblyArgs;
            }
            return Process.Start(binaryName, args);
        }

        /// <summary>Prepends the correct Mono name to the .NET executable, if needed.</summary>
        /// <param name="dotNetExecutable"></param>
        /// <returns></returns>
        public static string PrependMono([NotNull] string dotNetExecutable)
        {
            if (dotNetExecutable == null)
                throw new ArgumentNullException("dotNetExecutable");
            if (IsMono)
            {
                if (IsSGenCapable)
                {
                    return "mono-sgen " + dotNetExecutable;
                }
                else
                {
                    return "mono " + dotNetExecutable;
                }
            }
            else
            {
                return dotNetExecutable;
            }
        }
    }
}


text:
/**
 * $Id: JTextAreaCellRenderer.java 5903 2005-03-17 12:39:48Z brighton $
 */

package jsky.util.gui;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;

/**
 * A table cell renderer for multi-line text fields.
 */
public class JTextAreaCellRenderer extends JTextArea implements TableCellRenderer {

    private static final int ROW_PAD = 3;

    protected static Border noFocusBorder = new EmptyBorder(3, 3, 3, 3);
    protected static Border focusBorder = new CompoundBorder(
            UIManager.getBorder("Table.focusCellHighlightBorder"),
            new EmptyBorder(2, 2, 2, 2));

    private Color unselectedForeground;
    private Color unselectedBackground;

    public JTextAreaCellRenderer() {
        setWrapStyleWord(true);
        setLineWrap(true);
        setOpaque(true);
        setBorder(noFocusBorder);
    }

    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus,
                                                   int row, int column) {
        if (isSelected) {
            super.setForeground(table.getSelectionForeground());
            super.setBackground(table.getSelectionBackground());
        } else {
            super.setForeground((unselectedForeground != null) ?
                    unselectedForeground : table.getForeground());
            super.setBackground((unselectedBackground != null) ?
                    unselectedBackground : table.getBackground());
        }

        setFont(table.getFont());

        if (hasFocus) {
//            setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
            setBorder(focusBorder);
            if (table.isCellEditable(row, column)) {
                super.setForeground(UIManager.getColor("Table.focusCellForeground"));
                super.setBackground(UIManager.getColor("Table.focusCellBackground"));
            }
        } else {
            setBorder(noFocusBorder);
        }

        setText((value == null) ? "" : value.toString());
        _updateRowHeight(row, column, table);

        return this;
    }

    private void _updateRowHeight(int row, int column, JTable table) {
        if (row < 0 || column < 0) {
            return;
        }

        int tableColWidth = table.getColumnModel().getColumn(column).getWidth();
        Dimension d = getPreferredSize();
        if (d.width != tableColWidth) {
            setSize(new Dimension(tableColWidth, 1000));
            d = getPreferredSize();
        }

        int tableRowHeight = table.getRowHeight(row);
        int defaultTableRowHeight = table.getRowHeight();
        if (d.height < defaultTableRowHeight) {
            d.height = defaultTableRowHeight;
        }

        if (d.height+ROW_PAD != tableRowHeight) {
            table.setRowHeight(row, d.height+ROW_PAD);
        }
    }

    /**
     * Notification from the UIManager that the look and feel
     * [L&F] has changed.
     * Replaces the current UI object with the latest version from the
     * UIManager.
     *
     * @see JComponent#updateUI
     */
    public void updateUI() {
        super.updateUI();
        setForeground(null);
        setBackground(null);
    }

    /**
     * Overrides JComponent.setForeground to assign
     * the unselected-foreground color to the specified color.
     *
     * @param c set the foreground color to this value
     */
    public void setForeground(Color c) {
        super.setForeground(c);
        unselectedForeground = c;
    }

    /**
     * Overrides JComponent.setBackground to assign
     * the unselected-background color to the specified color.
     *
     * @param c set the background color to this value
     */
    public void setBackground(Color c) {
        super.setBackground(c);
        unselectedBackground = c;
    }

    /**
     * Overridden for performance reasons.
     * See the Implementation Note
     * for more information.
     */
    public boolean isOpaque() {
        Color back = getBackground();
        Component p = getParent();
        if (p != null) {
            p = p.getParent();
        }
        // p should now be the JTable.
        boolean colorMatch = (back != null) && (p != null) &&
                back.equals(p.getBackground()) && p.isOpaque();
        return !colorMatch && super.isOpaque();
    }

    /**
     * Overridden for performance reasons.
     * See the Implementation Note
     * for more information.
     */
    public void validate() {
    }

    /**
     * Overridden for performance reasons.
     * See the Implementation Note
     * for more information.
     */
    public void revalidate() {
    }

    /**
     * Overridden for performance reasons.
     * See the Implementation Note
     * for more information.
     */
    public void repaint(long tm, int x, int y, int width, int height) {
    }

    /**
     * Overridden for performance reasons.
     * See the Implementation Note
     * for more information.
     */
    public void repaint(Rectangle r) {
    }

    /**
     * Overridden for performance reasons.
     * See the Implementation Note
     * for more information.
     */
    protected void firePropertyChange(String propertyName, Object oldValue,
                                      Object newValue) {
        // Strings get interned...
        if (propertyName == "text") {
            super.firePropertyChange(propertyName, oldValue, newValue);
        }
    }

    /**
     * Overridden for performance reasons.
     * See the Implementation Note
     * for more information.
     */
//    public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) { }

    /**
     * A subclass of DefaultTableCellRenderer that
     * implements UIResource.
     * DefaultTableCellRenderer doesn't implement
     * UIResource
     * directly so that applications can safely override the
     * cellRenderer property with
     * DefaultTableCellRenderer subclasses.
     *

     * Warning:
     * Serialized objects of this class will not be compatible with
     * future Swing releases. The current serialization support is
     * appropriate for short term storage or RMI between applications running
     * the same version of Swing.  As of 1.4, support for long term storage
     * of all JavaBeansTM
     * has been added to the java.beans package.
     * Please see {@link java.beans.XMLEncoder}.
     */
    public static class UIResource extends DefaultTableCellRenderer
            implements javax.swing.plaf.UIResource {

    }
}


text:
var waiting = false;
showdown.setOption('headerLevelStart', 2);
//Extension
showdown.extension('header-anchors', function() {

  var ancTpl = '$1$4';

  return [{
    type: 'html',
    regex: /(<h([1-4]) id="([^"]+?)">)(.*<\/h\2>)/g,
    replace: ancTpl
  }];
});

function formatForForm(date) {
    var year = date.getFullYear();
    var month = leftPad(date.getMonth() + 1 + '', 2, '0');
    var day = leftPad(date.getDate() + '', 2, '0');
    var hours = leftPad(date.getHours() + '', 2, '0');
    var minutes = leftPad(date.getMinutes() + '', 2, '0');
    return year + '-' + month + '-' + day + 'T' + hours + ':' + minutes;
}

function leftPad(str, goalLength, padChar) {
    if (str.length < goalLength) {
        return new Array(goalLength - str.length + 1).join(padChar) + str;
    } else {
        return str;
    }
}

function getConverter() {
  return new showdown.Converter({
      extensions: ['header-anchors']
  });
}

function doLogout() {
    $.ajax({
        type: "GET",
        url: "/api/logout",
        cache: false,
        xhrFields: {
            withCredentials: true
        },
        success: function () {
            window.location.href = "/";
        },
        error: function () {
            alert("Failed logout: retry or contact an administrator.");
        }
    });
}

function delDoc(type, id, statusId, toHide, homeFn) {
    var csrfInput = $('input[name="csrf"]');
    var toHideObject = $(toHide);
    var loader = $('.loader');
    if (!waiting && confirm("This will delete the document, are you sure you want to continue?")) {
        hideMessage(statusId + "-error");
        waiting = true;
        toHideObject.hide();
        loader.show();
        $.ajax({
            type: "DELETE",
            url: "/api/"+type+"/" + id,
            cache: false,
            contentType: "application/json",
            headers: {
                'X-Csrf-Protection': csrfInput.val()
            },
            success: function () {
                waiting = false;
                loader.hide();
                showMessage(statusId + "-success", "Deletion successful.");
                setTimeout(function () {
                    homeFn()
                }, 500);
            },
            error: function (resp) {
                waiting = false;
                loader.hide();
                toHideObject.show();
                showMessage(statusId + "-error", "Could not delete for the following reason: " + resp.responseText);
            }
        });
    }
}

function downloadTrash(type, statusId) {
    if (!waiting) {
        hideMessage(statusId + "-error");
        waiting = true;
        $.ajax({
            type: "GET",
            url: "/api/trash/" + type,
            cache: false,
            contentType: "application/json",
            success: function (resp) {
                waiting = false;
                var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(resp, null, 2));
                var dlAnchorElem = $('#downloadAnchorElem')[0];
                dlAnchorElem.setAttribute("href", dataStr);
                dlAnchorElem.setAttribute("download", "deleted"+type+".json");
                dlAnchorElem.click();
                dlAnchorElem.removeAttribute("href");
                dlAnchorElem.removeAttribute("download");
            },
            error: function (resp) {
                waiting = false;
                showMessage(statusId + "-error", "Could not download deleted items for the following reason: " + resp.responseText);
            }
        });
    }
}

function purgeTrash(type, statusId) {
    var csrfInput = $('input[name="csrf"]');
    if (!waiting) {
        hideMessage(statusId + "-error");
        waiting = true;
        $.ajax({
            type: "DELETE",
            url: "/api/trash/" + type,
            cache: false,
            contentType: "application/json",
            headers: {
                'X-Csrf-Protection': csrfInput.val()
            },
            success: function () {
                waiting = false;
                showMessage(statusId + "-success", "Deleted items purged.");
                setTimeout(function () {
                    hideMessage(statusId + "-success");
                }, 1000);
            },
            error: function (resp) {
                waiting = false;
                showMessage(statusId + "-error", "Could not purge deleted items for the following reason: " + resp.responseText);
            }
        });
    }
}

function edit(type, id) {
    window.location.href = "/" + type + "/edit/" + id;
}

function add(type) {
    window.location.href = "/" + type + "/add";
}

function backHome() {
    window.location.href = "/";
}

function postsHome() {
    window.location.href = "/posts"
}

function projectsHome() {
    window.location.href = "/projects"
}

function editAbout() {
    window.location.href = "/perso/edit"
}

function showMessage(divId, message) {
    var errDiv = $("#" + divId);
    errDiv.empty();
    errDiv.text(message);
    errDiv.show();
}

function hideMessage(divId) {
    $("#" + divId).hide();
}

function checkStr(text, minLength) {
    return ((typeof text != "undefined") &&
    (typeof text.valueOf() == "string") &&
    (text.length >= minLength));
}

function doLogin() {
    var form = $('form[name="login"]');
    var loader = $('.loader');
    if (!waiting) {
        hideMessage("login-error");
        waiting = true;
        form.hide();
        loader.show();
        $.ajax
        ({
            type: "POST",
            url: "/api/token",
            dataType: 'json',
            data: '{"username":"' + form[0].username.value + '",' + '"password":"' + form[0].password.value + '"}',
            cache: false,
            xhrFields: {
                withCredentials: true
            },
            contentType: "application/json",
            success: function () {
                waiting = false;
                window.location.reload();
            },
            error: function () {
                waiting = false;
                loader.hide();
                form.show();
                showMessage("login-error", "Password/username combination is incorrect.");
            }
        });
    }
}

function updateAbout() {
    var form = $('form[name="aboutme-edit"]');
    var loader = $('.loader');
    if (!waiting) {
        hideMessage("form-error");
        waiting = true;
        form.hide();
        loader.show();

        var converter = getConverter();
        var introMarkdown = form[0].intromarkdown.value;
        var introHtml = converter.makeHtml(introMarkdown);

        var resumeMarkdown = form[0].resumemarkdown.value;
        var resumeHtml = converter.makeHtml(resumeMarkdown);

        var aboutMe = {};

        if (checkStr(introMarkdown, 1)) {
            aboutMe["introduction"] = {
                html: introHtml,
                markdown: introMarkdown
            }
        }

        if (checkStr(resumeMarkdown, 1)) {
            aboutMe["resume"] = {
                html: resumeHtml,
                markdown: resumeMarkdown
            }
        }

        $.ajax({
            type: "PUT",
            url: "/api/perso",
            data: JSON.stringify(aboutMe),
            cache: false,
            contentType: "application/json",
            headers: {
                'X-Csrf-Protection': form[0].csrf.value
            },
            success: function () {
                waiting = false;
                loader.hide();
                showMessage("form-success", "Update successful.");
                setTimeout(function () {
                    editAbout();
                }, 500);
            },
            error: function (resp) {
                console.log(resp);
                waiting = false;
                loader.hide();
                form.show();
                showMessage("form-error", "Could not update post for the following reason: " + resp.responseText);
            }
        });
    }
}

function update(type, add, formName) {
    var form = $('form[name="'+formName+'"]');
    var loader = $('.loader');
    if (!waiting) {
        hideMessage("form-error");
        waiting = true;
        form.hide();
        loader.show();
        var id = parseInt(form[0].id.value);
        var title = form[0].title.value;
        var abstract = form[0].abstract.value;

        var converter = getConverter();
        var contentMarkdown = form[0].contentmarkdown.value;
        var contentHtml = converter.makeHtml(contentMarkdown);
        var publishedDate = new Date(form[0].publication.value);
        var publishedDateStr = publishedDate.toISOString();

        var doc = {
            id: id,
            title: title,
            abstract: abstract,
            content: {
                html: contentHtml,
                markdown: contentMarkdown
            },
            published: publishedDateStr
        };

        if (type === "posts") {
          addPostValues(form, doc);
        }

        var reqType = add ? "POST" : "PUT";
        var urlEnd = add ? "" : "/" + id;

        $.ajax({
            type: reqType,
            url: "/api/" + type + urlEnd,
            data: JSON.stringify(doc),
            cache: false,
            contentType: "application/json",
            headers: {
                'X-Csrf-Protection': form[0].csrf.value
            },
            success: function (resp) {
                waiting = false;
                loader.hide();
                showMessage("form-success", "Update successful.");
                var editId = add ? resp.id : id;
                setTimeout(function () {
                    edit(type, editId);
                }, 500);
            },
            error: function (resp) {
                console.log(resp);
                waiting = false;
                loader.hide();
                form.show();
                showMessage("form-error", "Could not update for the following reason: " + resp.responseText);
            }
        });
    }
}

function addPostValues(form, doc) {
  var category = $("#category option:selected").text();
  var thumbnail = $("#thumbnail").val();
  if (category !== "None") {
    doc.category = category;
  }
  if (thumbnail && thumbnail !== "None") {
    doc.thumbnail = thumbnail;
  }
  doc.explicit = form[0].explicit.checked;
}

function submitNavbarConf() {
    var form = $('form[name="edit-navbar"]');
    var formTitle = $('#nav-title');
    var loader = $('.loader');
    if (!waiting) {
        hideMessage("form-error");
        waiting = true;
        form.hide();
        formTitle.hide();
        loader.show();

        var projects = form[0].projects.checked;
        var about = form[0].about.checked;

        var navBarConf = {
            projects: projects,
            about: about
        };

        $.ajax({
            type: "PUT",
            url: "/api/navbar",
            data: JSON.stringify(navBarConf),
            cache: false,
            contentType: "application/json",
            headers: {
                'X-Csrf-Protection': form[0].csrf.value
            },
            success: function () {
                waiting = false;
                loader.hide();
                showMessage("form-success", "Update successful.");
                setTimeout(function () {
                    hideMessage("form-success");
                    form.show();
                    formTitle.show();
                }, 500);
            },
            error: function (resp) {
                console.log(resp);
                waiting = false;
                loader.hide();
                form.show();
                formTitle.show();
                showMessage("form-error", "Could not update navigation bar for the following reason: " + resp.responseText);
            }
        });
    }
}

function publish(type, add, formName) {
    if (!waiting && confirm("This will publish the item on the blog.")) {
        var publishDate = new Date();
        $("input[type='datetime-local']").val(formatForForm(publishDate));
        update(type, add, formName)
    }
}

function showPreview(formName, fillPreview) {
    var form = $('form[name="'+ formName+ '"]');
    var preview = $('.preview');
    var loader = $('.loader');
    form.hide();
    loader.show();

    fillPreview(formName);

    loader.hide();
    preview.show();
}

function fillDocPreview(formName) {
    var form = $('form[name="' + formName + '"]');
    var preview = $('.preview');
    var title = form[0].title.value;
    var previewDoc = $('.preview > .doc');

    var converter = getConverter();
    var contentMarkdown = form[0].contentmarkdown.value;
    var contentHtml = converter.makeHtml(contentMarkdown);

    var thumbnail = $("#thumbnail").val();
    thumbnail = thumbnail && thumbnail !== 'None' ? '' : '';

    previewDoc.html(thumbnail + "
" + title + "
" + contentHtml);
    $('pre code').each(function (i, block) {
        hljs.highlightBlock(block);
    });
}

function fillAboutMePreview() {
    var form = $('form[name="aboutme-edit"]');
    var preview = $('.preview');
    var previewIntro = $('.preview > #introduction');
    var previewResume = $('.preview > #resume');

    var converter = getConverter();
    var introMarkdown = form[0].intromarkdown.value;
    var introHtml = converter.makeHtml(introMarkdown);

    var resumeMarkdown = form[0].resumemarkdown.value;
    var resumeHtml = converter.makeHtml(resumeMarkdown);

    previewIntro.html(introHtml);
    previewResume.html(resumeHtml);

    if (checkStr(introMarkdown, 1)) {
        previewIntro.show();
    } else {
        previewIntro.hide();
    }

    if (checkStr(resumeMarkdown, 1)) {
        previewResume.show();
    } else {
        previewResume.hide();
    }

    $('pre code').each(function (i, block) {
        hljs.highlightBlock(block);
    });
}

function hidePreview(formName) {
    var form = $('form[name="'+ formName+ '"]');
    var preview = $('.preview');
    preview.hide();
    form.show();
}

function changePassword() {
    var form = $('form[name="edit-password"]');
    var loader = $('.loader');
    if (!waiting) {
        hideMessage("edit-password-error");
        waiting = true;
        form.hide();
        loader.show();
        var oldpassword = form[0].oldpassword.value;
        var newpassword = form[0].newpassword.value;
        var confpassword = form[0].confpassword.value;

        if (!checkStr(newpassword, 10) || !checkStr(confpassword, 10)) {
            showMessage("edit-password-error", "New password is too short (minimum 10 characters).");
            form.show();
            loader.hide();
            waiting = false;
            return;
        }

        if (newpassword != confpassword) {
            showMessage("edit-password-error", "The new password and the confirmation should match.");
            form.show();
            loader.hide();
            waiting = false;
            return;
        }

        var newCredentials = {
            username: form[0].username.value,
            oldPassword: oldpassword,
            newPassword: newpassword
        };

        $.ajax
        ({
            type: "POST",
            url: "/api/new_password",
            data: JSON.stringify(newCredentials),
            cache: false,
            contentType: "application/json",
            headers: {
                'X-Csrf-Protection': form[0].csrf.value
            },
            success: function () {
                waiting = false;
                loader.hide();
                form.show();
                resetFields("edit-password", "edit-password-error");
                showMessage("edit-password-success", "Update successful.");
                setTimeout(function () {
                    hideMessage("edit-password-success");
                }, 1000);
            },
            error: function () {
                waiting = false;
                loader.hide();
                form.show();
                showMessage("edit-password-error", "Old password is incorrect.");
            }
        });
    }
}

function resetFields(formName, errorId) {
    hideMessage(errorId);
    var form = $('form[name="' + formName + '"]');
    form.find('input[type=password], input[type=text]').each(function () {
        var inputField = $(this);
        inputField.val("");
        inputField.removeClass("ok");
        inputField.addClass("not-ok");
    });
}

function removeCategory(id) {
  $('#category'+id).remove();
}

function addCategory() {
  var form = $('form[name="edit-categories"]');
  var nextCat = form[0].nextcat;
  var id = nextCat.value;
  var newCat = form[0].newcategory;
  var newCatName = newCat.value;
  if (newCatName !== "") {
    $('#categories').append(
      '
'+
         ''+newCatName+'
✖
'+
      '
'
    );
    newCat.value = '';
    nextCat.value = id + 1;
  }
}

function submitCategories() {
  var form = $('form[name="edit-categories"]');
  var formTitle = $('#cat-title');
  var loader = $('.loader');
  if (!waiting) {
    hideMessage("form-error");
    waiting = true;
    form.hide();
    formTitle.hide();
    loader.show();

    var nextCat = form[0].nextcat.value;
    var categories = {titles: []};
    var order = 0;
    for (var i = 0; i < nextCat; ++i) {
      var cat = $('#category'+i);
      if (cat.length) {
        categories.titles.push({
          title: cat.children('label').text(),
          order: order
        });
        order++;
      }
    }

    $.ajax({
      type: "PUT",
      url: "/api/categories",
      data: JSON.stringify(categories),
      cache: false,
      contentType: "application/json",
      headers: {
        'X-Csrf-Protection': form[0].csrf.value
      },
      success: function () {
        waiting = false;
        loader.hide();
        showMessage("form-success", "Update successful.");
        setTimeout(function () {
          hideMessage("form-success");
          form.show();
          formTitle.show();
        }, 500);
      },
      error: function (resp) {
        console.log(resp);
        waiting = false;
        loader.hide();
        form.show();
        formTitle.show();
        showMessage("form-error", "Could not update categories for the following reason: " + resp.responseText);
      }
    });
  }
}

function submitNewImage() {
  var form = $('form[name="upload-image"]');
  var imgList = $('#img-list');
  var formTitle = $('#img-title');
  var loader = $('.loader');
  if (!waiting && form[0].image.value) {
    hideMessage("form-error");
    waiting = true;
    form.hide();
    imgList.hide();
    formTitle.hide();
    loader.show();
    var formData = new FormData();
    var fileName = form[0].title.value;
    formData.append("fileName", fileName);
    formData.append("data", form[0].image.files[0]);

    $.ajax({
      type: "POST",
      url: "/api/images",
      data: formData,
      cache: false,
      contentType: false,
      processData: false,
      headers: {
        'X-Csrf-Protection': form[0].csrf.value
      },
      success: function () {
        waiting = false;
        loader.hide();
        showMessage("form-success", "Update successful.");
        setTimeout(function () {
          window.location.reload();
        }, 500);
      },
      error: function (resp) {
        console.log(resp);
        waiting = false;
        loader.hide();
        form.show();
        formTitle.show();
        imgList.show();
        if (resp.status == 413) {
          showMessage("form-error", "Could not upload image for the following reason: the file is too large, it should be less than 4 MB.");
        } else {
          showMessage("form-error", "Could not upload image for the following reason: " + resp.responseText);
        }
      }
    });
  }
}

function deleteImage(imageName) {
  var form = $('form[name="upload-image"]');
  var imgList = $('#img-list');
  var formTitle = $('#img-title');
  var loader = $('.loader');
  if (!waiting && confirm('This will delete the image called "' + imageName + '", are you sure you want to continue?')) {
    hideMessage("form-error");
    waiting = true;
    imgList.hide();
    form.hide();
    formTitle.hide();
    loader.show();

    $.ajax({
      type: "DELETE",
      url: "/api/images/" + imageName,
      cache: false,
      contentType: "application/json",
      headers: {
        'X-Csrf-Protection': form[0].csrf.value
      },
      success: function () {
        waiting = false;
        loader.hide();
        showMessage("form-success", "Deletion successful.");
        setTimeout(function () {
          window.location.reload();
        }, 500);
      },
      error: function (resp) {
        console.log(resp);
        waiting = false;
        loader.hide();
        form.show();
        imgList.show();
        formTitle.show();
        showMessage("form-error", "Could not delete image for the following reason: " + resp.responseText);
      }
    });
  }
}

// Transforms date in local format
$(function () {
  $('[data-raw-date]').each( function () {
    var rawDate = $(this).html();
    const options = { weekday: "short", year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "numeric"};
    $(this).html(new Date(rawDate).toLocaleString("en-GB", options));
  });
});


text:
var Blackfeather = require('../blackfeather-2.0.0');

var compressed = Blackfeather.Data.Compression.LZString.Compress("caw caw caw");
var decompressed = Blackfeather.Data.Compression.LZString.Decompress(compressed);

console.log(`compressed: ${compressed}, length: ${compressed.length}`);
console.log(`decompressed: ${decompressed}, length: ${decompressed.length}`);


text:
import mimetypes

from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.template.defaultfilters import slugify
from django.conf import settings
from django.urls import reverse

from bs4 import BeautifulSoup
from extended_choices import Choices

from mapentity.serializers import plain_text
from geotrek.common.mixins.models import TimeStampedModelMixin, BasePublishableMixin

FLATPAGES_TARGETS = Choices(
    ('ALL', 'all', _('All')),
    ('MOBILE', 'mobile', _('Mobile')),
    ('HIDDEN', 'hidden', _('Hidden')),
    ('WEB', 'web', _('Web')),
)

class FlatPage(BasePublishableMixin, TimeStampedModelMixin):
    """
    Manage *Geotrek-rando* static pages from Geotrek admin.

    Historically, we started static pages as static HTML files within
    *Geotrek-rando* folders.
    """
    title = models.CharField(verbose_name=_('Title'), max_length=200)
    external_url = models.URLField(verbose_name=_('External URL'), blank=True, default='',
                                   help_text=_('Link to external website instead of HTML content'))
    content = models.TextField(verbose_name=_('Content'), null=True, blank=True,
                               help_text=_('HTML content'))
    target = models.CharField(verbose_name=_('Target'), max_length=12, choices=FLATPAGES_TARGETS,
                              default=FLATPAGES_TARGETS.ALL)
    source = models.ManyToManyField('common.RecordSource',
                                    blank=True, related_name='flatpages',
                                    verbose_name=_("Source"))
    portal = models.ManyToManyField('common.TargetPortal',
                                    blank=True, related_name='flatpages',
                                    verbose_name=_("Portal"))
    order = models.IntegerField(default=None, null=True, blank=True,
                                help_text=_("ID order if blank", ),
                                verbose_name=_("Order"))
    attachments = GenericRelation(settings.PAPERCLIP_ATTACHMENT_MODEL)

    @property
    def slug(self):
        return slugify(self.title)

    class Meta:
        verbose_name = _('Flat page')
        verbose_name_plural = _('Flat pages')
        ordering = ['order', 'id']
        permissions = (
            ("read_flatpage", "Can read FlatPage"),
        )

    def __str__(self):
        return self.title

    def get_permission_codename(self, *args):
        return

    def clean(self):
        html_content = ''
        for language in settings.MAPENTITY_CONFIG['TRANSLATED_LANGUAGES']:
            html_content += getattr(self, 'content_%s' % language[0], None) or ''

    def parse_media(self):
        soup = BeautifulSoup(self.content or '', 'lxml')
        images = soup.findAll('img')
        results = []
        for image in images:
            url = image.get('src')
            if url is None:
                continue

            mt = mimetypes.guess_type(url, strict=True)[0]
            if mt is None:
                mt = 'application/octet-stream'

            results.append({
                'url': url,
                'title': image.get('title', ''),
                'alt': image.get('alt', ''),
                'mimetype': mt.split('/'),
            })

        return results

    def get_add_url(self):
        return reverse('admin:flatpages_flatpage_add')

    def get_update_url(self):
        return reverse('admin:flatpages_flatpage_change', args=[self.pk])

    def get_delete_url(self):
        return reverse('admin:flatpages_flatpage_delete', args=[self.pk])

    @property
    def rando_url(self):
        return 'informations/{}/'.format(self.slug)

    @property
    def meta_description(self):
        return plain_text(self.content)[:500]

    def is_public(self):
        return self.any_published


text:
#ifndef SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_OBSERVER_H_
#define SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_OBSERVER_H_

namespace application_manager {
class Message;
}

namespace hmi_message_handler {

class HMIMessageObserver {
 public:
  virtual ~HMIMessageObserver() {}
  virtual void OnMessageReceived(
      std::shared_ptr<application_manager::Message> message) = 0;
  virtual void OnErrorSending(
      std::shared_ptr<application_manager::Message> message) = 0;
};
}  // namespace hmi_message_handler

#endif  // SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_OBSERVER_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:activiti="http://activiti.org/bpmn"
  targetNamespace="Examples">

  <process id="ParallelScopeTasksScenario.nested" isExecutable="true">
    <startEvent id="start" />
    <sequenceFlow id="flow1" sourceRef="start" targetRef="subProcess" />

    <subProcess id="subProcess">
      <startEvent id="subProcessStart" />
      <sequenceFlow id="flow2" sourceRef="subProcessStart" targetRef="fork" />
      <parallelGateway id="fork" />

      <sequenceFlow id="flow3" sourceRef="fork" targetRef="task1" />
      <userTask id="task1" />
      <sequenceFlow id="flow4" sourceRef="task1" targetRef="join" />

      <sequenceFlow id="flow5" sourceRef="fork" targetRef="task2" />
      <userTask id="task2" />
      <sequenceFlow id="flow6" sourceRef="task2" targetRef="join" />

      <parallelGateway id="join" />
      <sequenceFlow id="flow7" sourceRef="join" targetRef="subProcessEnd" />
      <endEvent id="subProcessEnd" />

      <!-- boundary event 1 -->
      <boundaryEvent id="boundaryTimer1" cancelActivity="true" attachedToRef="task1">
        <timerEventDefinition>
          <timeDuration>P10D</timeDuration>
        </timerEventDefinition>
      </boundaryEvent>
      <sequenceFlow id="flow8" sourceRef="boundaryTimer1" targetRef="boundaryEnd1" />
      <endEvent id="boundaryEnd1" />

      <!-- boundary event 2 -->
      <boundaryEvent id="boundaryTimer2" cancelActivity="true" attachedToRef="task2">
        <timerEventDefinition>
          <timeDuration>P10D</timeDuration>
        </timerEventDefinition>
      </boundaryEvent>
      <sequenceFlow id="flow9" sourceRef="boundaryTimer2" targetRef="boundaryEnd2" />
      <endEvent id="boundaryEnd2" />
    </subProcess>

    <sequenceFlow id="flow10" sourceRef="subProcess" targetRef="end" />
    <endEvent id="end" />
  </process>
</definitions>


text:
UPDATE section
  INNER JOIN competition
    ON section.competition_id = competition.id
  INNER JOIN competition_type
    ON (competition.competition_type_id = competition_type.id
      OR competition.id = competition_type.template_competition_id)
    AND competition_type.name = 'Generic'
SET section.description = 'These are the questions which will be marked by the assessors.'
  WHERE section.name = 'Application questions';


text:
require 'geo_ruby/simple_features'

# Require if you need
# require 'geo_ruby/shp4r/shp'
# require 'geo_ruby/gpx4r/gpx'
# require 'geo_ruby/geojson'
# require 'geo_ruby/georss'
# require 'geo_ruby/kml'


text:
directory "/cookbook-test" do
  mode 0755
  owner "root"
  action :create
end


text:
<?php namespace CodeIgniter\Cache\Handlers;

class RedisHandlerTest extends \CodeIgniter\Test\CIUnitTestCase
{
	private $redisHandler;
	private static $key1 = 'key1';
	private static $key2 = 'key2';
	private static $key3 = 'key3';
	private static function getKeyArray()
	{
		return [
			self::$key1,
			self::$key2,
			self::$key3,
		];
	}

	private static $dummy = 'dymmy';
	private $config;

	protected function setUp(): void
	{
		parent::setUp();

		$this->config = new \Config\Cache();

		$this->redisHandler = new RedisHandler($this->config);
		if (! $this->redisHandler->isSupported())
		{
			$this->markTestSkipped('Not support redis');
		}

		$this->redisHandler->initialize();
	}

	public function tearDown(): void
	{
		foreach (self::getKeyArray() as $key)
		{
			$this->redisHandler->delete($key);
		}
	}

	public function testNew()
	{
		$this->assertInstanceOf(RedisHandler::class, $this->redisHandler);
	}

	public function testDestruct()
	{
		$this->redisHandler = new RedisHandler($this->config);
		$this->redisHandler->initialize();

		$this->assertInstanceOf(RedisHandler::class, $this->redisHandler);
	}

	public function testGet()
	{
		$this->redisHandler->save(self::$key1, 'value', 2);

		$this->assertSame('value', $this->redisHandler->get(self::$key1));
		$this->assertNull($this->redisHandler->get(self::$dummy));

		\CodeIgniter\CLI\CLI::wait(3);
		$this->assertNull($this->redisHandler->get(self::$key1));
	}

	public function testRemember()
	{
		$this->redisHandler->remember(self::$key1, 2, function () {
			return 'value';
		});

		$this->assertSame('value', $this->redisHandler->get(self::$key1));
		$this->assertNull($this->redisHandler->get(self::$dummy));

		\CodeIgniter\CLI\CLI::wait(3);
		$this->assertNull($this->redisHandler->get(self::$key1));
	}

	public function testSave()
	{
		$this->assertTrue($this->redisHandler->save(self::$key1, 'value'));
	}

	public function testDelete()
	{
		$this->redisHandler->save(self::$key1, 'value');

		$this->assertTrue($this->redisHandler->delete(self::$key1));
		$this->assertFalse($this->redisHandler->delete(self::$dummy));
	}

	//FIXME: I don't like all Hash logic very much. It's wasting memory.
	//public function testIncrement()
	//{
	//}

	//public function testDecrement()
	//{
	//}

	public function testClean()
	{
		$this->redisHandler->save(self::$key1, 1);
		$this->redisHandler->save(self::$key2, 'value');

		$this->assertTrue($this->redisHandler->clean());
	}

	public function testGetCacheInfo()
	{
		$this->redisHandler->save(self::$key1, 'value');

		$this->assertIsArray($this->redisHandler->getCacheInfo());
	}

	public function testGetMetaData()
	{
		$time = time();
		$this->redisHandler->save(self::$key1, 'value');

		$this->assertNull($this->redisHandler->getMetaData(self::$dummy));

		$actual = $this->redisHandler->getMetaData(self::$key1);
		$this->assertLessThanOrEqual(60, $actual['expire'] - $time);
		$this->assertLessThanOrEqual(0, $actual['mtime'] - $time);
		$this->assertSame('value', $actual['data']);
	}

	public function testIsSupported()
	{
		$this->assertTrue($this->redisHandler->isSupported());
	}
}


text:
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using DataStructures.Trees;
using Xunit;

namespace UnitTest.DataStructuresTests
{
    public static class TrieTest
    {
        [Fact]
        public static void DoTest()
        {
            var trie = new Trie();

            // Insert some how to words
            var prefix_howTo = "How to make";

            var word_howToSand = prefix_howTo + " a sandwitch";
            var word_howToRobot = prefix_howTo + " a robot";
            var word_howToOmelet = prefix_howTo + " an omelet";
            var word_howToProp = prefix_howTo + " a proposal";
            var listOfHow = new List<string>() { word_howToSand, word_howToRobot, word_howToOmelet, word_howToProp };

            trie.Add(word_howToOmelet);
            trie.Add(word_howToSand);
            trie.Add(word_howToRobot);
            trie.Add(word_howToProp);

            // Count of words = 4
            Assert.Equal(4, trie.Count);

            // Insert some dictionary words
            var prefix_act = "act";

            var word_acts = prefix_act + "s";
            var word_actor = prefix_act + "or";
            var word_acting = prefix_act + "ing";
            var word_actress = prefix_act + "ress";
            var word_active = prefix_act + "ive";
            var listOfActWords = new List<string>() { word_acts, word_actor, word_acting, word_actress, word_active };

            trie.Add(word_actress);
            trie.Add(word_active);
            trie.Add(word_acting);
            trie.Add(word_acts);
            trie.Add(word_actor);

            // Count of words = 9
            Assert.Equal(9, trie.Count);

            //
            // ASSERT THE WORDS IN TRIE.

            // Search for a word that doesn't exist
            Assert.False(trie.ContainsWord(prefix_howTo));

            // Search for prefix
            Assert.True(trie.ContainsPrefix(prefix_howTo));

            // Search for a prefix using a word
            Assert.True(trie.ContainsPrefix(word_howToSand));

            // Get all words that start with the how-to prefix
            var someHowToWords = trie.SearchByPrefix(prefix_howTo).ToList();
            Assert.Equal(someHowToWords.Count, listOfHow.Count);

            // Assert there are only two words under the prefix "acti" -> active, & acting
            var someActiWords = trie.SearchByPrefix("acti").ToList<string>();
            Assert.True(someActiWords.Count == 2);
            Assert.Contains(word_acting, someActiWords);
            Assert.Contains(word_active, someActiWords);

            // Assert that "acto" is not a word
            Assert.False(trie.ContainsWord("acto"));

            // Check the existance of other words
            Assert.True(trie.ContainsWord(word_actress));
            Assert.True(trie.ContainsWord(word_howToProp));

            //
            // TEST DELETING SOMETHINGS

            // Removing a prefix should fail
            var removing_acto_fails = false;
            try
            {
                // try removing a non-terminal word
                trie.Remove("acto");
                removing_acto_fails = false;
            }
            catch
            {
                // if exception occured then code works, word doesn't exist.
                removing_acto_fails = true;
            }

            Assert.True(removing_acto_fails);
            Assert.True(trie.Count == 9);

            // Removing a word should work
            var removing_acting_passes = false;
            try
            {
                // try removing a non-terminal word
                trie.Remove(word_acting);
                removing_acting_passes = true;
            }
            catch
            {
                // if exception occured then code DOESN'T work, word does exist.
                removing_acting_passes = false;
            }

            Assert.True(removing_acting_passes);
            Assert.True(trie.Count == 8);

            someActiWords = trie.SearchByPrefix("acti").ToList<string>();
            Assert.True(someActiWords.Count == 1);
            Assert.Contains(word_active, someActiWords);

            //
            // TEST ENUMERATOR

            var enumerator = trie.GetEnumerator();
            var allWords = new List<string>();
            while (enumerator.MoveNext())
                allWords.Add(enumerator.Current);

            // Assert size
            Assert.True(allWords.Count == trie.Count);

            // Assert each element
            foreach (var word in allWords)
                Debug.Assert(listOfActWords.Contains(word) || listOfHow.Contains(word));
        }
    }
}


text:
angular.module("melissa.train")
    .directive("melissaTrainBoard", ['chessGame', '$window', 'highlighter',
        function (chessGame, $window, highlighter) {
        var boardConfig = {
            draggable: true,
            pieceTheme: 'js/bower_components/chessboardjs/img/chesspieces/wikipedia/{piece}.png',
            position: 'start'
        };
        return {
            link: function (scope, element, attrs) {
                var id = attrs["id"];
                boardConfig.onDragStart = function (source, piece, position, orientation) {
                    // only pick up pieces for the side to move
                    if ((orientation === 'white' && piece.search(/^b/) !== -1) ||
                        (orientation === 'black' && piece.search(/^w/) !== -1) ||
                        !scope.training.puzzle) {
                        return false;
                    }
                }
                boardConfig.onDrop = function (source, target) {
                	if(source == target || !scope.training.puzzle) {
                		// it means that user returned piece to the same place, so need to do nothing, just give him another chance
                		return 'snapback';
                	}
                    var move = chessGame.move({
                        from: source,
                        to: target,
                        promotion: 'q'
                    });
                    if(move) {
                        // make board to display correctly such things like castling and promotion, so do real move on snapEnd only
                        chessGame.undo();
                    }
                    var isCorrect = (move != null) && (move.san === scope.training.puzzle.answer);
                    if (!isCorrect) {
                        scope.training.solvedFromFirstTry = false;
                        let squares = [];
                        if(move) {
                            const move = chessGame.move(scope.training.puzzle.answer);
                            if(move) {
                                squares.push(move.from);
                                squares.push(move.to);
                                chessGame.undo();
                            }
                        }
                        highlighter.highlightSquares(squares, id);
                        return 'snapback';
                    } else {
                        scope.registerCorrectAnswer();
                    }
                };
                boardConfig.onSnapEnd = function() {
                    chessGame.move(scope.training.puzzle.answer)
                    scope.board.position(chessGame.fen());
                };
                if ($window['ChessBoard'] !== undefined) {
                    scope.board = new $window.ChessBoard(id, boardConfig);
                }
            }
        };
    }])
;


text:
package allout58.mods.techtree.client;

import allout58.mods.techtree.lib.ModInfo;
import net.minecraft.util.ResourceLocation;

/**
 * Created by James Hollowell on 12/8/2014.
 */
public class Textures
{
    public static final ResourceLocation TREE_BACKGROUND = new ResourceLocation(ModInfo.MOD_ID, "textures/gui/tree_background.png");
}


text:
var webdriverio = require('webdriverio');

var options = {
    desiredCapabilities: {
        browserName: 'firefox'
    }
};
var expectedText = "Welcome to the automation stuff web service"
webdriverio
    .remote(options)
    .init()
    .url('http://localhost:5000')
    .getText('#msg').then(function(elementText) {
        console.log(elementText === expectedText)
    })
    .end();


text:
package msp

import (
	"os"
	"reflect"
	"testing"

	"github.com/hyperledger/fabric/core/crypto/primitives"
)

var mgr PeerMSPManager

func TestMSPSetupBad(t *testing.T) {
	err := mgr.Setup("barf")
	if err == nil {
		t.Fatalf("Setup should have failed on an invalid config file")
		return
	}
}

func TestMSPSetupGood(t *testing.T) {
	err := mgr.Setup("peer-config.json")
	if err != nil {
		t.Fatalf("Setup should have succeeded, got err %s instead", err)
		return
	}
}

func TestGetBadIdentities(t *testing.T) {
	idBad := IdentityIdentifier{Mspid: ProviderIdentifier{Value: "BARF"}, Value: "PEER"}
	id, err := mgr.GetSigningIdentity(&idBad)
	if err == nil {
		t.Fatalf("GetSigningIdentity for invalid identifier should have failed but it returned %s", id)
		return
	}

	idBad = IdentityIdentifier{Mspid: ProviderIdentifier{Value: "DEFAULT"}, Value: "BARF"}
	id, err = mgr.GetSigningIdentity(&idBad)
	if err == nil {
		t.Fatalf("GetSigningIdentity for invalid identifier should have failed but it returned %s", id)
		return
	}
}

func TestSerializeIdentities(t *testing.T) {
	idId := IdentityIdentifier{Mspid: ProviderIdentifier{Value: "DEFAULT"}, Value: "PEER"}
	id, err := mgr.GetSigningIdentity(&idId)
	if err != nil {
		t.Fatalf("GetSigningIdentity should have succeeded")
		return
	}

	serializedID, err := id.Serialize()
	if err != nil {
		t.Fatalf("Serialize should have succeeded")
		return
	}

	idBack, err := mgr.DeserializeIdentity(serializedID)
	if err != nil {
		t.Fatalf("DeserializeIdentity should have succeeded")
		return
	}

	valid, err := idBack.Validate()
	if err != nil || !valid {
		t.Fatalf("The identity should be valid")
		return
	}

	if !reflect.DeepEqual(id.GetPublicVersion(), idBack) {
		t.Fatalf("Identities should be equal (%s) (%s)", id, idBack)
		return
	}
}

func TestSignAndVerify(t *testing.T) {
	idId := IdentityIdentifier{Mspid: ProviderIdentifier{Value: "DEFAULT"}, Value: "PEER"}
	id, err := mgr.GetSigningIdentity(&idId)
	if err != nil {
		t.Fatalf("GetSigningIdentity should have succeeded")
		return
	}

	serializedID, err := id.Serialize()
	if err != nil {
		t.Fatalf("Serialize should have succeeded")
		return
	}

	idBack, err := mgr.DeserializeIdentity(serializedID)
	if err != nil {
		t.Fatalf("DeserializeIdentity should have succeeded")
		return
	}

	msg := []byte("foo")
	sig, err := id.Sign(msg)
	if err != nil {
		t.Fatalf("Sign should have succeeded")
		return
	}

	valid, err := id.Verify(msg, sig)
	if err != nil || !valid {
		t.Fatalf("The signature should be valid")
		return
	}

	valid, err = idBack.Verify(msg, sig)
	if err != nil || !valid {
		t.Fatalf("The signature should be valid")
		return
	}
}

func TestMain(m *testing.M) {
	primitives.SetSecurityLevel("SHA2", 256)
	mgr = GetManager()

	retVal := m.Run()
	os.Exit(retVal)
}


text:
#ifndef _INITLB_H_
#define _INITLB_H_
#include "helper.h"

/* reads the parameters for the lid driven cavity scenario from a config file */
int readParameters(
    int *xlength,                       /* reads domain size. Parameter name: "xlength" */
    double *tau,                        /* relaxation parameter tau. Parameter name: "tau" */
    double *velocityWall,               /* velocity of the lid. Parameter name: "characteristicvelocity" */
    int *timesteps,                     /* number of timesteps. Parameter name: "timesteps" */
    int *timestepsPerPlotting,          /* timesteps between subsequent VTK plots. Parameter name: "vtkoutput" */
    int *proc,				/* array with number of processes per axis */
    int argc,                           /* number of arguments. Should equal 2 (program + name of config file */
    char *argv[]                        /* argv[1] shall contain the path to the config file */
);

/* initialises the particle distribution functions and the flagfield */
void initialiseFields(double *collideField, double *streamField,int *flagField, int *subdomain, int rank, int *proc,
			double **sendBuffer, double **readBuffer);

/* broadcasts the given parameters, read by rank 0, to all other ranks */
void distributeParameters ( int *xlength, double *tau, double *velocityWall, int *timesteps, int *timestepsPerPlotting, int *proc );

#endif


text:
cadnano\.views\.propertyview\.oligoitem module
==============================================

.. automodule:: cadnano.views.propertyview.oligoitem
    :members:
    :undoc-members:
    :show-inheritance:


text:
#ifndef SkBlitter_DEFINED
#define SkBlitter_DEFINED

#include "SkBitmap.h"
#include "SkMatrix.h"
#include "SkPaint.h"
#include "SkRefCnt.h"
#include "SkRegion.h"
#include "SkMask.h"

/** SkBlitter and its subclasses are responsible for actually writing pixels
    into memory. Besides efficiency, they handle clipping and antialiasing.
*/
class SkBlitter {
public:
    virtual ~SkBlitter();

    /// Blit a horizontal run of one or more pixels.
    virtual void blitH(int x, int y, int width);
    /// Blit a horizontal run of antialiased pixels; runs[] is a *sparse*
    /// zero-terminated run-length encoding of spans of constant alpha values.
    virtual void blitAntiH(int x, int y, const SkAlpha antialias[],
                           const int16_t runs[]);
    /// Blit a vertical run of pixels with a constant alpha value.
    virtual void blitV(int x, int y, int height, SkAlpha alpha);
    /// Blit a solid rectangle one or more pixels wide.
    virtual void blitRect(int x, int y, int width, int height);
    /** Blit a rectangle with one alpha-blended column on the left,
        width (zero or more) opaque pixels, and one alpha-blended column
        on the right.
        The result will always be at least two pixels wide.
    */
    virtual void blitAntiRect(int x, int y, int width, int height,
                              SkAlpha leftAlpha, SkAlpha rightAlpha);
    /// Blit a pattern of pixels defined by a rectangle-clipped mask;
    /// typically used for text.
    virtual void blitMask(const SkMask&, const SkIRect& clip);

    /** If the blitter just sets a single value for each pixel, return the
        bitmap it draws into, and assign value. If not, return NULL and ignore
        the value parameter.
    */
    virtual const SkBitmap* justAnOpaqueColor(uint32_t* value);

    ///@name non-virtual helpers
    void blitMaskRegion(const SkMask& mask, const SkRegion& clip);
    void blitRectRegion(const SkIRect& rect, const SkRegion& clip);
    void blitRegion(const SkRegion& clip);
    ///@}

    /** @name Factories
        Return the correct blitter to use given the specified context.
     */
    static SkBlitter* Choose(const SkBitmap& device,
                             const SkMatrix& matrix,
                             const SkPaint& paint) {
        return Choose(device, matrix, paint, NULL, 0);
    }

    static SkBlitter* Choose(const SkBitmap& device,
                             const SkMatrix& matrix,
                             const SkPaint& paint,
                             void* storage, size_t storageSize);

    static SkBlitter* ChooseSprite(const SkBitmap& device,
                                   const SkPaint&,
                                   const SkBitmap& src,
                                   int left, int top,
                                   void* storage, size_t storageSize);
    ///@}

private:
};

/** This blitter silently never draws anything.
*/
class SkNullBlitter : public SkBlitter {
public:
    virtual void blitH(int x, int y, int width) SK_OVERRIDE;
    virtual void blitAntiH(int x, int y, const SkAlpha[],
                           const int16_t runs[]) SK_OVERRIDE;
    virtual void blitV(int x, int y, int height, SkAlpha alpha) SK_OVERRIDE;
    virtual void blitRect(int x, int y, int width, int height) SK_OVERRIDE;
    virtual void blitMask(const SkMask&, const SkIRect& clip) SK_OVERRIDE;
    virtual const SkBitmap* justAnOpaqueColor(uint32_t* value) SK_OVERRIDE;
};

/** Wraps another (real) blitter, and ensures that the real blitter is only
    called with coordinates that have been clipped by the specified clipRect.
    This means the caller need not perform the clipping ahead of time.
*/
class SkRectClipBlitter : public SkBlitter {
public:
    void init(SkBlitter* blitter, const SkIRect& clipRect) {
        SkASSERT(!clipRect.isEmpty());
        fBlitter = blitter;
        fClipRect = clipRect;
    }

    virtual void blitH(int x, int y, int width) SK_OVERRIDE;
    virtual void blitAntiH(int x, int y, const SkAlpha[],
                           const int16_t runs[]) SK_OVERRIDE;
    virtual void blitV(int x, int y, int height, SkAlpha alpha) SK_OVERRIDE;
    virtual void blitRect(int x, int y, int width, int height) SK_OVERRIDE;
    virtual void blitAntiRect(int x, int y, int width, int height,
                     SkAlpha leftAlpha, SkAlpha rightAlpha) SK_OVERRIDE;
    virtual void blitMask(const SkMask&, const SkIRect& clip) SK_OVERRIDE;
    virtual const SkBitmap* justAnOpaqueColor(uint32_t* value) SK_OVERRIDE;

private:
    SkBlitter*  fBlitter;
    SkIRect     fClipRect;
};

/** Wraps another (real) blitter, and ensures that the real blitter is only
    called with coordinates that have been clipped by the specified clipRgn.
    This means the caller need not perform the clipping ahead of time.
*/
class SkRgnClipBlitter : public SkBlitter {
public:
    void init(SkBlitter* blitter, const SkRegion* clipRgn) {
        SkASSERT(clipRgn && !clipRgn->isEmpty());
        fBlitter = blitter;
        fRgn = clipRgn;
    }

    virtual void blitH(int x, int y, int width) SK_OVERRIDE;
    virtual void blitAntiH(int x, int y, const SkAlpha[],
                           const int16_t runs[]) SK_OVERRIDE;
    virtual void blitV(int x, int y, int height, SkAlpha alpha) SK_OVERRIDE;
    virtual void blitRect(int x, int y, int width, int height) SK_OVERRIDE;
    virtual void blitAntiRect(int x, int y, int width, int height,
                     SkAlpha leftAlpha, SkAlpha rightAlpha) SK_OVERRIDE;
    virtual void blitMask(const SkMask&, const SkIRect& clip) SK_OVERRIDE;
    virtual const SkBitmap* justAnOpaqueColor(uint32_t* value) SK_OVERRIDE;

private:
    SkBlitter*      fBlitter;
    const SkRegion* fRgn;
};

/** Factory to set up the appropriate most-efficient wrapper blitter
    to apply a clip. Returns a pointer to a member, so lifetime must
    be managed carefully.
*/
class SkBlitterClipper {
public:
    SkBlitter*  apply(SkBlitter* blitter, const SkRegion* clip,
                      const SkIRect* bounds = NULL);

private:
    SkNullBlitter       fNullBlitter;
    SkRectClipBlitter   fRectBlitter;
    SkRgnClipBlitter    fRgnBlitter;
};

#endif


text:
CREATE VIEW [dbo].[vMovieWriter]
AS
SELECT mw.ID, mw.MovieID, mw.WriterID, w.Name AS WriterName
FROM MOV_M_Writer AS mw INNER JOIN
	INF_Writer w ON w.ID = mw.WriterID


text:
layout: base
title:  'Statistics of Poss in UD_Portuguese-PUD'
udver: '2'
---

## Treebank Statistics: UD_Portuguese-PUD: Features: `Poss`

This feature is universal.
It occurs with 1 different values: `Yes`.

4 tokens (0%) have a non-empty value of `Poss`.
3 types (0%) occur at least once with a non-empty value of `Poss`.
1 lemmas (0%) occur at least once with a non-empty value of `Poss`.
The feature is used with 1 part-of-speech tags: <tt>DET</tt> (4; 0% instances).

### `DET`

4 <tt>DET</tt> tokens (0% of all `DET` tokens) have a non-empty value of `Poss`.

The most frequent other feature values with which `DET` and `Poss` co-occurred: <tt>PronType</tt><tt>=Rel</tt> (4; 100%), <tt>Gender</tt><tt>=Masc</tt> (3; 75%), <tt>Number</tt><tt>=Sing</tt> (3; 75%).

`DET` tokens may have the following values of `Poss`:

* `Yes` (4; 100% of non-empty `Poss`): cujo, cuja, cujos
* `EMPTY` (3537): o, a, os, as, um, uma, esta, este, cada, muitos