text:
"""Session creators for tf.train.MonitoredSession."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf

# Need to initialize local variables or TF will hang on initialization
# The meta opt / global variables will be initialized for us.
# There is no SessionCreator that supports this naively, so I am hacking
# in a reset op into the check for ready
# I don't know what will happen in the case that i can't just span this
# init function (as is the case with random initializations).
# This should be fixed with a new session creator that
# calls an init op,
# then waits for remote variables to be initialized.
class WorkerSessionCreator(tf.train.WorkerSessionCreator):
  """A session creator for tf.train.MonitoredSession for our clusters.

  See tf.train.WorkerSessionCreator for more information.
  Do NOT pass a scaffold in,

  Args:
    remote_vars: list of tf.Variable list of variables located on remote (PS)
      devices.
    local_vars: list of tf.Variable list of variables located on the local
      device. There is one copy of these variables per worker and are stored on
      the worker.
  """

  def __init__(self, remote_vars, local_vars, *args, **kwargs):
    if local_vars:
      self.has_init = tf.is_variable_initialized(local_vars[0])
    else:
      self.has_init = tf.constant(True)

    ready_for_local_init_op = tf.report_uninitialized_variables(
        var_list=remote_vars)

    self.init_op = tf.group(
        tf.initialize_variables(local_vars),
        *tf.get_collection(tf.GraphKeys.LOCAL_INIT_OP))

    if "scaffold" in kwargs:
      # TODO(lmetz) I think this could technically be supported?
      raise ValueError("Do not set scaffold on the session creator.")

    scaffold = tf.train.Scaffold(
        ready_for_local_init_op=ready_for_local_init_op,
        ready_op=ready_for_local_init_op,
        local_init_op=ready_for_local_init_op,
        init_op=ready_for_local_init_op,
        init_fn=self._maybe_initialize_local_vars_and_state_fn,
        summary_op=tf.summary.merge([tf.summary.scalar("dummy", 0)]))

    kwargs["scaffold"] = scaffold
    super(WorkerSessionCreator, self).__init__(*args, **kwargs)

  # Sadly, this must be done in python control flow and passed in as a function
  # Tensorflow provides no way to conditionally reset variables (like with cond)
  def _maybe_initialize_local_vars_and_state_fn(self, scaffold, sess):
    if not sess.run(self.has_init):
      sess.run(self.init_op)

  def create_session(self):
    self._scaffold.finalize()
    session = self._get_session_manager().wait_for_session(
        self._master,
        config=self._config,
        max_wait_secs=30 * 60  # Wait up to 30 mins for the session to be ready.
    )
    self._maybe_initialize_local_vars_and_state_fn(self._scaffold, session)
    return session

class ChiefSessionCreator(tf.train.ChiefSessionCreator):
  """Session creator for chief workers.

  Identical to tf.train.ChiefSessionCreator except summaries are turned off
  by default.
  """

  def __init__(self, *args, **kwargs):
    no_summary_op = tf.summary.merge([tf.summary.scalar("dummy", 0.)])
    scaffold = tf.train.Scaffold(summary_op=no_summary_op)

    if "scaffold" in kwargs:
      # TODO(lmetz) this could technically be supported.
      raise ValueError("Do not set scaffold on the session creator")

    kwargs["scaffold"] = scaffold
    super(ChiefSessionCreator, self).__init__(*args, **kwargs)

redpajama_set_name: RedPajamaGithub


text:
XML Examples
############

This repository contains sample XML documents.
I also added some SimpleXML processing examples for the same data :)

***************
Project Folders
***************

/simple    Snippets of SimpleXML code to work with the same data as below
/data           XML data, with inside it ...
/1-xml     The data, modelled 5 different ways
/2-dtd     Same data. constrained with a DTD
/3-schema  Same data, constrained with a schema

*******
License
*******

Please see the `license
agreement <http://codeigniter.com/userguide3/license.html>`_

*********
Resources
*********

-  `The Official XML Home <https://www.w3.org/XML/>`_
-  `O'Reilly XML COmmunity <http://www.xml.com/>`_
-  `W3Schools <http://www.w3schools.com/xml/>`_

***************
Acknowledgement
***************

This webapp was written by James Parry, Instructor in Computer Systems
Technology at the British Columbia Institute of Technology,
and Project Lead for CodeIgniter.

CodeIgniter is a project of B.C.I.T.


text:
This object is used to represent user's stream on D\*.
It is basically a list of posts.

----

##### Getting stream

To get basic stream you have to have working `Connection()` as
this is required by `Stream()`'s constructor.

    c = diaspy.connection.Connection(pod='https://pod.example.com',
                                     username='foo',
                                     password='bar')
    c.login()
    stream = diaspy.streams.Stream(c)

Now you have a stream filled with posts (if any can be found on user's
stream).

Other streams you can use are `Activity()`, `Aspects()`, `Commented()`,
`Liked()`, `Mentions()`, `FollowedTags()` and `Tag()`.

Example: `stream = diaspy.streams.Activity(c)`

----

##### `fill()`, `update()` and `more()`

When you want to refresh stream call it's `fill()` method. It will
overwrite old stream contents.

On the contrary, `update()` will get a new stream but will not overwrite
 old stream saved in the object memory. It will append every new post to
 the old stream.

`more()` complements `update()` it will fetch you older posts instead of
 newer ones.

----

##### Length of and iterating over a stream

Stream's length can be checked by calling `len()` on it.

    len(stream)
    10

When you want to iterate over a stream (e.g. when you want to print
first *n* posts on the stream) you can do it in two ways.

First, using `len()` and `range()` functions.

    for i in range(len(stream)):
        # do stuff...

Second, iterating directly over the stream contents:

    for post in stream:
        # do stuff...

----

##### Posting data to stream

This is described in [`posting`](./posting.markdown) document in this
manual.

----

##### Clearing stream

##### `clear()`

This will remove all posts from visible stream.

##### `purge()`

This will scan stream for nonexistent posts (eg. deleted) and remove
them.

----

###### Manual for `diaspy`, written by Marek Marecki


text:
@implementation UIView (VBAutolayoutConvenience)

#pragma mark - addSubview
- (NSArray*) addSubview:(UIView *)view
             withLayout:(NSDictionary*)layout {
//#warning TODO validate dictionary

    id topItem = [self itemWithAttributeValue:layout[VBAutolayoutAttributeTop]];
    NSString* topDist = [self constantWithAttributeValue:layout[VBAutolayoutAttributeTop]];
    id bottomItem = [self itemWithAttributeValue:layout[VBAutolayoutAttributeBottom]];
    NSString* bottomDist = [self constantWithAttributeValue:layout[VBAutolayoutAttributeBottom]];
    id leadingItem = [self itemWithAttributeValue:layout[VBAutolayoutAttributeLeading]];
    NSString* leadingDist = [self constantWithAttributeValue:layout[VBAutolayoutAttributeLeading]];
    id trailingItem = [self itemWithAttributeValue:layout[VBAutolayoutAttributeTrailing]];
    NSString* trailingDist = [self constantWithAttributeValue:layout[VBAutolayoutAttributeTrailing]];

    [self addSubviewAutolayoutReady:view];

    NSMutableArray* constraints = [NSMutableArray new];
    [constraints addObjectsFromArray:
      [NSLayoutConstraint constraintsWithItem:view
                                      topItem:topItem
                                      topDist:topDist
                                   bottomItem:bottomItem
                                   bottomDist:bottomDist
                                  leadingItem:leadingItem
                                  leadingDist:leadingDist
                                 trailingItem:trailingItem
                                 trailingDist:trailingDist]];

    //
    NSString* width = [self constantWithAttributeValue:layout[VBAutolayoutAttributeWidth]];
    if (width.length) {
        [constraints addObject:
         [NSLayoutConstraint constraintWithItem:view
                                          width:width]];
    }

    //
    NSString* height = [self constantWithAttributeValue:layout[VBAutolayoutAttributeHeight]];
    if (height.length) {
        [constraints addObject:
         [NSLayoutConstraint constraintWithItem:view
                                         height:height]];
    }

    //
    NSString* centerXConst = [self constantWithAttributeValue:layout[VBAutolayoutAttributeCenterX]];
    if (centerXConst) {
        id centerXItem = [self itemWithAttributeValue:layout[VBAutolayoutAttributeCenterX]];
        if (centerXItem == nil) {
            centerXItem = self.superview;
        }
        [constraints addObject:
         [NSLayoutConstraint constraintWithItem:view
                                      attribute:NSLayoutAttributeCenterX
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:centerXItem
                                      attribute:NSLayoutAttributeCenterX
                                       constant:[centerXConst doubleValue]]];
    }

    //
    NSString* centerYConst = [self constantWithAttributeValue:layout[VBAutolayoutAttributeCenterY]];
    if (centerYConst) {
        id centerYItem = [self itemWithAttributeValue:layout[VBAutolayoutAttributeCenterY]];
        if (centerYItem == nil) {
            centerYItem = self.superview;
        }
        [constraints addObject:
         [NSLayoutConstraint constraintWithItem:view
                                      attribute:NSLayoutAttributeCenterY
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:centerYItem
                                      attribute:NSLayoutAttributeCenterY
                                       constant:[centerYConst doubleValue]]];
    }

    //
    [self addConstraintsAndLayoutSubviews:constraints];

    return constraints;
}

- (NSString*) constantWithAttributeValue:(id)attributeValue {
    return [attributeValue isKindOfClass:[NSDictionary class]] ? attributeValue[VBAutolayoutConstant] : attributeValue;
}

- (id) itemWithAttributeValue:(id)attributeValue {
    return [attributeValue isKindOfClass:[NSDictionary class]] ? attributeValue[VBAutolayoutItem] : nil;
}

@end


text:
module Relish
  module Mixin
    module FromFile

      # Loads a given ruby file, and runs instance_eval against it in the context of the current
      # object.
      #
      # Raises an IOError if the file cannot be found, or is not readable.
      def from_file(filename)
        if File.exists?(filename) && File.readable?(filename)
          self.instance_eval(IO.read(filename), filename, 1)
        else
          raise IOError, "Cannot open or read #{filename}!"
        end
      end
    end
  end
end


text:
import {Component, View, bootstrap} from 'angular2/angular2';
@Component({
  selector: 'my-app'
})
@View({
  template: '
My First Angular 2 App
<display></display>'
})
class AppComponent {
	constructor() {
		console.log("aids");
	}
}
bootstrap(AppComponent);


text:
ulit - You Lost In Translations
===============================

Ever wondered what happens when you try to translate some text of a language, stepwise into various intermediate langauges and back into the original langauge? When you start with a language and text of your choice (generally in the smae language) and translate the text into a series of languages, feeding previous result to the next one, you end up with something that generally does not look like the original text.

If that makes little sense but here is an example.

Example (using Yandex's API)
----------------------------

Given the steps to be followed : ['fr', 'uk', 'it', 'ru', 'pl', 'be', 'de', 'es'] and language of interest is 'en'.

Starting text in 'en': "Language is a process of free creation; its laws and principles are fixed, but the manner in which the principles of generation are used is free and infinitely varied. Even the interpretation and use of words involves a process of free creation."

'en' to 'fr': "La langue est un processus de création libre; ses lois et ses principes sont fixes, mais la manière dont les principes de génération sont utilisés est gratuit et infiniment variés. Même l'interprétation et de l'utilisation de mots implique un processus de création libre."

'fr' to 'uk': "Мова-це процес вільного творчості; його закони і принципи є фіксованими, але і як принципи побудови, використовуються безкоштовно, і нескінченно різноманітні. Навіть інтерпретація і використання слова передбачає процес створення безкоштовно."

. . . .

Finally, 'es' to 'en': "It is the Process, of free Creativity; its Laws and Principles do not change, but, as the Rules Of Construction, which is free, and is infinitely diverse. The Interpretation and Use of the Word means that the Process of Creating free of charge."

See usage section for more details.

Usage
-----

Use pip to install

.. code-block:: bash

    $ pip install ulit
    ...

You can use ulit with Google translate API or Yandex translate API

.. code-block:: python

    translate = ulit.Ulit("yandex", "YOUR YANDEX TRANSLATE API KEY HERE", loglevel="DEBUG")
    ...

.. code-block:: python

    translate = ulit.Ulit("yandex", "YOUR YANDEX TRANSLATE API KEY HERE", loglevel="DEBUG")
    ...

Yandex

.. code-block:: python

    import ulit

    cascade_steps = ['fr', 'uk', 'it', 'ru', 'pl', 'be', 'de', 'es']
    initial_language = "en"
    text = "Language is a process of free creation; its laws and principles are fixed, but the manner in which the principles of generation are used is free and infinitely varied. Even the interpretation and use of words involves a process of free creation."
    translate = ulit.Ulit("yandex", "YOUR YANDEX TRANSLATE API KEY HERE", loglevel="DEBUG")

    all_translations_steps, final_translation = translate.service.translate_cascade(initial_language=initial_language,
                                                                                cascade_steps=cascade_steps,
                                                                                text=text)

    # Output: all_translations_steps

    {
        'pl': 'Mowa jest procesem wolnego kreatywności; jego prawa i zasady są niezmienne, ale, jak i zasady budowy, są za darmo, i nieskończenie zróżnicowana. Również interpretacja i wykorzystanie słowa oznacza proces tworzenia za darmo.',
        'it': "Il discorso è un processo di libera creatività; le sue leggi e i principi sono fissi, ma come principi di costruzione, sono utilizzati gratuitamente, e infinitamente vario. Anche l'interpretazione e l'uso della parola implica il processo di creazione di gratis.",
        'ru': 'Речь-это процесс свободного творчества; его законы и принципы неизменны, но, как и принципы строительства, используются бесплатно, и бесконечно разнообразен. Также интерпретация и использование слова подразумевает процесс создания бесплатно.',
        'de': 'Es ist der Prozess, der freien Kreativität; seine Gesetze und Prinzipien nicht ändern, aber, wie die Regeln der Bau -, Sie sind kostenlos, und es ist unendlich vielfältig. Auch die Interpretation und die Verwendung des Wortes bedeutet, den Prozess der Erstellung kostenlos.',
        'fr': "La langue est un processus de création libre; ses lois et ses principes sont fixes, mais la manière dont les principes de génération sont utilisés est gratuit et infiniment variés. Même l'interprétation et de l'utilisation de mots implique un processus de création libre.",
        'uk': 'Мова-це процес вільного творчості; його закони і принципи є фіксованими, але і як принципи побудови, використовуються безкоштовно, і нескінченно різноманітні. Навіть інтерпретація і використання слова передбачає процес створення безкоштовно.',
        'es': 'Es el Proceso, de la libre Creatividad; sus Leyes y Principios no cambian, pero, como las Reglas De la Construcción, que es gratuita, y es infinitamente diversa. La Interpretación y el Uso de la Palabra significa que el Proceso de Creación de forma gratuita.',
        'be': 'Гаворка-гэта працэс свабоднага творчасці; яго законы і прынцыпы нязменныя, але, як і правілы будаўніцтва, яны бясплатна, і бясконца разнастайны. Таксама інтэрпрэтацыя і выкарыстанне слова азначае працэс стварэння бясплатна.',
        'en': 'It is the Process, of free Creativity; its Laws and Principles do not change, but, as the Rules Of Construction, which is free, and is infinitely diverse. The Interpretation and Use of the Word means that the Process of Creating free of charge.'
    }

    # Output: final_translation

    It is the Process, of free Creativity; its Laws and Principles do not change, but, as the Rules Of Construction, which is free, and is infinitely diverse. The Interpretation and Use of the Word means that the Process of Creating free of charge.

    ...

Google

.. code-block:: python

    import ulit

    cascade_steps = ['fr', 'uk', 'it', 'ru', 'pl', 'be', 'de', 'es']
    initial_language = "en"
    text = "Language is a process of free creation; its laws and principles are fixed, but the manner in which the principles of generation are used is free and infinitely varied. Even the interpretation and use of words involves a process of free creation."
    translate = ulit.Ulit("google", "YOUR YANDEX TRANSLATE API KEY HERE", loglevel="DEBUG")

    all_translations_steps, final_translation = translate.service.translate_cascade(initial_language=initial_language,
                                                                                cascade_steps=cascade_steps,
                                                                                text=text)

    # Output: all_translations_steps

    {
    'de': 'Sprache des Prozesses der freien Schöpfung; ihre Gesetze und Grundsätze festgelegt sind, aber das Prinzip der Produktionsweise frei. Auch die Interpretation und Verwendung von Wörtern findet ein Prozess der freien Schöpfung.',
    'en': 'Language of the process of free creation; its laws and principles are fixed, but the principle of free production. The interpretation and use of words involves a process of free creation.',
    'fr': 'La langue est un processus de création libre; ses lois et ses principes sont fixés, mais la manière dont les principes de la production sont utilisées est libre et infiniment varié. Même l'interprétation et de l'utilisation de mots implique un processus de création libre.',
    'es': 'Idioma del proceso de creación libre; sus leyes y principios son fijos, pero el principio de producción libre. La interpretación y el uso de las palabras implica un proceso de creación libre.',
    'ru': 'Язык процесс свободного создания; его законы и принципы закреплены, но принципы метода производства свободно и бесконечно разнообразны. Даже интерпретация и использование слов включает в себя процесс свободного создания.',
    'uk': 'Мова процес вільного створення; його закони і принципи закріплені, але спосіб принципи виробництва використовуються вільно і нескінченно різноманітні. Навіть інтерпретація і використання слів включає в себе процес вільного створення.',
    'it': 'Processo Lingua di libera creazione; le sue leggi e principi sono fissi, ma i principi del metodo di produzione utilizzati liberamente e infinitamente vario. Anche l'interpretazione e l'uso delle parole comporta un processo di creazione libera.',
    'be': 'Мова працэс свабоднага стварэння; яго законы і прынцыпы замацаваныя, але прынцып спосабу вытворчасці свабодна і плаўна. Нават інтэрпрэтацыя і выкарыстанне слоў ўключае ў сябе працэс свабоднага стварэння.',
    'pl': 'Język procesie utworzenia wolnego; jej prawa i zasady są stałe, ale zasady metody produkcji jest darmowy i płynnie. Nawet interpretacja i stosowanie słów obejmuje proces swobodnego tworzenia.'
    }

    \# Output: final_translation

    Language of the process of free creation; its laws and principles are fixed, but the principle of free production. The interpretation and use of words involves a process of free creation.

    ...

Running tests
-------------

Most of it is usual but you will need to set environment variable YANDEX_API_KEY with your API key.

.. code-block:: bash

    $ export YANDEX_API_KEY=<YOUR API KEY HERE>

    $ export GOOGLE_API_KEY=<YOUR API KEY HERE>

    $ python setup.py test
    ...


text:
/**
 * CSS and java-friendly checkbox and radios.
 */
jQuery.fn.reCheckbox = function() {
	var _this = this;

	$(":checkbox", this).each(function() {

		var check = this;
		var $check = $(this);
		var checkId = $check.attr("id");
		var checkName = $check.attr("name");
		var checkValue = $check.attr("value");
		var checkUnvalue = $check.attr("unvalue");
		if (!checkUnvalue) {
			checkUnvalue = 'off';
		}

		// add hidden field
		$check.after("<input type='hidden' name='" + checkName +"' value='" + check.checked + "' id='" + checkId + "_checkbox' checkValue='" + checkValue + "' checkUnvalue='" + checkUnvalue + "'/>");
		var $checkInput = $("input#" + checkId + "_checkbox", _this);

		// finds a label
		var label = $("label[for='" + checkId + "']", _this);
		$.fn._reCheckboxCheck(check.checked ? true : false, label, $checkInput, checkValue, checkUnvalue);
		label.addClass("checkboxLabel");

		// remove the checkbox, add label click handler
		$check.remove();
		label.click(function() {
			$.fn._reCheckboxCheck(!label.hasClass("checked"), label, $checkInput, checkValue, checkUnvalue);
			return false;
		});
	});
};

/**
 * Sets checkbox value.
 */
jQuery.fn.reCheckboxVal = function(id, value) {
	var _this = this;
	$('#' + id + "_checkbox:hidden", this).each(function() {
		var $checkInput = $(this);
		var checkValue = $checkInput.attr("checkValue");
		var checkUnvalue = $checkInput.attr("checkUnvalue");
		var label = $("label[for='" + id + "']", _this);
		$.fn._reCheckboxCheck(value, label, $checkInput, checkValue, checkUnvalue);
	});
};

jQuery.fn._reCheckboxCheck = function(value, label, checkInput, checkValue, checkUnvalue) {
	if (value === true) {
		label.addClass("checked");
		checkInput.attr('value', checkValue ? checkValue : true);
	} else if (value === false) {
		label.removeClass("checked");
		checkInput.attr('value', checkValue ? checkUnvalue : false);
	}
};

/**
 * CSS radio button.
 */
jQuery.fn.reRadio = function() {
	var _this = this;

	$(":radio", this)
			.hide()				// hide native radios
			.each(function() {	// find related labels and add all the fancy stuff

		var radio = this;
		var $radio = $(radio);
		var radioId = $radio.attr("id");
		var label = $("label[for='" + radioId + "']", _this);
		var name = $radio.attr('name');

		if (radio.checked) {
			label.addClass("radioChecked");
		}
		label.addClass("radioLabel");

		// label click state
		label.click(function() {
			$.fn._reRadioCheck(name, radioId, _this);
/*
			$(":radio[name=" + name + "]", _this).each(function() {
				var radio2 = $(this);
				var label2For = radio2.attr("id");
				var label2 = $("label[for='" + label2For + "']", _this);

				if (label2For == radioId) {
					label2.addClass("radioChecked");
					this.checked = true;
				} else {
					label2.removeClass("radioChecked");
					this.checked = false;
				}
			});
*/
			return false;
		});
	});
};

/**
 * Sets radio value.
 */
jQuery.fn.reRadioVal = function(radioId) {
	var r = $('#' + radioId, this);
	var radioName = r.attr("name");
	$.fn._reRadioCheck(radioName, radioId, this);
};

jQuery.fn._reRadioCheck = function(radioName, radioId, _this) {
	$(":radio[name=" + radioName + "]", _this).each(function() {
		var radio2 = $(this);
		var label2For = radio2.attr("id");
		var label2 = $("label[for='" + label2For + "']", _this);

		if (label2For == radioId) {
			label2.addClass("radioChecked");
			this.checked = true;
		} else {
			label2.removeClass("radioChecked");
			this.checked = false;
		}
	});
};


text:
/***************************************************************************//**
 * @file
 * @brief Direct memory access (LDMA) module peripheral API
 *******************************************************************************
 * # License
 * <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
 *******************************************************************************
 *
 * SPDX-License-Identifier: Zlib
 *
 * The licensor of this software is Silicon Laboratories Inc.
 *
 * This software is provided 'as-is', without any express or implied
 * warranty. In no event will the authors be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 *
 ******************************************************************************/

#include "em_ldma.h"

#if defined(LDMA_PRESENT) && (LDMA_COUNT == 1)

#include <stddef.h>
#include "em_assert.h"
#include "em_bus.h"
#include "em_cmu.h"
#include "em_core.h"

/***************************************************************************//**
 * @addtogroup emlib
 * @{
 ******************************************************************************/

/***************************************************************************//**
 * @addtogroup LDMA
 * @{
 ******************************************************************************/

#if defined(LDMA_IRQ_HANDLER_TEMPLATE)
/***************************************************************************//**
 * @brief
 *   A template for an LDMA IRQ handler.
 ******************************************************************************/
void LDMA_IRQHandler(void)
{
  uint32_t ch;
  /* Get all pending and enabled interrupts. */
  uint32_t pending = LDMA_IntGetEnabled();

  /* Loop on an LDMA error to enable debugging. */
  while (pending & LDMA_IF_ERROR) {
  }

  /* Iterate over all LDMA channels. */
  for (ch = 0; ch < DMA_CHAN_COUNT; ch++) {
    uint32_t mask = 0x1 << ch;
    if (pending & mask) {
      /* Clear the interrupt flag. */
      LDMA->IFC = mask;

      /* Perform more actions here, execute callbacks, and so on. */
    }
  }
}
#endif

/***************************************************************************//**
 * @brief
 *   De-initialize the LDMA controller.
 *
 *   LDMA interrupts are disabled and the LDMA clock is stopped.
 ******************************************************************************/
void LDMA_DeInit(void)
{
  NVIC_DisableIRQ(LDMA_IRQn);
  LDMA->IEN  = 0;
#if defined(_LDMA_CHDIS_MASK)
  LDMA->CHDIS = _LDMA_CHEN_MASK;
#else
  LDMA->CHEN = 0;
#endif
#if defined(LDMA_EN_EN)
  LDMA->EN = 0;
#endif

#if !defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1)
  CMU_ClockEnable(cmuClock_LDMA, false);
#endif

#if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2)
  CMU_ClockEnable(cmuClock_LDMAXBAR, false);
#endif
}

/***************************************************************************//**
 * @brief
 *   Enable or disable an LDMA channel request.
 *
 * @details
 *   Use this function to enable or disable an LDMA channel request. This will
 *   prevent the LDMA from proceeding after its current transaction if disabled.
 *
 * @param[in] channel
 *   LDMA channel to enable or disable requests.
 *
 * @param[in] enable
 *   If 'true', the request will be enabled. If 'false', the request will be disabled.
 ******************************************************************************/
void LDMA_EnableChannelRequest(int ch, bool enable)
{
  EFM_ASSERT(ch < (int)DMA_CHAN_COUNT);

  BUS_RegBitWrite(&LDMA->REQDIS, ch, !enable);
}

/***************************************************************************//**
 * @brief
 *   Initialize the LDMA controller.
 *
 * @details
 *   This function will disable all the LDMA channels and enable the LDMA bus
 *   clock in the CMU. This function will also enable the LDMA IRQ in the NVIC
 *   and set the LDMA IRQ priority to a user-configurable priority. The LDMA
 *   interrupt priority is configured using the @ref LDMA_Init_t structure.
 *
 * @note
 *   Since this function enables the LDMA IRQ, always add a custom
 *   LDMA_IRQHandler to the application to handle any interrupts
 *   from LDMA.
 *
 * @param[in] init
 *   A pointer to the initialization structure used to configure the LDMA.
 ******************************************************************************/
void LDMA_Init(const LDMA_Init_t *init)
{
  uint32_t ldmaCtrlVal;
  EFM_ASSERT(init != NULL);
  EFM_ASSERT(!(((uint32_t)init->ldmaInitCtrlNumFixed << _LDMA_CTRL_NUMFIXED_SHIFT)
               & ~_LDMA_CTRL_NUMFIXED_MASK));

#if defined(_LDMA_CTRL_SYNCPRSCLREN_SHIFT) && defined (_LDMA_CTRL_SYNCPRSSETEN_SHIFT)
  EFM_ASSERT(!(((uint32_t)init->ldmaInitCtrlSyncPrsClrEn << _LDMA_CTRL_SYNCPRSCLREN_SHIFT)
               & ~_LDMA_CTRL_SYNCPRSCLREN_MASK));
  EFM_ASSERT(!(((uint32_t)init->ldmaInitCtrlSyncPrsSetEn << _LDMA_CTRL_SYNCPRSSETEN_SHIFT)
               & ~_LDMA_CTRL_SYNCPRSSETEN_MASK));
#endif

#if defined(_LDMA_SYNCHWEN_SYNCCLREN_SHIFT) && defined (_LDMA_SYNCHWEN_SYNCSETEN_SHIFT)
  EFM_ASSERT(!(((uint32_t)init->ldmaInitCtrlSyncPrsClrEn << _LDMA_SYNCHWEN_SYNCCLREN_SHIFT)
               & ~_LDMA_SYNCHWEN_SYNCCLREN_MASK));
  EFM_ASSERT(!(((uint32_t)init->ldmaInitCtrlSyncPrsSetEn << _LDMA_SYNCHWEN_SYNCSETEN_SHIFT)
               & ~_LDMA_SYNCHWEN_SYNCSETEN_MASK));
#endif

  EFM_ASSERT(init->ldmaInitIrqPriority < (1 << __NVIC_PRIO_BITS));

#if !defined(_SILICON_LABS_32B_SERIES_2_CONFIG_1)
  CMU_ClockEnable(cmuClock_LDMA, true);
#endif

#if defined(_SILICON_LABS_32B_SERIES_2_CONFIG_2)
  CMU_ClockEnable(cmuClock_LDMAXBAR, true);
#endif

#if defined(LDMA_EN_EN)
  LDMA->EN = LDMA_EN_EN;
#endif

  ldmaCtrlVal = init->ldmaInitCtrlNumFixed << _LDMA_CTRL_NUMFIXED_SHIFT;

#if defined(_LDMA_CTRL_SYNCPRSCLREN_SHIFT) && defined (_LDMA_CTRL_SYNCPRSSETEN_SHIFT)
  ldmaCtrlVal |=  (init->ldmaInitCtrlSyncPrsClrEn << _LDMA_CTRL_SYNCPRSCLREN_SHIFT)
                 | (init->ldmaInitCtrlSyncPrsSetEn << _LDMA_CTRL_SYNCPRSSETEN_SHIFT);
#endif

  LDMA->CTRL = ldmaCtrlVal;

#if defined(_LDMA_SYNCHWEN_SYNCCLREN_SHIFT) && defined (_LDMA_SYNCHWEN_SYNCSETEN_SHIFT)
  LDMA->SYNCHWEN = (init->ldmaInitCtrlSyncPrsClrEn << _LDMA_SYNCHWEN_SYNCCLREN_SHIFT)
                   | (init->ldmaInitCtrlSyncPrsSetEn << _LDMA_SYNCHWEN_SYNCSETEN_SHIFT);
#endif

#if defined(_LDMA_CHDIS_MASK)
  LDMA->CHDIS = _LDMA_CHEN_MASK;
#else
  LDMA->CHEN    = 0;
#endif
  LDMA->DBGHALT = 0;
  LDMA->REQDIS  = 0;

  /* Enable the LDMA error interrupt. */
#if defined (LDMA_IEN_ERRORIEN)
  LDMA->IEN = LDMA_IEN_ERRORIEN;
#elif defined (LDMA_IEN_ERROR)
  LDMA->IEN = LDMA_IEN_ERROR;
#else
  #error "IEN register not defined!!!"
#endif

#if defined (LDMA_HAS_SET_CLEAR)
  LDMA->IF_CLR = 0xFFFFFFFFU;
#else
  LDMA->IFC = 0xFFFFFFFFU;
#endif
  NVIC_ClearPendingIRQ(LDMA_IRQn);

  /* Range is 0-7, where 0 is the highest priority. */
  NVIC_SetPriority(LDMA_IRQn, init->ldmaInitIrqPriority);

  NVIC_EnableIRQ(LDMA_IRQn);
}

/***************************************************************************//**
 * @brief
 *   Start a DMA transfer.
 *
 * @param[in] ch
 *   A DMA channel.
 *
 * @param[in] transfer
 *   The initialization structure used to configure the transfer.
 *
 * @param[in] descriptor
 *   The transfer descriptor, which can be an array of descriptors linked together.
 ******************************************************************************/
void LDMA_StartTransfer(int ch,
                        const LDMA_TransferCfg_t *transfer,
                        const LDMA_Descriptor_t  *descriptor)
{
#if !(defined (_LDMA_SYNCHWEN_SYNCCLREN_SHIFT) && defined (_LDMA_SYNCHWEN_SYNCSETEN_SHIFT))
  uint32_t tmp;
#endif
  CORE_DECLARE_IRQ_STATE;
  uint32_t chMask = 1UL << (uint8_t)ch;

  EFM_ASSERT(ch < (int)DMA_CHAN_COUNT);
  EFM_ASSERT(transfer != NULL);

#if defined (_LDMAXBAR_CH_REQSEL_MASK)
  EFM_ASSERT(!(transfer->ldmaReqSel & ~_LDMAXBAR_CH_REQSEL_MASK));
#elif defined (_LDMA_CH_REQSEL_MASK)
  EFM_ASSERT(!(transfer->ldmaReqSel & ~_LDMA_CH_REQSEL_MASK));
#endif

#if defined (_LDMA_SYNCHWEN_SYNCCLREN_SHIFT) && defined (_LDMA_SYNCHWEN_SYNCSETEN_SHIFT)
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCtrlSyncPrsClrOff << _LDMA_SYNCHWEN_SYNCCLREN_SHIFT)
               & ~_LDMA_SYNCHWEN_SYNCCLREN_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCtrlSyncPrsClrOn << _LDMA_SYNCHWEN_SYNCCLREN_SHIFT)
               & ~_LDMA_SYNCHWEN_SYNCCLREN_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCtrlSyncPrsSetOff << _LDMA_SYNCHWEN_SYNCSETEN_SHIFT)
               & ~_LDMA_SYNCHWEN_SYNCSETEN_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCtrlSyncPrsSetOn << _LDMA_SYNCHWEN_SYNCSETEN_SHIFT)
               & ~_LDMA_SYNCHWEN_SYNCSETEN_MASK));
#elif defined (_LDMA_CTRL_SYNCPRSCLREN_SHIFT) && defined (_LDMA_CTRL_SYNCPRSSETEN_SHIFT)
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCtrlSyncPrsClrOff << _LDMA_CTRL_SYNCPRSCLREN_SHIFT)
               & ~_LDMA_CTRL_SYNCPRSCLREN_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCtrlSyncPrsClrOn << _LDMA_CTRL_SYNCPRSCLREN_SHIFT)
               & ~_LDMA_CTRL_SYNCPRSCLREN_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCtrlSyncPrsSetOff << _LDMA_CTRL_SYNCPRSSETEN_SHIFT)
               & ~_LDMA_CTRL_SYNCPRSSETEN_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCtrlSyncPrsSetOn << _LDMA_CTRL_SYNCPRSSETEN_SHIFT)
               & ~_LDMA_CTRL_SYNCPRSSETEN_MASK));
#endif

  EFM_ASSERT(!(((uint32_t)transfer->ldmaCfgArbSlots << _LDMA_CH_CFG_ARBSLOTS_SHIFT)
               & ~_LDMA_CH_CFG_ARBSLOTS_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCfgSrcIncSign << _LDMA_CH_CFG_SRCINCSIGN_SHIFT)
               & ~_LDMA_CH_CFG_SRCINCSIGN_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaCfgDstIncSign << _LDMA_CH_CFG_DSTINCSIGN_SHIFT)
               & ~_LDMA_CH_CFG_DSTINCSIGN_MASK));
  EFM_ASSERT(!(((uint32_t)transfer->ldmaLoopCnt << _LDMA_CH_LOOP_LOOPCNT_SHIFT)
               & ~_LDMA_CH_LOOP_LOOPCNT_MASK));

#if defined(LDMAXBAR)
  LDMAXBAR->CH[ch].REQSEL = transfer->ldmaReqSel;
#else
  LDMA->CH[ch].REQSEL = transfer->ldmaReqSel;
#endif
  LDMA->CH[ch].LOOP = transfer->ldmaLoopCnt << _LDMA_CH_LOOP_LOOPCNT_SHIFT;
  LDMA->CH[ch].CFG = (transfer->ldmaCfgArbSlots << _LDMA_CH_CFG_ARBSLOTS_SHIFT)
                     | (transfer->ldmaCfgSrcIncSign << _LDMA_CH_CFG_SRCINCSIGN_SHIFT)
                     | (transfer->ldmaCfgDstIncSign << _LDMA_CH_CFG_DSTINCSIGN_SHIFT);

  /* Set the descriptor address. */
  LDMA->CH[ch].LINK = (uint32_t)descriptor & _LDMA_CH_LINK_LINKADDR_MASK;

  /* Clear the pending channel interrupt. */
#if defined (LDMA_HAS_SET_CLEAR)
  LDMA->IF_CLR = chMask;
#else
  LDMA->IFC = chMask;
#endif

  /* A critical region. */
  CORE_ENTER_ATOMIC();

  /* Enable the channel interrupt. */
  LDMA->IEN |= chMask;

  if (transfer->ldmaReqDis) {
    LDMA->REQDIS |= chMask;
  }

  if (transfer->ldmaDbgHalt) {
    LDMA->DBGHALT |= chMask;
  }

#if defined (_LDMA_SYNCHWEN_SYNCCLREN_SHIFT) && defined (_LDMA_SYNCHWEN_SYNCSETEN_SHIFT)

  LDMA->SYNCHWEN_CLR =
    ((transfer->ldmaCtrlSyncPrsClrOff << _LDMA_SYNCHWEN_SYNCCLREN_SHIFT)
     | (transfer->ldmaCtrlSyncPrsSetOff << _LDMA_SYNCHWEN_SYNCSETEN_SHIFT))
    & _LDMA_SYNCHWEN_MASK;

  LDMA->SYNCHWEN_SET =
    ((transfer->ldmaCtrlSyncPrsClrOn << _LDMA_SYNCHWEN_SYNCCLREN_SHIFT)
     | (transfer->ldmaCtrlSyncPrsSetOn << _LDMA_SYNCHWEN_SYNCSETEN_SHIFT))
    & _LDMA_SYNCHWEN_MASK;

#elif defined (_LDMA_CTRL_SYNCPRSCLREN_SHIFT) && defined (_LDMA_CTRL_SYNCPRSSETEN_SHIFT)

  tmp = LDMA->CTRL;

  if (transfer->ldmaCtrlSyncPrsClrOff) {
    tmp &= ~_LDMA_CTRL_SYNCPRSCLREN_MASK
           | (~transfer->ldmaCtrlSyncPrsClrOff << _LDMA_CTRL_SYNCPRSCLREN_SHIFT);
  }

  if (transfer->ldmaCtrlSyncPrsClrOn) {
    tmp |= transfer->ldmaCtrlSyncPrsClrOn << _LDMA_CTRL_SYNCPRSCLREN_SHIFT;
  }

  if (transfer->ldmaCtrlSyncPrsSetOff) {
    tmp &= ~_LDMA_CTRL_SYNCPRSSETEN_MASK
           | (~transfer->ldmaCtrlSyncPrsSetOff << _LDMA_CTRL_SYNCPRSSETEN_SHIFT);
  }

  if (transfer->ldmaCtrlSyncPrsSetOn) {
    tmp |= transfer->ldmaCtrlSyncPrsSetOn << _LDMA_CTRL_SYNCPRSSETEN_SHIFT;
  }

  LDMA->CTRL = tmp;

#else

  #error  "SYNC Set and SYNC Clear not defined"

#endif

  BUS_RegMaskedClear(&LDMA->CHDONE, chMask);  /* Clear the done flag.     */
  LDMA->LINKLOAD = chMask;      /* Start a transfer by loading the descriptor.  */

  /* A critical region end. */
  CORE_EXIT_ATOMIC();
}

/***************************************************************************//**
 * @brief
 *   Stop a DMA transfer.
 *
 * @note
 *   The DMA will complete the current AHB burst transfer before stopping.
 *
 * @param[in] ch
 *   A DMA channel to stop.
 ******************************************************************************/
void LDMA_StopTransfer(int ch)
{
  uint32_t chMask = 1UL << (uint8_t)ch;

  EFM_ASSERT(ch < (int)DMA_CHAN_COUNT);

  CORE_ATOMIC_SECTION(
    LDMA->IEN &= ~chMask;
#if defined(_LDMA_CHDIS_MASK)
    LDMA->CHDIS = chMask;
#else
    BUS_RegMaskedClear(&LDMA->CHEN, chMask);
#endif
    )
}

/***************************************************************************//**
 * @brief
 *   Check if a DMA transfer has completed.
 *
 * @param[in] ch
 *   A DMA channel to check.
 *
 * @return
 *   True if transfer has completed, false if not.
 ******************************************************************************/
bool LDMA_TransferDone(int ch)
{
  bool     retVal = false;
  uint32_t chMask = 1UL << (uint8_t)ch;

  EFM_ASSERT(ch < (int)DMA_CHAN_COUNT);

  CORE_ATOMIC_SECTION(
    if (
#if defined(_LDMA_CHSTATUS_MASK)
      ((LDMA->CHSTATUS & chMask) == 0)
#else
      ((LDMA->CHEN & chMask) == 0)
#endif
      && ((LDMA->CHDONE & chMask) == chMask)) {
    retVal = true;
  }
    )

  return retVal;
}

/***************************************************************************//**
 * @brief
 *  Get the number of items remaining in a transfer.
 *
 * @note
 *  This function does not take into account that a DMA transfer with
 *  a chain of linked transfers might be ongoing. It will only check the
 *  count for the current transfer.
 *
 * @param[in] ch
 *  The channel number of the transfer to check.
 *
 * @return
 *  A number of items remaining in the transfer.
 ******************************************************************************/
uint32_t LDMA_TransferRemainingCount(int ch)
{
  uint32_t remaining, done, iflag;
  uint32_t chMask = 1UL << (uint8_t)ch;

  EFM_ASSERT(ch < (int)DMA_CHAN_COUNT);

  CORE_ATOMIC_SECTION(
    iflag  = LDMA->IF;
    done   = LDMA->CHDONE;
    remaining = LDMA->CH[ch].CTRL;
    )

  iflag    &= chMask;
  done     &= chMask;
  remaining = (remaining & _LDMA_CH_CTRL_XFERCNT_MASK)
              >> _LDMA_CH_CTRL_XFERCNT_SHIFT;

  if (done || ((remaining == 0) && iflag)) {
    return 0;
  }

  return remaining + 1;
}

/** @} (end addtogroup LDMA) */
/** @} (end addtogroup emlib) */
#endif /* defined( LDMA_PRESENT ) && ( LDMA_COUNT == 1 ) */


text:
import { Effect } from 'redux-saga'

type SagaIterator = IterableIterator<Effect|Effect[]|Promise<any>|void>;

export default SagaIterator;


text:
module PubMedArticlesHelper
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.android.support</groupId>
  <artifactId>notification</artifactId>
  <version>0.1</version>
  <versioning>
    <versions>
      <version>0.1</version>
    </versions>
    <lastUpdated>20140609033422</lastUpdated>
  </versioning>
</metadata>


text:
namespace extensions {

// A structure to hold the Content-Security-Policy information.
struct CSPInfo : public Extension::ManifestData {
  explicit CSPInfo(std::string extension_pages_csp);
  ~CSPInfo() override;

  // The Content-Security-Policy for an extension. This is applied to an
  // extension's background contexts i.e. its background page, event page and
  // service worker. Extensions can use Content-Security-Policies to mitigate
  // cross-site scripting and other vulnerabilities.
  std::string extension_pages_csp;

  // Content security policy to be used for extension isolated worlds.
  std::string isolated_world_csp;

  // Content Security Policy that should be used to enforce the sandbox used
  // by sandboxed pages (guaranteed to have the "sandbox" directive without the
  // "allow-same-origin" token).
  std::string sandbox_csp;

  // Returns the CSP to be used for the extension frames (tabs, popups, iframes)
  // and background contexts, or an empty string if there is no defined CSP.
  // Note that for extensions, platform apps and legacy packaged apps, a default
  // CSP is used even if the manifest didn't specify one, so an empty string
  // shouldn't be returned for those cases.
  static const std::string& GetExtensionPagesCSP(const Extension* extension);

  // Returns the Content Security Policy to be used for extension isolated
  // worlds or null if there is no defined CSP. Note that for extensions,
  // platform apps and legacy packaged apps, a default CSP is used even if the
  // manifest didn't specify one, so null shouldn't be returned for those cases.
  static const std::string* GetIsolatedWorldCSP(const Extension& extension);

  // Returns the extension's Content Security Policy for the sandboxed pages.
  static const std::string& GetSandboxContentSecurityPolicy(
      const Extension* extension);

  // Returns the Content Security Policy that the specified resource should be
  // served with.
  static const std::string& GetResourceContentSecurityPolicy(
      const Extension* extension,
      const std::string& relative_path);
};

// Parses "content_security_policy", "app.content_security_policy" and
// "sandbox.content_security_policy" manifest keys.
class CSPHandler : public ManifestHandler {
 public:
  CSPHandler();
  ~CSPHandler() override;

  // ManifestHandler override:
  bool Parse(Extension* extension, base::string16* error) override;

 private:
  // Parses the "content_security_policy" dictionary in the manifest.
  bool ParseCSPDictionary(Extension* extension, base::string16* error);

  // Parses the content security policy specified in the manifest for extension
  // pages.
  bool ParseExtensionPagesCSP(Extension* extension,
                              base::string16* error,
                              base::StringPiece manifest_key,
                              bool secure_only,
                              const base::Value* content_security_policy);

  // Parses the content security policy specified in the manifest for isolated
  // worlds.
  bool ParseIsolatedWorldCSP(Extension* extension, base::string16* error);

  // Parses the content security policy specified in the manifest for sandboxed
  // pages. This should be called after ParseExtensionPagesCSP.
  bool ParseSandboxCSP(Extension* extension,
                       base::string16* error,
                       base::StringPiece manifest_key,
                       const base::Value* sandbox_csp);

  // Helper to set the extension pages content security policy manifest data.
  bool SetExtensionPagesCSP(Extension* extension,
                            base::StringPiece manifest_key,
                            bool secure_only,
                            std::string content_security_policy);

  // Helper to set the isolated world content security policy manifest data.
  void SetIsolatedWorldCSP(Extension* extension,
                           std::string isolated_world_csp);

  // Helper to set the sandbox content security policy manifest data.
  void SetSandboxCSP(Extension* extension, std::string sandbox_csp);

  // ManifestHandler overrides:
  bool AlwaysParseForType(Manifest::Type type) const override;
  base::span<const char* const> Keys() const override;

  DISALLOW_COPY_AND_ASSIGN(CSPHandler);
};

}  // namespace extensions

#endif  // EXTENSIONS_COMMON_MANIFEST_HANDLERS_CSP_INFO_H_


text:
package bluejelly.runtime;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import bluejelly.runtime.Config.OutStyle;
import bluejelly.runtime.nodes.Executable;
import bluejelly.runtime.nodes.NApp;
import bluejelly.runtime.nodes.Node;

/**
 * BlueJelly runtime. Most of the action takes place here.
 *
 * @author ppedemon
 */
public class Runtime {

    // For command line processing
    private static final String SIZES = "kKmM";
    private static final String CMD_LINE_ARGS = "sSmMhvlb";
    private static final String VERSION = "The Bluejelly Runtime System, v";
    private static final String USAGE =
        "\nRuntime [options] function, where options are:\n" +
        "-v           show program version\n" +
        "-l           print result as a list\n" +
        "-b           print result as a boolean\n" +
        "-s <size>    initial stack size (default = 2K entries)\n" +
        "-S <size>    maximum stack size (default = 4K entries)\n" +
        "-m <size>    initial marker stack size (default = 1K entry)\n" +
        "-M <size>    maximum marker stack size (default = 2K entries)\n\n" +
        "Size is an integer number followed by a unit specifier. \n" +
        "Unit specifiers are K,k,M, or m, default unit is K.\n";

    // Runtime configuration
    private final Config config;

    // Table of executable heap nodes
    private final Map<String,Executable> codeTable =
        new HashMap<String,Executable>(31);

    // Module loader component
    private final ModuleLoader loader = new ModuleLoader(this);

    /**
     * Default constructor. Use default {@link Config} values.
     */
    public Runtime() {
        this(new Config());
    }

    /**
     * Create a new instance with the given configuration.
     * @param config    {@link Config} for this runtime instance
     */
    public Runtime(Config config) {
        this.config = config;
    }

    /**
     * Get runtime configuration.
     * @return    runtime {@link Config}
     */
    public Config getConfig() {
        return this.config;
    }

    /**
     * Load the given module.
     *
     * @param module    module to load
     * @throws JellyException    if module can't be loaded
     */
    public void load(String moduleName) throws JellyException {
        this.loader.load(moduleName);
    }

    /**
     * Register an {@link Executable} function.
     *
     * @param funId     function name
     * @param e         {@link Executable} node for the function
     */
    protected void register(String funId, Executable e) {
        this.codeTable.put(funId, e);
    }

    /**
     * Get the {@link Executable} node for the given function id.
     * We ensure thread-safe usage of the loader by making this
     * method synchronized.
     *
     * @param funId    function id whose code we want to retrieve
     * @return         intended code node
     */
    public synchronized Executable getFun(String funId) {
        Executable e = this.codeTable.get(funId);
        if (e != null) {
            return e;
        }
        String moduleName = IdUtils.qualifier(funId);
        if (this.loader.isLoaded(moduleName)) {
            throw new JellyRuntimeException("No definition for: " + funId);
        } else {
            this.loadIfNecessary(moduleName);
            return getFun(funId);
        }
    }

    /**
     * Evaluate a function with the given Id in a new {@link ExecutionContext}.
     * Module defining the function must have been loaded first.
     *
     * @param funId    id of function to evaluate.
     *
     * @return
     *   a {@link Future} that will make available the
     *   {@link ExecutionContext} where the evaluation took place
     */
    public Future<ExecutionContext> eval(String funId) {
        Executable e = this.getFun(funId);
        ExecutionContext ctx = new ExecutionContext(this);
        return ctx.eval(funId, e);
    }

    /**
     * Eval the given node in a new {@link ExecutionContext}. Any code
     * referenced by the module must have been loaded first.
     *
     * @param name    name identifying the execution context
     * @param n       {@link Node} to evaluate
     *
     * @return
     *   a {@link Future} that will make available the
     *   {@link ExecutionContext} where the evaluation took place
     */
    public Future<ExecutionContext> eval(String name, Node n) {
        ExecutionContext ctx = new ExecutionContext(this);
        return ctx.eval(name, n);
    }

    // Convenient wrapper to load call
    private void loadIfNecessary(String moduleName) {
        if (this.loader.isLoaded(moduleName)) {
            return;
        }
        try {
            this.loader.load(moduleName);
        } catch (JellyException e) {
            throw new JellyRuntimeException(e);
        }
    }

    // -------------------------------------------------------------------
    // Parse command line. Yes, by hand.
    // -------------------------------------------------------------------

    /**
     * Parse command line, modifying settings in the given
     * {@link Config} object. Return the name of the function
     * to execute. If there is no function to execute or if the
     * command line is invalid in any way, we abort the program.
     *
     * @param args    command line arguments
     * @param c       {@link Config} to fill-in
     * @return        function to execute
     */
    private static String parseCmdLine(String[] args, Config c) {
        char lastOpt = 0;
        String fun = null;

        for (String s: args) {
            if (s.charAt(0) == '-') {
                if (s.length() != 2) {
                    invalidCmdLine("Invalid option: " + s);
                    return null;
                }
                char chr = s.charAt(1);
                int i = CMD_LINE_ARGS.indexOf(chr);
                if (i == -1) {
                    invalidCmdLine("Invalid option: " + s);
                    return null;
                }
                switch (chr) {
                case 'h':
                    System.out.println(USAGE);
                    System.exit(0);
                case 'v':
                    System.out.println(VERSION + getVersion());
                    System.exit(0);
                case 'l':
                    c.style = OutStyle.LIST;
                    break;
                case 'b':
                    c.style = OutStyle.BOOL;
                    break;
                default:
                    lastOpt = chr;
                    break;
                }
            } else {
                switch (lastOpt) {
                case 's':
                    c.initStackSize = parseSize(s); lastOpt = 0; break;
                case 'S':
                    c.maxStackSize = parseSize(s);  lastOpt = 0; break;
                case 'm':
                    c.initMarkerStackSize = parseSize(s); lastOpt = 0; break;
                case 'M':
                    c.maxMarkerStackSize = parseSize(s); lastOpt = 0; break;
                case 0:
                    if (fun == null) {
                        fun = s;
                    } else {
                        invalidCmdLine("Multiple functions to execute:" +
                            s + " and " + fun);
                        return null;
                    }
                }
            }
        }
        if (lastOpt != 0) {
            invalidCmdLine("Missing argument for option: -" + lastOpt);
            return null;
        }
        if (fun == null) {
            invalidCmdLine("Missing function to execute");
            return null;
        }
        c.maxStackSize = Math.max(
                c.maxStackSize,
                c.initStackSize);
        c.maxMarkerStackSize = Math.max(
                c.maxMarkerStackSize,
                c.initMarkerStackSize);
        return fun;
    }

    private static void invalidCmdLine(String msg) {
        System.err.println(msg);
        System.err.println("Use -h for help");
        System.exit(1);
    }

    private static int parseSize(String s) {
        int mult = 10;
        char last = s.charAt(s.length() - 1);
        if (SIZES.indexOf(last) != -1) {
            if (last == 'M' || last == 'm') {
                mult = 20;
            }
            s = s .substring(0, s.length() - 1);
        }
        try {
            int size = Integer.parseInt(s);
            return size << mult;
        } catch (NumberFormatException e) {
            invalidCmdLine("Invalid size specification: " + s);
            return 0;
        }
    }

    private static String getVersion() {
        try {
            Properties p = new Properties();
            p.load(Runtime.class.getResourceAsStream("/brt-cfg.properties"));
            return p.getProperty("brt.version");
        } catch (IOException e) {
            // Should never get here
            return "<?>";
        }
    }

    /**
     * Entry point: for a given function f, evaluate print(f)
     * @param args               name of the function to execute
     * @throws JellyException    if execution fails
     */
    public static void main(String[] args) throws JellyException {
        Config c = new Config();
        String funId = parseCmdLine(args, c);
        Runtime r = new Runtime(c);

        String printFun = "bluejelly.runtime.Printer.";
        switch (c.style) {
        case DEFAULT: printFun += "println"       ; break;
        case LIST:    printFun += "printListln"   ; break;
        case BOOL:    printFun += "printBooleanln"; break;
        }

        NApp app = new NApp(new Node[] {r.getFun(funId), r.getFun(printFun)});
        Future<ExecutionContext> f = r.eval("<toplevel>",app);
        f.get();
    }

}


text:
Define_Module(TrafficGen);

void TrafficGen::initialize(int stage)
{
	BaseApplLayer::initialize(stage);

	if(stage == 0) {
		BaseLayer::catPacketSignal.initialize();
		world           = FindModule<BaseWorldUtility*>::findGlobalModule();
		delayTimer      = new cMessage("delay-timer", SEND_PACKET_TIMER);

		packetTime      = par("packetTime");
		pppt            = par("packetsPerPacketTime");
		burstSize       = par("burstSize");

		nbPacketDropped = 0;
	} else if (stage == 1) {
		if(burstSize > 0) {
			remainingBurst = burstSize;
			scheduleAt(dblrand() * packetTime * burstSize / pppt, delayTimer);
		}
	} else {

	}
}

TrafficGen::~TrafficGen() {
	cancelAndDelete(delayTimer);
}

void TrafficGen::finish()
{
	recordScalar("dropped", nbPacketDropped);
}

void TrafficGen::handleSelfMsg(cMessage *msg)
{
	switch( msg->getKind() )
	{
	case SEND_PACKET_TIMER:
		assert(msg == delayTimer);

		sendBroadcast();

		remainingBurst--;

		if(remainingBurst == 0) {
			remainingBurst = burstSize;
			scheduleAt(simTime() + (dblrand()*1.4+0.3)*packetTime * burstSize / pppt, msg);
		} else {
			scheduleAt(simTime() + packetTime * 2, msg);
		}

		break;
	default:
		EV << "Unkown selfmessage! -> delete, kind: "<<msg->getKind() <<endl;
		delete msg;
		break;
	}
}

void TrafficGen::handleLowerMsg(cMessage *msg)
{
	cPacket* pkt = static_cast<cPacket*>(msg);
	Packet p(pkt->getBitLength(), 1, 0);
	emit(BaseLayer::catPacketSignal, &p);

	delete msg;
	msg = 0;
}

void TrafficGen::sendBroadcast()
{
	ApplPkt *pkt = new ApplPkt("BROADCAST_MESSAGE", TRAFFIC_GEN_PACKET);
	pkt->setDestAddr(LAddress::L3BROADCAST);
	// we use the host modules getIndex() as a appl address
	pkt->setSrcAddr( myApplAddr() );
	pkt->setBitLength(headerLength);

	// set the control info to tell the network layer the layer 3
	// address;
	NetwControlInfo::setControlInfo(pkt, LAddress::L3BROADCAST);

	debugEV << "Sending broadcast packet!" << endl;
	sendDown( pkt );
}


text:
// GRPC client to perform on-demand profiling

#ifndef TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_TEST_UTIL_H_
#define TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_TEST_UTIL_H_

#include <memory>
#include <string>

#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "third_party/tensorflow/core/profiler/lib/profiler_session.h"
#include "third_party/tensorflow/core/profiler/rpc/profiler_server.h"
#include "tsl/platform/logging.h"
#include "tsl/platform/test.h"
#include "tsl/platform/types.h"
#include "tsl/profiler/protobuf/profiler_options.pb.h"
#include "tsl/profiler/protobuf/profiler_service.pb.h"

namespace tsl {
namespace profiler {
namespace test {

using tensorflow::ProfileRequest;
using tensorflow::ProfilerSession;
using tensorflow::profiler::ProfilerServer;

inline std::unique_ptr<ProfilerServer> StartServer(
    absl::Duration duration, std::string* service_address,
    ProfileRequest* request = nullptr) {
  auto profiler_server = absl::make_unique<ProfilerServer>();
  int port = testing::PickUnusedPortOrDie();
  profiler_server->StartProfilerServer(port);

  DCHECK(service_address);
  *service_address = absl::StrCat("localhost:", port);

  if (request) {
    request->set_duration_ms(absl::ToInt64Milliseconds(duration));
    request->set_max_events(10000);
    *request->mutable_opts() = ProfilerSession::DefaultOptions();
    request->mutable_opts()->set_duration_ms(
        absl::ToInt64Milliseconds(duration));
    request->set_session_id("test_session");
    request->set_host_name(*service_address);
    request->set_repository_root(testing::TmpDir());
  }

  LOG(INFO) << "Started " << *service_address << " at " << absl::Now();
  LOG(INFO) << "Duration: " << duration;

  return profiler_server;
}

inline ::testing::Matcher<absl::Duration> DurationNear(
    const absl::Duration duration, absl::Duration epsilon = absl::Seconds(1)) {
  return ::testing::AllOf(::testing::Ge(duration - epsilon),
                          ::testing::Le(duration + epsilon));
}

inline ::testing::Matcher<absl::Duration> DurationApproxLess(
    const absl::Duration duration, absl::Duration epsilon = absl::Seconds(1)) {
  return ::testing::Le(duration + epsilon);
}

}  // namespace test
}  // namespace profiler
}  // namespace tsl

#endif  // TENSORFLOW_TSL_PROFILER_RPC_CLIENT_PROFILER_CLIENT_TEST_UTIL_H_


text:
function [scores, candidateIds] = cnn_computeScores_pairwiseModel( net, imdb, getBatch, varargin )
%cnn_computeScores_pairwiseModel computes the scores using the structure network

if ~exist('varargin', 'var')
    varargin = {};
end

%% compute results w.r.t. patches
opts = struct;
opts.conserveMemory = true;
opts.sync = true;
opts.imageSet = 1 : size( imdb.imageFiles, 4 );
opts.scoreMode = 'maxMarginals';
% parse input
opts = vl_argparse(opts, varargin);

%% do the job
numImages = length( opts.imageSet );
scores = cell( max(opts.imageSet), 1);
candidateIds = cell( max(opts.imageSet), 1);

for iImageId = 1 : numImages
    iImage = opts.imageSet( iImageId );
    fprintf('Image %d/%d: ', iImageId, numImages);
    tImageStart = tic;

    [patchData, patchLabels, patchInfo] = getBatch( imdb, iImage );
    curNumCandidates = size( patchData, 4 );
    fprintf('patches=%d, ', curNumCandidates );

    [~, ~, predictions] = vl_structuredNetwork_pairwiseModel(net, patchData, [], patchLabels, [], ...
        'computeMaxMarginals', true, ...
        'disableDropout', true, ...
        'conserveMemory', opts.conserveMemory, ...
        'sync', opts.sync);
    maxMarginals = predictions{1}.maxMarginals;

    candidateIds{ iImage } = int32( patchInfo.candidateIds{1}(:) );

    switch opts.scoreMode
        case 'maxMarginals'
            curScores = maxMarginals(:, 1) - maxMarginals(:, 2);
        otherwise
            error('cnn_computeScores_pairwiseModel:unknownScoreMode', 'options scoreMode is of incorrect value');
    end

    curScores = curScores(:);
    if numel(curScores) ~= numel( candidateIds{iImage} )
        error('cnn_computeScores_pairwiseModel:inconsistentCandidates', 'something went wrong')
    end
    scores{ iImage } = single( curScores );

    fprintf('time: %fs\n', toc(tImageStart) );
end

end


text:
package org.zmpp.zcode

import org.scalatest._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.BeforeAndAfterEach

class MockOutputStream extends OutputStream {
  val buffer = new StringBuilder
  def charsWritten = buffer.toString
  def putChar(c: Char) = buffer.append(c)
  def flush {}
  def select(flag: Boolean) { }
  def isSelected: Boolean = true
}

@RunWith(classOf[JUnitRunner])
class EncodingSpec extends FlatSpec with Matchers
with BeforeAndAfterEach {
  var out: MockOutputStream = null
  override def beforeEach {
    out = new MockOutputStream
  }

  "Encoding" should "have a defined initial state" in {
    val encoding = new ZsciiEncoding(new MockVMState(5, null))
    encoding.resetVMState
    encoding.currentAlphabet should be (Alphabet0)
  }
  it should "move to alphabet 1 on shift 4" in {
    val encoding = new ZsciiEncoding(new MockVMState(5, null))
    encoding.resetVMState
    encoding.decodeZchar(4, out)
    encoding.currentAlphabet should be (Alphabet1)
  }
  it should "move to alphabet 2 on shift 5" in {
    val encoding = new ZsciiEncoding(new MockVMState(5, null))
    encoding.resetVMState
    encoding.decodeZchar(5, out)
    encoding.currentAlphabet should be (Alphabet2)
  }
  it should "fall back to alphabet 0 on shift 4 after a character was decoded" in {
    val encoding = new ZsciiEncoding(new MockVMState(5, null))
    encoding.resetVMState
    encoding.decodeZchar(4, out)
    encoding.decodeZchar(6, out)
    out.charsWritten should be ("A")
    encoding.currentAlphabet should be (Alphabet0)
  }
  it should "fall back to alphabet 0 on shift 5 after a character was decoded" in {
    val encoding = new ZsciiEncoding(new MockVMState(5, null))
    encoding.resetVMState
    encoding.decodeZchar(5, out)
    encoding.decodeZchar(8, out)
    out.charsWritten should be ("0")
    encoding.currentAlphabet should be (Alphabet0)
  }

  // **********************************************************************
  // ******* Version 1/2 specific cases
  // **********************************************************************
  it should "fall back to alphabet 0 on shift 2 after a character was decoded" in {
    val encoding = new ZsciiEncoding(new MockVMState(2, null))
    encoding.resetVMState
    encoding.decodeZchar(2, out)
    encoding.decodeZchar(6, out)
    out.charsWritten should be ("A")
    encoding.currentAlphabet should be (Alphabet0)
  }
  it should "switch to alphabet 2 after receiving two shift-2's in a row and fallback to alphabet 1" in {
    val encoding = new ZsciiEncoding(new MockVMState(2, null))
    encoding.resetVMState
    encoding.decodeZchar(2, out)
    encoding.decodeZchar(2, out)
    encoding.currentAlphabet should be (Alphabet2)
    encoding.decodeZchar(8, out)
    out.charsWritten should be ("0")
    encoding.currentAlphabet should be (Alphabet1)
  }
  it should "fall back to alphabet 0 on shift 3 after a character was decoded" in {
    val encoding = new ZsciiEncoding(new MockVMState(1, null))
    encoding.resetVMState
    encoding.decodeZchar(3, out)
    encoding.decodeZchar(8, out)
    out.charsWritten should be ("1")
    encoding.currentAlphabet should be (Alphabet0)
  }
  it should "not fall back on shift 4 after a character was decoded in V1/V2" in {
    val encoding = new ZsciiEncoding(new MockVMState(1, null))
    encoding.resetVMState
    encoding.decodeZchar(4, out)
    encoding.decodeZchar(6, out)
    out.charsWritten should be ("A")
    encoding.currentAlphabet should be (Alphabet1)
  }
  it should "not fall back on shift 5 after a character was decoded in V2" in {
    val encoding = new ZsciiEncoding(new MockVMState(2, null))
    encoding.resetVMState
    encoding.decodeZchar(5, out)
    encoding.decodeZchar(8, out)
    out.charsWritten should be ("0")
    encoding.currentAlphabet should be (Alphabet2)
  }
  it should "not fall back on shift 5 after a character was decoded in V1" in {
    val encoding = new ZsciiEncoding(new MockVMState(1, null))
    encoding.resetVMState
    encoding.decodeZchar(5, out)
    encoding.decodeZchar(8, out)
    out.charsWritten should be ("1")
    encoding.currentAlphabet should be (Alphabet2_V1)
  }
  it should "reset a shift lock when a shift character comes after a lock-4" in {
    val encoding = new ZsciiEncoding(new MockVMState(1, null))
    encoding.resetVMState
    encoding.decodeZchar(4, out)
    encoding.decodeZchar(2, out)
    encoding.decodeZchar(10, out)
    encoding.currentAlphabet should be (Alphabet1)
  }
  it should "reset a shift lock when a shift character comes after a lock-5" in {
    val encoding = new ZsciiEncoding(new MockVMState(2, null))
    encoding.resetVMState
    encoding.decodeZchar(5, out)
    encoding.decodeZchar(3, out)
    encoding.decodeZchar(10, out)
    encoding.currentAlphabet should be (Alphabet2)
  }
  it should "reset its state properly after invoking reset" in {
    val encoding = new ZsciiEncoding(new MockVMState(2, null))
    encoding.resetVMState
    encoding.decodeZchar(2, out)
    encoding.decodeZchar(5, out)
    encoding.resetEncodingState
    encoding.currentAlphabet should be (Alphabet0)
    encoding.lastAlphabet should be (Alphabet0)
    encoding.shiftLock should be (false)
    encoding.decode10bit should be (false)
  }
}


text:
.exception_file { font-size: 0.9em; color: black; }

.exception_title {margin: 1em 0.5em 0.5em 0.5em; font-weight: bold; text-align: left; font-size: 0.8em;}

.exception_trace {
	border-collapse: collapse;
	background-color: white;
	border: solid gray 1px;
	font-size: 1em;
}

.exception_trace_number, .exception_highlight { font-weight: bold;}

.exception_trace_number { background-color: #C0C0C0; }

.exception_line { padding-left: 1em; }

.exception_highlight { background-color: #ffdddd; width: 100%; }

.exception{
padding:1em;
}
.round{
border-radius: 5px;
}
.exception h1 {
text-shadow:1px 1px 1px rgba(0, 0, 0, 0.4);
}
.exception h2 {
background-color: #D1C2A3;
padding:.2em;
margin: 1em 0 .3em;
color:rgb(138, 111, 92);
border-radius: 5px;
text-shadow:1px 1px 1px rgba(255, 255, 255, 0.8);
}
.exception em {
color: black;
}
.solution {
background-color: lime;
}
pre {
background-color: #eee;
padding: 1em;
border:1px solid #ccc;
color: #000;
margin: 1em 0;

}
.exception table {
width: 100%;

border-spacing: 2px 2px;
color: rgb(138, 111, 92);
}
.exception thead {
background-color: #D1C2A3;
}
.exception tr {
border-bottom:1px solid #D1C2A3;
}
.exception td{
padding: .2em .2em;
}


text:
<?php

namespace Klimesf\Hateoas\DI;

use Hateoas\HateoasBuilder as Builder;
use Klimesf\Hateoas\NetteUrlGenerator;
use Nette\DI\Container;

/**
 * Builds Hateoas service with given configuration.
 * @package   Klimesf\Hateoas\DI
 * @author    Filip Klimes <filip@filipklimes.cz>
 */
class HateoasBuilder
{

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

	/**
	 * @var Container
	 */
	private $container;

	/**
	 * HateoasBuilder constructor.
	 * @param array             $config
	 * @param Container         $container
	 */
	public function __construct(array $config, Container $container)
	{
		$this->config = $config;
		$this->container = $container;
	}

	/**
	 * @return \Hateoas\Hateoas
	 */
	public function getHateoas()
	{
		$hateoasBuilder = Builder::create()
			->setCacheDir($this->config['cacheDir'])
			->setDebug($this->config['debugMode']);

		$this->setJsonSerializer($hateoasBuilder);
		$this->setXmlSerializer($hateoasBuilder);
		$this->addUrlGenerators($hateoasBuilder);

		if (!empty($this->config['expressionContextVariables'])) {
			$this->addExpressionContextVariables($hateoasBuilder);
		}

		if ($this->config['expressionLanguage']) {
			$hateoasBuilder->setExpressionLanguage(new $this->config['expressionLanguage']);
		}

		if (!empty($this->config['expressionFunctions'])) {
			$this->setExpressionLanguageFunctions($hateoasBuilder);
		}

		if ($this->config['relationProviderResolvers']) {
			$this->addRelationProviderResolvers($hateoasBuilder);
		}

		$hateoasBuilder->includeInterfaceMetadata($this->config['includeInterfaceMetadata']);

		return $hateoasBuilder->build();
	}

	/**
	 * @param Builder $hateoasBuilder
	 */
	private function addUrlGenerators(Builder & $hateoasBuilder)
	{
		if (!empty($this->config['urlGenerators'])) {
			$hasDefault = false;
			foreach ($this->config['urlGenerators'] as $name => $generator) {
				if (is_numeric($name) && !$hasDefault) {
					$name = null;
					$hasDefault = true;
				}
				$hateoasBuilder->setUrlGenerator($name, $this->container->getByType($generator));
			}
		}
	}

	/**
	 * @param $hateoasBuilder
	 */
	public function setXmlSerializer(Builder & $hateoasBuilder)
	{
		if ($this->config['xmlSerializer'] === 'default') {
			$hateoasBuilder->setDefaultXmlSerializer();
		} else {
			$hateoasBuilder->setXmlSerializer(new $this->config['xmlSerializer']);
		}
	}

	/**
	 * @param $hateoasBuilder
	 */
	public function setJsonSerializer(Builder & $hateoasBuilder)
	{
		if ($this->config['jsonSerializer'] === 'default') {
			$hateoasBuilder->setDefaultJsonSerializer();
		} else {
			$hateoasBuilder->setJsonSerializer(new $this->config['jsonSerializer']);
		}
	}

	/**
	 * @param Builder $hateoasBuilder
	 */
	private function addExpressionContextVariables(Builder & $hateoasBuilder)
	{
		foreach ($this->config['expressionContextVariables'] as $name => $value) {
			$hateoasBuilder->setExpressionContextVariable($name, $value);
		}
	}

	/**
	 * @param Builder $hateoasBuilder
	 */
	private function setExpressionLanguageFunctions(Builder & $hateoasBuilder)
	{
		foreach ($this->config['expressionFunctions'] as $function) {
			$hateoasBuilder->registerExpressionFunction(new $function);
		}
	}

	/**
	 * @param Builder $hateoasBuilder
	 */
	private function addRelationProviderResolvers(Builder & $hateoasBuilder)
	{
		foreach ($this->config['relationProviderResolvers'] as $resolver) {
			$hateoasBuilder->addRelationProviderResolver(new $resolver);
		}
	}

}


text:
<?php

namespace DvsaMotApi\Controller;

use Doctrine\ORM\EntityManager;
use DvsaCommon\Utility\DtoHydrator;
use DvsaCommonApi\Controller\AbstractDvsaRestfulController;
use DvsaCommonApi\Model\ApiResponse;
use DvsaElasticSearch\Service\ElasticSearchService;
use DvsaEntities\DqlBuilder\SearchParam\MotTestLogSearchParam;
use DvsaMotApi\Service\TesterMotTestLogService;

class TesterMotTestLogController extends AbstractDvsaRestfulController
{
    const ERR_TESTER_ID = 'Invalid tester Id entered.';

    /**
     * @var TesterMotTestLogService
     */
    private $motTestLogService;

    /**
     * @var ElasticSearchService
     */
    private $elasticSearchService;

    /**
     * @var EntityManager
     */
    private $entityManager;

    public function __construct(
        TesterMotTestLogService $motTestLogService,
        ElasticSearchService $elasticSearchService,
        EntityManager $entityManager
    ) {
        $this->motTestLogService = $motTestLogService;
        $this->elasticSearchService = $elasticSearchService;
        $this->entityManager = $entityManager;
    }

    public function summaryAction()
    {
        $testerId = $this->params()->fromRoute('id');

        return ApiResponse::jsonOk(
            $this->motTestLogService->getMotTestLogSummaryForTester($testerId)
        );
    }

    public function logDataAction()
    {
        $testerId = (int) $this->params()->fromRoute('id');
        if ($testerId <= 0) {
            return $this->returnBadRequestResponseModel(
                self::ERR_TESTER_ID,
                self::ERROR_CODE_REQUIRED,
                self::ERR_TESTER_ID
            );
        }

        $postData = $this->processBodyContent($this->getRequest());

        $searchParams = new MotTestLogSearchParam($this->entityManager);
        $searchParams
            ->fromDto(DtoHydrator::jsonToDto($postData))
            ->setTesterId($testerId);

        return ApiResponse::jsonOk($this->elasticSearchService->findTesterTestsLog($searchParams));
    }
}


text:
require 'spec_helper'

describe Bitcoin::Message::MemPool do

  describe 'to_pkt' do
    subject {
      Bitcoin::Message::MemPool.new.to_pkt
    }
    it 'should be generate' do
      expect(subject).to eq('0b1109076d656d706f6f6c0000000000000000005df6e0e2'.htb)
    end
  end

end


text:
namespace WhatThe.Mods.CitiesSkylines.ServiceDispatcher.SerializableSettings
{
    /// <summary>
    /// The different service types.
    /// </summary>
    public enum ServiceType
    {
        /// <summary>
        /// Not a service.
        /// </summary>
        None = 0,

        /// <summary>
        /// The death care standard service.
        /// </summary>
        DeathCare = 1,

        /// <summary>
        /// The garbage standard service.
        /// </summary>
        Garbage = 2,

        /// <summary>
        /// The health care standard service.
        /// </summary>
        HealthCare = 3,

        /// <summary>
        /// The wrecking crew hidden service.
        /// </summary>
        WreckingCrews = 4,

        /// <summary>
        /// The recovery crew hidden service.
        /// </summary>
        RecoveryCrews = 5
    }

    /// <summary>
    /// The different settings types.
    /// </summary>
    public enum SettingsType
    {
        /// <summary>
        /// Not a settngs block.
        /// </summary>
        None = 0,

        /// <summary>
        /// A standard service block.
        /// </summary>
        StandardService = 1,

        /// <summary>
        /// A hidden service block.
        /// </summary>
        HiddenService = 2,

        /// <summary>
        /// The service range settings block.
        /// </summary>
        ServiceRanges = 3,

        /// <summary>
        /// The compatibility settings block.
        /// </summary>
        Compatibility = 4
    }

    /// <summary>
    /// Result of deserialization.
    /// </summary>
    internal enum DeserializationResult
    {
        /// <summary>
        /// The end of data was reached.
        /// </summary>
        EndOfData = 0,

        /// <summary>
        /// Deserialization was successfull.
        /// </summary>
        Success = 1,

        /// <summary>
        /// An error occured.
        /// </summary>
        Error = 2
    }
}


text:
robust-subtract
===============
Exactly computes the difference of two non-increasing overlapping sequences.  See [robust-sum for more details](https://github.com/mikolalysenko/robust-sum).

# Example

```javascript
var robustDiff = require("robust-subtract")

console.log(robustDiff([1], [1e-64]))
```

# Install

```
npm install robust-subtract
```

# API

### `require("robust-subtract")(a,b)`
Returns the difference of the sequences `a` and `b` encoded as a non-overlapping increasing sequence.

* `a` is the first number
* `b` is the second number

**Returns** The difference of `a` and `b`

## Credits
(c) 2014 Mikola Lysenko. MIT License


text:
package de.marcusschiesser.dbpendler.client.adapters;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import de.marcusschiesser.dbpendler.common.vo.ConnectionVO;

public final class EditConnectionAdapter extends ArrayAdapter<ConnectionVO> {
	public EditConnectionAdapter(Context context, int textViewResourceId,
			ConnectionVO[] result) {
		super(context, textViewResourceId, result);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View textView = super.getView(position, convertView, parent);
		ConnectionVO connection = getItem(position);
		String formated = String.format("%tR - %tR", connection.getStartTime(), connection.getDestinationTime());
		((TextView)textView).setText(formated);
		return textView;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<set xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@anim/decelerate_interpolator"
        android:zAdjustment="top">
    <!-- For now stay like the normal activity transition.
    <scale android:fromXScale="2.0" android:toXScale="1.0"
           android:fromYScale="2.0" android:toYScale="1.0"
           android:pivotX="100%p" android:pivotY="50%p"
           android:duration="@android:integer/config_shortAnimTime" />
    -->
    <translate android:fromXDelta="-100%" android:toXDelta="0"
        android:duration="@android:integer/config_shortAnimTime"/>
</set>


text:
settings = Chef::DataBagItem.load('flume', 'settings')[node.chef_environment] rescue {}
Chef::Log.debug "Loaded settings: #{settings.inspect}"

# Initialize the node attributes with node attributes merged with data bag attributes
#
node.default[:flume] ||= {}
node.normal[:flume]  ||= {}

node.normal[:flume]    = DeepMerge.merge(node.default[:flume].to_hash, node.normal[:flume].to_hash)
node.normal[:flume]    = DeepMerge.merge(node.normal[:flume].to_hash, settings.to_hash)

# === VERSION AND LOCATION
#
default.flume[:version]       = "1.5.2"
default.flume[:host]          = "http://apache.mirrors.lucidnetworks.net"
default.flume[:repository]    = "flume/#{node.flume[:version]}"
default.flume[:filename]      = nil
default.flume[:download_url]  = nil

# === USER & PATHS
#
default.flume[:dir]       = "/usr/local"
default.flume[:user]      = "flume"
default.flume[:uid]       = nil
default.flume[:gid]       = nil

default.flume[:path][:conf] = "/etc/flume"
default.flume[:path][:dir] = "#{node.flume[:dir]}/flume"
default.flume[:path][:logs] = "/var/log/flume"

default.flume[:pid_path]  = "/var/run/flume"
default.flume[:pid_file]  = "#{node.flume[:pid_path]}/flume.pid"

default.flume[:templates][:flume_conf]  = "flume.conf.erb"
default.flume[:templates][:log4j_properties] = "log4j.properties.erb"
default.flume[:templates][:flume_env] = "flume-env.sh.erb"

# === MEMORY
#
# Maximum amount of memory to use is automatically computed as one half of total available memory on the machine.
# You may choose to set it in your node/role configuration instead.
#
allocated_memory = "#{(node.memory.total.to_i * 0.8 ).floor / 1024}m"
default.flume[:allocated_memory] = allocated_memory
default.flume[:env] = [
  %Q[JAVA_OPTS=" -Xmx#{allocated_memory} -Xms#{allocated_memory} -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+HeapDumpOnOutOfMemoryError "]
]

default.flume[:agent_config] = [
  "# Licensed to the Apache Software Foundation (ASF) under one",
  "# or more contributor license agreements.  See the NOTICE file",
  "# distributed with this work for additional information",
  "# regarding copyright ownership.  The ASF licenses this file",
  "# to you under the Apache License, Version 2.0 (the",
  "# 'License'); you may not use this file except in compliance",
  "# with the License.  You may obtain a copy of the License at",
  "#",
  "#  http://www.apache.org/licenses/LICENSE-2.0",
  "#",
  "# Unless required by applicable law or agreed to in writing,",
  "# software distributed under the License is distributed on an",
  "# 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
  "# KIND, either express or implied.  See the License for the",
  "# specific language governing permissions and limitations",
  "# under the License.",
  "",
  "",
  "# The configuration file needs to define the sources,",
  "# the channels and the sinks.",
  "# Sources, channels and sinks are defined per agent,",
  "# in this case called 'agent'",
  "",
  "agent.sources = avro",
  "agent.channels = memoryChannel",
  "agent.sinks = loggerSink",
  "",
  "# For each one of the sources, the type is defined",
  "agent.sources.avro.type = avro",
  "agent.sources.avro.bind = 0.0.0.0",
  "agent.sources.avro.port = 5000",
  "",
  "# The channel can be defined as follows.",
  "agent.sources.avro.channels = memoryChannel",
  "",
  "# Each sink's type must be defined",
  "agent.sinks.loggerSink.type = logger",
  "",
  "#Specify the channel the sink should use",
  "agent.sinks.loggerSink.channel = memoryChannel",
  "",
  "# Each channel's type is defined.",
  "agent.channels.memoryChannel.type = memory",
  "",
  "# Other config values specific to each type of channel(sink or source)",
  "# can be defined as well",
  "# In this case, it specifies the capacity of the memory channel",
  "agent.channels.memoryChannel.capacity = 100"
]

# === LIMITS
#
default.flume[:limits][:memlock] = 'unlimited'
default.flume[:limits][:nofile]  = '64000'

# === PRODUCTION SETTINGS
#
default.flume[:env_options] = ""

# === OTHER SETTINGS
#
default.flume[:skip_restart] = false
default.flume[:skip_start] = false

# === CUSTOM CONFIGURATION
#
default.flume[:custom_config] = {}

# === LOGGING
#
# See `attributes/logging.rb`
#
default.flume[:logging] = {}


text:
/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created: Tue Apr 20 14:41:40 2010
**      by: Qt User Interface Compiler version 4.6.3
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHeaderView>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QPushButton>
#include <QtGui/QSpacerItem>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralWidget;
    QVBoxLayout *verticalLayout;
    QPushButton *buttonForget;
    QPushButton *pushButton;
    QPushButton *pushButton_2;
    QListWidget *listWidget;
    QSpacerItem *verticalSpacer;

    void setupUi(QMainWindow *MainWindow)
    {
        if (MainWindow->objectName().isEmpty())
            MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
        MainWindow->resize(321, 457);
        centralWidget = new QWidget(MainWindow);
        centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
        verticalLayout = new QVBoxLayout(centralWidget);
        verticalLayout->setSpacing(6);
        verticalLayout->setContentsMargins(11, 11, 11, 11);
        verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
        buttonForget = new QPushButton(centralWidget);
        buttonForget->setObjectName(QString::fromUtf8("buttonForget"));

        verticalLayout->addWidget(buttonForget);

        pushButton = new QPushButton(centralWidget);
        pushButton->setObjectName(QString::fromUtf8("pushButton"));

        verticalLayout->addWidget(pushButton);

        pushButton_2 = new QPushButton(centralWidget);
        pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));

        verticalLayout->addWidget(pushButton_2);

        listWidget = new QListWidget(centralWidget);
        listWidget->setObjectName(QString::fromUtf8("listWidget"));

        verticalLayout->addWidget(listWidget);

        verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);

        verticalLayout->addItem(verticalSpacer);

        MainWindow->setCentralWidget(centralWidget);

        retranslateUi(MainWindow);

        QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
        MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
        buttonForget->setText(QApplication::translate("MainWindow", "Forget", 0, QApplication::UnicodeUTF8));
        pushButton->setText(QApplication::translate("MainWindow", "Login to facebook", 0, QApplication::UnicodeUTF8));
        pushButton_2->setText(QApplication::translate("MainWindow", "Get all my friends", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_MAINWINDOW_H


text:
layout: page
title: Not found (404)
permalink: /404.html
tags:
description: "Not found"
sitemap: false
---
<p>
Sorry, but this content was not found.
</p>


text:
layout: page
subheadline:
title:  "COBECORE will contribute to ACRE and the ISPD"
teaser: "helping support global atmospheric re-analysis..."
breadcrumb: true
tags:
    - digitization
    - re-analysis
    - meteorology
    - atmospheric_circulation
categories:
    - blog
header:
   image_fullwidth: "header/header_4.jpg"
---

As outlined in the research proposal of COBECORE the data contained within the historical NILCO archives have significant importance towards reconstructing the past climate across the Congo Basin and the central African continent.

Within this context COBECORE will contribute barometric pressure measurements at 7 site locations across the Congo Basin (more data might be integrated later). These data will be shared with the ['Atmospheric Circulation Reconstruction over the Earth (ACRE)'](http://www.met-acre.net/) project and integrated through the ['International Surface Pressure Database (ISPD)'](https://reanalyses.org/observations/international-surface-pressure-databank).

Similar to COBECORE, ACRE allies several partners and citizen science platforms to [facilitate data rescue and recovery](http://www.met-acre.net/data%20rescue.htm) of historical climate records of both marine and terrestrial sensor data.

As shown in the map below, very few surface pressure measurements exist on the African continent during the late 1930's. However, we hope to fill some of these gaps in knowledge and further constrain global atmospheric re-analysis models through our contributions.

{% include _image.html url="/images/documentation/ISPD_COBECORE_stations.png" description="Fig 1. - new surface pressure stations throughout the Congo Basin. (current ISPD stations as red dots, new COBECORE stations as blue dots)" %}


text:
<?php namespace System\Database\Seeds;

use Admin\Models\Customer_groups_model;
use Admin\Models\Mealtimes_model;
use Admin\Models\Staff_groups_model;
use Admin\Models\Statuses_model;
use Illuminate\Database\Seeder;
use System\Models\Countries_model;
use System\Models\Currencies_model;
use System\Models\Languages_model;
use System\Models\Permissions_model;
use System\Models\Settings_model;

class InitialSchemaSeeder extends Seeder
{
    protected $recordsPath = __DIR__.'/../records';

    /**
     * Run the initial schema seeds.
     * @return void
     */
    public function run()
    {
        $this->seedCountries();

        $this->seedCurrencies();

        $this->seedCustomerGroups();

        $this->seedLanguages();

        $this->seedMealtimes();

        $this->seedPermissions();

        $this->seedSettings();

        $this->seedStaffGroups();

        $this->seedStatuses();
    }

    protected function seedCountries()
    {
        if (Countries_model::count())
            return;

        $countries = $this->getSeedRecords('countries');

        foreach ($countries as $country) {
            Countries_model::insert($country);
        }
    }

    protected function seedCurrencies()
    {
        if (Currencies_model::count())
            return;

        $currencies = $this->getSeedRecords('currencies');

        foreach ($currencies as $currency) {
            Currencies_model::insert($currency);
        }
    }

    protected function seedCustomerGroups()
    {
        if (Customer_groups_model::count())
            return;

        Customer_groups_model::create([
            'group_name' => 'Default group',
            'approval' => FALSE,
        ]);
    }

    protected function seedLanguages()
    {
        if (Languages_model::count())
            return;

        Languages_model::insert([
            'code' => 'en',
            'name' => 'English',
            'image' => 'flags/gb.png',
            'idiom' => 'english',
            'status' => TRUE,
            'can_delete' => FALSE,
        ]);
    }

    protected function seedMealtimes()
    {
        if (Mealtimes_model::count())
            return;

        Mealtimes_model::insert([
            [
                "mealtime_name" => "Breakfast",
                "start_time" => "07:00:00",
                "end_time" => "10:00:00",
                "mealtime_status" => TRUE,
            ],
            [
                "mealtime_name" => "Lunch",
                "start_time" => "12:00:00",
                "end_time" => "14:30:00",
                "mealtime_status" => TRUE,
            ],
            [
                "mealtime_name" => "Dinner",
                "start_time" => "18:00:00",
                "end_time" => "20:00:00",
                "mealtime_status" => TRUE,
            ],
        ]);
    }

    protected function seedPermissions()
    {
        if (Permissions_model::count())
            return;

        $permissions = $this->getSeedRecords('permissions');

        foreach ($permissions as $permission) {
            Permissions_model::insert($permission);
        }
    }

    protected function seedSettings()
    {
        if (Settings_model::count())
            return;

        $settings = $this->getSeedRecords('settings');

        foreach ($settings as $setting) {
            Settings_model::insert($setting);
        }
    }

    protected function seedStaffGroups()
    {
        if (Staff_groups_model::count())
            return;

        Staff_groups_model::insert([
            'staff_group_name' => 'Administrator',
            'customer_account_access' => TRUE,
            'location_access' => FALSE,
            'permissions' => '',
        ]);
    }

    protected function seedStatuses()
    {
        if (Statuses_model::count())
            return;

        $statuses = $this->getSeedRecords('statuses');

        foreach ($statuses as $status) {
            Statuses_model::insert($status);
        }
    }

    protected function getSeedRecords($name)
    {
        return json_decode(file_get_contents($this->recordsPath.'/'.$name.'.json'), TRUE);
    }
}


text:
module Azure::ServiceFabric::V6_4_0_36
  module Models
    #
    # A container event.
    #
    class ContainerEvent

      include MsRestAzure

      # @return [String] The name of the container event.
      attr_accessor :name

      # @return [Integer] The count of the event.
      attr_accessor :count

      # @return [String] Date/time of the first event.
      attr_accessor :first_timestamp

      # @return [String] Date/time of the last event.
      attr_accessor :last_timestamp

      # @return [String] The event message
      attr_accessor :message

      # @return [String] The event type.
      attr_accessor :type

      #
      # Mapper for ContainerEvent class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ContainerEvent',
          type: {
            name: 'Composite',
            class_name: 'ContainerEvent',
            model_properties: {
              name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              count: {
                client_side_validation: true,
                required: false,
                serialized_name: 'count',
                type: {
                  name: 'Number'
                }
              },
              first_timestamp: {
                client_side_validation: true,
                required: false,
                serialized_name: 'firstTimestamp',
                type: {
                  name: 'String'
                }
              },
              last_timestamp: {
                client_side_validation: true,
                required: false,
                serialized_name: 'lastTimestamp',
                type: {
                  name: 'String'
                }
              },
              message: {
                client_side_validation: true,
                required: false,
                serialized_name: 'message',
                type: {
                  name: 'String'
                }
              },
              type: {
                client_side_validation: true,
                required: false,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
  Gottenhouse est
       un village
       localisé dans le département de Bas-Rhin en Alsace. Elle comptait 373 habitants en 2008.

Le parc d'habitations, à Gottenhouse, était réparti en 2011 en neuf appartements et 153 maisons soit
 un marché plutôt équilibré.

À coté de Gottenhouse sont localisées les communes de
Lochwiller située à 4 km, 372 habitants,
Marmoutier localisée à 3 km, 2 657 habitants,
Ottersthal située à 3 km, 745 habitants,
Schwenheim localisée à 3 km, 684 habitants,
Haegen localisée à 1 km, 636 habitants,
Monswiller située à 4 km, 2 076 habitants,
 entre autres. De plus, Gottenhouse est située à seulement 29 km de Lingolsheim.

Si vous pensez venir habiter à Gottenhouse, vous pourrez facilement trouver une maison à vendre.


text:
'''
Created on 12 déc. 2013

@author: Alexandre Bonhomme
'''
from fr.lille1.maven_data_extraction.scrapers.maven.maven_browser import \
    MavenBrowser
import unittest

class Test(unittest.TestCase):

    def setUp(self):
        self.browser = MavenBrowser()

    def testBuildURL(self):
        url = 'http://search.maven.org/solrsearch/select'
        params = [('q', 'id:"-1764970778" OR parentId:"-1764970778"'),
                 ('rows', '100000'),
                 ('core', 'filelisting'),
                 ('wt', 'json')]

        safeUrl = self.browser.buildURL(url, params)

        assert safeUrl == 'http://search.maven.org/solrsearch/select?q=id%3A%22-1764970778%22+OR+parentId%3A%22-1764970778%22&rows=100000&core=filelisting&wt=json'


text:
#import "NBSMockedApplication.h"
#import <objc/runtime.h>

@interface NBSMockedApplication ()

@property (nonatomic) BOOL isSwizzled;

@end

@interface UIFont (Swizzling)

+ (void)nbs_swizzle;

@end

@interface UIApplication (Swizzling)

+ (void)nbs_swizzle;

@property (nonatomic) UIContentSizeCategory nbs_preferredContentSizeCategory;

@end

@interface UITraitCollection (Swizzling)

+ (void)nbs_swizzle;

@end

@implementation NBSMockedApplication

/* On iOS 9, +[UIFont preferredFontForTextStyle:] uses -[UIApplication preferredContentSizeCategory]
    to get the content size category. However, this changed on iOS 10. While I haven't found what UIFont uses to get
    the current category, swizzling preferredFontForTextStyle: to use +[UIFont preferredFontForTextStyle: compatibleWithTraitCollection:]
    (only available on iOS >= 10), passing an UITraitCollection with the desired contentSizeCategory.
 */

- (void)mockPreferredContentSizeCategory:(UIContentSizeCategory)category {
    UIApplication.sharedApplication.nbs_preferredContentSizeCategory = category;

    if (!self.isSwizzled) {
        [UIApplication nbs_swizzle];
        [UIFont nbs_swizzle];
        [UITraitCollection nbs_swizzle];
        self.isSwizzled = YES;
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:UIContentSizeCategoryDidChangeNotification
                                                        object:[UIApplication sharedApplication]
                                                      userInfo:@{UIContentSizeCategoryNewValueKey: category}];
}

- (void)stopMockingPreferredContentSizeCategory {
    if (self.isSwizzled) {
        [UIApplication nbs_swizzle];
        [UIFont nbs_swizzle];
        [UITraitCollection nbs_swizzle];
        self.isSwizzled = NO;
    }
}

- (void)dealloc {
    [self stopMockingPreferredContentSizeCategory];
}

@end

@implementation UIFont (Swizzling)

+ (UIFont *)nbs_preferredFontForTextStyle:(UIFontTextStyle)style {
    UIContentSizeCategory category = UIApplication.sharedApplication.preferredContentSizeCategory;
    if (@available(iOS 10.0, tvOS 10.0, *)) {
        UITraitCollection *categoryTrait = [UITraitCollection traitCollectionWithPreferredContentSizeCategory:category];
        return [UIFont preferredFontForTextStyle:style compatibleWithTraitCollection:categoryTrait];
    } else {
        return [UIFont preferredFontForTextStyle:style];
    }
}

+ (void)nbs_swizzle {
    if (![UITraitCollection instancesRespondToSelector:@selector(preferredContentSizeCategory)]) {
        return;
    }

    SEL selector = @selector(preferredFontForTextStyle:);
    SEL replacedSelector = @selector(nbs_preferredFontForTextStyle:);

    Method originalMethod = class_getClassMethod(self, selector);
    Method extendedMethod = class_getClassMethod(self, replacedSelector);
    method_exchangeImplementations(originalMethod, extendedMethod);
}

@end

@implementation UIApplication (Swizzling)

- (UIContentSizeCategory)nbs_preferredContentSizeCategory {
    return objc_getAssociatedObject(self, @selector(nbs_preferredContentSizeCategory));
}

- (void)setNbs_preferredContentSizeCategory:(UIContentSizeCategory)category {
    objc_setAssociatedObject(self, @selector(nbs_preferredContentSizeCategory),
                             category, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

+ (void)nbs_swizzle {
    SEL selector = @selector(preferredContentSizeCategory);
    SEL replacedSelector = @selector(nbs_preferredContentSizeCategory);

    Method originalMethod = class_getInstanceMethod(self, selector);
    Method extendedMethod = class_getInstanceMethod(self, replacedSelector);
    method_exchangeImplementations(originalMethod, extendedMethod);
}

@end

@implementation UITraitCollection (Swizzling)

- (UIContentSizeCategory)nbs_preferredContentSizeCategory {
    return UIApplication.sharedApplication.preferredContentSizeCategory;
}

- (BOOL)nbs__changedContentSizeCategoryFromTraitCollection:(id)arg {
    return YES;
}

+ (void)nbs_swizzle {
    [self nbs_swizzlePreferredContentSizeCategory];
    [self nbs_swizzleChangedContentSizeCategoryFromTraitCollection];
}

+ (void)nbs_swizzlePreferredContentSizeCategory {
    SEL selector = @selector(preferredContentSizeCategory);

    if (![self instancesRespondToSelector:selector]) {
        return;
    }

    SEL replacedSelector = @selector(nbs_preferredContentSizeCategory);

    Method originalMethod = class_getInstanceMethod(self, selector);
    Method extendedMethod = class_getInstanceMethod(self, replacedSelector);
    method_exchangeImplementations(originalMethod, extendedMethod);
}

+ (void)nbs_swizzleChangedContentSizeCategoryFromTraitCollection {
    SEL selector = sel_registerName("_changedContentSizeCategoryFromTraitCollection:");

    if (![self instancesRespondToSelector:selector]) {
        return;
    }

    SEL replacedSelector = @selector(nbs__changedContentSizeCategoryFromTraitCollection:);

    Method originalMethod = class_getInstanceMethod(self, selector);
    Method extendedMethod = class_getInstanceMethod(self, replacedSelector);
    method_exchangeImplementations(originalMethod, extendedMethod);
}

@end