text:
'use strict';

const Audit = require('./audit.js');
const i18n = require('../lib/i18n/i18n.js');
const ComputedChains = require('../computed/critical-request-chains.js');

const UIStrings = {
  /** Imperative title of a Lighthouse audit that tells the user to reduce the depth of critical network requests to enhance initial load of a page. Critical request chains are series of dependent network requests that are important for page rendering. For example, here's a 4-request-deep chain: The biglogo.jpg image is required, but is requested via the styles.css style code, which is requested by the initialize.js javascript, which is requested by the page's HTML. This is displayed in a list of audit titles that Lighthouse generates. */
  title: 'Avoid chaining critical requests',
  /** Description of a Lighthouse audit that tells the user *why* they should reduce the depth of critical network requests to enhance initial load of a page . This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */
  description: 'The Critical Request Chains below show you what resources are ' +
      'loaded with a high priority. Consider reducing ' +
      'the length of chains, reducing the download size of resources, or ' +
      'deferring the download of unnecessary resources to improve page load. ' +
      '[Learn more](https://web.dev/critical-request-chains).',
  /** [ICU Syntax] Label for an audit identifying the number of sequences of dependent network requests used to load the page. */
  displayValue: `{itemCount, plural,
    =1 {1 chain found}
    other {# chains found}
    }`,
};

const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);

class CriticalRequestChains extends Audit {
  /**
   * @return {LH.Audit.Meta}
   */
  static get meta() {
    return {
      id: 'critical-request-chains',
      title: str_(UIStrings.title),
      description: str_(UIStrings.description),
      scoreDisplayMode: Audit.SCORING_MODES.INFORMATIVE,
      requiredArtifacts: ['devtoolsLogs', 'URL'],
    };
  }

  /** @typedef {{depth: number, id: string, chainDuration: number, chainTransferSize: number, node: LH.Audit.SimpleCriticalRequestNode[string]}} CrcNodeInfo */

  /**
   * @param {LH.Audit.SimpleCriticalRequestNode} tree
   * @param {function(CrcNodeInfo): void} cb
   */
  static _traverse(tree, cb) {
    /**
     * @param {LH.Audit.SimpleCriticalRequestNode} node
     * @param {number} depth
     * @param {number=} startTime
     * @param {number=} transferSize
     */
    function walk(node, depth, startTime, transferSize = 0) {
      const children = Object.keys(node);
      if (children.length === 0) {
        return;
      }
      children.forEach(id => {
        const child = node[id];
        if (!startTime) {
          startTime = child.request.startTime;
        }

        // Call the callback with the info for this child.
        cb({
          depth,
          id,
          node: child,
          chainDuration: (child.request.endTime - startTime) * 1000,
          chainTransferSize: (transferSize + child.request.transferSize),
        });

        // Carry on walking.
        if (child.children) {
          walk(child.children, depth + 1, startTime);
        }
      }, '');
    }

    walk(tree, 0);
  }

  /**
   * Get stats about the longest initiator chain (as determined by time duration)
   * @param {LH.Audit.SimpleCriticalRequestNode} tree
   * @return {{duration: number, length: number, transferSize: number}}
   */
  static _getLongestChain(tree) {
    const longest = {
      duration: 0,
      length: 0,
      transferSize: 0,
    };
    CriticalRequestChains._traverse(tree, opts => {
      const duration = opts.chainDuration;
      if (duration > longest.duration) {
        longest.duration = duration;
        longest.transferSize = opts.chainTransferSize;
        longest.length = opts.depth;
      }
    });
    // Always return the longest chain + 1 because the depth is zero indexed.
    longest.length++;
    return longest;
  }

  /**
   * @param {LH.Artifacts.CriticalRequestNode} tree
   * @return {LH.Audit.SimpleCriticalRequestNode}
   */
  static flattenRequests(tree) {
    /** @type {LH.Audit.SimpleCriticalRequestNode} */
    const flattendChains = {};
    /** @type {Map<string, LH.Audit.SimpleCriticalRequestNode[string]>} */
    const chainMap = new Map();

    /** @param {CrcNodeInfo} opts */
    function flatten(opts) {
      const request = opts.node.request;
      const simpleRequest = {
        url: request.url,
        startTime: request.startTime,
        endTime: request.endTime,
        responseReceivedTime: request.responseReceivedTime,
        transferSize: request.transferSize,
      };

      let chain = chainMap.get(opts.id);
      if (chain) {
        chain.request = simpleRequest;
      } else {
        chain = {
          request: simpleRequest,
        };
        flattendChains[opts.id] = chain;
      }

      if (opts.node.children) {
        for (const chainId of Object.keys(opts.node.children)) {
          // Note: cast should be Partial<>, but filled in when child node is traversed.
          const childChain = /** @type {LH.Audit.SimpleCriticalRequestNode[string]} */ ({
            request: {},
          });
          chainMap.set(chainId, childChain);
          if (!chain.children) {
            chain.children = {};
          }
          chain.children[chainId] = childChain;
        }
      }
      chainMap.set(opts.id, chain);
    }

    CriticalRequestChains._traverse(tree, flatten);

    return flattendChains;
  }

  /**
   * Audits the page to give a score for First Meaningful Paint.
   * @param {LH.Artifacts} artifacts The artifacts from the gather phase.
   * @param {LH.Audit.Context} context
   * @return {Promise<LH.Audit.Product>}
   */
  static audit(artifacts, context) {
    const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
    const URL = artifacts.URL;
    return ComputedChains.request({devtoolsLog, URL}, context).then(chains => {
      let chainCount = 0;
      /**
       * @param {LH.Audit.SimpleCriticalRequestNode} node
       * @param {number} depth
       */
      function walk(node, depth) {
        const childIds = Object.keys(node);

        childIds.forEach(id => {
          const child = node[id];
          if (child.children) {
            walk(child.children, depth + 1);
          } else {
            // if the node doesn't have a children field, then it is a leaf, so +1
            chainCount++;
          }
        }, '');
      }
      // Convert
      const flattenedChains = CriticalRequestChains.flattenRequests(chains);

      // Account for initial navigation
      const initialNavKey = Object.keys(flattenedChains)[0];
      const initialNavChildren = initialNavKey && flattenedChains[initialNavKey].children;
      if (initialNavChildren && Object.keys(initialNavChildren).length > 0) {
        walk(initialNavChildren, 0);
      }

      const longestChain = CriticalRequestChains._getLongestChain(flattenedChains);

      return {
        score: Number(chainCount === 0),
        notApplicable: chainCount === 0,
        displayValue: chainCount ? str_(UIStrings.displayValue, {itemCount: chainCount}) : '',
        extendedInfo: {
          value: {
            chains: flattenedChains,
            longestChain,
          },
        },
        details: {
          type: /** @type {'criticalrequestchain'} */('criticalrequestchain'),
          chains: flattenedChains,
          longestChain,
        },
      };
    });
  }
}

module.exports = CriticalRequestChains;
module.exports.UIStrings = UIStrings;


text:
package com.technoirarts.autumn.matcher;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

/**
 * @author Filinger
 * @author $Author$ (current maintainer)
 * @version $Revision$, $Date$
 * @since 1.0
 */
public class ThrownMatcher extends TypeSafeMatcher<Runnable> {

    private final String expected;
    private String actual;

    public ThrownMatcher(String s) {
        expected = s;
    }

    @Factory
    public static Matcher<Runnable> thrown(Class<? extends Throwable> expected) {
        return new ThrownMatcher(expected.getName());
    }

    @Override
    public boolean matchesSafely(Runnable action) {
        try {
            action.run();
            actual = "nothing";
            return false;
        } catch (Throwable t) {
            actual = t.getClass().getName();
            return actual.equals(expected);
        }
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("Should have thrown " + expected + " but threw " + actual);
    }
}

redpajama_set_name: RedPajamaGithub


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: Para que a primeira renderização aconteça o mais rápido possível, precisamos otimizar três variáveis: minimizar o número de recursos essenciais, minimizar o número de bytes essenciais e minimizar a extensão do caminho essencial.

{# wf_updated_on: 2014-04-27 #}
{# wf_published_on: 2014-03-31 #}

# Como otimizar o caminho de processamento essencial {: .page-title }

{% include "web/_shared/contributors/ilyagrigorik.html" %}

Para que a primeira renderização aconteça o mais rápido possível, precisamos otimizar três variáveis:

* **Minimizar o número de recursos essenciais.**
* **Minimizar o número de bytes essenciais.**
* ** Minimizar a extensão do caminho essencial.**

Um recurso essencial é qualquer recurso que possa bloquear a renderização inicial da página. Quanto menos recursos desse tipo houver na página, menos trabalho o navegador precisa fazer para exibir o conteúdo na tela, e menor é a contenção de CPU e outros recursos.

Da mesma forma, quanto menos bytes essenciais o navegador precisar fazer o download, mais rápido ele poderá começar a processar o conteúdo e exibi-lo na tela. Para reduzir o número de bytes, podemos reduzir o número de recursos (eliminá-los ou torná-los não essenciais) e também garantir a diminuição do tamanho da transferência por meio da compactação e otimização de cada recurso.

Finalmente, a extensão do caminho essencial é uma função do gráfico de dependência entre todos os recursos essenciais necessários para a página e seu número de bytes: o download de alguns recursos só pode ser iniciado uma vez que um recurso anterior é processado, e, quanto maior o recurso, mais idas e voltas serão necessárias para fazer o download.

Em outras palavras, o número de recursos, seu número de bytes e a extensão do caminho essencial estão relacionados uns aos outros, mas não são exatamente iguais. Por exemplo, pode não ser possível reduzir o número de recursos essenciais ou diminuir a extensão do caminho essencial, mas a redução do número de bytes essenciais ainda pode ser uma otimização importante — e vice-versa.

**A sequência geral de etapas para otimizar o caminho de processamento essencial é:**

1. Analisar e caracterizar seu caminho essencial: número de recursos, bytes, extensão.
2. Minimizar o número de recursos essenciais: eliminá-los, adiar seu download, marcá-los como assíncronos etc.
3. Otimizar a ordem em que os recursos essenciais restantes são carregados: é melhor fazer o download de todos os recursos essenciais o quanto antes para diminuir a extensão do caminho essencial.
4. Otimizar o número de bytes essenciais para reduzir o tempo de download (número de idas e voltas).


text:
from django.test import SimpleTestCase

from canary_endpoint.constants import ERROR
from canary_endpoint.mocks import MockTestCaseMixin, MockGitMixin
from canary_endpoint.resources.projects import GitProject

class GitProjectTestCase(MockTestCaseMixin, MockGitMixin, SimpleTestCase):
    def test_checks_status(self):
        self.mock_git_revision('f1o2o3\n')
        project = GitProject('foo', root='/foo', version='1.2.3')
        result = project.check()
        self.assertEqual(result, {
            'name': 'foo',
            'version': '1.2.3',
            'revision': 'f1o2o3',
        })
        command = ('git', 'rev-parse', 'HEAD')
        self.mock_git_output.assert_called_once_with(command, cwd='/foo')

    def test_reports_error_on_error(self):
        self.mock_git_error()
        project = GitProject('foo', root='/foo', version='1.2.3')
        result = project.check()
        self.assertEqual(result['status'], ERROR)
        self.assertEqual(result['revision'], None)
        self.assertEqual(
            result['error'],
            "Command 'foo' returned non-zero exit status 1"
        )

    def test_reports_error_on_git_not_found(self):
        self.mock_git_not_found()
        project = GitProject('foo', root='/foo', version='1.2.3')
        result = project.check()
        self.assertEqual(result['status'], ERROR)
        self.assertEqual(result['revision'], None)
        self.assertEqual(result['error'], 'command not found: git')


text:
//Author: Rok Kos<kosrok97@gmail.com>
//File: Grid.cs
//File path: /D/Documents/Unity/DragonHack2017/Grid.cs
//Date: 20.05.2017
//Description: Scipt that controls grid layout

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Grid : MonoBehaviour {
    Image image;

    private void Start () {
        image = GetComponent<Image>();
    }

    public IEnumerator fadeAnimacija () {
        int diff = -1;
        while (true) {

            if (image.color.a < 0.5 || image.color.a == 1.0) {
                diff *= -1;
            }

            image.color = new Color(image.color.r, image.color.g, image.color.b, image.color.a + diff * 0.05f);
            yield return null;
        }

    }
}


text:
<?php

namespace Subscribo\Omnipay\Shared\Widget;

use PHPUnit_Framework_TestCase;
use Subscribo\Omnipay\Shared\Widget\AbstractBasicWidget;
use Subscribo\Omnipay\Shared\Exception\WidgetInvalidRenderingParametersException;

class AbstractBasicWidgetTest extends PHPUnit_Framework_TestCase
{
    public function testRenderSuccess()
    {
        $widget = new ExtendedAbstractBasicWidgetForTesting();
        $text = 'This is widget';
        $widget->stringToRender = $text;
        $this->assertTrue($widget->isRenderable());
        $this->assertSame($text, $widget->render());
        $this->assertSame($text, (string) $widget);
    }

    public function testRenderNotRenderable()
    {
        $widget = new ExtendedAbstractBasicWidgetForTesting();
        $this->assertFalse($widget->isRenderable());
        $this->assertSame('', (string) $widget);
    }

    public function testRenderParameters()
    {
        $widget = new ExtendedAbstractBasicWidgetForTesting();
        $text = 'This is widget';
        $parameters = ['stringToRender' => $text];
        $this->assertTrue($widget->isRenderable($parameters));
        $this->assertSame($text, $widget->render($parameters));
        $this->assertSame('', (string) $widget);
    }

    /**
     * @expectedException \Subscribo\Omnipay\Shared\Exception\WidgetInvalidRenderingParametersException
     */
    public function testRenderFailure()
    {
        $widget = new ExtendedAbstractBasicWidgetForTesting();
        $widget->render();
    }

    public function testSimpleWidget()
    {
        $widget= new SimpleExtendedAbstractBasicWidgetForTesting(['someOption' => 'someValue']);
        $this->assertSame('Simple widget', (string) $widget);
        $this->assertTrue($widget->isRenderable());
        $this->assertSame('Simple widget', $widget->render());
        $this->assertSame([], $widget->getDefaultParameters());
        $this->assertSame([], $widget->getParameters());
        $this->assertSame($widget, $widget->initialize(['nonexistent' => 'some value']));
        $this->assertSame([], $widget->getParameters());
        $this->assertSame($widget, $widget->loadParameters(['nonexistent2' => 'some value2']));
        $this->assertSame([], $widget->getParameters());
    }

    public function testSettersAndGetters()
    {
        $widget = new WithParametersExtendedAbstractBasicWidgetForTesting();
        $defaults = $widget->getDefaultParameters();
        foreach($defaults as $key => $val) {
            $getter = 'get'.ucfirst($key);
            $setter = 'set'.ucfirst($key);
            $this->assertTrue(method_exists($widget, $getter), "Getter '".$getter."' does not exists for default parameter '".$key."'");
            $this->assertTrue(method_exists($widget, $setter), "Setter '".$setter."' does not exists for default parameter '".$key."'");
            $testValue = uniqid();
            $this->assertSame($widget, $widget->$setter($testValue), "Setter '".$setter."' does not have fluent interface'");
            $this->assertSame($testValue, $widget->$getter(), "Getter '".$getter."' does not return the same value as the one provided for setter '".$setter."'");
        }
    }

    public function testParametersEmptyConstruct()
    {
        $widget = new WithParametersExtendedAbstractBasicWidgetForTesting();
        $expectedDefaults = [
            'selection' => ['one', 'two', 'three'],
            'simpleParameter' => 'Some string',
        ];
        $expectedUnchanged = [
            'selection' => 'one',
            'simpleParameter' => 'Some string',
        ];
        $this->assertSame($expectedDefaults, $widget->getDefaultParameters());
        $this->assertSame($expectedUnchanged, $widget->getParameters());
        $this->assertNull($widget->getNonDefaultParameter());
        $this->assertSame($widget, $widget->setNonDefaultParameter('Some value'));
        $this->assertSame('Some value', $widget->getNonDefaultParameter());
        $expected = $expectedUnchanged;
        $expected['nonDefaultParameter'] = 'Some value';
        $this->assertSame($expectedDefaults, $widget->getDefaultParameters());
        $this->assertSame($expected, $widget->getParameters());
        $this->assertSame($widget, $widget->loadParameters(['simpleParameter' => 'Different string']));
        $expected['simpleParameter'] = 'Different string';
        $this->assertSame($expectedDefaults, $widget->getDefaultParameters());
        $this->assertSame($expected, $widget->getParameters());
        $this->assertSame($widget, $widget->initialize(['selection' => 'two']));
        // initialize resets parameters in defaults to defaults
        $expected = $expectedUnchanged;
        $expected['selection'] = 'two';
        $expected['nonDefaultParameter'] = 'Some value';
        $this->assertSame($expectedDefaults, $widget->getDefaultParameters());
        $this->assertSame($expected, $widget->getParameters());
        $this->assertSame('Some value', $widget->getNonDefaultParameter());
    }

    public function testParametersWithConstruct()
    {
        $parameters = [
            'nonDefaultParameter' => 5,
            'simpleParameter' => '',
        ];
        $widget = new WithParametersExtendedAbstractBasicWidgetForTesting($parameters);
        $expected = [
            'selection' => 'one',
            'simpleParameter' => '',
            'nonDefaultParameter' => 5,
        ];
        $this->assertSame($expected, $widget->getParameters());
        $this->assertSame('', $widget->getSimpleParameter());
        $this->assertSame(5, $widget->getNonDefaultParameter());
        $this->assertSame('one', $widget->getSelection());
        $this->assertSame($widget, $widget->setSimpleParameter(null));
        $this->assertNull($widget->getSimpleParameter());
        $expected['simpleParameter'] = null;
        $this->assertSame($expected, $widget->getParameters());
        $this->assertSame($widget, $widget->setNonDefaultParameter(null));
        $this->assertNull($widget->getNonDefaultParameter());
        $expected['nonDefaultParameter'] = null;
        $this->assertSame($expected, $widget->getParameters());
    }

    public function testSettersAndGettersSimple()
    {
        $widget = new SimpleExtendedAbstractBasicWidgetForTesting();
        $defaults = $widget->getDefaultParameters();
        foreach($defaults as $key => $val) {
            $getter = 'get'.ucfirst($key);
            $setter = 'set'.ucfirst($key);
            $this->assertTrue(method_exists($widget, $getter), "Getter '".$getter."' does not exists for default parameter '".$key."'");
            $this->assertTrue(method_exists($widget, $setter), "Setter '".$setter."' does not exists for default parameter '".$key."'");
            $testValue = uniqid();
            $this->assertSame($widget, $widget->$setter($testValue), "Setter '".$setter."' does not have fluent interface'");
            $this->assertSame($testValue, $widget->$getter(), "Getter '".$getter."' does not return the same value as the one provided for setter '".$setter."'");
        }
    }

}

class ExtendedAbstractBasicWidgetForTesting extends AbstractBasicWidget
{
    public $stringToRender;

    public function isRenderable($parameters = [])
    {
        if (isset($parameters['stringToRender'])) {
            return true;
        }
        return ! is_null($this->stringToRender);
    }

    public function render($parameters = [])
    {
        if (isset($parameters['stringToRender'])) {
            return $parameters['stringToRender'];
        }
        if (is_null($this->stringToRender)) {
            throw new WidgetInvalidRenderingParametersException('stringToRender not provided');
        }
        return $this->stringToRender;
    }
}

class SimpleExtendedAbstractBasicWidgetForTesting extends AbstractBasicWidget
{
    public function isRenderable($parameters = [])
    {
        return true;
    }

    public function render($parameters = [])
    {
        return 'Simple widget';
    }
}

class WithParametersExtendedAbstractBasicWidgetForTesting extends AbstractBasicWidget
{
    public function isRenderable($parameters = [])
    {
        return true;
    }

    public function render($parameters = [])
    {
        return 'Widget with parameters';
    }

    public function getDefaultParameters()
    {
        return [
            'selection' => ['one', 'two', 'three'],
            'simpleParameter' => 'Some string',
        ];
    }

    public function getSelection()
    {
        return $this->getParameter('selection');
    }

    public function setSelection($value)
    {
        return $this->setParameter('selection', $value);
    }

    public function getSimpleParameter()
    {
        return $this->getParameter('simpleParameter');
    }

    public function setSimpleParameter($value)
    {
        return $this->setParameter('simpleParameter', $value);
    }

    public function getNonDefaultParameter()
    {
        return $this->getParameter('nonDefaultParameter');
    }

    public function setNonDefaultParameter($value)
    {
        return $this->setParameter('nonDefaultParameter', $value);
    }
}


text:
.PHONY: help book clean serve

help:
	@echo "Please use 'make <target>' where <target> is one of:"
	@echo "  install     to install the necessary dependencies for jupyter-book to build"
	@echo "  book        to convert the content/ folder into Jekyll markdown in _build/"
	@echo "  clean       to clean out site build files"
	@echo "  runall      to run all notebooks in-place, capturing outputs with the notebook"
	@echo "  serve       to serve the repository locally with Jekyll"
	@echo "  build       to build the site HTML locally with Jekyll and store in _site/"

install:
	# Check to see whether bundler is already installed. If not, install it.
	if [ hash bundler 2>/dev/null ]; then \
	gem install bundler;\
	fi
	bundle install

book:
	jupyter-book build ./

runall:
	jupyter-book run ./content

clean:
	python scripts/clean.py

serve:
	bundle exec guard

build:
	bundle exec jekyll build
	touch _site/.nojekyll


text:
package com.brightgenerous.compress.zip.delegate;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.brightgenerous.compress.zip.ZipException;

@Deprecated
public class ZipUtility {

    private static final Logger log = Logger.getAnonymousLogger();

    public static final boolean USEFUL;

    private static final ZipDelegater delegater;

    private static final RuntimeException rex;

    static {
        ZipDelegater tmp = null;
        boolean useful = false;
        RuntimeException ex = null;
        try {
            tmp = new ZipDelegaterZip4j();
            useful = true;
        } catch (NoClassDefFoundError | RuntimeException e) {

            if (log.isLoggable(Level.INFO)) {
                log.log(Level.INFO, "does not resolve zip4j");
            }

            if (e instanceof RuntimeException) {
                Throwable th = e.getCause();
                if ((th == null) || !(th instanceof ClassNotFoundException)) {
                    throw e;
                }
                ex = (RuntimeException) e;
            } else {
                ex = new RuntimeException(e);
            }
        }
        USEFUL = useful;
        delegater = tmp;
        rex = ex;
    }

    private ZipUtility() {
    }

    private static ZipDelegater getDelegater() {
        if (delegater == null) {
            throw rex;
        }
        return delegater;
    }

    public static void addFile(File zip, File file) throws ZipException {
        getDelegater().addFile(zip, file);
    }

    public static void addFile(File zip, File file, String password) throws ZipException {
        getDelegater().addFile(zip, file, password);
    }

    public static void addFiles(File zip, List<File> files) throws ZipException {
        getDelegater().addFiles(zip, files);
    }

    public static void addFiles(File zip, List<File> files, String password) throws ZipException {
        getDelegater().addFiles(zip, files, password);
    }

    public static void addFile(File zip, InputStream inputStream, String fileNameInZip)
            throws ZipException {
        getDelegater().addFile(zip, inputStream, fileNameInZip);
    }

    public static void addFile(File zip, InputStream inputStream, String fileNameInZip,
            String password) throws ZipException {
        getDelegater().addFile(zip, inputStream, fileNameInZip, password);
    }

    public static void addFolder(File zip, File folder) throws ZipException {
        getDelegater().addFolder(zip, folder);
    }

    public static void addFolder(File zip, File folder, String password) throws ZipException {
        getDelegater().addFolder(zip, folder, password);
    }

    public static void extractAll(File zip, File dest) throws ZipException {
        getDelegater().extractAll(zip, dest);
    }

    public static void extractAll(File zip, File dest, String password) throws ZipException {
        getDelegater().extractAll(zip, dest, password);
    }

    public static void extract(File zip, String fileName, File dest) throws ZipException {
        getDelegater().extract(zip, fileName, dest);
    }

    public static void extract(File zip, String fileName, File dest, String password)
            throws ZipException {
        getDelegater().extract(zip, fileName, dest, password);
    }

    public static InputStream extract(File zip, String fileName) throws ZipException {
        return getDelegater().extract(zip, fileName);
    }

    public static InputStream extract(File zip, String fileName, String password)
            throws ZipException {
        return getDelegater().extract(zip, fileName, password);
    }

    public static void remove(File zip, String fileName) throws ZipException {
        getDelegater().remove(zip, fileName);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcContrib.PortableAreas;

namespace QuickLinks
{
    public class QuickLinksRegistration : PortableAreaRegistration
    {
        public override void RegisterArea(System.Web.Mvc.AreaRegistrationContext context, IApplicationBus bus)
        {
            context.MapRoute("ResourceRoute", "quicklinks/resource/{resourceName}",
                new { controller = "EmbeddedResource", action = "Index" },
                new string[] { "MvcContrib.PortableAreas" });

            context.MapRoute("ResourceImageRoute", "quicklinks/images/{resourceName}",
                new { controller = "EmbeddedResource", action = "Index", resourcePath = "images" },
                new string[] { "MvcContrib.PortableAreas" });

            context.MapRoute("quicklink", "quicklinks/{controller}/{action}",
			    new {controller = "links", action = "index"});

            this.RegisterAreaEmbeddedResources();
        }

        public override string AreaName
        {
            get
            {
                return "QuickLinks";
            }
        }
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CSGenerator.
// </auto-generated>
//------------------------------------------------------------------------------
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

using jsval = JSApi.jsval;

public class JSB_UnityEngine_AssetBundleRequest
{

////////////////////// AssetBundleRequest ///////////////////////////////////////
// constructors

static bool AssetBundleRequest_AssetBundleRequest1(JSVCall vc, int argc)
{
    int _this = JSApi.getObject((int)JSApi.GetType.Arg);
    JSApi.attachFinalizerObject(_this);
    --argc;

    int len = argc;
    if (len == 0)
    {
        JSMgr.addJSCSRel(_this, new UnityEngine.AssetBundleRequest());
    }

    return true;
}

// fields

// properties
static void AssetBundleRequest_asset(JSVCall vc)
{
        UnityEngine.AssetBundleRequest _this = (UnityEngine.AssetBundleRequest)vc.csObj;
        var result = _this.asset;
                JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
}
static void AssetBundleRequest_allAssets(JSVCall vc)
{
        UnityEngine.AssetBundleRequest _this = (UnityEngine.AssetBundleRequest)vc.csObj;
        var result = _this.allAssets;
                var arrRet = result;
        for (int i = 0; arrRet != null && i < arrRet.Length; i++)
        {
            JSMgr.datax.setObject((int)JSApi.SetType.SaveAndTempTrace, arrRet[i]);
            JSApi.moveSaveID2Arr(i);
        }
        JSApi.setArrayS((int)JSApi.SetType.Rval, (arrRet != null ? arrRet.Length : 0), true);
}

// methods

//register

public static void __Register()
{
    JSMgr.CallbackInfo ci = new JSMgr.CallbackInfo();
    ci.type = typeof(UnityEngine.AssetBundleRequest);
    ci.fields = new JSMgr.CSCallbackField[]
    {

    };
    ci.properties = new JSMgr.CSCallbackProperty[]
    {
        AssetBundleRequest_asset,
        AssetBundleRequest_allAssets,

    };
    ci.constructors = new JSMgr.MethodCallBackInfo[]
    {
        new JSMgr.MethodCallBackInfo(AssetBundleRequest_AssetBundleRequest1, ".ctor"),

    };
    ci.methods = new JSMgr.MethodCallBackInfo[]
    {

    };
    JSMgr.allCallbackInfo.Add(ci);
}

}


text:
from atom.mixins import AdminTestCaseMixin
from test_plus import TestCase

from poradnia.events.factories import EventFactory
from poradnia.events.models import Event
from poradnia.users.factories import UserFactory

class EventAdminTestCase(AdminTestCaseMixin, TestCase):
    user_factory_cls = UserFactory
    factory_cls = EventFactory
    model = Event


text:
<?php

namespace Drupal\search_api\Plugin\search_api\datasource;

use Drupal\Component\Utility\Html;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\ComplexDataInterface;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Drupal\field\FieldConfigInterface;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\search_api\Datasource\DatasourcePluginBase;
use Drupal\search_api\Entity\Index;
use Drupal\search_api\Plugin\PluginFormTrait;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Utility\FieldsHelperInterface;
use Drupal\search_api\Utility\Utility;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Represents a datasource which exposes the content entities.
 *
 * @SearchApiDatasource(
 *   id = "entity",
 *   deriver = "Drupal\search_api\Plugin\search_api\datasource\ContentEntityDeriver"
 * )
 */
class ContentEntity extends DatasourcePluginBase implements EntityDatasourceInterface, PluginFormInterface {

  use PluginFormTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface|null
   */
  protected $entityTypeManager;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface|null
   */
  protected $entityFieldManager;

  /**
   * The entity display repository manager.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface|null
   */
  protected $entityDisplayRepository;

  /**
   * The entity type bundle info.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface|null
   */
  protected $entityTypeBundleInfo;

  /**
   * The typed data manager.
   *
   * @var \Drupal\Core\TypedData\TypedDataManagerInterface|null
   */
  protected $typedDataManager;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface|null
   */
  protected $configFactory;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The fields helper.
   *
   * @var \Drupal\search_api\Utility\FieldsHelperInterface|null
   */
  protected $fieldsHelper;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition) {
    if (!empty($configuration['#index']) && $configuration['#index'] instanceof IndexInterface) {
      $this->setIndex($configuration['#index']);
      unset($configuration['#index']);
    }

    // Since defaultConfiguration() depends on the plugin definition, we need to
    // override the constructor and set the definition property before calling
    // that method.
    $this->pluginDefinition = $plugin_definition;
    $this->pluginId = $plugin_id;
    $this->configuration = $configuration + $this->defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    /** @var static $datasource */
    $datasource = parent::create($container, $configuration, $plugin_id, $plugin_definition);

    $datasource->setEntityTypeManager($container->get('entity_type.manager'));
    $datasource->setEntityFieldManager($container->get('entity_field.manager'));
    $datasource->setEntityDisplayRepository($container->get('entity_display.repository'));
    $datasource->setEntityTypeBundleInfo($container->get('entity_type.bundle.info'));
    $datasource->setTypedDataManager($container->get('typed_data_manager'));
    $datasource->setConfigFactory($container->get('config.factory'));
    $datasource->setLanguageManager($container->get('language_manager'));
    $datasource->setFieldsHelper($container->get('search_api.fields_helper'));

    return $datasource;
  }

  /**
   * Retrieves the entity type manager.
   *
   * @return \Drupal\Core\Entity\EntityTypeManagerInterface
   *   The entity type manager.
   */
  public function getEntityTypeManager() {
    return $this->entityTypeManager ?: \Drupal::entityTypeManager();
  }

  /**
   * Retrieves the entity storage.
   *
   * @return \Drupal\Core\Entity\EntityStorageInterface
   *   The entity storage.
   */
  protected function getEntityStorage() {
    return $this->getEntityTypeManager()->getStorage($this->getEntityTypeId());
  }

  /**
   * Returns the definition of this datasource's entity type.
   *
   * @return \Drupal\Core\Entity\EntityTypeInterface
   *   The entity type definition.
   */
  protected function getEntityType() {
    return $this->getEntityTypeManager()
      ->getDefinition($this->getEntityTypeId());
  }

  /**
   * Sets the entity type manager.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The new entity type manager.
   *
   * @return $this
   */
  public function setEntityTypeManager(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
    return $this;
  }

  /**
   * Retrieves the entity field manager.
   *
   * @return \Drupal\Core\Entity\EntityFieldManagerInterface
   *   The entity field manager.
   */
  public function getEntityFieldManager() {
    return $this->entityFieldManager ?: \Drupal::service('entity_field.manager');
  }

  /**
   * Sets the entity field manager.
   *
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The new entity field manager.
   *
   * @return $this
   */
  public function setEntityFieldManager(EntityFieldManagerInterface $entity_field_manager) {
    $this->entityFieldManager = $entity_field_manager;
    return $this;
  }

  /**
   * Retrieves the entity display repository.
   *
   * @return \Drupal\Core\Entity\EntityDisplayRepositoryInterface
   *   The entity entity display repository.
   */
  public function getEntityDisplayRepository() {
    return $this->entityDisplayRepository ?: \Drupal::service('entity_display.repository');
  }

  /**
   * Sets the entity display repository.
   *
   * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
   *   The new entity display repository.
   *
   * @return $this
   */
  public function setEntityDisplayRepository(EntityDisplayRepositoryInterface $entity_display_repository) {
    $this->entityDisplayRepository = $entity_display_repository;
    return $this;
  }

  /**
   * Retrieves the entity display repository.
   *
   * @return \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   *   The entity entity display repository.
   */
  public function getEntityTypeBundleInfo() {
    return $this->entityTypeBundleInfo ?: \Drupal::service('entity_type.bundle.info');
  }

  /**
   * Sets the entity type bundle info.
   *
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The new entity type bundle info.
   *
   * @return $this
   */
  public function setEntityTypeBundleInfo(EntityTypeBundleInfoInterface $entity_type_bundle_info) {
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    return $this;
  }

  /**
   * Retrieves the typed data manager.
   *
   * @return \Drupal\Core\TypedData\TypedDataManagerInterface
   *   The typed data manager.
   */
  public function getTypedDataManager() {
    return $this->typedDataManager ?: \Drupal::typedDataManager();
  }

  /**
   * Sets the typed data manager.
   *
   * @param \Drupal\Core\TypedData\TypedDataManagerInterface $typed_data_manager
   *   The new typed data manager.
   *
   * @return $this
   */
  public function setTypedDataManager(TypedDataManagerInterface $typed_data_manager) {
    $this->typedDataManager = $typed_data_manager;
    return $this;
  }

  /**
   * Retrieves the config factory.
   *
   * @return \Drupal\Core\Config\ConfigFactoryInterface
   *   The config factory.
   */
  public function getConfigFactory() {
    return $this->configFactory ?: \Drupal::configFactory();
  }

  /**
   * Retrieves the config value for a certain key in the Search API settings.
   *
   * @param string $key
   *   The key whose value should be retrieved.
   *
   * @return mixed
   *   The config value for the given key.
   */
  protected function getConfigValue($key) {
    return $this->getConfigFactory()->get('search_api.settings')->get($key);
  }

  /**
   * Sets the config factory.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The new config factory.
   *
   * @return $this
   */
  public function setConfigFactory(ConfigFactoryInterface $config_factory) {
    $this->configFactory = $config_factory;
    return $this;
  }

  /**
   * Retrieves the language manager.
   *
   * @return \Drupal\Core\Language\LanguageManagerInterface
   *   The language manager.
   */
  public function getLanguageManager() {
    return $this->languageManager ?: \Drupal::languageManager();
  }

  /**
   * Sets the language manager.
   *
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The new language manager.
   */
  public function setLanguageManager(LanguageManagerInterface $language_manager) {
    $this->languageManager = $language_manager;
  }

  /**
   * Retrieves the fields helper.
   *
   * @return \Drupal\search_api\Utility\FieldsHelperInterface
   *   The fields helper.
   */
  public function getFieldsHelper() {
    return $this->fieldsHelper ?: \Drupal::service('search_api.fields_helper');
  }

  /**
   * Sets the fields helper.
   *
   * @param \Drupal\search_api\Utility\FieldsHelperInterface $fields_helper
   *   The new fields helper.
   *
   * @return $this
   */
  public function setFieldsHelper(FieldsHelperInterface $fields_helper) {
    $this->fieldsHelper = $fields_helper;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getPropertyDefinitions() {
    $type = $this->getEntityTypeId();
    $properties = $this->getEntityFieldManager()->getBaseFieldDefinitions($type);
    if ($bundles = array_keys($this->getBundles())) {
      foreach ($bundles as $bundle_id) {
        $properties += $this->getEntityFieldManager()->getFieldDefinitions($type, $bundle_id);
      }
    }
    // Exclude properties with custom storage, since we can't extract them
    // currently, due to a shortcoming of Core's Typed Data API. See #2695527.
    // Computed properties should mostly be OK, though, even though they still
    // count as having "custom storage". The "Path" field from the Core module
    // does not work, though, so we explicitly exclude it here to avoid
    // confusion.
    foreach ($properties as $key => $property) {
      if (!$property->isComputed() || $key === 'path') {
        if ($property->getFieldStorageDefinition()->hasCustomStorage()) {
          unset($properties[$key]);
        }
      }
    }
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function loadMultiple(array $ids) {
    $allowed_languages = $this->getLanguages();
    // Always allow items with undefined language. (Can be the case when
    // entities are created programmatically.)
    $allowed_languages[LanguageInterface::LANGCODE_NOT_SPECIFIED] = TRUE;
    $allowed_languages[LanguageInterface::LANGCODE_NOT_APPLICABLE] = TRUE;

    $entity_ids = [];
    foreach ($ids as $item_id) {
      $pos = strrpos($item_id, ':');
      // This can only happen if someone passes an invalid ID, since we always
      // include a language code. Still, no harm in guarding against bad input.
      if ($pos === FALSE) {
        continue;
      }
      $entity_id = substr($item_id, 0, $pos);
      $langcode = substr($item_id, $pos + 1);
      if (isset($allowed_languages[$langcode])) {
        $entity_ids[$entity_id][$item_id] = $langcode;
      }
    }

    /** @var \Drupal\Core\Entity\ContentEntityInterface[] $entities */
    $entities = $this->getEntityStorage()->loadMultiple(array_keys($entity_ids));
    $items = [];
    $allowed_bundles = $this->getBundles();
    foreach ($entity_ids as $entity_id => $langcodes) {
      if (empty($entities[$entity_id]) || !isset($allowed_bundles[$entities[$entity_id]->bundle()])) {
        continue;
      }
      foreach ($langcodes as $item_id => $langcode) {
        if ($entities[$entity_id]->hasTranslation($langcode)) {
          $items[$item_id] = $entities[$entity_id]->getTranslation($langcode)->getTypedData();
        }
      }
    }

    return $items;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $default_configuration = [];

    if ($this->hasBundles()) {
      $default_configuration['bundles'] = [
        'default' => TRUE,
        'selected' => [],
      ];
    }

    if ($this->isTranslatable()) {
      $default_configuration['languages'] = [
        'default' => TRUE,
        'selected' => [],
      ];
    }

    return $default_configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    if ($this->hasBundles() && ($bundles = $this->getEntityBundleOptions())) {
      $form['bundles'] = [
        '#type' => 'details',
        '#title' => $this->t('Bundles'),
        '#open' => TRUE,
      ];
      $form['bundles']['default'] = [
        '#type' => 'radios',
        '#title' => $this->t('Which bundles should be indexed?'),
        '#options' => [
          1 => $this->t('All except those selected'),
          0 => $this->t('None except those selected'),
        ],
        '#default_value' => (int) $this->configuration['bundles']['default'],
      ];
      $form['bundles']['selected'] = [
        '#type' => 'checkboxes',
        '#title' => $this->t('Bundles'),
        '#options' => $bundles,
        '#default_value' => $this->configuration['bundles']['selected'],
        '#size' => min(4, count($bundles)),
        '#multiple' => TRUE,
      ];
    }

    if ($this->isTranslatable()) {
      $form['languages'] = [
        '#type' => 'details',
        '#title' => $this->t('Languages'),
        '#open' => TRUE,
      ];
      $form['languages']['default'] = [
        '#type' => 'radios',
        '#title' => $this->t('Which languages should be indexed?'),
        '#options' => [
          1 => $this->t('All except those selected'),
          0 => $this->t('None except those selected'),
        ],
        '#default_value' => (int) $this->configuration['languages']['default'],
      ];
      $form['languages']['selected'] = [
        '#type' => 'checkboxes',
        '#title' => $this->t('Languages'),
        '#options' => $this->getTranslationOptions(),
        '#default_value' => $this->configuration['languages']['selected'],
        '#multiple' => TRUE,
      ];
    }

    return $form;
  }

  /**
   * Retrieves the available bundles of this entity type as an options list.
   *
   * @return array
   *   An associative array of bundle labels, keyed by the bundle name.
   */
  protected function getEntityBundleOptions() {
    $options = [];
    if (($bundles = $this->getEntityBundles())) {
      foreach ($bundles as $bundle => $bundle_info) {
        $options[$bundle] = Html::escape($bundle_info['label']);
      }
    }
    return $options;
  }

  /**
   * Retrieves the available languages of this entity type as an options list.
   *
   * @return array
   *   An associative array of language labels, keyed by the language name.
   */
  protected function getTranslationOptions() {
    $options = [];
    foreach ($this->getLanguageManager()->getLanguages() as $language) {
      $options[$language->getId()] = $language->getName();
    }

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    // Filter out empty checkboxes.
    foreach (['bundles', 'languages'] as $key) {
      if ($form_state->hasValue($key)) {
        $parents = [$key, 'selected'];
        $value = $form_state->getValue($parents, []);
        $value = array_keys(array_filter($value));
        $form_state->setValue($parents, $value);
      }
    }

    $this->setConfiguration($form_state->getValues());
  }

  /**
   * Retrieves the entity from a search item.
   *
   * @param \Drupal\Core\TypedData\ComplexDataInterface $item
   *   An item of this datasource's type.
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   *   The entity object represented by that item, or NULL if none could be
   *   found.
   */
  protected function getEntity(ComplexDataInterface $item) {
    $value = $item->getValue();
    return $value instanceof EntityInterface ? $value : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getItemId(ComplexDataInterface $item) {
    if ($entity = $this->getEntity($item)) {
      $enabled_bundles = $this->getBundles();
      if (isset($enabled_bundles[$entity->bundle()])) {
        return $entity->id() . ':' . $entity->language()->getId();
      }
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getItemLabel(ComplexDataInterface $item) {
    if ($entity = $this->getEntity($item)) {
      return $entity->label();
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getItemBundle(ComplexDataInterface $item) {
    if ($entity = $this->getEntity($item)) {
      return $entity->bundle();
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getItemUrl(ComplexDataInterface $item) {
    if ($entity = $this->getEntity($item)) {
      if ($entity->hasLinkTemplate('canonical')) {
        return $entity->toUrl('canonical');
      }
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function checkItemAccess(ComplexDataInterface $item, AccountInterface $account = NULL) {
    if ($entity = $this->getEntity($item)) {
      return $this->getEntityTypeManager()
        ->getAccessControlHandler($this->getEntityTypeId())
        ->access($entity, 'view', $account);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getItemIds($page = NULL) {
    return $this->getPartialItemIds($page);
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityTypeId() {
    $plugin_definition = $this->getPluginDefinition();
    return $plugin_definition['entity_type'];
  }

  /**
   * Determines whether the entity type supports bundles.
   *
   * @return bool
   *   TRUE if the entity type supports bundles, FALSE otherwise.
   */
  protected function hasBundles() {
    return $this->getEntityType()->hasKey('bundle');
  }

  /**
   * Determines whether the entity type supports translations.
   *
   * @return bool
   *   TRUE if the entity is translatable, FALSE otherwise.
   */
  protected function isTranslatable() {
    return $this->getEntityType()->isTranslatable();
  }

  /**
   * Retrieves all bundles of this datasource's entity type.
   *
   * @return array
   *   An associative array of bundle infos, keyed by the bundle names.
   */
  protected function getEntityBundles() {
    return $this->hasBundles() ? $this->getEntityTypeBundleInfo()->getBundleInfo($this->getEntityTypeId()) : [];
  }

  /**
   * {@inheritdoc}
   */
  public function getPartialItemIds($page = NULL, array $bundles = NULL, array $languages = NULL) {
    // These would be pretty pointless calls, but for the sake of completeness
    // we should check for them and return early. (Otherwise makes the rest of
    // the code more complicated.)
    if (($bundles === [] && !$languages) || ($languages === [] && !$bundles)) {
      return NULL;
    }

    $select = $this->getEntityTypeManager()
      ->getStorage($this->getEntityTypeId())
      ->getQuery();

    // We want to determine all entities of either one of the given bundles OR
    // one of the given languages. That means we can't just filter for $bundles
    // if $languages is given. Instead, we have to filter for all bundles we
    // might want to include and later sort out those for which we want only the
    // translations in $languages and those (matching $bundles) where we want
    // all (enabled) translations.
    if ($this->hasBundles()) {
      $bundle_property = $this->getEntityType()->getKey('bundle');
      if ($bundles && !$languages) {
        $select->condition($bundle_property, $bundles, 'IN');
      }
      else {
        $enabled_bundles = array_keys($this->getBundles());
        // Since this is also called for removed bundles/languages,
        // $enabled_bundles might not include $bundles.
        if ($bundles) {
          $enabled_bundles = array_unique(array_merge($bundles, $enabled_bundles));
        }
        if (count($enabled_bundles) < count($this->getEntityBundles())) {
          $select->condition($bundle_property, $enabled_bundles, 'IN');
        }
      }
    }

    if (isset($page)) {
      $page_size = $this->getConfigValue('tracking_page_size');
      assert('$page_size', 'Tracking page size is not set.');
      $select->range($page * $page_size, $page_size);
      // For paging to reliably work, a sort should be present.
      $entity_id = $this->getEntityType()->getKey('id');
      $select->sort($entity_id);
    }

    $entity_ids = $select->execute();

    if (!$entity_ids) {
      return NULL;
    }

    // For all loaded entities, compute all their item IDs (one for each
    // translation we want to include). For those matching the given bundles (if
    // any), we want to include translations for all enabled languages. For all
    // other entities, we just want to include the translations for the
    // languages passed to the method (if any).
    $item_ids = [];
    $enabled_languages = array_keys($this->getLanguages());
    // As above for bundles, $enabled_languages might not include $languages.
    if ($languages) {
      $enabled_languages = array_unique(array_merge($languages, $enabled_languages));
    }
    // Also, we want to always include entities with unknown language.
    $enabled_languages[] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
    $enabled_languages[] = LanguageInterface::LANGCODE_NOT_APPLICABLE;

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    foreach ($this->getEntityStorage()->loadMultiple($entity_ids) as $entity_id => $entity) {
      $translations = array_keys($entity->getTranslationLanguages());
      $translations = array_intersect($translations, $enabled_languages);
      // If only languages were specified, keep only those translations matching
      // them. If bundles were also specified, keep all (enabled) translations
      // for those entities that match those bundles.
      if ($languages !== NULL
          && (!$bundles || !in_array($entity->bundle(), $bundles))) {
        $translations = array_intersect($translations, $languages);
      }
      foreach ($translations as $langcode) {
        $item_ids[] = "$entity_id:$langcode";
      }
    }

    return $item_ids;
  }

  /**
   * {@inheritdoc}
   */
  public function getBundles() {
    if (!$this->hasBundles()) {
      // For entity types that have no bundle, return a default pseudo-bundle.
      return [$this->getEntityTypeId() => $this->label()];
    }

    $configuration = $this->getConfiguration();

    // If "default" is TRUE (that is, "All except those selected"),remove all
    // the selected bundles from the available ones to compute the indexed
    // bundles. Otherwise, return all the selected bundles.
    $bundles = [];
    $entity_bundles = $this->getEntityBundles();
    $selected_bundles = array_flip($configuration['bundles']['selected']);
    $function = $configuration['bundles']['default'] ? 'array_diff_key' : 'array_intersect_key';
    $entity_bundles = $function($entity_bundles, $selected_bundles);
    foreach ($entity_bundles as $bundle_id => $bundle_info) {
      $bundles[$bundle_id] = isset($bundle_info['label']) ? $bundle_info['label'] : $bundle_id;
    }
    return $bundles ?: [$this->getEntityTypeId() => $this->label()];
  }

  /**
   * Retrieves the enabled languages.
   *
   * @return \Drupal\Core\Language\LanguageInterface[]
   *   All languages that are enabled for this datasource, keyed by language
   *   code.
   */
  protected function getLanguages() {
    $all_languages = $this->getLanguageManager()->getLanguages();

    if ($this->isTranslatable()) {
      $selected_languages = array_flip($this->configuration['languages']['selected']);
      if ($this->configuration['languages']['default']) {
        return array_diff_key($all_languages, $selected_languages);
      }
      else {
        return array_intersect_key($all_languages, $selected_languages);
      }
    }

    return $all_languages;
  }

  /**
   * {@inheritdoc}
   */
  public function getViewModes($bundle = NULL) {
    if (isset($bundle) && $this->hasBundles()) {
      return $this->getEntityDisplayRepository()->getViewModeOptionsByBundle($this->getEntityTypeId(), $bundle);
    }
    else {
      return $this->getEntityDisplayRepository()->getViewModeOptions($this->getEntityTypeId());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function viewItem(ComplexDataInterface $item, $view_mode, $langcode = NULL) {
    try {
      if ($entity = $this->getEntity($item)) {
        $langcode = $langcode ?: $entity->language()->getId();
        return $this->getEntityTypeManager()->getViewBuilder($this->getEntityTypeId())->view($entity, $view_mode, $langcode);
      }
    }
    catch (\Exception $e) {
      // The most common reason for this would be a
      // \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException in
      // getViewBuilder(), because the entity type definition doesn't specify a
      // view_builder class.
    }
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function viewMultipleItems(array $items, $view_mode, $langcode = NULL) {
    try {
      $view_builder = $this->getEntityTypeManager()->getViewBuilder($this->getEntityTypeId());
      // Langcode passed, use that for viewing.
      if (isset($langcode)) {
        $entities = [];
        foreach ($items as $i => $item) {
          if ($entity = $this->getEntity($item)) {
            $entities[$i] = $entity;
          }
        }
        if ($entities) {
          return $view_builder->viewMultiple($entities, $view_mode, $langcode);
        }
        return [];
      }
      // Otherwise, separate the items by language, keeping the keys.
      $items_by_language = [];
      foreach ($items as $i => $item) {
        if ($item instanceof EntityInterface) {
          $items_by_language[$item->language()->getId()][$i] = $item;
        }
      }
      // Then build the items for each language. We initialize $build beforehand
      // and use array_replace() to add to it so the order stays the same.
      $build = array_fill_keys(array_keys($items), []);
      foreach ($items_by_language as $langcode => $language_items) {
        $build = array_replace($build, $view_builder->viewMultiple($language_items, $view_mode, $langcode));
      }
      return $build;
    }
    catch (\Exception $e) {
      // The most common reason for this would be a
      // \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException in
      // getViewBuilder(), because the entity type definition doesn't specify a
      // view_builder class.
      return [];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $this->dependencies = parent::calculateDependencies();

    $this->addDependency('module', $this->getEntityType()->getProvider());

    return $this->dependencies;
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldDependencies(array $fields) {
    $dependencies = [];
    $properties = $this->getPropertyDefinitions();

    foreach ($fields as $field_id => $property_path) {
      $dependencies[$field_id] = $this->getPropertyPathDependencies($property_path, $properties);
    }

    return $dependencies;
  }

  /**
   * Computes all dependencies of the given property path.
   *
   * @param string $property_path
   *   The property path of the property.
   * @param \Drupal\Core\TypedData\DataDefinitionInterface[] $properties
   *   The properties which form the basis for the property path.
   *
   * @return string[][]
   *   An associative array with the dependencies for the given property path,
   *   mapping dependency types to arrays of dependency names.
   */
  protected function getPropertyPathDependencies($property_path, array $properties) {
    $dependencies = [];

    list($key, $nested_path) = Utility::splitPropertyPath($property_path, FALSE);
    if (!isset($properties[$key])) {
      return $dependencies;
    }

    $property = $properties[$key];
    if ($property instanceof FieldConfigInterface) {
      $storage = $property->getFieldStorageDefinition();
      if ($storage instanceof FieldStorageConfigInterface) {
        $name = $storage->getConfigDependencyName();
        $dependencies[$storage->getConfigDependencyKey()][$name] = $name;
      }
    }

    $property = $this->getFieldsHelper()->getInnerProperty($property);

    if ($property instanceof EntityDataDefinitionInterface) {
      $entity_type_definition = $this->getEntityTypeManager()
        ->getDefinition($property->getEntityTypeId());
      if ($entity_type_definition) {
        $module = $entity_type_definition->getProvider();
        $dependencies['module'][$module] = $module;
      }
    }

    if (isset($nested_path) && $property instanceof ComplexDataDefinitionInterface) {
      $nested = $this->getFieldsHelper()->getNestedProperties($property);
      $nested_dependencies = $this->getPropertyPathDependencies($nested_path, $nested);
      foreach ($nested_dependencies as $type => $names) {
        $dependencies += [$type => []];
        $dependencies[$type] += $names;
      }
    }

    return array_map('array_values', $dependencies);
  }

  /**
   * {@inheritdoc}
   */
  public static function getIndexesForEntity(ContentEntityInterface $entity) {
    $datasource_id = 'entity:' . $entity->getEntityTypeId();
    $entity_bundle = $entity->bundle();
    $has_bundles = $entity->getEntityType()->hasKey('bundle');

    // Needed for PhpStorm. See https://youtrack.jetbrains.com/issue/WI-23395.
    /** @var \Drupal\search_api\IndexInterface[] $indexes */
    $indexes = Index::loadMultiple();

    foreach ($indexes as $index_id => $index) {
      // Filter our indexes that don't contain the datasource in question.
      if (!$index->isValidDatasource($datasource_id)) {
        unset($indexes[$index_id]);
      }
      elseif ($has_bundles) {
        // If the entity type supports bundles, we also have to filter out
        // indexes that exclude the entity's bundle.
        $config = $index->getDatasource($datasource_id)->getConfiguration();
        $default = !empty($config['bundles']['default']);
        $bundle_set = in_array($entity_bundle, $config['bundles']['selected']);
        if ($default == $bundle_set) {
          unset($indexes[$index_id]);
        }
      }
    }

    return $indexes;
  }

  /**
   * Filters a set of datasource-specific item IDs.
   *
   * Returns only those item IDs that are valid for the given datasource and
   * index. This method only checks the item language, though – whether an
   * entity with that ID actually exists, or whether it has a bundle included
   * for that datasource, is not verified.
   *
   * @param \Drupal\search_api\IndexInterface $index
   *   The index for which to validate.
   * @param string $datasource_id
   *   The ID of the datasource on the index for which to validate.
   * @param string[] $item_ids
   *   The item IDs to be validated.
   *
   * @return string[]
   *   All given item IDs that are valid for that index and datasource.
   */
  public static function filterValidItemIds(IndexInterface $index, $datasource_id, array $item_ids) {
    if (!$index->isValidDatasource($datasource_id)) {
      return $item_ids;
    }
    $config = $index->getDatasource($datasource_id)->getConfiguration();
    // If the entity type doesn't allow translations, we just accept all IDs.
    // (If the entity type were translatable, the config key would have been set
    // with the default configuration.)
    if (!isset($config['languages']['selected'])) {
      return $item_ids;
    }
    $default = !empty($config['languages']['default']);
    $selected = $config['languages']['selected'];
    $always_valid = [
      LanguageInterface::LANGCODE_NOT_SPECIFIED,
      LanguageInterface::LANGCODE_NOT_APPLICABLE,
    ];
    $valid_ids = [];
    foreach ($item_ids as $item_id) {
      $pos = strrpos($item_id, ':');
      // Item IDs without colons are always invalid.
      if ($pos === FALSE) {
        continue;
      }
      $langcode = substr($item_id, $pos + 1);
      if ($default != in_array($langcode, $selected)
          || in_array($langcode, $always_valid)) {
        $valid_ids[] = $item_id;
      }
    }
    return $valid_ids;
  }

}


text:
#include "fsl_flexio_uart_edma.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/* Component ID definition, used by tools. */
#ifndef FSL_COMPONENT_ID
#define FSL_COMPONENT_ID "platform.drivers.flexio_uart_edma"
#endif

/*<! Structure definition for uart_edma_private_handle_t. The structure is private. */
typedef struct _flexio_uart_edma_private_handle
{
    FLEXIO_UART_Type *base;
    flexio_uart_edma_handle_t *handle;
} flexio_uart_edma_private_handle_t;

/* UART EDMA transfer handle. */
enum _flexio_uart_edma_tansfer_states
{
    kFLEXIO_UART_TxIdle, /* TX idle. */
    kFLEXIO_UART_TxBusy, /* TX busy. */
    kFLEXIO_UART_RxIdle, /* RX idle. */
    kFLEXIO_UART_RxBusy  /* RX busy. */
};

/*******************************************************************************
 * Variables
 ******************************************************************************/

/*< @brief user configurable flexio uart handle count. */
#define FLEXIO_UART_HANDLE_COUNT 2

/*<! Private handle only used for internally. */
static flexio_uart_edma_private_handle_t s_edmaPrivateHandle[FLEXIO_UART_HANDLE_COUNT];

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*!
 * @brief FLEXIO UART EDMA send finished callback function.
 *
 * This function is called when FLEXIO UART EDMA send finished. It disables the UART
 * TX EDMA request and sends @ref kStatus_FLEXIO_UART_TxIdle to FLEXIO UART callback.
 *
 * @param handle The EDMA handle.
 * @param param Callback function parameter.
 */
static void FLEXIO_UART_TransferSendEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds);

/*!
 * @brief FLEXIO UART EDMA receive finished callback function.
 *
 * This function is called when FLEXIO UART EDMA receive finished. It disables the UART
 * RX EDMA request and sends @ref kStatus_FLEXIO_UART_RxIdle to UART callback.
 *
 * @param handle The EDMA handle.
 * @param param Callback function parameter.
 */
static void FLEXIO_UART_TransferReceiveEDMACallback(edma_handle_t *handle,
                                                    void *param,
                                                    bool transferDone,
                                                    uint32_t tcds);

/*******************************************************************************
 * Code
 ******************************************************************************/

static void FLEXIO_UART_TransferSendEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds)
{
    flexio_uart_edma_private_handle_t *uartPrivateHandle = (flexio_uart_edma_private_handle_t *)param;

    assert(uartPrivateHandle->handle != NULL);

    /* Avoid the warning for unused variables. */
    handle = handle;
    tcds   = tcds;

    if (transferDone)
    {
        FLEXIO_UART_TransferAbortSendEDMA(uartPrivateHandle->base, uartPrivateHandle->handle);

        if (uartPrivateHandle->handle->callback != NULL)
        {
            uartPrivateHandle->handle->callback(uartPrivateHandle->base, uartPrivateHandle->handle,
                                                kStatus_FLEXIO_UART_TxIdle, uartPrivateHandle->handle->userData);
        }
    }
}

static void FLEXIO_UART_TransferReceiveEDMACallback(edma_handle_t *handle,
                                                    void *param,
                                                    bool transferDone,
                                                    uint32_t tcds)
{
    flexio_uart_edma_private_handle_t *uartPrivateHandle = (flexio_uart_edma_private_handle_t *)param;

    assert(uartPrivateHandle->handle != NULL);

    /* Avoid the warning for unused variables. */
    handle = handle;
    tcds   = tcds;

    if (transferDone)
    {
        /* Disable transfer. */
        FLEXIO_UART_TransferAbortReceiveEDMA(uartPrivateHandle->base, uartPrivateHandle->handle);

        if (uartPrivateHandle->handle->callback != NULL)
        {
            uartPrivateHandle->handle->callback(uartPrivateHandle->base, uartPrivateHandle->handle,
                                                kStatus_FLEXIO_UART_RxIdle, uartPrivateHandle->handle->userData);
        }
    }
}

/*!
 * brief Initializes the UART handle which is used in transactional functions.
 *
 * param base Pointer to FLEXIO_UART_Type.
 * param handle Pointer to flexio_uart_edma_handle_t structure.
 * param callback The callback function.
 * param userData The parameter of the callback function.
 * param rxEdmaHandle User requested DMA handle for RX DMA transfer.
 * param txEdmaHandle User requested DMA handle for TX DMA transfer.
 * retval kStatus_Success Successfully create the handle.
 * retval kStatus_OutOfRange The FlexIO SPI eDMA type/handle table out of range.
 */
status_t FLEXIO_UART_TransferCreateHandleEDMA(FLEXIO_UART_Type *base,
                                              flexio_uart_edma_handle_t *handle,
                                              flexio_uart_edma_transfer_callback_t callback,
                                              void *userData,
                                              edma_handle_t *txEdmaHandle,
                                              edma_handle_t *rxEdmaHandle)
{
    assert(handle != NULL);

    uint8_t index = 0U;

    /* Find the an empty handle pointer to store the handle. */
    for (index = 0U; index < (uint8_t)FLEXIO_UART_HANDLE_COUNT; index++)
    {
        if (s_edmaPrivateHandle[index].base == NULL)
        {
            s_edmaPrivateHandle[index].base   = base;
            s_edmaPrivateHandle[index].handle = handle;
            break;
        }
    }

    if (index == (uint8_t)FLEXIO_UART_HANDLE_COUNT)
    {
        return kStatus_OutOfRange;
    }

    (void)memset(handle, 0, sizeof(*handle));

    handle->rxState = (uint8_t)kFLEXIO_UART_RxIdle;
    handle->txState = (uint8_t)kFLEXIO_UART_TxIdle;

    handle->rxEdmaHandle = rxEdmaHandle;
    handle->txEdmaHandle = txEdmaHandle;

    handle->callback = callback;
    handle->userData = userData;

    /* Configure TX. */
    if (txEdmaHandle != NULL)
    {
        EDMA_SetCallback(handle->txEdmaHandle, FLEXIO_UART_TransferSendEDMACallback, &s_edmaPrivateHandle);
    }

    /* Configure RX. */
    if (rxEdmaHandle != NULL)
    {
        EDMA_SetCallback(handle->rxEdmaHandle, FLEXIO_UART_TransferReceiveEDMACallback, &s_edmaPrivateHandle);
    }

    return kStatus_Success;
}

/*!
 * brief Sends data using eDMA.
 *
 * This function sends data using eDMA. This is a non-blocking function, which returns
 * right away. When all data is sent out, the send callback function is called.
 *
 * param base Pointer to FLEXIO_UART_Type
 * param handle UART handle pointer.
 * param xfer UART eDMA transfer structure, see #flexio_uart_transfer_t.
 * retval kStatus_Success if succeed, others failed.
 * retval kStatus_FLEXIO_UART_TxBusy Previous transfer on going.
 */
status_t FLEXIO_UART_TransferSendEDMA(FLEXIO_UART_Type *base,
                                      flexio_uart_edma_handle_t *handle,
                                      flexio_uart_transfer_t *xfer)
{
    assert(handle->txEdmaHandle != NULL);

    edma_transfer_config_t xferConfig;
    status_t status;

    /* Return error if xfer invalid. */
    if ((0U == xfer->dataSize) || (NULL == xfer->data))
    {
        return kStatus_InvalidArgument;
    }

    /* If previous TX not finished. */
    if ((uint8_t)kFLEXIO_UART_TxBusy == handle->txState)
    {
        status = kStatus_FLEXIO_UART_TxBusy;
    }
    else
    {
        handle->txState       = (uint8_t)kFLEXIO_UART_TxBusy;
        handle->txDataSizeAll = xfer->dataSize;

        /* Prepare transfer. */
        EDMA_PrepareTransfer(&xferConfig, xfer->data, sizeof(uint8_t),
                             (uint32_t *)FLEXIO_UART_GetTxDataRegisterAddress(base), sizeof(uint8_t), sizeof(uint8_t),
                             xfer->dataSize, kEDMA_MemoryToPeripheral);

        /* Store the initially configured eDMA minor byte transfer count into the FLEXIO UART handle */
        handle->nbytes = 1U;

        /* Submit transfer. */
        (void)EDMA_SubmitTransfer(handle->txEdmaHandle, &xferConfig);
        EDMA_StartTransfer(handle->txEdmaHandle);

        /* Enable UART TX EDMA. */
        FLEXIO_UART_EnableTxDMA(base, true);

        status = kStatus_Success;
    }

    return status;
}

/*!
 * brief Receives data using eDMA.
 *
 * This function receives data using eDMA. This is a non-blocking function, which returns
 * right away. When all data is received, the receive callback function is called.
 *
 * param base Pointer to FLEXIO_UART_Type
 * param handle Pointer to flexio_uart_edma_handle_t structure
 * param xfer UART eDMA transfer structure, see #flexio_uart_transfer_t.
 * retval kStatus_Success if succeed, others failed.
 * retval kStatus_UART_RxBusy Previous transfer on going.
 */
status_t FLEXIO_UART_TransferReceiveEDMA(FLEXIO_UART_Type *base,
                                         flexio_uart_edma_handle_t *handle,
                                         flexio_uart_transfer_t *xfer)
{
    assert(handle->rxEdmaHandle != NULL);

    edma_transfer_config_t xferConfig;
    status_t status;

    /* Return error if xfer invalid. */
    if ((0U == xfer->dataSize) || (NULL == xfer->data))
    {
        return kStatus_InvalidArgument;
    }

    /* If previous RX not finished. */
    if ((uint8_t)kFLEXIO_UART_RxBusy == handle->rxState)
    {
        status = kStatus_FLEXIO_UART_RxBusy;
    }
    else
    {
        handle->rxState       = (uint8_t)kFLEXIO_UART_RxBusy;
        handle->rxDataSizeAll = xfer->dataSize;

        /* Prepare transfer. */
        EDMA_PrepareTransfer(&xferConfig, (uint32_t *)FLEXIO_UART_GetRxDataRegisterAddress(base), sizeof(uint8_t),
                             xfer->data, sizeof(uint8_t), sizeof(uint8_t), xfer->dataSize, kEDMA_PeripheralToMemory);

        /* Store the initially configured eDMA minor byte transfer count into the FLEXIO UART handle */
        handle->nbytes = (uint8_t)sizeof(uint8_t);

        /* Submit transfer. */
        (void)EDMA_SubmitTransfer(handle->rxEdmaHandle, &xferConfig);
        EDMA_StartTransfer(handle->rxEdmaHandle);

        /* Enable UART RX EDMA. */
        FLEXIO_UART_EnableRxDMA(base, true);

        status = kStatus_Success;
    }

    return status;
}

/*!
 * brief Aborts the sent data which using eDMA.
 *
 * This function aborts sent data which using eDMA.
 *
 * param base Pointer to FLEXIO_UART_Type
 * param handle Pointer to flexio_uart_edma_handle_t structure
 */
void FLEXIO_UART_TransferAbortSendEDMA(FLEXIO_UART_Type *base, flexio_uart_edma_handle_t *handle)
{
    assert(handle->txEdmaHandle != NULL);

    /* Disable UART TX EDMA. */
    FLEXIO_UART_EnableTxDMA(base, false);

    /* Stop transfer. */
    EDMA_StopTransfer(handle->txEdmaHandle);

    handle->txState = (uint8_t)kFLEXIO_UART_TxIdle;
}

/*!
 * brief Aborts the receive data which using eDMA.
 *
 * This function aborts the receive data which using eDMA.
 *
 * param base Pointer to FLEXIO_UART_Type
 * param handle Pointer to flexio_uart_edma_handle_t structure
 */
void FLEXIO_UART_TransferAbortReceiveEDMA(FLEXIO_UART_Type *base, flexio_uart_edma_handle_t *handle)
{
    assert(handle->rxEdmaHandle != NULL);

    /* Disable UART RX EDMA. */
    FLEXIO_UART_EnableRxDMA(base, false);

    /* Stop transfer. */
    EDMA_StopTransfer(handle->rxEdmaHandle);

    handle->rxState = (uint8_t)kFLEXIO_UART_RxIdle;
}

/*!
 * brief Gets the number of bytes received.
 *
 * This function gets the number of bytes received.
 *
 * param base Pointer to FLEXIO_UART_Type
 * param handle Pointer to flexio_uart_edma_handle_t structure
 * param count Number of bytes received so far by the non-blocking transaction.
 * retval kStatus_NoTransferInProgress transfer has finished or no transfer in progress.
 * retval kStatus_Success Successfully return the count.
 */
status_t FLEXIO_UART_TransferGetReceiveCountEDMA(FLEXIO_UART_Type *base,
                                                 flexio_uart_edma_handle_t *handle,
                                                 size_t *count)
{
    assert(handle != NULL);
    assert(handle->rxEdmaHandle != NULL);
    assert(count != NULL);

    if ((uint8_t)kFLEXIO_UART_RxIdle == handle->rxState)
    {
        return kStatus_NoTransferInProgress;
    }

    *count = handle->rxDataSizeAll -
             (uint32_t)handle->nbytes *
                 EDMA_GetRemainingMajorLoopCount(handle->rxEdmaHandle->base, handle->rxEdmaHandle->channel);

    return kStatus_Success;
}

/*!
 * brief Gets the number of bytes sent out.
 *
 * This function gets the number of bytes sent out.
 *
 * param base Pointer to FLEXIO_UART_Type
 * param handle Pointer to flexio_uart_edma_handle_t structure
 * param count Number of bytes sent so far by the non-blocking transaction.
 * retval kStatus_NoTransferInProgress transfer has finished or no transfer in progress.
 * retval kStatus_Success Successfully return the count.
 */
status_t FLEXIO_UART_TransferGetSendCountEDMA(FLEXIO_UART_Type *base, flexio_uart_edma_handle_t *handle, size_t *count)
{
    assert(handle != NULL);
    assert(handle->txEdmaHandle != NULL);
    assert(count != NULL);

    if ((uint8_t)kFLEXIO_UART_TxIdle == handle->txState)
    {
        return kStatus_NoTransferInProgress;
    }

    *count = handle->txDataSizeAll -
             (uint32_t)handle->nbytes *
                 EDMA_GetRemainingMajorLoopCount(handle->txEdmaHandle->base, handle->txEdmaHandle->channel);

    return kStatus_Success;
}


text:
require 'twitter'
require 'tweetstream'
require 'rufus/scheduler'

module Ebooks
  class Bot
    attr_accessor :consumer_key, :consumer_secret,
                  :oauth_token, :oauth_token_secret

    attr_accessor :username

    attr_reader :twitter, :stream

    @@all = [] # List of all defined bots
    def self.all; @@all; end

    def self.get(name)
      all.find { |bot| bot.username == name }
    end

    def initialize(username, &b)
      # Set defaults
      @username = username

      # Override with callback
      b.call(self)

      Bot.all.push(self)
    end

    def log(*args)
      STDOUT.puts "@#{@username}: " + args.map(&:to_s).join(' ')
      STDOUT.flush
    end

    def configure
      TweetStream.configure do |config|
        config.consumer_key = @consumer_key
        config.consumer_secret = @consumer_secret
        config.oauth_token = @oauth_token
        config.oauth_token_secret = @oauth_token_secret
      end

      Twitter.configure do |config|
        config.consumer_key = @consumer_key
        config.consumer_secret = @consumer_secret
        config.oauth_token = @oauth_token
        config.oauth_token_secret = @oauth_token_secret
      end

      needs_stream = [@on_follow, @on_message, @on_mention, @on_timeline].any? {|e| !e.nil?}

      @twitter = Twitter::Client.new
      @stream = TweetStream::Client.new if needs_stream
    end

    # Connects to tweetstream and opens event handlers for this bot
    def start
      configure

      @on_startup.call if @on_startup

      if not @stream
        log "not bothering with stream for #@username"
        return
      end

      log "starting stream for #@username"
      @stream.on_error do |msg|
        log "ERROR: #{msg}"
      end

      @stream.on_inited do
        log "Online!"
      end

      @stream.on_event(:follow) do |event|
        next if event[:source][:screen_name] == @username
        log "Followed by #{event[:source][:screen_name]}"
        @on_follow.call(event[:source]) if @on_follow
      end

      @stream.on_direct_message do |dm|
        next if dm[:sender][:screen_name] == @username # Don't reply to self
        log "DM from @#{dm[:sender][:screen_name]}: #{dm[:text]}"
        @on_message.call(dm) if @on_message
      end

      @stream.userstream do |ev|
        next unless ev[:text] # If it's not a text-containing tweet, ignore it
        next if ev[:user][:screen_name] == @username # Ignore our own tweets

        meta = {}
        mentions = ev.attrs[:entities][:user_mentions].map { |x| x[:screen_name] }

        reply_mentions = mentions.reject { |m| m.downcase == @username.downcase }
        reply_mentions = [ev[:user][:screen_name]] + reply_mentions

        meta[:reply_prefix] = reply_mentions.uniq.map { |m| '@'+m }.join(' ') + ' '
        meta[:limit] = 140 - meta[:reply_prefix].length

        mless = ev[:text]
        begin
          ev.attrs[:entities][:user_mentions].reverse.each do |entity|
            last = mless[entity[:indices][1]..-1]||''
            mless = mless[0...entity[:indices][0]] + last.strip
          end
        rescue Exception
          p ev.attrs[:entities][:user_mentions]
          p ev[:text]
          raise
        end
        meta[:mentionless] = mless

        # To check if this is a mention, ensure:
        # - The tweet mentions list contains our username
        # - The tweet is not being retweeted by somebody else
        # - Or soft-retweeted by somebody else
        if mentions.map(&:downcase).include?(@username.downcase) && !ev[:retweeted_status] && !ev[:text].start_with?('RT ')
          log "Mention from @#{ev[:user][:screen_name]}: #{ev[:text]}"
          @on_mention.call(ev, meta) if @on_mention
        else
          @on_timeline.call(ev, meta) if @on_timeline
        end
      end
    end

    # Wrapper for EM.add_timer
    # Delays add a greater sense of humanity to bot behaviour
    def delay(time, &b)
      time = time.to_a.sample unless time.is_a? Integer
      EM.add_timer(time, &b)
    end

    # Reply to a tweet or a DM.
    # Applies configurable @reply_delay range
    def reply(ev, text, opts={})
      opts = opts.clone

      if ev.is_a? Twitter::DirectMessage
        log "Sending DM to @#{ev[:sender][:screen_name]}: #{text}"
        @twitter.direct_message_create(ev[:sender][:screen_name], text, opts)
      elsif ev.is_a? Twitter::Tweet
        log "Replying to @#{ev[:user][:screen_name]} with: #{text}"
        @twitter.update(text, in_reply_to_status_id: ev[:id])
      else
        raise Exception("Don't know how to reply to a #{ev.class}")
      end
    end

    def scheduler
      @scheduler ||= Rufus::Scheduler.new
    end

    def follow(*args)
      log "Following #{args}"
      @twitter.follow(*args)
    end

    def tweet(*args)
      log "Tweeting #{args.inspect}"
      @twitter.update(*args)
    end

    def on_startup(&b); @on_startup = b; end
    def on_follow(&b); @on_follow = b; end
    def on_mention(&b); @on_mention = b; end
    def on_timeline(&b); @on_timeline = b; end
    def on_message(&b); @on_message = b; end
  end
end