text:
package org.projog.core.kb;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.projog.TermFactory.atom;
import static org.projog.TermFactory.structure;
import static org.projog.TermFactory.variable;

import java.util.List;

import org.junit.Test;
import org.projog.TestUtils;
import org.projog.core.event.ProjogListeners;
import org.projog.core.event.SpyPoints;
import org.projog.core.io.FileHandles;
import org.projog.core.math.ArithmeticOperators;
import org.projog.core.parser.Operands;
import org.projog.core.predicate.PredicateKey;
import org.projog.core.term.Term;
import org.projog.core.term.TermFormatter;

public class KnowledgeBaseUtilsTest {
   private final KnowledgeBase kb = TestUtils.createKnowledgeBase();

   @Test
   public void testConjunctionPredicateName() {
      assertEquals(",", KnowledgeBaseUtils.CONJUNCTION_PREDICATE_NAME);
   }

   @Test
   public void testImplicationPredicateName() {
      assertEquals(":-", KnowledgeBaseUtils.IMPLICATION_PREDICATE_NAME);
   }

   @Test
   public void testQuestionPredicateName() {
      assertEquals("?-", KnowledgeBaseUtils.QUESTION_PREDICATE_NAME);
   }

   @Test
   public void testGetPredicateKeysByName() {
      String predicateName = "testGetPredicateKeysByName";

      assertTrue(KnowledgeBaseUtils.getPredicateKeysByName(kb, predicateName).isEmpty());

      PredicateKey input[] = {new PredicateKey(predicateName, 0), new PredicateKey(predicateName, 1), new PredicateKey(predicateName, 2), new PredicateKey(predicateName, 3)};

      for (PredicateKey key : input) {
         kb.getPredicates().createOrReturnUserDefinedPredicate(key);
         // add entries with a different name to the name we are calling getPredicateKeysByName with
         // to check that the method isn't just returning ALL keys
         PredicateKey keyWithDifferentName = new PredicateKey(predicateName + "X", key.getNumArgs());
         kb.getPredicates().createOrReturnUserDefinedPredicate(keyWithDifferentName);
      }

      List<PredicateKey> output = KnowledgeBaseUtils.getPredicateKeysByName(kb, predicateName);
      assertEquals(input.length, output.size());
      for (PredicateKey key : input) {
         assertTrue(output.contains(key));
      }
   }

   @Test
   public void testIsQuestionOrDirectiveFunctionCall() {
      assertTrue(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(structure("?-", atom())));
      assertTrue(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(structure("?-", structure("=", atom(), atom()))));
      assertTrue(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(structure(":-", atom())));
      assertTrue(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(structure(":-", structure("=", atom(), atom()))));

      assertFalse(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(atom("?-")));
      assertFalse(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(structure("?-", atom(), atom())));
      assertFalse(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(atom(":-")));
      assertFalse(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(structure(":-", atom(), atom())));
      assertFalse(KnowledgeBaseUtils.isQuestionOrDirectiveFunctionCall(structure(">=", atom())));
   }

   @Test
   public void testIsConjuction() {
      assertFalse(KnowledgeBaseUtils.isConjunction(TestUtils.parseSentence("true.")));
      assertTrue(KnowledgeBaseUtils.isConjunction(TestUtils.parseSentence("true, true.")));
      assertTrue(KnowledgeBaseUtils.isConjunction(TestUtils.parseSentence("true, true, true.")));
      assertTrue(KnowledgeBaseUtils.isConjunction(TestUtils.parseSentence("repeat(3), X<1, write(V), nl, true, !, fail.")));
   }

   @Test
   public void testIsSingleAnswer_NonRetryablePredicate() {
      // test single term representing a predicate that is not repeatable
      assertTrue(KnowledgeBaseUtils.isSingleAnswer(kb, atom("true")));
   }

   @Test
   public void testIsSingleAnswer_RetryablePredicate() {
      // test single term representing a predicate that *is* repeatable
      assertFalse(KnowledgeBaseUtils.isSingleAnswer(kb, atom("repeat")));
   }

   @Test
   public void testIsSingleAnswer_NonRetryableConjuction() {
      // test conjunction of terms that are all not repeatable
      Term conjuctionOfNonRepeatableTerms = TestUtils.parseSentence("write(X), nl, true, X<1.");
      assertTrue(KnowledgeBaseUtils.isSingleAnswer(kb, conjuctionOfNonRepeatableTerms));
   }

   @Test
   public void testIsSingleAnswer_RetryableConjuction() {
      // test conjunction of terms where one is repeatable
      Term conjuctionIncludingRepeatableTerm = TestUtils.parseSentence("write(X), nl, repeat, true, X<1.");
      assertFalse(KnowledgeBaseUtils.isSingleAnswer(kb, conjuctionIncludingRepeatableTerm));
   }

   @Test
   public void testIsSingleAnswer_Disjunction() {
      // test disjunction
      // (Note that the disjunction used in the test *would* only give a single answer
      // but KnowledgeBaseUtils.isSingleAnswer is not currently smart enough to spot this)
      Term disjunctionOfTerms = TestUtils.parseSentence("true ; fail.");
      assertFalse(KnowledgeBaseUtils.isSingleAnswer(kb, disjunctionOfTerms));
   }

   @Test
   public void testIsSingleAnswer_Variable() {
      assertFalse(KnowledgeBaseUtils.isSingleAnswer(kb, variable()));
   }

   @Test
   public void testToArrayOfConjunctions() {
      Term t = TestUtils.parseSentence("a, b(1,2,3), c.");
      Term[] conjunctions = KnowledgeBaseUtils.toArrayOfConjunctions(t);
      assertEquals(3, conjunctions.length);
      assertSame(t.getArgument(0).getArgument(0), conjunctions[0]);
      assertSame(t.getArgument(0).getArgument(1), conjunctions[1]);
      assertSame(t.getArgument(1), conjunctions[2]);
   }

   @Test
   public void testToArrayOfConjunctionsNoneConjunctionArgument() {
      Term t = TestUtils.parseSentence("a(b(1,2,3), c).");
      Term[] conjunctions = KnowledgeBaseUtils.toArrayOfConjunctions(t);
      assertEquals(1, conjunctions.length);
      assertSame(t, conjunctions[0]);
   }

   @Test
   public void testGetProjogListeners() {
      KnowledgeBase kb1 = TestUtils.createKnowledgeBase();
      KnowledgeBase kb2 = TestUtils.createKnowledgeBase();
      ProjogListeners o1 = kb1.getProjogListeners();
      ProjogListeners o2 = kb2.getProjogListeners();
      assertNotNull(o1);
      assertNotNull(o2);
      assertNotSame(o1, o2);
      assertSame(o1, kb1.getProjogListeners());
      assertSame(o2, kb2.getProjogListeners());
   }

   @Test
   public void testGetProjogProperties() {
      KnowledgeBase kb1 = TestUtils.createKnowledgeBase();
      KnowledgeBase kb2 = TestUtils.createKnowledgeBase();
      ProjogProperties o1 = kb1.getProjogProperties();
      ProjogProperties o2 = kb2.getProjogProperties();
      assertNotNull(o1);
      assertNotNull(o2);
      assertNotSame(o1, o2);
      assertSame(o1, kb1.getProjogProperties());
      assertSame(o2, kb2.getProjogProperties());
   }

   @Test
   public void testGetOperands() {
      KnowledgeBase kb1 = TestUtils.createKnowledgeBase();
      KnowledgeBase kb2 = TestUtils.createKnowledgeBase();
      Operands o1 = kb1.getOperands();
      Operands o2 = kb2.getOperands();
      assertNotNull(o1);
      assertNotNull(o2);
      assertNotSame(o1, o2);
      assertSame(o1, kb1.getOperands());
      assertSame(o2, kb2.getOperands());
   }

   @Test
   public void testGetTermFormatter() {
      KnowledgeBase kb1 = TestUtils.createKnowledgeBase();
      KnowledgeBase kb2 = TestUtils.createKnowledgeBase();
      TermFormatter o1 = kb1.getTermFormatter();
      TermFormatter o2 = kb2.getTermFormatter();
      assertNotNull(o1);
      assertNotNull(o2);
      assertNotSame(o1, o2);
      assertSame(o1, kb1.getTermFormatter());
      assertSame(o2, kb2.getTermFormatter());
   }

   @Test
   public void testGetSpyPoints() {
      KnowledgeBase kb1 = TestUtils.createKnowledgeBase();
      KnowledgeBase kb2 = TestUtils.createKnowledgeBase();
      SpyPoints o1 = kb1.getSpyPoints();
      SpyPoints o2 = kb2.getSpyPoints();
      assertNotNull(o1);
      assertNotNull(o2);
      assertNotSame(o1, o2);
      assertSame(o1, kb1.getSpyPoints());
      assertSame(o2, kb2.getSpyPoints());
   }

   @Test
   public void testGetFileHandles() {
      KnowledgeBase kb1 = TestUtils.createKnowledgeBase();
      KnowledgeBase kb2 = TestUtils.createKnowledgeBase();
      FileHandles o1 = kb1.getFileHandles();
      FileHandles o2 = kb2.getFileHandles();
      assertNotNull(o1);
      assertNotNull(o2);
      assertNotSame(o1, o2);
      assertSame(o1, kb1.getFileHandles());
      assertSame(o2, kb2.getFileHandles());
   }

   @Test
   public void testArithmeticOperators() {
      KnowledgeBase kb1 = TestUtils.createKnowledgeBase();
      KnowledgeBase kb2 = TestUtils.createKnowledgeBase();
      ArithmeticOperators o1 = kb1.getArithmeticOperators();
      ArithmeticOperators o2 = kb2.getArithmeticOperators();
      assertNotNull(o1);
      assertNotNull(o2);
      assertNotSame(o1, o2);
      assertSame(o1, kb1.getArithmeticOperators());
      assertSame(o2, kb2.getArithmeticOperators());
   }
}


text:
{% extends "../layout_search.html" %}

{% block page_title %}
Careers Service - Skills match results
{% endblock %}

{% block content %}

		{% include "../includes/phase_banner_alpha.html" %}
		{% include "../includes/breadcrumb_plum_match.html" %}

Skills check results:
 Plumber

It looks like you have the skills to become a plumber.

You have:

customer care skills

practical skills

problem solving skills

technical drawing skills

You can now go on to build a skills profile.

A profile shows the skills you have, how you've gained them and gives examples of when you've used them to achieve something.

You can use it to help you:

build a CV

 write an application for a job or an apprenticeship

prepare for an interview

prepare to meet a careers adviser

Skills you nearly have

You nearly have:

time management

team working

					It's great that you're already working towards these skills. Gaining these skills may help you to get
					this job.

Skills you don't have yet

You don't have but could get:

methodical and logical approach

health and safety

Think about how you could learn these skills. You could do:

college courses

distance or online learning

volunteering

traineeship

mentoring or job shadowing

					Choose the method that suits your preferred learning style the best.

					If you're employed, ask your employer if there are any learning or training opportunities that could
					help you.

					If you're not working, check with the Jobcentre and local learning providers for opportunities.

					You can go back to the job profile for plumber to find information about courses and training.

Create a skills profile

Now you've done the skills check, you can create a skills profile or contact our careers advisers for help.

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
<?php

defined('PHPFOX') or exit('NO DICE!');

?>
{if !empty($aGroup.image_path)}
<div class="t_center" style="margin-bottom:10px;">
	{img thickbox=true server_id=$aGroup.server_id title=$aGroup.title path='group.url_image' file=$aGroup.image_path suffix='_200' max_width='200' max_height='200'}
</div>
{/if}


text:
package org.ovirt.engine.core.common.businessentities;

import java.util.HashMap;

public enum VDSNiceType {
    RHEL(0),
    RHEVH(2);

    private int intValue;
    private static java.util.HashMap<Integer, VDSNiceType> mappings = new HashMap<Integer, VDSNiceType>();

    static {
        for (VDSNiceType type : values()) {
            mappings.put(type.getValue(), type);
        }
    }

    private VDSNiceType(int value) {
        intValue = value;
    }

    public int getValue() {
        return intValue;
    }

    public static VDSNiceType forValue(int value) {
        return mappings.get(value);
    }
}


text:
#include <FreeRTOS.h>
#include <semphr.h>

#include <bl_uart.h>
#include <hosal_uart.h>

#include <board.h>

extern hosal_uart_dev_t uart_stdio;

#if CONFIG_ENABLE_CHIP_SHELL || PW_RPC_ENABLED

#define CHIP_UART_RX_TIMER_ID 1
#define MAX_BUFFER_SIZE 256

typedef struct _chipUart
{
    SemaphoreHandle_t sema;
    StaticSemaphore_t mutx;
    uint32_t head;
    uint32_t tail;
    uint8_t rxbuf[MAX_BUFFER_SIZE];
} chipUart_t;

static chipUart_t chipUart_var;

static int uartTxCallback(void * p_arg)
{
    hosal_uart_ioctl(&uart_stdio, HOSAL_UART_TX_TRIGGER_OFF, NULL);

    return 0;
}

static int uartRxCallback(void * p_arg)
{
    uint32_t len = 0, readlen = 0;
    BaseType_t xHigherPriorityTaskWoken = 1;

    if (chipUart_var.head >= chipUart_var.tail)
    {
        if (chipUart_var.head < MAX_BUFFER_SIZE)
        {
            readlen = len =
                hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, MAX_BUFFER_SIZE - chipUart_var.head);
            chipUart_var.head = (chipUart_var.head + len) % MAX_BUFFER_SIZE;
        }

        if (0 == chipUart_var.head)
        {
            len = hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf, chipUart_var.tail - 1);
            chipUart_var.head += len;
            readlen += len;
        }
    }
    else
    {
        readlen =
            hosal_uart_receive(&uart_stdio, chipUart_var.rxbuf + chipUart_var.head, chipUart_var.tail - chipUart_var.head - 1);
        chipUart_var.head += readlen;
    }

    if (0 == readlen || (chipUart_var.head + 1) % MAX_BUFFER_SIZE == chipUart_var.tail)
    {
        xSemaphoreGiveFromISR(chipUart_var.sema, &xHigherPriorityTaskWoken);
    }

    return 0;
}

void uartInit(void)
{
    memset(&chipUart_var, 0, offsetof(chipUart_t, rxbuf));

    chipUart_var.sema = xSemaphoreCreateBinaryStatic(&chipUart_var.mutx);

    hosal_uart_finalize(&uart_stdio);
    hosal_uart_init(&uart_stdio);
    hosal_uart_callback_set(&uart_stdio, HOSAL_UART_RX_CALLBACK, uartRxCallback, NULL);
    hosal_uart_callback_set(&uart_stdio, HOSAL_UART_TX_CALLBACK, uartTxCallback, NULL);
    hosal_uart_ioctl(&uart_stdio, HOSAL_UART_MODE_SET, (void *) HOSAL_UART_MODE_INT);
}

int16_t uartRead(char * Buf, uint16_t NbBytesToRead)
{
    int16_t len = 0;

    xSemaphoreTake(chipUart_var.sema, portMAX_DELAY);

    taskENTER_CRITICAL();

    for (len = 0; len < NbBytesToRead && chipUart_var.head != chipUart_var.tail; len++)
    {
        Buf[len]          = chipUart_var.rxbuf[chipUart_var.tail];
        chipUart_var.tail = (chipUart_var.tail + 1) % MAX_BUFFER_SIZE;
    }

    taskEXIT_CRITICAL();

    if (chipUart_var.head != chipUart_var.tail)
    {
        xSemaphoreGive(chipUart_var.sema);
    }

    return len;
}
#endif

int16_t uartWrite(const char * Buf, uint16_t BufLength)
{
    return hosal_uart_send(&uart_stdio, Buf, BufLength);
}


text:
package org.apache.kylin.measure.topn;

import org.apache.kylin.common.util.ByteArray;
import org.apache.kylin.measure.MeasureAggregator;

/**
 *
 */
@SuppressWarnings("serial")
public class TopNAggregator extends MeasureAggregator<TopNCounter<ByteArray>> {

    int capacity = 0;
    TopNCounter<ByteArray> sum = null;

    @Override
    public void reset() {
        sum = null;
    }

    @Override
    public void aggregate(TopNCounter<ByteArray> value) {
        if (sum == null) {
            capacity = value.getCapacity();
            sum = new TopNCounter<>(capacity * 10);
        }
        sum.merge(value);
    }

    @Override
    public TopNCounter<ByteArray> aggregate(TopNCounter<ByteArray> value1, TopNCounter<ByteArray> value2) {
        int thisCapacity = value1.getCapacity();
        TopNCounter<ByteArray> aggregated = new TopNCounter<>(thisCapacity * 2);
        aggregated.merge(value1);
        aggregated.merge(value2);
        aggregated.retain(thisCapacity);
        return aggregated;
    }

    @Override
    public TopNCounter<ByteArray> getState() {
        sum.retain(capacity);
        return sum;
    }

    @Override
    public int getMemBytesEstimate() {
        return 8 * capacity / 4;
    }

    public TopNAggregator copy() {
        TopNAggregator result = new TopNAggregator();
        result.capacity = this.capacity;
        TopNCounter<ByteArray> cpCounter = sum.copy();
        result.sum = cpCounter;
        return result;
    }

}


text:
[![DOI](https://zenodo.org/badge/63707930.svg)](https://zenodo.org/badge/latestdoi/63707930)

##### Overview
EDLib is a C++ template finite temperature Exact diagonalization solver for quantum electron models.
The central class of the library is `Hamiltonian<Storage, Model>`, that is parametrized by Storage and Model:

- There exists a following set of implementation of models for common purposes:
    - `HubbardModel<precision>`. The finite Hubbard model cluster.
    - `SingleImpurityAndersonModel<precision>`. The single multi-orbital impurity Anderson Model.

- For the Hamiltonian matrix storage there are three implementation of sparse matrix storages:
    - `SpinResolvedStorage<Model>`. A storage that takes into account the case when hopping Hamiltonian
    can be expressed as Kronecker sum for each spin. This storage is implemented with *MPI* support.
    - `SOCRSStorage<Model>`. A storage that store only fermion signs for each element in Hamiltonian.
    This storage is implemented with *OpenMP* support.
    - `CRSStorage<Model>`. A simple CRS storage.

The resluting eigenpairs are stored as a set of `EigenPair<precision, SymmetrySectorType>` structures in
the Hamiltonian object.

The following observable can be computed by means of Lanczos continuous fraction
(`Lanczos<Hamiltonian, Mesh, MeshArguments...>` class template) of the Lehmann representation:
- Single-particle Green's function (`GreensFunction<Hamiltonian, Mesh, MeshArguments...>` class template).
- Spin suseptibility (`ChiLoc<Hamiltonian, Mash, MeshArguments...>` class template).
Greens functions are implemented on top of *ALPSCore* Greens functions module and can use either positive
Matsubara frequency mesh or Real frequency mesh.

Look for examples in the "examples/" directory for a detailed information.

##### Installation ###
The code is is provided as a header-only library with a set of examples and tests.
At least the `edlib/Hamiltonian.h` should be included in any derivative projects.
To compile examples and tests create a build directory and run

1. `cmake -DARPACK_DIR=<path to ARPACK-ng library dir> -DExamples=ON -DTesting=ON {path_to_edlib}`
2. `make`
3. `make test` (for running tests)
4. example will be build in examples subdirectory

To build with MPI support add `-DUSE_MPI=ON` *CMake* flag. *MPI* library should be installed and *ALPSCore*
library should be compiled with *MPI* support. To build with a specific *ALPSCore* library
`-DALPSCore_DIR=<path to ALPSCore>` *CMake* flag. Since the critical for current library implementation
MPI-related *ARPACK-ng* bug was recenlty fixed it is stricly recommended to use the latest version
of *ARPACK-ng* from github repository.

##### Dependencies
- c++11-compatible compiler (tested with clang >= 3.1, gcc >= 4.8.2, icpc >= 14.0.2)
- *ALPSCore* library >= 0.5.6-alpha3
- *arpack-ng* >= 3.5.0
- *MPI* standard >= 2.1 (optional)
- *git* to fetch the code
- *cmake* to build tests and examples (optional)

##### Authors
- Sergei Iskakov, *iskakoff[at]q-solvers.ru*, 2016-now
- Michael Danilov, 2016-now

##### Distribution
Open-source under MIT License.


text:
using Grpc.Core;
using Issue;

namespace FunctionalTestsWebsite.Services;

public class IssueService : Issue.IssueService.IssueServiceBase
{
    public override Task<GetLibraryResponse> GetLibrary(GetLibraryRequest request, ServerCallContext context)
    {
        GetLibraryResponse response = new GetLibraryResponse();
        response.UserId = request.UserId;
        response.SearchTerm = request.SearchTerm;
        response.Carriers.AddRange(request.Carriers);

        return Task.FromResult(response);
    }
}


text:
import Link from 'next/link'
import { FaPencilAlt } from 'react-icons/fa'
import { MdLock, MdOutlineEmail } from 'react-icons/md'
import DefaultLayout from '../../components/DefaultLayout'
import PageContainer from '../../components/PageContainer'
import Avatar from '../../components/Avatar'
import Loader from '../../components/Loader'
import { useUser } from '../../utils'

export default function Page () {
  const { user } = useUser({ redirectTo: '/login' })

  if (!user) return <DefaultLayout><Loader /></DefaultLayout>

  return (
    <DefaultLayout title={`Settings for ${user.name}`}>
      <PageContainer>

Settings

            <Avatar uuid={user.id} height='96' width='96' />

{user.name}

            {!user.hasAccount &&
              <Link href='/register' passHref>

                    <FaPencilAlt className='mx-auto block w-5 h-5 text-lg' />

Register

              </Link>}
            {user.hasAccount &&
              <Link href='/account/email' passHref>

                    <MdOutlineEmail className='mx-auto block w-5 h-5 text-lg' />

Email

              </Link>}
            {user.hasAccount &&
              <Link href='/account/password' passHref>

                    <MdLock className='mx-auto block w-5 h-5 text-lg' />

Password

              </Link>}

      </PageContainer>
    </DefaultLayout>
  )
}


text:
<?php

namespace AppBundle\Controller\Admin\Crud;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Entity\OrderStatusLabel;
use AppBundle\Form\OrderStatusLabelType;

/**
 * OrderStatusLabel controller.
 *
 * @Route("/admin/orderstatuslabel")
 */
class OrderStatusLabelController extends Controller
{
    /**
     * Lists all OrderStatusLabel entities.
     *
     * @Route("/", name="admin_orderstatuslabel_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $orderStatusLabels = $em->getRepository('AppBundle:OrderStatusLabel')->findAll();

        return $this->render('admin/crud/orderstatuslabel/index.html.twig', array(
            'orderStatusLabels' => $orderStatusLabels,
        ));
    }

    /**
     * Creates a new OrderStatusLabel entity.
     *
     * @Route("/new", name="admin_orderstatuslabel_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $orderStatusLabel = new OrderStatusLabel();
        $form = $this->createForm('AppBundle\Form\OrderStatusLabelType', $orderStatusLabel);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($orderStatusLabel);
            $em->flush();

            return $this->redirectToRoute('admin_orderstatuslabel_show', array('id' => $orderStatusLabel->getId()));
        }

        return $this->render('admin/crud/orderstatuslabel/new.html.twig', array(
            'orderStatusLabel' => $orderStatusLabel,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a OrderStatusLabel entity.
     *
     * @Route("/{id}", name="admin_orderstatuslabel_show")
     * @Method("GET")
     */
    public function showAction(OrderStatusLabel $orderStatusLabel)
    {
        $deleteForm = $this->createDeleteForm($orderStatusLabel);

        return $this->render('admin/crud/orderstatuslabel/show.html.twig', array(
            'orderStatusLabel' => $orderStatusLabel,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing OrderStatusLabel entity.
     *
     * @Route("/{id}/edit", name="admin_orderstatuslabel_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, OrderStatusLabel $orderStatusLabel)
    {
        $deleteForm = $this->createDeleteForm($orderStatusLabel);
        $editForm = $this->createForm('AppBundle\Form\OrderStatusLabelType', $orderStatusLabel);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($orderStatusLabel);
            $em->flush();

            return $this->redirectToRoute('admin_orderstatuslabel_edit', array('id' => $orderStatusLabel->getId()));
        }

        return $this->render('admin/crud/orderstatuslabel/edit.html.twig', array(
            'orderStatusLabel' => $orderStatusLabel,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a OrderStatusLabel entity.
     *
     * @Route("/{id}", name="admin_orderstatuslabel_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, OrderStatusLabel $orderStatusLabel)
    {
        $form = $this->createDeleteForm($orderStatusLabel);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($orderStatusLabel);
            $em->flush();
        }

        return $this->redirectToRoute('admin_orderstatuslabel_index');
    }

    /**
     * Creates a form to delete a OrderStatusLabel entity.
     *
     * @param OrderStatusLabel $orderStatusLabel The OrderStatusLabel entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(OrderStatusLabel $orderStatusLabel)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_orderstatuslabel_delete', array('id' => $orderStatusLabel->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
namespace content {

namespace {

constexpr size_t kTestBlobStorageMaxBytesDataItemSize = 13;
constexpr size_t kTestBlobStorageMaxBlobMemorySize = 500;
constexpr uint64_t kTestBlobStorageMinFileSizeBytes = 32;
constexpr uint64_t kTestBlobStorageMaxFileSizeBytes = 100;
constexpr uint64_t kTestBlobStorageMaxDiskSpace = 1000;

}  // namespace

class WebBundleBlobDataSourceTest : public testing::Test {
 public:
  WebBundleBlobDataSourceTest(const WebBundleBlobDataSourceTest&) = delete;
  WebBundleBlobDataSourceTest& operator=(const WebBundleBlobDataSourceTest&) =
      delete;

 protected:
  WebBundleBlobDataSourceTest() = default;
  ~WebBundleBlobDataSourceTest() override = default;
  void SetUp() override {
    ASSERT_TRUE(data_dir_.CreateUniqueTempDir());
    context_ = std::make_unique<storage::BlobStorageContext>(
        data_dir_.GetPath(), data_dir_.GetPath(),
        base::ThreadPool::CreateTaskRunner({base::MayBlock()}));
    storage::BlobStorageLimits limits;
    limits.max_ipc_memory_size = kTestBlobStorageMaxBytesDataItemSize;
    limits.max_shared_memory_size = kTestBlobStorageMaxBytesDataItemSize;
    limits.max_bytes_data_item_size = kTestBlobStorageMaxBytesDataItemSize;
    limits.max_blob_in_memory_space = kTestBlobStorageMaxBlobMemorySize;
    limits.min_page_file_size = kTestBlobStorageMinFileSizeBytes;
    limits.max_file_size = kTestBlobStorageMaxFileSizeBytes;
    limits.desired_max_disk_space = kTestBlobStorageMaxDiskSpace;
    limits.effective_max_disk_space = kTestBlobStorageMaxDiskSpace;
    context_->set_limits_for_testing(limits);
  }

  std::unique_ptr<WebBundleBlobDataSource> CreateTestDataSource(
      const std::string& test_data,
      mojo::Remote<web_package::mojom::BundleDataSource>* remote_source,
      absl::optional<int64_t> content_length = absl::nullopt) {
    mojo::ScopedDataPipeProducerHandle producer;
    mojo::ScopedDataPipeConsumerHandle consumer;
    CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, producer, consumer));
    mojo::BlockingCopyFromString(test_data, producer);
    producer.reset();

    auto source = std::make_unique<WebBundleBlobDataSource>(
        content_length ? *content_length : test_data.size(),
        std::move(consumer), nullptr, ContextGetter());
    source->AddReceiver(remote_source->BindNewPipeAndPassReceiver());
    return source;
  }
  std::unique_ptr<storage::BlobStorageContext> context_;

 private:
  BrowserContext::BlobContextGetter ContextGetter() {
    return base::BindRepeating(
        [](base::WeakPtr<storage::BlobStorageContext> weak_context) {
          return weak_context;
        },
        context_->AsWeakPtr());
  }

  base::ScopedTempDir data_dir_;
  BrowserTaskEnvironment task_environment_;
};

TEST_F(WebBundleBlobDataSourceTest, Read) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  base::test::TestFuture<const absl::optional<std::vector<uint8_t>>&> future;
  remote_source->Read(1, 3, future.GetCallback());
  auto read_result = future.Get();
  ASSERT_TRUE(read_result);
  ASSERT_EQ(3u, read_result->size());
  EXPECT_EQ('e', (*read_result)[0]);
  EXPECT_EQ('s', (*read_result)[1]);
  EXPECT_EQ('t', (*read_result)[2]);
}

TEST_F(WebBundleBlobDataSourceTest, Read_EndOfSourceReached) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  base::test::TestFuture<const absl::optional<std::vector<uint8_t>>&> future;
  remote_source->Read(6, 100, future.GetCallback());
  auto read_result = future.Get();
  ASSERT_EQ(3u, read_result->size());
  EXPECT_EQ('a', (*read_result)[0]);
  EXPECT_EQ('t', (*read_result)[1]);
  EXPECT_EQ('a', (*read_result)[2]);
}

TEST_F(WebBundleBlobDataSourceTest, Read_OutOfRangeError) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  base::test::TestFuture<const absl::optional<std::vector<uint8_t>>&> future;
  remote_source->Read(10, 100, future.GetCallback());
  EXPECT_FALSE(future.Get());
}

TEST_F(WebBundleBlobDataSourceTest, Read_ContentLengthTooSmall) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source, kData.size() - 1);

  base::test::TestFuture<const absl::optional<std::vector<uint8_t>>&> future;
  remote_source->Read(0, kData.size(), future.GetCallback());
  auto read_result = future.Get();
  ASSERT_EQ(kData.size(), read_result->size());
  EXPECT_EQ(kData, std::string(reinterpret_cast<char*>(read_result->data()),
                               read_result->size()));
}

TEST_F(WebBundleBlobDataSourceTest, Read_ContentLengthTooLarge) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source, kData.size() + 1);

  base::test::TestFuture<const absl::optional<std::vector<uint8_t>>&> future;
  remote_source->Read(0, kData.size() + 1, future.GetCallback());
  auto read_result = future.Get();
  ASSERT_EQ(kData.size(), read_result->size());
  EXPECT_EQ(kData, std::string(reinterpret_cast<char*>(read_result->data()),
                               read_result->size()));
}

TEST_F(WebBundleBlobDataSourceTest, Read_NoStorage) {
  std::string content = "Test Data";
  // Make the content larger than the disk space.
  content.resize(kTestBlobStorageMaxDiskSpace + 1, ' ');
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(content, &remote_source);

  base::test::TestFuture<const absl::optional<std::vector<uint8_t>>&> future;
  remote_source->Read(1, 100, future.GetCallback());
  EXPECT_FALSE(future.Get());
}

TEST_F(WebBundleBlobDataSourceTest, Length) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  base::test::TestFuture<int64_t> future;
  remote_source->Length(future.GetCallback());
  EXPECT_EQ(-1, future.Get());
}

TEST_F(WebBundleBlobDataSourceTest, IsRandomAccessContext) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  base::test::TestFuture<bool> future;
  remote_source->IsRandomAccessContext(future.GetCallback());
  EXPECT_EQ(false, future.Get());
}

TEST_F(WebBundleBlobDataSourceTest, ReadToDataPipe) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  mojo::ScopedDataPipeProducerHandle producer;
  mojo::ScopedDataPipeConsumerHandle consumer;
  CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, producer, consumer));

  base::test::TestFuture<net::Error> future;
  source->ReadToDataPipe(1, 3, std::move(producer), future.GetCallback());
  net::Error read_response_body_result = future.Get();
  EXPECT_EQ(net::OK, read_response_body_result);

  std::string result_string;
  mojo::BlockingCopyToString(std::move(consumer), &result_string);
  EXPECT_EQ(3u, result_string.size());
  EXPECT_EQ(kData.substr(1, 3), result_string);
}

TEST_F(WebBundleBlobDataSourceTest, ReadToDataPipe_EndOfSourceReached) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  mojo::ScopedDataPipeProducerHandle producer;
  mojo::ScopedDataPipeConsumerHandle consumer;
  CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, producer, consumer));

  base::test::TestFuture<net::Error> future;
  source->ReadToDataPipe(0, 100, std::move(producer), future.GetCallback());
  net::Error read_response_body_result = future.Get();
  EXPECT_EQ(net::OK, read_response_body_result);

  std::string result_string;
  mojo::BlockingCopyToString(std::move(consumer), &result_string);
  EXPECT_EQ(kData, result_string);
}

TEST_F(WebBundleBlobDataSourceTest, ReadToDataPipe_OutOfRangeError) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  mojo::ScopedDataPipeProducerHandle producer;
  mojo::ScopedDataPipeConsumerHandle consumer;
  CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, producer, consumer));

  base::test::TestFuture<net::Error> future;
  source->ReadToDataPipe(10, 100, std::move(producer), future.GetCallback());
  net::Error read_response_body_result = future.Get();
  EXPECT_EQ(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE, read_response_body_result);
}

TEST_F(WebBundleBlobDataSourceTest, ReadToDataPipe_ContentLengthTooSmall) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source, kData.size() - 1);

  mojo::ScopedDataPipeProducerHandle producer;
  mojo::ScopedDataPipeConsumerHandle consumer;
  CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, producer, consumer));

  base::test::TestFuture<net::Error> future;
  source->ReadToDataPipe(0, kData.size(), std::move(producer),
                         future.GetCallback());
  net::Error read_response_body_result = future.Get();
  EXPECT_EQ(net::OK, read_response_body_result);

  std::string result_string;
  mojo::BlockingCopyToString(std::move(consumer), &result_string);
  EXPECT_EQ(kData, result_string);
}

TEST_F(WebBundleBlobDataSourceTest, ReadToDataPipe_ContentLengthTooLarge) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source, kData.size() + 1);

  mojo::ScopedDataPipeProducerHandle producer;
  mojo::ScopedDataPipeConsumerHandle consumer;
  CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, producer, consumer));

  base::test::TestFuture<net::Error> future;
  source->ReadToDataPipe(0, kData.size(), std::move(producer),
                         future.GetCallback());
  net::Error read_response_body_result = future.Get();
  EXPECT_EQ(net::OK, read_response_body_result);

  std::string result_string;
  mojo::BlockingCopyToString(std::move(consumer), &result_string);
  EXPECT_EQ(kData, result_string);
}

TEST_F(WebBundleBlobDataSourceTest, ReadToDataPipe_NoStorage) {
  std::string content = "Test Data";
  // Make the content larger than the disk space.
  content.resize(kTestBlobStorageMaxDiskSpace + 1, ' ');
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(content, &remote_source);

  mojo::ScopedDataPipeProducerHandle producer;
  mojo::ScopedDataPipeConsumerHandle consumer;
  CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, producer, consumer));

  base::test::TestFuture<net::Error> future;
  source->ReadToDataPipe(1, 3, std::move(producer), future.GetCallback());
  net::Error read_response_body_result = future.Get();
  EXPECT_EQ(net::ERR_FAILED, read_response_body_result);
}

TEST_F(WebBundleBlobDataSourceTest, ReadToDataPipe_Destructed) {
  const std::string kData = "Test Data";
  mojo::Remote<web_package::mojom::BundleDataSource> remote_source;
  auto source = CreateTestDataSource(kData, &remote_source);

  mojo::ScopedDataPipeProducerHandle producer;
  mojo::ScopedDataPipeConsumerHandle consumer;
  CHECK_EQ(MOJO_RESULT_OK, mojo::CreateDataPipe(nullptr, producer, consumer));

  base::test::TestFuture<net::Error> future;
  source->ReadToDataPipe(1, 3, std::move(producer), future.GetCallback());
  source.reset();
  net::Error read_response_body_result = future.Get();
  EXPECT_EQ(net::ERR_FAILED, read_response_body_result);
}

}  // namespace content


text:
/**
 */
package isostdisois_13584_32ed_1techxmlschemaontomlSimplified;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'SHORTNAME'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.SHORTNAME#getLabels Labels}

 *

 *
 * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getSHORTNAME()
 * @model
 * @generated
 */
public interface SHORTNAME extends EObject {
	/**
	 * Returns the value of the 'Labels' containment reference list.
	 * The list contents are of type {@link isostdisois_13584_32ed_1techxmlschemaontomlSimplified.SHORTNAMELABEL}.
	 *
	 *

	 * If the meaning of the 'Labels' containment reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Labels' containment reference list.
	 * @see isostdisois_13584_32ed_1techxmlschemaontomlSimplified.Isostdisois_13584_32ed_1techxmlschemaontomlSimplifiedPackage#getSHORTNAME_Labels()
	 * @model containment="true" required="true"
	 * @generated
	 */
	EList<SHORTNAMELABEL> getLabels();

} // SHORTNAME


text:
using namespace hyperion;

LinearColorSmoothing::LinearColorSmoothing( LedDevice * ledDevice, double ledUpdateFrequency_hz, int settlingTime_ms, unsigned updateDelay, bool continuousOutput)
	: LedDevice()
	, _ledDevice(ledDevice)
	, _updateInterval(1000 / ledUpdateFrequency_hz)
	, _settlingTime(settlingTime_ms)
	, _timer()
	, _outputDelay(updateDelay)
	, _writeToLedsEnable(true)
	, _continuousOutput(continuousOutput)
	, _enabled(true)
{
	_log = Logger::getInstance("Smoothing");
	_timer.setSingleShot(false);
	_timer.setInterval(_updateInterval);

	connect(&_timer, SIGNAL(timeout()), this, SLOT(updateLeds()));
	Info( _log, "Created linear-smoothing with interval: %d ms, settlingTime: %d ms, updateDelay: %d frames",
	      _updateInterval, settlingTime_ms,  _outputDelay );
}

LinearColorSmoothing::~LinearColorSmoothing()
{
	// Make sure to switch off the underlying led-device (because switchOff is no longer forwarded)
	_ledDevice->switchOff();
	delete _ledDevice;
}

int LinearColorSmoothing::write(const std::vector<ColorRgb> &ledValues)
{
	// received a new target color
	if (_previousValues.empty())
	{
		// not initialized yet
		_targetTime = QDateTime::currentMSecsSinceEpoch() + _settlingTime;
		_targetValues = ledValues;

		_previousTime = QDateTime::currentMSecsSinceEpoch();
		_previousValues = ledValues;
		_timer.start();
	}
	else
	{
		_targetTime = QDateTime::currentMSecsSinceEpoch() + _settlingTime;
		memcpy(_targetValues.data(), ledValues.data(), ledValues.size() * sizeof(ColorRgb));
	}

	return 0;
}

int LinearColorSmoothing::switchOff()
{
	// We will keep updating the leds (but with pure-black)

	// Clear the smoothing parameters
	std::fill(_targetValues.begin(), _targetValues.end(), ColorRgb::BLACK);
	_targetTime = 0;

	// Erase the output-queue
	for (unsigned i=0; i<_outputQueue.size(); ++i)
	{
		_outputQueue.push_back(_targetValues);
		_outputQueue.pop_front();
	}

	return 0;
}

void LinearColorSmoothing::updateLeds()
{
	int64_t now = QDateTime::currentMSecsSinceEpoch();
	int deltaTime = _targetTime - now;

	if (deltaTime < 0)
	{
		memcpy(_previousValues.data(), _targetValues.data(), _targetValues.size() * sizeof(ColorRgb));
		_previousTime = now;

		queueColors(_previousValues);
		_writeToLedsEnable = _continuousOutput;
	}
	else
	{
		_writeToLedsEnable = true;
		float k = 1.0f - 1.0f * deltaTime / (_targetTime - _previousTime);

		int reddif = 0, greendif = 0, bluedif = 0;

		for (size_t i = 0; i < _previousValues.size(); ++i)
		{
			ColorRgb & prev   = _previousValues[i];
			ColorRgb & target = _targetValues[i];

			reddif   = target.red   - prev.red;
			greendif = target.green - prev.green;
			bluedif  = target.blue  - prev.blue;

			prev.red   += (reddif   < 0 ? -1:1) * std::ceil(k * std::abs(reddif));
			prev.green += (greendif < 0 ? -1:1) * std::ceil(k * std::abs(greendif));
			prev.blue  += (bluedif  < 0 ? -1:1) * std::ceil(k * std::abs(bluedif));
		}
		_previousTime = now;

		queueColors(_previousValues);
	}
}

void LinearColorSmoothing::queueColors(const std::vector<ColorRgb> & ledColors)
{
	if (_outputDelay == 0)
	{
		// No output delay => immediate write
		if ( _writeToLedsEnable )
			_ledDevice->setLedValues(ledColors);
	}
	else
	{
		// Push new colors in the delay-buffer
		if ( _writeToLedsEnable )
			_outputQueue.push_back(ledColors);

		// If the delay-buffer is filled pop the front and write to device
		if (_outputQueue.size() > 0 )
		{
			if ( _outputQueue.size() > _outputDelay || !_writeToLedsEnable )
			{
				_ledDevice->setLedValues(_outputQueue.front());
				_outputQueue.pop_front();
			}
		}
	}
}

void LinearColorSmoothing::setEnable(bool enable)
{
	_enabled = enable;
	if (!enable)
	{
		_timer.stop();
		_previousValues.clear();

	}
}

bool LinearColorSmoothing::enabled()
{
	return _enabled;
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>Über</title>
  <meta name="description" content="Ein Newsletter über Künstliche Intelligenz, Machine Learning, neuronale Netzwerke und die Zukunft des Computings." />

  <meta name="HandheldFriendly" content="True" />
  <meta name="MobileOptimized" content="320" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@caltf4" />
    <meta name="twitter:title" content="Über" />
    <meta name="twitter:image" content="http://altf4.cool/assets/images/ai.png" />

    <meta name="twitter:description" content="Ein Newsletter über Künstliche Intelligenz, Machine Learning, neuronale Netzwerke und die Zukunft des Computings." />

  <meta property="og:site_name" content="Alt+F4" />
  <meta property="og:title" content="Über"/>

  <meta property="og:description" content="Ein Newsletter über Künstliche Intelligenz, Machine Learning, neuronale Netzwerke und die Zukunft des Computings." />

  <meta property="og:image" content="http://altf4.cool/assets/images/ai.png" />
  <meta property="og:url" content="http://altf4.cool/about/" >
  <meta property="og:type" content="blog" />

  <link rel="canonical" href="http://altf4.cool/about/"/>
  <link rel="shortcut icon" href="/assets/images/favicon.png" type="image/png"/>
  <link rel="stylesheet" href="//brick.a.ssl.fastly.net/Linux+Libertine:400,400i,700,700i/Open+Sans:400,400i,700,700i">
  <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

  <link rel="stylesheet" type="text/css" media="screen" href="/css/main.css" />
  <link rel="stylesheet" type="text/css" media="print" href="/css/print.css" />

Über

Blog Logo

Der Newsletter

Ein Newsletter über Künstliche Intelligenz, Machine Learning, neuronale Netzwerke und die Zukunft des Computings. Für mich ist Künstliche Intelligenz  mehr als nur ein Buzzword, das einem während des Conference Calls mal aus dem Mund fällt. Ich bin davon überzeugt, dass künstliche Intelligenz unser alltägliches Leben auf den Kopf stellen wird. Und je besser wir Bescheid wissen, wo die Grenzen und Möglichkeiten der Technik liegen, desto besser können wir uns darauf einstellen und teilhaben. Verschwinden wird KI nicht mehr. Denn wie KI-Pionier John McCarthy schon wusste: "As soon as it works, no one calls it AI anymore"

Der Autor

Ich heiße Christian Alt und ich bin freier Journalist. Am ehesten hört man mich im Radio, vor allem im Zündfunk auf Bayern 2 oder auf PULS. Sonst: Deutschlandradio Kultur, Dradio, SWR2, WASD Magazin.

Ich lebe in München.

Interessen: Podcasts, TV-Serien, Kino, VR, Videospiele, Technik und Gesellschaft. Und natürlich: KI und Machine Learning.

        Image

Alt+F4

Ein Newsletter über Künstliche Intelligenz, Machine Learning, neuronale Netzwerke und die Zukunft des Computings.

        Strg+Z


text:
using namespace qglviewer;

class VEDFilter
{
 public :
  VEDFilter();
  ~VEDFilter();

  QString start(VolumeFileManager*,
		int, int, int,
		Vec, Vec,
		QString,
		Vec,
		QList<Vec>,
		QList<Vec>,
		QList<CropObject>,
		QList<PathObject>,
		uchar*,
		int, int, int, int,
		QVector<uchar>);

 private :
  QTextEdit *m_meshLog;
  QProgressBar *m_meshProgress;

  VolumeFileManager *m_vfm;
  int m_voxelType;
  int m_nX, m_nY, m_nZ;
  int m_depth, m_width, m_height;
  Vec m_dataMin, m_dataMax, m_dataSize;

  bool m_blendPresent;
  bool m_tearPresent;
  bool m_cropPresent;
  bool m_pathBlendPresent;
  bool m_pathCropPresent;
  QList<CropObject> m_crops;
  QList<PathObject> m_paths;

  int m_pruneX, m_pruneY, m_pruneZ;
  float m_pruneLod;
  QVector<uchar> m_pruneData;

  void applyFilter(QString,
		   Vec,
		   QList<Vec>,
		   QList<Vec>,
		   QList<CropObject>,
		   QList<PathObject>,
		   uchar*,
		   int,
		   float, float, int, int,
		   bool);

  bool checkPathCrop(Vec);
  bool checkPathBlend(Vec, ushort, uchar*);
  bool checkCrop(Vec);
  bool checkBlend(Vec, ushort, uchar*);

  void savePvl(QString);

  int m_niter;
  int m_prog;
  void next();
};

#endif


text: A secure, end-to-end encrypted communication framework


text:
package game.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;

import game.controller.GameRunnerMVC;
import game.model.Option;
import game.model.Player;
import java.awt.Font;

public class GameUI extends JFrame{

	private JPanel contentPane;
	private GameRunnerMVC controller;
	private JTextArea textArea;
	private JTextPane textPane1;
	private JTextPane textPane2;
	private JTextPane textPane3;
	private JButton button1;
	private JButton button2;
	private JButton button3;
	private JButton button4;
	private JButton button5;
	private JButton button6;

	public void runEvent(String description, List<Option> options,
			Player player) {
		textPane1.setText("Health: "+player.getHealth());
		textPane2.setText("Money: "+player.getMoney());
		textPane3.setText("Life Satisfaction: "+player.getSatisfaction());
		textArea.setText(description);

		if(options == null){
			return;
		}

		JButton[] buttons = { button1, button2, button3, button4, button5, button6 };

		for(JButton b: buttons){
			b.setText("");
		    for( ActionListener al : b.getActionListeners() ) {
		        b.removeActionListener( al );
		    }
		}

		if(options.size() >= 1){
			button1.setText(options.get(0).getDescription());
			button1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					controller.evaluateOption(options.get(0), player);
				}
			});
		}
		if(options.size() >= 2){
			button2.setText(options.get(1).getDescription());
			button2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					controller.evaluateOption(options.get(1), player);
				}
			});
		}
		if(options.size() >= 3){
			button3.setText(options.get(2).getDescription());
			button3.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					controller.evaluateOption(options.get(2), player);
				}
			});
		}
		if(options.size() >= 4){
			button4.setText(options.get(3).getDescription());
			button4.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					controller.evaluateOption(options.get(3), player);
				}
			});
		}
		if(options.size() >= 5){
			button5.setText(options.get(4).getDescription());
			button5.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					controller.evaluateOption(options.get(4), player);
				}
			});
		}
		if(options.size() >= 6){
			button6.setText(options.get(5).getDescription());
			button6.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					controller.evaluateOption(options.get(5), player);
				}
			});
		}
	}

	/**
	 * Create the frame.
	 */
	public GameUI(GameRunnerMVC controller) {
		this.controller = controller;
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 491, 426);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		textArea = new JTextArea();
		textArea.setLineWrap(true);
		textArea.setBounds(10, 25, 455, 196);
		textArea.setText("");
		contentPane.add(textArea);

		textPane1 = new JTextPane();
		textPane1.setBounds(10, 0, 149, 20);
		textPane1.setText("Health: 50");
		contentPane.add(textPane1);

		textPane2 = new JTextPane();
		textPane2.setBounds(169, 0, 134, 20);
		textPane2.setText("Money: 50");
		contentPane.add(textPane2);

		textPane3 = new JTextPane();
		textPane3.setBounds(313, 0, 134, 20);
		textPane3.setText("Satisfaction: 50");
		contentPane.add(textPane3);

		button1 = new JButton("");
		button1.setFont(new Font("Tahoma", Font.PLAIN, 11));
		button1.setBounds(10, 230, 222, 40);
		contentPane.add(button1);

		button2 = new JButton("");
		button2.setBounds(243, 230, 222, 40);
		contentPane.add(button2);

		button3 = new JButton("");
		button3.setBounds(10, 281, 222, 40);
		contentPane.add(button3);

		button4 = new JButton("");
		button4.setBounds(243, 281, 222, 40);
		contentPane.add(button4);

		button5 = new JButton("");
		button5.setBounds(10, 332, 222, 40);
		contentPane.add(button5);

		button6 = new JButton("");
		button6.setBounds(243, 332, 222, 40);
		contentPane.add(button6);
	}
}


text:
using namespace LepusEngine::Lepus3D;

void FPPCamera::SetWindow(GLFWwindow* wnd)
{
	m_Wnd = wnd; // set the window handle

	// Centers (or recenters) the XY coordinates of the cursor in the frame.
	m_LastX = 0.5f;
	m_LastY = 0.5f;

	_fppCamPtr = this; // Sets this camera as the current instance.
	glfwSetWindowSizeCallback(wnd, ResizeCallback); // Sets the resize callback for the window handle to FPPCamera's callback function.
}

glm::mat4 FPPCamera::Run()
{
	// Return View matrix
	return this->GetView();
}

void FPPCamera::ProcessInput(float deltaTime)
{
	// Check whether window is out of focus
	if (!glfwGetWindowAttrib(m_Wnd, GLFW_FOCUSED))
	{
		glfwSetInputMode(m_Wnd, GLFW_CURSOR, GLFW_CURSOR_NORMAL); // Give back cursor control
		return;
	}

	// If window is in focus, request unlimited mouse movement from the window.
	glfwSetInputMode(m_Wnd, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	// TODO: This should be moved to LepusEngine, with an input manager class.
	const float lookSensitivity = 100.f;

	// Get current camera position.
	glm::vec3 position = m_Transform.GetPosition().vec3();

	// Check for key presses (WASD).
	// TODO: Build an input handler in LepusEngine separate from Camera classes. Replace this with calls to the handler.
	if (glfwGetKey(m_Wnd, GLFW_KEY_W) == GLFW_PRESS)
	{
		position += m_Target.vec3() * deltaTime * 2.f;
	}
	if (glfwGetKey(m_Wnd, GLFW_KEY_S) == GLFW_PRESS)
	{
		position -= m_Target.vec3() * deltaTime * 2.f;
	}
	if (glfwGetKey(m_Wnd, GLFW_KEY_A) == GLFW_PRESS)
	{
		position -= glm::normalize(glm::cross(m_Target.vec3(), m_Up.vec3())) * 2.0f * deltaTime;
	}
	if (glfwGetKey(m_Wnd, GLFW_KEY_D) == GLFW_PRESS)
	{
		position += glm::normalize(glm::cross(m_Target.vec3(), m_Up.vec3())) * 2.0f * deltaTime;
	}

	// Update the position after reading WASD input.
	m_Transform.SetPosition(Vector3(position.x, position.y, position.z));

	// Get current camera rotation.
	Vector3 rotation = m_Transform.GetRotation();

	double mouseX = 0.0, mouseY = 0.0;
	glfwGetCursorPos(m_Wnd, &mouseX, &mouseY); // Get XY coordinates of the cursor in the window, in pixels.

	int wndWidth = 0, wndHeight = 0;
	glfwGetWindowSize(m_Wnd, &wndWidth, &wndHeight); // Get width and height of the window in pixels.

	// Normalise the cursor XY coordinates in the window.
	mouseX /= wndWidth;
	mouseY /= wndHeight;

	// Calculate the relative rotation value
	Vector2 mouseRot(mouseX - 0.5, mouseY - 0.5);

	// Add the relative rotation to the camera's rotation
	rotation.y += mouseRot.x * lookSensitivity;
	if (rotation.y <= 0.0f)
		rotation.y += 360.0f; // This is a quick fix for issue #2, where negative rotation was not supported
	rotation.x -= mouseRot.y * lookSensitivity;
	Logger::LogInfo("FPPCamera", "ProcessInput", (char*)std::to_string(mouseY).c_str());

	// quick fix for issue #2 (no negative rotation)
	if (rotation.x <= 0.0f)
		rotation.x = 360.0f;

	// Lock rotation so that camera cannot turn upside down
	if (rotation.x > 449.9f)
		rotation.x = 449.9f;
	if (rotation.x < 360.0f - 89.9f)
		rotation.x = 360.0f - 89.9f;

	// Apply new rotation
	m_Transform.SetRotation(rotation);

	// Update last cursor position
	m_LastX = mouseX;
	m_LastY = mouseY;

	// Recenter cursor for next frame
	if (glfwGetWindowAttrib(m_Wnd, GLFW_FOCUSED))
	{
		glfwSetCursorPos(m_Wnd, wndWidth / 2, wndHeight / 2);
		glfwSetInputMode(m_Wnd, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	}
}


text:
cd "$(readlink -f "$(dirname "$0")/..")"

if [ -z "$LIBDOT_SEARCH_PATH" ]; then
  export LIBDOT_SEARCH_PATH="$(readlink -f "../")"
fi

source "../libdot/bin/common.sh"

BUILT_HTERM_VERSION=$(grep -A1 "lib.resource.add('hterm/changelog/version'" \
  ./js/nassh_deps.concat.js | tail -1 | tr -d \'\+\ )

if [ -z "$BUILT_HTERM_VERSION" ]; then
  echo_err "Error reading hterm version."
  exit
fi

AVAILABLE_HTERM_VERSION="$(echo_changelog \
    "version" "../hterm/doc/changelog.txt")"

if [ "$BUILT_HTERM_VERSION" != "$AVAILABLE_HTERM_VERSION" ]; then
  echo_err "Warning: nassh_deps has hterm $BUILT_HTERM_VERSION but the" \
    "current version is $AVAILABLE_HTERM_VERSION"
  echo_err "Press ^C to cancel or enter to continue."
  read
fi

mkdir -p ./dist/zip

../libdot/bin/mkzip.sh -s "." -w ./dist/zip/ "$@"


text:
package com.mercadopago.android.px.model;

import com.mercadopago.android.px.internal.viewmodel.Summary;
import com.mercadopago.android.px.internal.viewmodel.SummaryDetail;
import com.mercadopago.android.px.internal.viewmodel.SummaryItemType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * Created by mromar on 9/14/17.
 */

public class SummaryTest {

    @Test
    public void getSummaryProductDetailWhenSetProduct() {
        BigDecimal amount = new BigDecimal(100);
        String productTitle = "Entradas de cine";
        Integer textColor = 16777215;

        Summary summary = new Summary.Builder()
            .addSummaryProductDetail(amount, productTitle, textColor)
            .build();

        List<SummaryDetail> summaryDetails = summary.getSummaryDetails();

        assertTrue(summaryDetails.get(0).getTitle().equals(productTitle));
        assertTrue(summaryDetails.get(0).getSummaryItemDetails().get(0).getAmount().equals(amount));
    }

    @Test
    public void getSummaryDetailsWhenSetAllDetails() {
        BigDecimal amount = new BigDecimal(100);
        String productTitle = "Entradas de cine";
        String testTitle = "Test Title";
        Integer textColor = 16777215;

        Summary summary = new Summary.Builder()
            .addSummaryProductDetail(amount, productTitle, textColor)
            .addSummaryDiscountDetail(amount, testTitle, textColor)
            .build();

        List<SummaryDetail> summaryDetails = summary.getSummaryDetails();

        assertTrue(summaryDetails.get(0).getTitle().equals(productTitle));
        assertTrue(summaryDetails.get(0).getSummaryItemDetails().get(0).getAmount().equals(amount));

        assertTrue(summaryDetails.get(1).getTitle().equals(testTitle));
        assertTrue(summaryDetails.get(1).getSummaryItemDetails().get(0).getAmount().equals(amount));
    }

    @Test
    public void getCustomSummaryDetailOrderWhenSetCustomOrder() {
        BigDecimal amount = new BigDecimal(100);
        String productTitle = "Entradas de cine";
        String discountTitle = "Descuento";
        String chargeTitle = "Cargos";
        String arrearTitle = "Mora";
        String shippingTitle = "Envio";
        String taxesTitle = "Impuestos";

        Integer textColor = 16777215;

        Summary summary = new Summary.Builder()
            .addSummaryProductDetail(amount, productTitle, textColor)
            .addSummaryDiscountDetail(amount, discountTitle, textColor)
            .addSummaryChargeDetail(amount, chargeTitle, textColor)
            .addSummaryArrearsDetail(amount, arrearTitle, textColor)
            .addSummaryShippingDetail(amount, shippingTitle, textColor)
            .addSummaryTaxesDetail(amount, taxesTitle, textColor)
            .setSummaryDetailsOrder(getCustomSummaryDetailsOrder())
            .build();

        List<SummaryDetail> summaryDetails = summary.getSummaryDetails();

        assertTrue(summaryDetails.get(0).getTitle().equals(productTitle));
        assertTrue(summaryDetails.get(0).getSummaryItemDetails().get(0).getAmount().equals(amount));

        assertTrue(summaryDetails.get(1).getTitle().equals(chargeTitle));
        assertTrue(summaryDetails.get(1).getSummaryItemDetails().get(0).getAmount().equals(amount));

        assertTrue(summaryDetails.get(2).getTitle().equals(taxesTitle));
        assertTrue(summaryDetails.get(2).getSummaryItemDetails().get(0).getAmount().equals(amount));

        assertTrue(summaryDetails.get(3).getTitle().equals(arrearTitle));
        assertTrue(summaryDetails.get(3).getSummaryItemDetails().get(0).getAmount().equals(amount));

        assertTrue(summaryDetails.get(4).getTitle().equals(shippingTitle));
        assertTrue(summaryDetails.get(4).getSummaryItemDetails().get(0).getAmount().equals(amount));

        assertTrue(summaryDetails.get(5).getTitle().equals(discountTitle));
        assertTrue(summaryDetails.get(5).getSummaryItemDetails().get(0).getAmount().equals(amount));
    }

    private List<String> getCustomSummaryDetailsOrder() {
        List<String> defaultSummaryDetailsOrder = new ArrayList<>();

        defaultSummaryDetailsOrder.add(SummaryItemType.PRODUCT);
        defaultSummaryDetailsOrder.add(SummaryItemType.CHARGE);
        defaultSummaryDetailsOrder.add(SummaryItemType.TAXES);
        defaultSummaryDetailsOrder.add(SummaryItemType.ARREARS);
        defaultSummaryDetailsOrder.add(SummaryItemType.SHIPPING);
        defaultSummaryDetailsOrder.add(SummaryItemType.DISCOUNT);

        return defaultSummaryDetailsOrder;
    }
}


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.mtController',
  'myApp.mtUppercase',
    'myApp.mtagRegexFilter',
    'myApp.mtagArrayFilter',
    'myApp.mtagColorPicker',
    'myApp.mtagMouseDown'
]);


text:
package k8sdnssky
import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger}

import akka.actor.{Actor, ActorRef, ActorSystem, OneForOneStrategy, Props, SupervisorStrategy}
import akka.pattern.{Backoff, BackoffSupervisor}
import akka.testkit.{ImplicitSender, TestKit, TestProbe}
import org.scalatest.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, MustMatchers}
import org.slf4j.{Logger, LoggerFactory}

import scala.concurrent.duration.FiniteDuration

class SupervisionSuite extends TestKit(ActorSystem("dns-controller-suite"))
    with LogbackInitializer
    with ImplicitSender with FlatSpecLike with MustMatchers
    with MockitoSugar with BeforeAndAfterAll {

  private val log: Logger = LoggerFactory.getLogger(classOf[SupervisionSuite])

  class InitializingActor(
      name: String,
      initFn: () => Unit,
      receiveFn: (Any) => Unit,
      preRestartFn: () => Unit
  ) extends Actor {

    log.info(s"[name] initialize")
    initFn.apply()

    override def supervisorStrategy: SupervisorStrategy = {
      OneForOneStrategy() {
        case _ => SupervisorStrategy.Restart
      }
    }
    override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
      log.info(s"[$name] preRestart")
      preRestartFn.apply()
      super.preRestart(reason, message)
    }

    override def postStop(): Unit = {
      log.info(s"[name] postStop")
      super.postStop()
    }
    override def postRestart(reason: Throwable): Unit = {
      log.info(s"[name] postRestart")
      super.postRestart(reason)
    }
    override def receive: Receive = {
      case x: Any =>
        log.info(s"[name] receive")
        receiveFn(x)
    }
  }

  "a backoff supervisor" must "restart an actor that fails to initialize" in {
    val probe = TestProbe()
    object Failed
    object Succeeded

    val fail = new AtomicBoolean(true)
    val failOnceProps = Props(new InitializingActor(
      "failOnce",
      () => {
        if (fail.get()) {
          probe.ref.tell(Failed, ActorRef.noSender)
          fail.set(false)
          throw new RuntimeException("Failure requested")
        } else {
          probe.ref.tell(Succeeded, ActorRef.noSender)
        }
      }, (_) => {}, () => {}))

    val supervisorProps = BackoffSupervisor.props(
      Backoff.onFailure(
        failOnceProps,
        childName = "dns-controller",
        minBackoff = FiniteDuration(1, "second"),
        maxBackoff = FiniteDuration(5, "minutes"),
        randomFactor = 0.2
      ).withAutoReset(FiniteDuration(30, "seconds"))
          .withSupervisorStrategy(
            OneForOneStrategy() {
              case _ => SupervisorStrategy.Restart
            }))
    system.actorOf(supervisorProps)

    probe.expectMsg(Failed)
    probe.expectMsg(Succeeded)
    probe.expectNoMsg(FiniteDuration(1, "second"))
  }

  it must "restart an actor that fails during a receive operation" in {
    val probe = TestProbe()
    object Init
    object PreRestart
    object Fail
    object Succeed

    val failOnceProps = Props(new InitializingActor(
      "failOnMessage",
      () => {
        probe.ref.tell(Init, ActorRef.noSender)
      }, {
        case Fail => throw new RuntimeException("Failure requested")
        case x: Any => probe.ref.tell(x, ActorRef.noSender)
      },
      () => {
        probe.ref.tell(PreRestart, ActorRef.noSender)
      }
    ))

    val supervisorProps = BackoffSupervisor.props(
      Backoff.onFailure(
        failOnceProps,
        childName = "dns-controller",
        minBackoff = FiniteDuration(1, "second"),
        maxBackoff = FiniteDuration(1, "minute"),
        randomFactor = 0.2
      ).withAutoReset(FiniteDuration(1, "minutes"))
          .withSupervisorStrategy(
            OneForOneStrategy() {
              case _ => SupervisorStrategy.Restart
            }))
    val supervisor = system.actorOf(supervisorProps)

    probe.expectMsg(Init)
    supervisor ! Succeed
    probe.expectMsg(Succeed)
    supervisor ! Fail
    // with a backoff supervisor, prerestart is not called
    //probe.expectMsg(FiniteDuration(5, "minutes"), PreRestart)
    probe.expectMsg(Init)
    supervisor ! Succeed
    probe.expectMsg(Succeed)
    probe.expectNoMsg(FiniteDuration(1, "second"))
  }

  it must "restart an actor and its children if it fails during a receive operation" in {
    val probe = TestProbe()
    object Init
    object PreRestart
    object Fail
    object Succeed
    object SpawnChild

    class SpawningActor(name: String) extends Actor {
      log.info(s"[$name ${this.hashCode()}] initializing")
      probe.ref.tell(Init, ActorRef.noSender)
      val childCount = new AtomicInteger()

      override def preStart(): Unit = {
        log.info(s"[$name] preStart")
        super.preStart()
      }
      override def postStop(): Unit = {
        log.info(s"[$name] postStop")
        super.postStop()
      }
      override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
        log.info(s"[$name] preRestart")
        super.preRestart(reason, message)
      }
      override def postRestart(reason: Throwable): Unit = {
        log.info(s"[$name] postRestart")
        super.postRestart(reason)
      }

      override def receive: Receive = {
        case Fail =>
          log.info(s"[$name] failing")
          throw new RuntimeException("Failure requested")
        case SpawnChild =>
          log.info(s"[$name] spawning child")
          context.actorOf(Props(new SpawningActor("child-" + childCount.incrementAndGet())))
        case x: Any => probe.ref.tell(x, ActorRef.noSender)
      }
    }

    val props = Props(new SpawningActor("parent"))

    val supervisorProps = BackoffSupervisor.props(
      Backoff.onFailure(
        props,
        childName = "dns-controller",
        minBackoff = FiniteDuration(1, "second"),
        maxBackoff = FiniteDuration(1, "minute"),
        randomFactor = 0.2
      ).withAutoReset(FiniteDuration(1, "minute"))
          .withSupervisorStrategy(
            OneForOneStrategy() {
              case _ => SupervisorStrategy.Restart
            }))
    val supervisor = system.actorOf(supervisorProps)

    probe.expectMsg(Init)
    supervisor ! Succeed
    probe.expectMsg(Succeed)
    supervisor ! SpawnChild
    probe.expectMsg(Init)

    supervisor ! Fail
    // with a backoff supervisor, prerestart is not called
    //probe.expectMsg(FiniteDuration(5, "minutes"), PreRestart)
    probe.expectMsg(Init)
    supervisor ! Succeed
    probe.expectMsg(Succeed)
    probe.expectNoMsg(FiniteDuration(1, "second"))
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('data_request', '0031_auto_20160821_1557'),
    ]

    operations = [
        migrations.AddField(
            model_name='requestcontent',
            name='content3_en',
            field=models.TextField(blank=True, default='content third', null=True),
        ),
        migrations.AddField(
            model_name='requestcontent',
            name='content3_fi',
            field=models.TextField(blank=True, default='content third', null=True),
        ),
    ]


text:
title: "Tetris Bot"
excerpt: "Created a invincible bot which can play tetris without losing."
header:
  teaser: /assets/images/projects/tetris-th.jpg
sidebar:
  - title: " GitHub Repo"
    image: /assets/images/projects/tetris-sb.jpg
    image_alt: "thumbnail"
  - title: "Languages/Technologies Used"
    text: "Python"
  - title: "Responsibilities"
    text: "See part 2 of the above repo."
---
This bot was created as a part of an assignment, where we were provided a skeleton code for the tetris game. I had to create the algorithm and logic to determine the next move of the bot. This was done using search algorithms and using a probabilistic approach. The heuristic for this algorithm was determined using a Genetic algorithm.

The heuristic or scoring function gave a particular configuration of the game state a score taking into account various factors like average height, max height, holes, bumpiness and complete lines.

The parameters to be considered and weights of each parameter were referenced from [here](https://codemyroad.wordpress.com/2013/04/14/tetris-ai-the-near-perfect-player/).

Briefly, the algorithm worked as follows:

1. For each piece and the upcoming piece generate all possible successor configurations of the game.
2. Choose the next position from the successors with best score using the above scoring function and make the moves to reach that configuration of the board.

Once the best successor configuration was found, then move the piece accordingly to reach that state. Thus we could get an impossible to beat bot given the probability distribution of the incoming pieces. If the probability distribution of the incoming pieces were changed dynamically, it would require us to run the genetic algorithm to learn the weights used in the scoring function for the given new probability distribution. Thus making it difficult to have a set of weights which could be perfect for dynamically updating distribution of pieces.


text:
package pl.tkowalcz.examples.basic;

import java.io.IOException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import rx.Observable;

public class Exercise2 {

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static void main(String[] args) throws IOException {
        String tweet1 = "{\"created_at\": \"Fri Oct 10 11:26:33 +0000 2014\", \"text\": \"Charging by induction is like proof by induction. It takes ages and you're never quite sure if it worked.\", \"user\": { \"screen_name\": \"tastapod\", \"location\": \"Agilia\" }}";
        String tweet2 = "{\"created_at\": \"Fri Oct 10 11:26:33 +0000 2014\", \"text\": \"TIL the movie Inception was based on node.js callbacks\", \"user\": { \"screen_name\": \"HackerNewsOnion\", \"location\": \"HackerNews\" }}";
        String tweet3 = "{\"created_at\": \"Fri Oct 10 12:26:33 +0000 2014\", \"text\": \"Shark Facts: Statistically, you are a more likely to be killed by a statistician than by a shark\", \"user\": { \"screen_name\": \"TheTechShark\"}}";
        String tweet4 = "{\"delete\":{\"status\":{\"id\":48223552775705600}}}";
        String tweet5 = "{\"created_at\": \"Fri Oct 10 08:26:33 +0000 2014\", \"text\": \"Keep calm and don't block threads\", \"user\": { \"screen_name\": \"tkowalcz\", \"location\": \"JDD\"}}";

        Gson gson = new GsonBuilder().create();

        Observable<String> tweets = Observable.create(null);

        System.in.read();
    }
}


text:
/*
Currying

Currying is the process of decomposing a function of multiple arguments into a chained sequence
of functions of one argument. It accomplishes this using partial applications.

Moreover, currying is the technique of transforming a function that takes multiple arguments
into a function that takes a single argument
*/

// uncurried
def add(x: Int, y: Int) = {
  x + y
}

add(1, 2)   // 3
add(7, 3)   // 10

// curried
def add(x: Int) = {
  (y: Int) => x + y
}

add(1)(2)   // 3
add(7)(3)   // 10


text:
package org.omg.PortableServer;

//
// IDL:omg.org/PortableServer/LifespanPolicyValue:1.0
//
final public class LifespanPolicyValueHolder implements org.omg.CORBA.portable.Streamable
{
    public LifespanPolicyValue value;

    public
    LifespanPolicyValueHolder()
    {
    }

    public
    LifespanPolicyValueHolder(LifespanPolicyValue initial)
    {
        value = initial;
    }

    public void
    _read(org.omg.CORBA.portable.InputStream in)
    {
        value = LifespanPolicyValueHelper.read(in);
    }

    public void
    _write(org.omg.CORBA.portable.OutputStream out)
    {
        LifespanPolicyValueHelper.write(out, value);
    }

    public org.omg.CORBA.TypeCode
    _type()
    {
        return LifespanPolicyValueHelper.type();
    }
}


text:
title:    Collapse Tabs
layout:   examples
base:   "../"
---

Collapse Tabs

      Home

      Profile

      Messages

      Settings

Home

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
          laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
          ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
          laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
          ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Profile

Ut wisi enim ad minim veniam, quis nostrud exerci tation
          ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
          laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
          ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Messages

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
          laoreet dolore magna aliquam erat volutpat.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
          laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
          ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Settings

Ut wisi enim ad minim veniam, quis nostrud exerci tation
          ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
          laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
          ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
          laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
          ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.


text:
package org.elasticsearch.action.admin.indices.create;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ack.ClusterStateUpdateListener;
import org.elasticsearch.cluster.ack.ClusterStateUpdateResponse;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.MetaDataCreateIndexService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

/**
 * Create index action.
 */
public class TransportCreateIndexAction extends TransportMasterNodeOperationAction<CreateIndexRequest, CreateIndexResponse> {

    private final MetaDataCreateIndexService createIndexService;

    @Inject
    public TransportCreateIndexAction(Settings settings, TransportService transportService, ClusterService clusterService,
                                      ThreadPool threadPool, MetaDataCreateIndexService createIndexService) {
        super(settings, transportService, clusterService, threadPool);
        this.createIndexService = createIndexService;
    }

    @Override
    protected String executor() {
        // we go async right away
        return ThreadPool.Names.SAME;
    }

    @Override
    protected String transportAction() {
        return CreateIndexAction.NAME;
    }

    @Override
    protected CreateIndexRequest newRequest() {
        return new CreateIndexRequest();
    }

    @Override
    protected CreateIndexResponse newResponse() {
        return new CreateIndexResponse();
    }

    @Override
    protected ClusterBlockException checkBlock(CreateIndexRequest request, ClusterState state) {
        return state.blocks().indexBlockedException(ClusterBlockLevel.METADATA, request.index());
    }

    @Override
    protected void masterOperation(final CreateIndexRequest request, final ClusterState state, final ActionListener<CreateIndexResponse> listener) throws ElasticsearchException {
        String cause = request.cause();
        if (cause.length() == 0) {
            cause = "api";
        }

        CreateIndexClusterStateUpdateRequest updateRequest = new CreateIndexClusterStateUpdateRequest(cause, request.index())
                .ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout())
                .settings(request.settings()).mappings(request.mappings())
                .aliases(request.aliases()).customs(request.customs());

        createIndexService.createIndex(updateRequest, new ClusterStateUpdateListener() {

            @Override
            public void onResponse(ClusterStateUpdateResponse response) {
                listener.onResponse(new CreateIndexResponse(response.isAcknowledged()));
            }

            @Override
            public void onFailure(Throwable t) {
                if (t instanceof IndexAlreadyExistsException) {
                    logger.trace("[{}] failed to create", t, request.index());
                } else {
                    logger.debug("[{}] failed to create", t, request.index());
                }
                listener.onFailure(t);
            }
        });
    }
}


text:
//
//  WCHeaderScrollView.m
//  WCCarInsurance
//
//  Created by Macx on 15/11/18.
//  Copyright © 2015年 Macx. All rights reserved.
//

#import "WCHeaderScrollView.h"

#import <AFNetworking.h>
#import <MJExtension.h>
#import <UIButton+WebCache.h>
#import "WCWeather.h"
#import "WCWeatherButton.h"
#import "WCHeaderScrollViewModel.h"
#import "WCTabBarController.h"
#import "WCNavigationController.h"
#import "WCHeaderScrollViewController.h"
static CGFloat const moveImageTimer = 5.0;

@interface WCHeaderScrollView()<UIScrollViewDelegate>

/** 图片轮播器 */
@property (nonatomic, weak) UIScrollView *scrollView;
/** 页码管理器 */
@property (nonatomic, weak) UIPageControl *pageControl;
/** 当前视图 */
@property (nonatomic, weak) UIImageView *currentImageView;
/** 上一个视图 */
@property (nonatomic, weak) UIImageView *prefixImageView;
/** 下一个视图 */
@property (nonatomic, weak) UIImageView *nextImageView;
/** 当前图片的下标 */
@property (nonatomic, assign) NSInteger currentImageIndex;
/** 请求管理者 */
@property (nonatomic, weak) AFHTTPSessionManager *manager;
/** 滚动视图模型数组 */
@property (nonatomic, strong) NSArray *headerScrollViewModels;
/** 天气界面 */
@property (nonatomic, weak) UIView *weatherView;
/** 天气城市按钮 */
@property (nonatomic, weak) WCWeatherButton *chooseCityButton;
/** 显示天气按钮 */
@property (nonatomic, weak) UIButton *weatherButton;
/** 加载天气 */
@property (nonatomic, weak) UIActivityIndicatorView *weatherLoadingView;
/** 天气模型 */
@property (nonatomic, strong) WCWeather *wether;
/** 天气温度 */
@property (nonatomic, weak) UILabel *tempLabel;
/** 天气状况 */
@property (nonatomic, weak) UILabel *weatherLabel;
/** 洗车状况 */
@property (nonatomic, weak) UILabel *clearCarLabel;
/** 定时器 */
@property (nonatomic, strong) NSTimer *moveTimer;
/** 是否手动滚动轮播 */
@property (nonatomic, assign, getter=isMoveAuto) BOOL moveAuto;

@end

@implementation WCHeaderScrollView

#pragma mark - 懒加载
- (AFHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

- (UILabel *)tempLabel {
    if (!_tempLabel) {
        UILabel *tempLabel = [[UILabel alloc] init];
        tempLabel.WC_x = CGRectGetMaxX(self.weatherButton.frame) + WCcommonSmallMargin;
        tempLabel.WC_y = self.weatherButton.WC_y + WCcommonSmallMargin;
        tempLabel.WC_width = WCCommonMargin * 14;
        tempLabel.WC_height = self.weatherButton.WC_height * 0.5;
        tempLabel.font = [UIFont boldSystemFontOfSize:25.0];
        tempLabel.textColor = [UIColor whiteColor];
        _tempLabel = tempLabel;
        [self.weatherView addSubview:tempLabel];
    }
    return _tempLabel;
}

- (UILabel *)weatherLabel {
    if (!_weatherLabel) {
        UILabel *weatherLabel = [[UILabel alloc] init];
        weatherLabel.WC_x = self.tempLabel.WC_x;
        weatherLabel.WC_y = CGRectGetMaxY(self.tempLabel.frame);
        weatherLabel.WC_width = self.tempLabel.WC_width;
        weatherLabel.WC_height = CGRectGetMaxY(self.weatherButton.frame) - CGRectGetMaxY(self.tempLabel.frame);
        weatherLabel.font = [UIFont systemFontOfSize:15.0];
        weatherLabel.textColor = [UIColor whiteColor];
        _weatherLabel = weatherLabel;
        [self.weatherView addSubview:weatherLabel];
    }
    return _weatherLabel;
}

- (UILabel *)clearCarLabel {
    if (!_clearCarLabel) {
        UILabel *clearCarLabel = [[UILabel alloc] init];
        clearCarLabel.WC_x = CGRectGetMaxX(self.tempLabel.frame);
        clearCarLabel.WC_y  = self.tempLabel.WC_y + WCcommonSmallMargin;
        clearCarLabel.WC_width = self.weatherLabel.WC_width;
        clearCarLabel.WC_height = self.weatherLabel.WC_height;
        clearCarLabel.font = [UIFont systemFontOfSize:16.0];
        clearCarLabel.textColor = [UIColor whiteColor];
        _clearCarLabel = clearCarLabel;
        [self.weatherView addSubview:clearCarLabel];
    }
    return _clearCarLabel;
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self loadData];
    }
    return self;
}

/**
 *  加载数据
 */
- (void)loadData {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"type"] = @1;
    __weak typeof(self) weakSelf = self;
    [self.manager POST:WCRecommendRequest parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        weakSelf.headerScrollViewModels = [WCHeaderScrollViewModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"POSTER"]];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [self setUpScrollView];
            [self setUpPageControl];
            [self setUpImageView];
            [self setUpWeatherReport];
        }];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {

    }];
}

/**
 *  设置滚动容器
 */
- (void)setUpScrollView
{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    scrollView.bounces = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    scrollView.contentSize = CGSizeMake(3 * self.WC_width, kNilOptions);
    self.scrollView = scrollView;
    [self addSubview:scrollView];
#warning 不知道啥意思
    if (self.headerScrollViewModels.count == 0 || self.headerScrollViewModels.count == 1) {
        scrollView.userInteractionEnabled = NO;
        return;
    }
    [self.scrollView setContentOffset:CGPointMake(self.WC_width, kNilOptions) animated:NO];
    self.moveTimer = [NSTimer scheduledTimerWithTimeInterval:moveImageTimer target:self selector:@selector(animateMoveImage) userInfo:nil repeats:YES];
    self.moveAuto = NO;
}

/**
 *  设置页码管理器
 */
- (void)setUpPageControl {
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.WC_x = kNilOptions;
    pageControl.WC_width = self.WC_width;
    pageControl.WC_height = WCCommonMargin;
    pageControl.WC_y = self.WC_height - WCCommonMargin - WCcommonSmallMargin;
    pageControl.numberOfPages = self.headerScrollViewModels.count;
    pageControl.currentPage = kNilOptions;
    pageControl.currentPageIndicatorTintColor = WCNavigationColor;
    pageControl.pageIndicatorTintColor = WCCommentBackgroundColor;
    pageControl.enabled = NO;
    self.pageControl = pageControl;
    [self addSubview:pageControl];
}

- (void)setUpImageView
{
    if (self.headerScrollViewModels.count == 0)return;
    if (self.headerScrollViewModels.count == 1){
        UIImageView *currentImageView = [[UIImageView alloc]init];
        currentImageView.frame = CGRectMake(kNilOptions, kNilOptions, self.WC_width,self.WC_height);
        WCHeaderScrollViewModel *imageModel = self.headerScrollViewModels.firstObject;
        currentImageView.image = [UIImage imageNamed:imageModel.posterLink];
        self.currentImageView = currentImageView;
        [self.scrollView addSubview:currentImageView];
        return;
    }
    UIImageView *currentImageView = [[UIImageView alloc]init];
    currentImageView.userInteractionEnabled = YES;
    currentImageView.frame = CGRectMake(kNilOptions, kNilOptions, self.WC_width,self.WC_height);
    WCHeaderScrollViewModel *currentModel = self.headerScrollViewModels.firstObject;
    [currentImageView setUpImageWithUrl:currentModel.posterLink];
    [currentImageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tappedPushClick)]];
    self.currentImageView = currentImageView;
    [self.scrollView addSubview:currentImageView];

    UIImageView *nextImageView = [[UIImageView alloc]init];
    nextImageView.frame = CGRectMake(self.WC_width * 2, kNilOptions, self.WC_width, self.WC_height);
    WCHeaderScrollViewModel *nextModel = self.headerScrollViewModels[1];
    [nextImageView setUpImageWithUrl:nextModel.posterLink];
    self.nextImageView = nextImageView;
    [self.scrollView addSubview:nextImageView];

    UIImageView *prefixImageView = [[UIImageView alloc]init];
    prefixImageView.frame = CGRectMake(kNilOptions, kNilOptions, self.WC_width, self.WC_height);
    WCHeaderScrollViewModel *prefixModel = self.headerScrollViewModels.lastObject;
    [prefixImageView setUpImageWithUrl:prefixModel.posterLink];
    self.prefixImageView = prefixImageView;
    [self.scrollView addSubview:prefixImageView];
}

- (void)setUpWeatherReport
{

}

#pragma mark - 跳转到对应页面控制器
- (void)tappedPushClick
{
    if (self.currentImageIndex == 0) return ;
    WCTabBarController *tabBar = (WCTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    WCNavigationController *nav = (WCNavigationController *)tabBar.selectedViewController;
    WCHeaderScrollViewModel *model = self.headerScrollViewModels[self.currentImageIndex];
    WCHeaderScrollViewController *headerVc = [[WCHeaderScrollViewController alloc]init];
    headerVc.model = model;
    [nav pushViewController:headerVc animated:YES];
}

#pragma mark - 定时器自动轮播
- (void)animateMoveImage {
    [self.scrollView setContentOffset:CGPointMake(2 *self.WC_width, kNilOptions) animated:YES];
    self.moveAuto = YES;
    [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(scrollViewDidEndDecelerating:) userInfo:nil repeats:NO];
}

@end


text:
package com.exxeta.iss.sonar.esql.api.tree.function;

import com.exxeta.iss.sonar.esql.api.tree.expression.ExpressionTree;
import com.exxeta.iss.sonar.esql.api.tree.lexical.SyntaxToken;

public interface PositionFunctionTree extends StringManipulationFunctionTree {
	SyntaxToken positionKeyword();
	SyntaxToken openingParenthesis();
	ExpressionTree searchExpression();
	SyntaxToken inKeyword();
	ExpressionTree sourceExpression();
	SyntaxToken fromKeyword();
	ExpressionTree fromExpression();
	SyntaxToken repeatKeyword();
	ExpressionTree repeatExpression();
	SyntaxToken closingParenthesis();
}


text:
from msrest.serialization import Model

class GrantAccessData(Model):
    """Data used for requesting a SAS.

    :param access: Possible values include: 'None', 'Read'
    :type access: str or ~azure.mgmt.compute.v2017_03_30.models.AccessLevel
    :param duration_in_seconds: Time duration in seconds until the SAS access
     expires.
    :type duration_in_seconds: int
    """

    _validation = {
        'access': {'required': True},
        'duration_in_seconds': {'required': True},
    }

    _attribute_map = {
        'access': {'key': 'access', 'type': 'AccessLevel'},
        'duration_in_seconds': {'key': 'durationInSeconds', 'type': 'int'},
    }

    def __init__(self, access, duration_in_seconds):
        super(GrantAccessData, self).__init__()
        self.access = access
        self.duration_in_seconds = duration_in_seconds


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.Extensions.DependencyInjection;

namespace FubarDev.FtpServer.ServerCommands
{
    /// <summary>
    /// This <see cref="IServerCommandExecutor"/> implementation creates a compiled delegate to call the server command handlers.
    /// </summary>
    public class DelegateServerCommandExecutor : IServerCommandExecutor
    {
        private readonly IFtpConnectionAccessor _ftpConnectionAccessor;
        private readonly Dictionary<Type, Delegate> _serverCommandHandlerDelegates = new Dictionary<Type, Delegate>();

        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateServerCommandExecutor"/> class.
        /// </summary>
        /// <param name="ftpConnectionAccessor">Accessor to get the FTP connection.</param>
        public DelegateServerCommandExecutor(IFtpConnectionAccessor ftpConnectionAccessor)
        {
            _ftpConnectionAccessor = ftpConnectionAccessor;
        }

        /// <inheritdoc />
        public Task ExecuteAsync(IServerCommand serverCommand, CancellationToken cancellationToken)
        {
            var serverCommandType = serverCommand.GetType();
            if (!_serverCommandHandlerDelegates.TryGetValue(serverCommandType, out var cmdDelegate))
            {
                var handlerType = typeof(IServerCommandHandler<>).MakeGenericType(serverCommandType);
                var executeAsyncMethod = handlerType.GetRuntimeMethod("ExecuteAsync", new[] { serverCommandType, typeof(CancellationToken) });
                var handler = _ftpConnectionAccessor.FtpConnection.ConnectionServices.GetRequiredService(handlerType);
                var commandParameter = Expression.Parameter(serverCommandType, "serverCommand");
                var cancellationTokenParameter = Expression.Parameter(typeof(CancellationToken), "cancellationToken");
                var call = Expression.Call(
                    Expression.Constant(handler),
                    executeAsyncMethod,
                    commandParameter,
                    cancellationTokenParameter);
                var expr = Expression.Lambda(call, commandParameter, cancellationTokenParameter);
                cmdDelegate = expr.Compile();
                _serverCommandHandlerDelegates.Add(serverCommandType, cmdDelegate);
            }

            return (Task)cmdDelegate.DynamicInvoke(serverCommand, cancellationToken)!;
        }
    }
}


text:
context('Aliasing', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/aliasing')
  })

  it('.as() - alias a DOM element for later use', () => {
    // https://on.cypress.io/as

    // Alias a DOM element for use later
    // We don't have to traverse to the element
    // later in our code, we reference it with @

    cy.get('.as-table').find('tbody>tr')
      .first().find('td').first()
      .find('button').as('firstBtn')

    // when we reference the alias, we place an
    // @ in front of its name
    cy.get('@firstBtn').click()

    cy.get('@firstBtn')
      .should('have.class', 'btn-success')
      .and('contain', 'Changed')
  })

  it('.as() - alias a route for later use', () => {

    // Alias the route to wait for its response
    cy.server()
    cy.route('GET', 'comments/*').as('getComment')

    // we have code that gets a comment when
    // the button is clicked in scripts.js
    cy.get('.network-btn').click()

    // https://on.cypress.io/wait
    cy.wait('@getComment').its('status').should('eq', 200)

  })
})


text:
package com.swingsane.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

/**
 * @author Roland Quast (roland@formreturn.com)
 *
 */
public class FilenameExtensionFilter implements FilenameFilter {

  private ArrayList<String> extensions = new ArrayList<String>();

  @Override
  public final boolean accept(File dir, String name) {
    if (new File(dir, name).isDirectory()) {
      return false;
    }
    name = name.toLowerCase();
    return extensions.contains(getExtension(name));
  }

  public final void addExtension(String extension) {
    extensions.add(extension);
  }

  private String getExtension(String name) {
    if (name != null) {
      int i = name.lastIndexOf('.');
      if ((i > 0) && (i < (name.length() - 1))) {
        return name.substring(i + 1).toLowerCase();
      }
    }
    return null;
  }

}


text:
require 'steam-condenser/community/game_item'

module SteamCondenser::Community

  # Represents a Team Fortress 2 item
  #
  # @author Sebastian Staudt
  class TF2Item < GameItem

    # The names of the classes available in Team Fortress 2
    CLASSES = [ :scout, :sniper, :soldier, :demoman, :medic, :heavy, :pyro, :spy ]

    # Returns the slot where this item can be equipped in or `nil` if this item
    # cannot be equipped
    #
    # @return [String, nil] The slot where this item can be equipped in
    attr_reader :slot

    # Creates a new instance of a TF2 item with the given data
    #
    # @param [TF2Inventory] inventory The inventory this item is contained in
    # @param [Hash<Symbol, Object>] item_data The data specifying this item
    # @raise [Error::WebApi] on Web API errors
    def initialize(inventory, item_data)
      super

      @slot = schema_data[:item_slot]

      @equipped = {}
      CLASSES.each_index do |class_id|
        @equipped[CLASSES[class_id]] = (item_data[:inventory] & (1 << 16 + class_id) != 0)
      end
    end

    # Returns the class symbols for each class this player has equipped this item
    #
    # @return [Array<String>] The names of the classes this player has equipped
    #         this item
    def classes_equipped?
      @equipped.reject { |_, equipped| !equipped }
    end

    # Returns whether this item is equipped by this player at all
    #
    # @return [Boolean] `true` if the player has equipped this item at all
    def equipped?
      @equipped.has_value? true
    end

  end
end


text:
package com.thetonymaster.pipesandfilters

import com.thetonymaster.CompletableApp
import com.thetonymaster.pipesandfilters.weatherendpoint.WeatherEndpoint
import com.thetonymaster.pipesandfilters.weatherforecast.WeatherForecast
import com.thetonymaster.pipesandfilters.sink.Sink

import akka.actor._
import scalaj.http._

object PipesAndFiltersDriver extends CompletableApp(10) {

    val filter3 = system.actorOf(Props[Sink], "sink")
    val filter2 = system.actorOf(Props(classOf[WeatherForecast], filter3), "weatherForecast")
    val filter1 = system.actorOf(Props(classOf[WeatherEndpoint], filter2), "weatherEndpoint")
    val weatherURL: String = "http://api.openweathermap.org/data/2.5/group?id=3979844,4005539,3530597,4005270&units=metric&appid=5a917cc621913d534c113dbae4b5e5d9"

    val request: HttpRequest = Http(weatherURL)
    for(_ <- 0 until 10){
      val response = request.asString
      filter1 ! response.body
      Thread.sleep(1000)
    }
     awaitCompletion
    println("PipesAndFilters: is completed.")

}


text:
using System.Data.Entity.Migrations;
using Abp.MultiTenancy;
using Abp.Zero.EntityFramework;
using ImproveX.Migrations.SeedData;
using EntityFramework.DynamicFilters;

namespace ImproveX.Migrations
{
    public sealed class Configuration : DbMigrationsConfiguration<ImproveX.EntityFramework.ImproveXDbContext>, IMultiTenantSeed
    {
        public AbpTenantBase Tenant { get; set; }

        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
            ContextKey = "ImproveX";
        }

        protected override void Seed(ImproveX.EntityFramework.ImproveXDbContext context)
        {
            context.DisableAllFilters();

            if (Tenant == null)
            {
                //Host seed
                new InitialHostDbBuilder(context).Create();

                //Default tenant seed (in host database).
                new DefaultTenantCreator(context).Create();
                new TenantRoleAndUserBuilder(context, 1).Create();
            }
            else
            {
                //You can add seed for tenant databases and use Tenant property...
            }

            context.SaveChanges();
        }
    }
}


text:
module BootstrapFilestyleRails
  # Public: String gem version number, which reflects the asset version number.
  VERSION = '1.2.1'
end