text:
import React, { Component } from 'react'
import axios from 'axios'

export default class PersonalInfo extends Component {
  constructor(props) {
    super(props)
    this.state = {
      username: {edit: false, info: ''},
      password: {edit: false, info: ''},
      email: {edit: false, info: ''},
      phone: {edit: false, info: ''},
      firstName: {edit: false, info: ''},
      lastName: {edit: false, info: ''},
      birthday: {edit: false, info: ''},
      gender: {edit: false, info: ''},
    }
    this._beingEdited = this._beingEdited.bind(this)
    this._edit = this._edit.bind(this)
    this._editOrSave = this._editOrSave.bind(this)
    this._saveInfo = this._saveInfo.bind(this)
  }

  componentDidMount() {
    for (var key in this.props.info) {
      if (key in this.state) {
        var item = {}
        var obj = Object.assign({}, this.state[key])
        obj.info = this.props.info[key]
        item[key] = obj
        this.setState(item)
      }
    }
  }

  _beingEdited(current, name) {
    if (current.edit) {
      return (
        <input type="text" className="personal-info-entry col-md-11" id={name} placeholder={current.info}/>
      )
    } else {
      return (
{current.info}
)
    }
  }

  _edit(passed) {
    var obj = {}
    var item = {
      edit: !this.state[passed].edit,
      info: this.state[passed].info
    }
    obj[passed] = item
    this.setState(obj)
  }

  _editOrSave(passed) {
    if (!this.state[passed].edit) {
      return (
<button onClick={() => this._edit(passed)} type="button" className="journey-btn journey-btn-secondary journey-btn-sm">Edit</button>
)
    } else {
      return
<button onClick={() => this._saveInfo(passed)} type="button" className="journey-btn journey-btn-primary journey-btn-sm">Save</button>

    }
  }

  _saveInfo(passed) {
    var val = document.getElementById(passed).value
    var obj = {}
    var item = {
      edit: false,
      info: val
    }
    obj[passed] = item
    this.setState(obj)
    var sendObj = {}
    sendObj[passed] = val
    this.props.saveParent(sendObj)
    axios.post('/api/profile', {
      updated: JSON.stringify(sendObj)
    })
  }

  render() {
    return (

Hello, {this.state.firstName.info}!

Name

          {this.state.firstName.info} {this.state.lastName.info}

Email

            {this._beingEdited(this.state.email, 'email')}
            {this._editOrSave('email')}

Phone

            {this._beingEdited(this.state.phone, 'phone')}
            {this._editOrSave('phone')}

Birthday

            {this._beingEdited(this.state.birthday, 'birthday')}
            {this._editOrSave('birthday')}

Gender

            {this._beingEdited(this.state.gender)}
            {this._editOrSave('gender')}

    )
  }
}


text:
<?php

declare(strict_types=1);

namespace Sonata\AdminBundle\Tests\Security\Handler;

use PHPUnit\Framework\TestCase;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Security\Acl\Permission\MaskBuilder;
use Sonata\AdminBundle\Security\Handler\AclSecurityHandler;
use Symfony\Component\Security\Acl\Model\MutableAclInterface;
use Symfony\Component\Security\Acl\Model\MutableAclProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;

final class AclSecurityHandlerTest extends TestCase
{
    /**
     * NEXT_MAJOR: Remove the group legacy.
     *
     * @group legacy
     */
    public function testAcl(): void
    {
        $admin = $this->createMock(AdminInterface::class);
        $admin
            ->method('getCode')
            ->willReturn('test');

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker
            ->method('isGranted')
            ->willReturn(true);

        $aclProvider = $this->createMock(MutableAclProviderInterface::class);

        $handler = new AclSecurityHandler($this->createMock(TokenStorageInterface::class), $authorizationChecker, $aclProvider, MaskBuilder::class, 'ROLE_SUPER_ADMIN');

        // NEXT_MAJOR: Remove the next line.
        static::assertTrue($handler->isGranted($admin, ['TOTO']));
        static::assertTrue($handler->isGranted($admin, 'TOTO'));

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker
            ->method('isGranted')
            ->willReturn(false);

        $handler = new AclSecurityHandler($this->createMock(TokenStorageInterface::class), $authorizationChecker, $aclProvider, MaskBuilder::class, 'ROLE_SUPER_ADMIN');

        // NEXT_MAJOR: Remove the next line.
        static::assertFalse($handler->isGranted($admin, ['TOTO']));
        static::assertFalse($handler->isGranted($admin, 'TOTO'));
    }

    public function testBuildInformation(): void
    {
        $informations = [
            'EDIT' => ['EDIT'],
        ];

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $admin = $this->createMock(AdminInterface::class);
        $admin->expects(static::once())
            ->method('getCode')
            ->willReturn('test');

        $admin->expects(static::once())
            ->method('getSecurityInformation')
            ->willReturn($informations);

        $aclProvider = $this->createMock(MutableAclProviderInterface::class);

        $handler = new AclSecurityHandler($this->createMock(TokenStorageInterface::class), $authorizationChecker, $aclProvider, MaskBuilder::class, 'ROLE_SUPER_ADMIN');

        $results = $handler->buildSecurityInformation($admin);

        static::assertArrayHasKey('ROLE_TEST_EDIT', $results);
    }

    public function testWithAuthenticationCredentialsNotFoundException(): void
    {
        $admin = $this->createMock(AdminInterface::class);

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker
            ->method('isGranted')
            ->will(static::throwException(new AuthenticationCredentialsNotFoundException('FAIL')));

        $aclProvider = $this->createMock(MutableAclProviderInterface::class);

        $handler = new AclSecurityHandler($this->createMock(TokenStorageInterface::class), $authorizationChecker, $aclProvider, MaskBuilder::class, 'ROLE_SUPER_ADMIN');

        static::assertFalse($handler->isGranted($admin, 'raise exception', $admin));
    }

    public function testWithNonAuthenticationCredentialsNotFoundException(): void
    {
        $this->expectException(\RuntimeException::class);

        $admin = $this->createMock(AdminInterface::class);

        $authorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
        $authorizationChecker
            ->method('isGranted')
            ->will(static::throwException(new \RuntimeException('FAIL')));

        $aclProvider = $this->createMock(MutableAclProviderInterface::class);

        $handler = new AclSecurityHandler($this->createMock(TokenStorageInterface::class), $authorizationChecker, $aclProvider, MaskBuilder::class, 'ROLE_SUPER_ADMIN');

        static::assertFalse($handler->isGranted($admin, 'raise exception', $admin));
    }

    public function testSuccessfulUpdateAcl(): void
    {
        $acl = $this->createStub(MutableAclInterface::class);
        $aclProvider = $this->createMock(MutableAclProviderInterface::class);

        $aclProvider
            ->expects(static::once())
            ->method('updateAcl')
            ->with($acl);

        $handler = new AclSecurityHandler(
            $this->createMock(TokenStorageInterface::class),
            $this->createMock(AuthorizationCheckerInterface::class),
            $aclProvider,
            MaskBuilder::class,
            'ROLE_SUPER_ADMIN'
        );
        $handler->updateAcl($acl);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package gov.nih.nci.cagrid.core;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import jdepend.framework.JDepend;
import jdepend.framework.JavaPackage;
import junit.framework.TestCase;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

public class CycleTestCase extends TestCase {

    private JDepend jdepend;

    public CycleTestCase(String name) {
        super(name);
    }

    protected void setUp() {
        jdepend = new JDepend();
        try {
            String dir = System.getProperty("build.dir", ".");
            jdepend.addDirectory(dir);
            jdepend.analyzeTestClasses(false);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            fail(ioe.getMessage());
        }
    }

    protected void tearDown() {
        jdepend = null;
    }

    /**
     * Tests that a package dependency cycle does not exist for any of the
     * analyzed packages.
     */
    public void testAllPackagesCycle() {
        int numCycles = 0;
        Collection packages = jdepend.analyze();
        if (jdepend.containsCycles()) {
            Iterator iter = packages.iterator();
            while (iter.hasNext()) {
                JavaPackage p = (JavaPackage) iter.next();
                if (p.containsCycle()) {
                    System.out.println("\nPackage: " + p.getName() + " contains a cycle with:");
                    numCycles++;
                    List list = new ArrayList();
                    p.collectAllCycles(list);
                    for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                        JavaPackage dependsP = (JavaPackage) iterator.next();
                        System.out.println("->" + dependsP.getName());

                    }
                }
            }
        }
        System.out.println("\n===== Found " + numCycles + " cyclic packages. =====\n\n");

        assertEquals("Cycles exist", false, jdepend.containsCycles());
    }

    public static void main(String args[]) {

        TestRunner runner = new TestRunner();
        TestResult result = runner.doRun(new TestSuite(CycleTestCase.class));
        System.exit(result.errorCount() + result.failureCount());
    }
}


text:
<?php
include_once("connection.php");
include_once("function.php");
include_once("configfetch.php");
	$tsqlInformation = "select count(*) Total FROM [NOAH].[dbo].[DNSCacheAudited] tableInf, [NOAH].[dbo].[ServerAudited] sa, [NOAH].[dbo].[Hunt] hu
		WHERE
		tableInf.serverID = sa.serverID
		AND hu.huntingID = sa.huntingID $sqlFilter";
		$getInformation = sqlsrv_query($conn, $tsqlInformation);
	if ( $getInformation === false)
	die( print_r( sqlsrv_errors(), true));
	$data = array();
	$data['data'] = '';
	if(sqlsrv_has_rows($getInformation)) {
	if( $row = sqlsrv_fetch_array( $getInformation, SQLSRV_FETCH_ASSOC)) {
		$total = $row['Total'];
	}
	//break records into pages
	$total_pages = ceil($total/$item_per_page);

	//position of records
	$page_position = (($page_number-1) * $item_per_page);
	$tsqlInformation = "SELECT
		hu.huntingGUID, sa.serverName, sa.serverID, DNSCacheAuditedID, [RecordName]
	  FROM [NOAH].[dbo].[DNSCacheAudited] tableInf, [NOAH].[dbo].[ServerAudited] sa, [NOAH].[dbo].[Hunt] hu
		WHERE
		tableInf.serverID = sa.serverID
		AND hu.huntingID = sa.huntingID
		$sqlFilter
		GROUP BY hu.huntingGUID, sa.serverName, sa.serverID, DNSCacheAuditedID, [RecordName]
		ORDER BY DNSCacheAuditedID
		OFFSET ".$page_position." ROWS
		FETCH NEXT ".$item_per_page." ROWS ONLY
		";
	}
$getInformation = sqlsrv_query($conn, $tsqlInformation);
if ( $getInformation === false)
die( print_r( sqlsrv_errors(), true));
$data = array();
$data['data'] = '';
if(sqlsrv_has_rows($getInformation)) {
	while( $row = sqlsrv_fetch_array( $getInformation, SQLSRV_FETCH_ASSOC)) {
		echo '
'.$row['huntingGUID'].'	'.$row['serverName'].'	'.$row['RecordName'].'
';
	}
}

echo '

';
echo paginate_function($item_per_page, $page_number, $total, $total_pages);
echo '
';


text: Facultad de Contaduría y Administración


text:
package org.ray.runtime.object;

import java.util.List;
import java.util.stream.Collectors;
import org.ray.api.id.BaseId;
import org.ray.api.id.ObjectId;
import org.ray.runtime.context.WorkerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Object store methods for cluster mode. This is a wrapper class for core worker object interface.
 */
public class NativeObjectStore extends ObjectStore {

  private static final Logger LOGGER = LoggerFactory.getLogger(NativeObjectStore.class);

  /**
   * The native pointer of core worker.
   */
  private final long nativeCoreWorkerPointer;

  public NativeObjectStore(WorkerContext workerContext, long nativeCoreWorkerPointer) {
    super(workerContext);
    this.nativeCoreWorkerPointer = nativeCoreWorkerPointer;
  }

  @Override
  public ObjectId putRaw(NativeRayObject obj) {
    return new ObjectId(nativePut(nativeCoreWorkerPointer, obj));
  }

  @Override
  public void putRaw(NativeRayObject obj, ObjectId objectId) {
    nativePut(nativeCoreWorkerPointer, objectId.getBytes(), obj);
  }

  @Override
  public List<NativeRayObject> getRaw(List<ObjectId> objectIds, long timeoutMs) {
    return nativeGet(nativeCoreWorkerPointer, toBinaryList(objectIds), timeoutMs);
  }

  @Override
  public List<Boolean> wait(List<ObjectId> objectIds, int numObjects, long timeoutMs) {
    return nativeWait(nativeCoreWorkerPointer, toBinaryList(objectIds), numObjects, timeoutMs);
  }

  @Override
  public void delete(List<ObjectId> objectIds, boolean localOnly, boolean deleteCreatingTasks) {
    nativeDelete(nativeCoreWorkerPointer, toBinaryList(objectIds), localOnly, deleteCreatingTasks);
  }

  private static List<byte[]> toBinaryList(List<ObjectId> ids) {
    return ids.stream().map(BaseId::getBytes).collect(Collectors.toList());
  }

  private static native byte[] nativePut(long nativeCoreWorkerPointer, NativeRayObject obj);

  private static native void nativePut(long nativeCoreWorkerPointer, byte[] objectId,
      NativeRayObject obj);

  private static native List<NativeRayObject> nativeGet(long nativeCoreWorkerPointer,
      List<byte[]> ids, long timeoutMs);

  private static native List<Boolean> nativeWait(long nativeCoreWorkerPointer,
      List<byte[]> objectIds, int numObjects, long timeoutMs);

  private static native void nativeDelete(long nativeCoreWorkerPointer, List<byte[]> objectIds,
      boolean localOnly, boolean deleteCreatingTasks);
}


text:
import Hand from './Hand';
import EventEmitter from './../misc/EventEmitter';

class Player extends EventEmitter {

  constructor() {
    super();

    this.hand = new Hand();
  }

  attachGame(game) {
    this.game = game;
  }

  drawCard() {
    var card = this.game.drawCard();
    // If the count of card decks is not balanced well with the count of
    // players and the cards they are initially dealt, the drawing stack
    // can run out of cards.
    if (card) {
      this.hand.takeCard(card);
      this.emit('player:drawn', card);
    }
  }

  playCard() {
    return this.chooseCard().then(
      card => {
        this.hand.dropCard(card);
        this.game.playCard(card);
        this.emit('player:played', card);
      });
  }

}

export default Player;


text:
Imports System.Runtime.InteropServices
Imports System.IO

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim objFolder As DirectoryInfo
        Dim objFileInfo As FileInfo
        Dim objApplication As SolidEdgeFramework.Application = Nothing
        Dim objDocuments As SolidEdgeFramework.Documents = Nothing
        Dim objSheetMetalDocument As SolidEdgePart.SheetMetalDocument = Nothing
        Dim objSketch As SolidEdgePart.Sketch = Nothing

        Dim objProfile As SolidEdgePart.Profile = Nothing
        Dim objProfCollection As SolidEdgePart.Profiles = Nothing
        Dim objProfArray(0 To 2) As SolidEdgePart.Profile
        Dim i As Integer
        Dim objNormCutOut As SolidEdgePart.NormalCutout = Nothing
        Dim objModel As SolidEdgePart.Model = Nothing
        Try

            objFolder = GetTrainingFolder()
            objFileInfo = New FileInfo(Path.Combine(objFolder.FullName, "Foot1.psm"))
            ' Start Solid Edge
            objApplication = Activator.CreateInstance(Type.GetTypeFromProgID("SolidEdge.Application"))
            'Get running instance of Solid Edge
            'objApplication = Marshal.GetActiveObject("SolidEdge.Application")
            objApplication.Visible = True
            objDocuments = objApplication.Documents

            objSheetMetalDocument = objDocuments.Open(objFileInfo.FullName)
            objModel = objSheetMetalDocument.Models.Item(1)

            ' Add a sketch & profile
            objSketch = objSheetMetalDocument.Sketches.Add
            objProfile = objSketch.Profiles.Add(objSheetMetalDocument.RefPlanes.Item(1))
            objProfile.Circles2d.AddByCenterRadius(x:=0.01, y:=0.05, Radius:=0.05)
            objProfile.Visible = False
            objProfCollection = objProfile.Parent.Profiles
            For i = 0 To objProfCollection.Count
                objProfArray(i) = objProfCollection(i)
            Next i

            objNormCutOut = objModel.NormalCutouts.AddThroughNextMulti(1, objProfArray, SolidEdgePart.FeaturePropertyConstants.igLeft, SolidEdgePart.FeaturePropertyConstants.igSMFaceCutout)

        Catch ex As Exception
            MsgBox(ex.ToString)
        Finally

        End Try

    End Sub
    Function GetTrainingFolder() As DirectoryInfo
        Dim objInstallData As SEInstallDataLib.SEInstallData = Nothing
        Dim objInstallFolder As DirectoryInfo = Nothing
        Dim objTrainingFolder As DirectoryInfo = Nothing

        Try
            objInstallData = New SEInstallDataLib.SEInstallData
            objInstallFolder = New DirectoryInfo(objInstallData.GetInstalledPath())
            objTrainingFolder = New DirectoryInfo(Path.Combine(objInstallFolder.Parent.FullName, "Training"))
        Catch
        Finally
            If Not (objInstallData Is Nothing) Then
                Marshal.FinalReleaseComObject(objInstallData)
                objInstallData = Nothing
            End If
        End Try

        Return objTrainingFolder
    End Function

End Class


text:
package io.zucchiniui.backend.scenario.domainimpl;

import io.zucchiniui.backend.scenario.dao.ScenarioDAO;
import io.zucchiniui.backend.scenario.domain.Scenario;
import io.zucchiniui.backend.scenario.domain.ScenarioQuery;
import io.zucchiniui.backend.scenario.domain.ScenarioRepository;
import io.zucchiniui.backend.support.ddd.morphia.MorphiaQueriableRepository;
import org.springframework.stereotype.Component;

@Component
class ScenarioRepositoryImpl extends MorphiaQueriableRepository<Scenario, String, ScenarioQuery> implements ScenarioRepository {

    public ScenarioRepositoryImpl(final ScenarioDAO dao) {
        super(dao);
    }

}


text:
*> \brief  DPPSVX computes the solution to system of linear equations A * X = B for OTHER matrices
*
*  =========== DOCUMENTATION ===========
*
* Online html documentation available at
*            http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download DPPSVX + dependencies
*>
*> [TGZ]
*>
*> [ZIP]
*>
*> [TXT]
*> \endhtmlonly
*
*  Definition:
*  ===========
*
*       SUBROUTINE DPPSVX( FACT, UPLO, N, NRHS, AP, AFP, EQUED, S, B, LDB,
*                          X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO )
*
*       .. Scalar Arguments ..
*       CHARACTER          EQUED, FACT, UPLO
*       INTEGER            INFO, LDB, LDX, N, NRHS
*       DOUBLE PRECISION   RCOND
*       ..
*       .. Array Arguments ..
*       INTEGER            IWORK( * )
*       DOUBLE PRECISION   AFP( * ), AP( * ), B( LDB, * ), BERR( * ),
*      $                   FERR( * ), S( * ), WORK( * ), X( LDX, * )
*       ..
*
*
*> \par Purpose:
*  =============
*>
*> \verbatim
*>
*> DPPSVX uses the Cholesky factorization A = U**T*U or A = L*L**T to
*> compute the solution to a real system of linear equations
*>    A * X = B,
*> where A is an N-by-N symmetric positive definite matrix stored in
*> packed format and X and B are N-by-NRHS matrices.
*>
*> Error bounds on the solution and a condition estimate are also
*> provided.
*> \endverbatim
*
*> \par Description:
*  =================
*>
*> \verbatim
*>
*> The following steps are performed:
*>
*> 1. If FACT = 'E', real scaling factors are computed to equilibrate
*>    the system:
*>       diag(S) * A * diag(S) * inv(diag(S)) * X = diag(S) * B
*>    Whether or not the system will be equilibrated depends on the
*>    scaling of the matrix A, but if equilibration is used, A is
*>    overwritten by diag(S)*A*diag(S) and B by diag(S)*B.
*>
*> 2. If FACT = 'N' or 'E', the Cholesky decomposition is used to
*>    factor the matrix A (after equilibration if FACT = 'E') as
*>       A = U**T* U,  if UPLO = 'U', or
*>       A = L * L**T,  if UPLO = 'L',
*>    where U is an upper triangular matrix and L is a lower triangular
*>    matrix.
*>
*> 3. If the leading i-by-i principal minor is not positive definite,
*>    then the routine returns with INFO = i. Otherwise, the factored
*>    form of A is used to estimate the condition number of the matrix
*>    A.  If the reciprocal of the condition number is less than machine
*>    precision, INFO = N+1 is returned as a warning, but the routine
*>    still goes on to solve for X and compute error bounds as
*>    described below.
*>
*> 4. The system of equations is solved for X using the factored form
*>    of A.
*>
*> 5. Iterative refinement is applied to improve the computed solution
*>    matrix and calculate error bounds and backward error estimates
*>    for it.
*>
*> 6. If equilibration was used, the matrix X is premultiplied by
*>    diag(S) so that it solves the original system before
*>    equilibration.
*> \endverbatim
*
*  Arguments:
*  ==========
*
*> \param[in] FACT
*> \verbatim
*>          FACT is CHARACTER*1
*>          Specifies whether or not the factored form of the matrix A is
*>          supplied on entry, and if not, whether the matrix A should be
*>          equilibrated before it is factored.
*>          = 'F':  On entry, AFP contains the factored form of A.
*>                  If EQUED = 'Y', the matrix A has been equilibrated
*>                  with scaling factors given by S.  AP and AFP will not
*>                  be modified.
*>          = 'N':  The matrix A will be copied to AFP and factored.
*>          = 'E':  The matrix A will be equilibrated if necessary, then
*>                  copied to AFP and factored.
*> \endverbatim
*>
*> \param[in] UPLO
*> \verbatim
*>          UPLO is CHARACTER*1
*>          = 'U':  Upper triangle of A is stored;
*>          = 'L':  Lower triangle of A is stored.
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*>          N is INTEGER
*>          The number of linear equations, i.e., the order of the
*>          matrix A.  N >= 0.
*> \endverbatim
*>
*> \param[in] NRHS
*> \verbatim
*>          NRHS is INTEGER
*>          The number of right hand sides, i.e., the number of columns
*>          of the matrices B and X.  NRHS >= 0.
*> \endverbatim
*>
*> \param[in,out] AP
*> \verbatim
*>          AP is DOUBLE PRECISION array, dimension (N*(N+1)/2)
*>          On entry, the upper or lower triangle of the symmetric matrix
*>          A, packed columnwise in a linear array, except if FACT = 'F'
*>          and EQUED = 'Y', then A must contain the equilibrated matrix
*>          diag(S)*A*diag(S).  The j-th column of A is stored in the
*>          array AP as follows:
*>          if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j;
*>          if UPLO = 'L', AP(i + (j-1)*(2n-j)/2) = A(i,j) for j<=i<=n.
*>          See below for further details.  A is not modified if
*>          FACT = 'F' or 'N', or if FACT = 'E' and EQUED = 'N' on exit.
*>
*>          On exit, if FACT = 'E' and EQUED = 'Y', A is overwritten by
*>          diag(S)*A*diag(S).
*> \endverbatim
*>
*> \param[in,out] AFP
*> \verbatim
*>          AFP is DOUBLE PRECISION array, dimension (N*(N+1)/2)
*>          If FACT = 'F', then AFP is an input argument and on entry
*>          contains the triangular factor U or L from the Cholesky
*>          factorization A = U**T*U or A = L*L**T, in the same storage
*>          format as A.  If EQUED .ne. 'N', then AFP is the factored
*>          form of the equilibrated matrix A.
*>
*>          If FACT = 'N', then AFP is an output argument and on exit
*>          returns the triangular factor U or L from the Cholesky
*>          factorization A = U**T * U or A = L * L**T of the original
*>          matrix A.
*>
*>          If FACT = 'E', then AFP is an output argument and on exit
*>          returns the triangular factor U or L from the Cholesky
*>          factorization A = U**T * U or A = L * L**T of the equilibrated
*>          matrix A (see the description of AP for the form of the
*>          equilibrated matrix).
*> \endverbatim
*>
*> \param[in,out] EQUED
*> \verbatim
*>          EQUED is CHARACTER*1
*>          Specifies the form of equilibration that was done.
*>          = 'N':  No equilibration (always true if FACT = 'N').
*>          = 'Y':  Equilibration was done, i.e., A has been replaced by
*>                  diag(S) * A * diag(S).
*>          EQUED is an input argument if FACT = 'F'; otherwise, it is an
*>          output argument.
*> \endverbatim
*>
*> \param[in,out] S
*> \verbatim
*>          S is DOUBLE PRECISION array, dimension (N)
*>          The scale factors for A; not accessed if EQUED = 'N'.  S is
*>          an input argument if FACT = 'F'; otherwise, S is an output
*>          argument.  If FACT = 'F' and EQUED = 'Y', each element of S
*>          must be positive.
*> \endverbatim
*>
*> \param[in,out] B
*> \verbatim
*>          B is DOUBLE PRECISION array, dimension (LDB,NRHS)
*>          On entry, the N-by-NRHS right hand side matrix B.
*>          On exit, if EQUED = 'N', B is not modified; if EQUED = 'Y',
*>          B is overwritten by diag(S) * B.
*> \endverbatim
*>
*> \param[in] LDB
*> \verbatim
*>          LDB is INTEGER
*>          The leading dimension of the array B.  LDB >= max(1,N).
*> \endverbatim
*>
*> \param[out] X
*> \verbatim
*>          X is DOUBLE PRECISION array, dimension (LDX,NRHS)
*>          If INFO = 0 or INFO = N+1, the N-by-NRHS solution matrix X to
*>          the original system of equations.  Note that if EQUED = 'Y',
*>          A and B are modified on exit, and the solution to the
*>          equilibrated system is inv(diag(S))*X.
*> \endverbatim
*>
*> \param[in] LDX
*> \verbatim
*>          LDX is INTEGER
*>          The leading dimension of the array X.  LDX >= max(1,N).
*> \endverbatim
*>
*> \param[out] RCOND
*> \verbatim
*>          RCOND is DOUBLE PRECISION
*>          The estimate of the reciprocal condition number of the matrix
*>          A after equilibration (if done).  If RCOND is less than the
*>          machine precision (in particular, if RCOND = 0), the matrix
*>          is singular to working precision.  This condition is
*>          indicated by a return code of INFO > 0.
*> \endverbatim
*>
*> \param[out] FERR
*> \verbatim
*>          FERR is DOUBLE PRECISION array, dimension (NRHS)
*>          The estimated forward error bound for each solution vector
*>          X(j) (the j-th column of the solution matrix X).
*>          If XTRUE is the true solution corresponding to X(j), FERR(j)
*>          is an estimated upper bound for the magnitude of the largest
*>          element in (X(j) - XTRUE) divided by the magnitude of the
*>          largest element in X(j).  The estimate is as reliable as
*>          the estimate for RCOND, and is almost always a slight
*>          overestimate of the true error.
*> \endverbatim
*>
*> \param[out] BERR
*> \verbatim
*>          BERR is DOUBLE PRECISION array, dimension (NRHS)
*>          The componentwise relative backward error of each solution
*>          vector X(j) (i.e., the smallest relative change in
*>          any element of A or B that makes X(j) an exact solution).
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*>          WORK is DOUBLE PRECISION array, dimension (3*N)
*> \endverbatim
*>
*> \param[out] IWORK
*> \verbatim
*>          IWORK is INTEGER array, dimension (N)
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*>          INFO is INTEGER
*>          = 0:  successful exit
*>          < 0:  if INFO = -i, the i-th argument had an illegal value
*>          > 0:  if INFO = i, and i is
*>                <= N:  the leading minor of order i of A is
*>                       not positive definite, so the factorization
*>                       could not be completed, and the solution has not
*>                       been computed. RCOND = 0 is returned.
*>                = N+1: U is nonsingular, but RCOND is less than machine
*>                       precision, meaning that the matrix is singular
*>                       to working precision.  Nevertheless, the
*>                       solution and error bounds are computed because
*>                       there are a number of situations where the
*>                       computed solution can be more accurate than the
*>                       value of RCOND would suggest.
*> \endverbatim
*
*  Authors:
*  ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date April 2012
*
*> \ingroup doubleOTHERsolve
*
*> \par Further Details:
*  =====================
*>
*> \verbatim
*>
*>  The packed storage scheme is illustrated by the following example
*>  when N = 4, UPLO = 'U':
*>
*>  Two-dimensional storage of the symmetric matrix A:
*>
*>     a11 a12 a13 a14
*>         a22 a23 a24
*>             a33 a34     (aij = conjg(aji))
*>                 a44
*>
*>  Packed storage of the upper triangle of A:
*>
*>  AP = [ a11, a12, a22, a13, a23, a33, a14, a24, a34, a44 ]
*> \endverbatim
*>
*  =====================================================================
      SUBROUTINE DPPSVX( FACT, UPLO, N, NRHS, AP, AFP, EQUED, S, B, LDB,
     $                   X, LDX, RCOND, FERR, BERR, WORK, IWORK, INFO )
*
*  -- LAPACK driver routine (version 3.7.1) --
*  -- LAPACK is a software package provided by Univ. of Tennessee,    --
*  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
*     April 2012
*
*     .. Scalar Arguments ..
      CHARACTER          EQUED, FACT, UPLO
      INTEGER            INFO, LDB, LDX, N, NRHS
      DOUBLE PRECISION   RCOND
*     ..
*     .. Array Arguments ..
      INTEGER            IWORK( * )
      DOUBLE PRECISION   AFP( * ), AP( * ), B( LDB, * ), BERR( * ),
     $                   FERR( * ), S( * ), WORK( * ), X( LDX, * )
*     ..
*
*  =====================================================================
*
*     .. Parameters ..
      DOUBLE PRECISION   ZERO, ONE
      PARAMETER          ( ZERO = 0.0D+0, ONE = 1.0D+0 )
*     ..
*     .. Local Scalars ..
      LOGICAL            EQUIL, NOFACT, RCEQU
      INTEGER            I, INFEQU, J
      DOUBLE PRECISION   AMAX, ANORM, BIGNUM, SCOND, SMAX, SMIN, SMLNUM
*     ..
*     .. External Functions ..
      LOGICAL            LSAME
      DOUBLE PRECISION   DLAMCH, DLANSP
      EXTERNAL           LSAME, DLAMCH, DLANSP
*     ..
*     .. External Subroutines ..
      EXTERNAL           DCOPY, DLACPY, DLAQSP, DPPCON, DPPEQU, DPPRFS,
     $                   DPPTRF, DPPTRS, XERBLA
*     ..
*     .. Intrinsic Functions ..
      INTRINSIC          MAX, MIN
*     ..
*     .. Executable Statements ..
*
      INFO = 0
      NOFACT = LSAME( FACT, 'N' )
      EQUIL = LSAME( FACT, 'E' )
      IF( NOFACT .OR. EQUIL ) THEN
         EQUED = 'N'
         RCEQU = .FALSE.
      ELSE
         RCEQU = LSAME( EQUED, 'Y' )
         SMLNUM = DLAMCH( 'Safe minimum' )
         BIGNUM = ONE / SMLNUM
      END IF
*
*     Test the input parameters.
*
      IF( .NOT.NOFACT .AND. .NOT.EQUIL .AND. .NOT.LSAME( FACT, 'F' ) )
     $     THEN
         INFO = -1
      ELSE IF( .NOT.LSAME( UPLO, 'U' ) .AND. .NOT.LSAME( UPLO, 'L' ) )
     $          THEN
         INFO = -2
      ELSE IF( N.LT.0 ) THEN
         INFO = -3
      ELSE IF( NRHS.LT.0 ) THEN
         INFO = -4
      ELSE IF( LSAME( FACT, 'F' ) .AND. .NOT.
     $         ( RCEQU .OR. LSAME( EQUED, 'N' ) ) ) THEN
         INFO = -7
      ELSE
         IF( RCEQU ) THEN
            SMIN = BIGNUM
            SMAX = ZERO
            DO 10 J = 1, N
               SMIN = MIN( SMIN, S( J ) )
               SMAX = MAX( SMAX, S( J ) )
   10       CONTINUE
            IF( SMIN.LE.ZERO ) THEN
               INFO = -8
            ELSE IF( N.GT.0 ) THEN
               SCOND = MAX( SMIN, SMLNUM ) / MIN( SMAX, BIGNUM )
            ELSE
               SCOND = ONE
            END IF
         END IF
         IF( INFO.EQ.0 ) THEN
            IF( LDB.LT.MAX( 1, N ) ) THEN
               INFO = -10
            ELSE IF( LDX.LT.MAX( 1, N ) ) THEN
               INFO = -12
            END IF
         END IF
      END IF
*
      IF( INFO.NE.0 ) THEN
         CALL XERBLA( 'DPPSVX', -INFO )
         RETURN
      END IF
*
      IF( EQUIL ) THEN
*
*        Compute row and column scalings to equilibrate the matrix A.
*
         CALL DPPEQU( UPLO, N, AP, S, SCOND, AMAX, INFEQU )
         IF( INFEQU.EQ.0 ) THEN
*
*           Equilibrate the matrix.
*
            CALL DLAQSP( UPLO, N, AP, S, SCOND, AMAX, EQUED )
            RCEQU = LSAME( EQUED, 'Y' )
         END IF
      END IF
*
*     Scale the right-hand side.
*
      IF( RCEQU ) THEN
         DO 30 J = 1, NRHS
            DO 20 I = 1, N
               B( I, J ) = S( I )*B( I, J )
   20       CONTINUE
   30    CONTINUE
      END IF
*
      IF( NOFACT .OR. EQUIL ) THEN
*
*        Compute the Cholesky factorization A = U**T * U or A = L * L**T.
*
         CALL DCOPY( N*( N+1 ) / 2, AP, 1, AFP, 1 )
         CALL DPPTRF( UPLO, N, AFP, INFO )
*
*        Return if INFO is non-zero.
*
         IF( INFO.GT.0 )THEN
            RCOND = ZERO
            RETURN
         END IF
      END IF
*
*     Compute the norm of the matrix A.
*
      ANORM = DLANSP( 'I', UPLO, N, AP, WORK )
*
*     Compute the reciprocal of the condition number of A.
*
      CALL DPPCON( UPLO, N, AFP, ANORM, RCOND, WORK, IWORK, INFO )
*
*     Compute the solution matrix X.
*
      CALL DLACPY( 'Full', N, NRHS, B, LDB, X, LDX )
      CALL DPPTRS( UPLO, N, NRHS, AFP, X, LDX, INFO )
*
*     Use iterative refinement to improve the computed solution and
*     compute error bounds and backward error estimates for it.
*
      CALL DPPRFS( UPLO, N, NRHS, AP, AFP, B, LDB, X, LDX, FERR, BERR,
     $             WORK, IWORK, INFO )
*
*     Transform the solution matrix X to a solution of the original
*     system.
*
      IF( RCEQU ) THEN
         DO 50 J = 1, NRHS
            DO 40 I = 1, N
               X( I, J ) = S( I )*X( I, J )
   40       CONTINUE
   50    CONTINUE
         DO 60 J = 1, NRHS
            FERR( J ) = FERR( J ) / SCOND
   60    CONTINUE
      END IF
*
*     Set INFO = N+1 if the matrix is singular to working precision.
*
      IF( RCOND.LT.DLAMCH( 'Epsilon' ) )
     $   INFO = N + 1
*
      RETURN
*
*     End of DPPSVX
*
      END


text:
$(document).ready(function(){

	$('.item-wrapper').each(function(){

		$(this).height( $(this).parent().height() )

	})
})


text:
if [ ! -f /var/run/docker.pid ]
then
    echo "!!! Docker service is probably not running !!!"
fi

function prepare_venv() {
	virtualenv -p python3 venv && source venv/bin/activate && python3 `which pip3` install -r requirements.txt
}

[ "$NOVENV" == "1" ] || prepare_venv || exit 1

PYTHONDONTWRITEBYTECODE=1 python3 `which behave` --tags=-skip -D dump_errors=true @feature_list.txt $@


text:
@class Alert;

@interface Patch : NSManagedObject

@property (nonatomic, retain) NSNumber * lat;
@property (nonatomic, retain) NSNumber * lon;
@property (nonatomic, retain) NSString * plantName;
@property (nonatomic, retain) NSData * photo;
@property (nonatomic, retain) Alert *alert;

@end


text:
\documentclass[10pt, compress, xcolor={usenames,dvipsnames}]{beamer}
\usepackage[utf8x]{inputenc}

%%% Theme and style
\usetheme{metropolis}
\metroset{progressbar=frametitle}
\metroset{numbering=fraction}

%%% Packages %%%

% Use T1 and a modern font family for better support of accents, etc.
\usepackage[T1]{fontenc}
\usepackage{palatino}  % Palatino

% Language support
\usepackage[english]{babel}

% Support for easily changing the enumerator in
% enumerate-environments.
\usepackage{enumerate}

% Support for importing images
%\usepackage{graphicx}

% Use hyperlinks
\usepackage{hyperref}

% Don't load xcolors package in beamer: use document class option
% instead...
%\usepackage[usenames,dvipsnames]{xcolor}

% Use colors in tables
%\usepackage[pdftex]{colortbl}

% A nice monospace font for listings, etc.
\usepackage[scaled]{beramono}
%\usepackage{inconsolata}

% Using TikZ for diagrams
\usepackage{tikz}
\usetikzlibrary{shapes,mindmap}
%\usetikzlibrary{er,mindmap,calc,intersections,shapes,arrows,fit,matrix,positioning,decorations.pathmorphing,topaths,trees,automata}
\usepackage{tikz-cd} % for CM-arrow tips.

% Don't use externalize with gradients!!!
%\usetikzlibrary{external,arrows,fit,matrix,positioning}
%\tikzexternalize % Activate externalizing TikZ graphics.

\usepackage{pifont} % for ding
\usepackage[inline]{enumitem}
\usepackage{xspace}
\usepackage{listings}

% Scala listings.  Use colored Scala style by default.
\usepackage{lstscala}
\lstnewenvironment{lstscalasmall}{%
  \lstset{style=scala-color,basicstyle=\scriptsize\tt}}{}

\colorlet{ImportantCode}{ForestGreen}
\colorlet{ImportantCode2}{RubineRed}

\lstset{style=scala-color}

\lstnewenvironment{C}
  {\lstset{
    language=C,
    flexiblecolumns=false,
    mathescape=false,
    moredelim=**[is][\color{ImportantCode}]{@}{@},
    moredelim=**[is][\color{ImportantCode2}]{§}{§},
    basicstyle=\small\color{blue!30!darkgray}\tt,
commentstyle=\color{CadetBlue}}}
  {}
\lstnewenvironment{Scala}
  {\lstset{
    style=scala-color,
    flexiblecolumns=false,
    mathescape=false,
    basicstyle=\small\color{blue!30!darkgray}\tt}}
  {}

%%%% Custom macros %%%%
\newif\ifcompileTreeSlides
%\compileTreeSlidesfalse
\compileTreeSlidestrue

\newcommand{\SmallArrow}{\ding{228}}
\newcommand{\BigArrow}{$\longrightarrow$\xspace}
\newcommand{\Triangle}{$\triangleright$\xspace}
\renewcommand{\emph}[1]{\alert{#1}}
\newcommand{\light}{\color{TealBlue}}
\renewcommand{\hbar}{{\color{mLightBrown}\hrulefill}}

% http://tex.stackexchange.com/a/56585/77356
\tikzset{
  invisible/.style={opacity=0},
  visible on/.style={alt=#1{}{invisible}},
  alt/.code args={<#1>#2#3}{%
    \alt<#1>{\pgfkeysalso{#2}}{\pgfkeysalso{#3}} % \pgfkeysalso doesn't change the path
  },
}

%%% Document info %%%

\title{From Verified Functions to Safe C Code}

\author{Marco Antognini}

% To show the TOC at the beginning of each section, uncomment this:
% \AtBeginSection[]
% {
%   \begin{frame}<beamer>{Outline}
%     \tableofcontents[currentsection]
%   \end{frame}
% }

% To show the TOC at the beginning of each subsection, uncomment this:
% \AtBeginSubsection[]
% {
%   \begin{frame}<beamer>{Outline}
%     \tableofcontents[currentsection,currentsubsection]
%   \end{frame}
% }

% To uncover everything in a step-wise fashion, uncomment this:
% \beamerdefaultoverlayspecification{<+->}

\date{%
  \small Fall 2015\\[2em]
  \includegraphics[height=7mm]{img/epfl-logo}}

%%% Start of the actual document %%%

\begin{document}

\begin{frame}
  \titlepage
\end{frame}

% No outline, too short a talk...
% \begin{frame}{Outline}
%   \tableofcontents
%   % You might wish to add the option [pausesections]
% \end{frame}

\section{Motivation}

\begin{frame}[fragile]{Motivation}

  \begin{itemize}[label=\SmallArrow]

    \item Software keeps getting more complex.
    \item Hardware gets cheaper and more robust.
    \item For some industry, development cost is high mostly because of
      software verification process.
    \item Failure can have disastrous impact on human lives or huge monetary
      loss.

  \end{itemize}

  \vspace{1em}

  \BigArrow We need tools to \emph{verify complex software}.

\end{frame}

\begin{frame}[fragile]{Leon?}

  \begin{itemize}[label=\SmallArrow]

    \item Leon offers tools to reduce this cost.
    \item \emph{But!} It's JVM-based hence useless for \emph{very small
      devices} \\
      (e.g. pacemakers, spacecraft, \ldots)
    \item Need {\light native} code.
    \item That's why C-like languages are widely used in the industry.

  \end{itemize}

\end{frame}

\begin{frame}[fragile]{Verifier for C?}

  \begin{itemize}[label=\SmallArrow]
    \item Why not but low level, verbose and error prone.
    \item Modern C++ or D might solve many issues from C\ldots
    \item \ldots but no good verifiers exist.
  \end{itemize}

\end{frame}

\section{val GenC = (CAST) Leon}

\begin{frame}[fragile]{GenC}

  \begin{itemize}[label=\Triangle]
    \item Use Leon to {\light verify, repair and synthesis} code using high level
      features of Scala*. \pause
    \item Translate code into \emph{equivalent} C99 code. \pause
    \item Compile it with your favourite C compiler for your destination
      architecture. \pause
    \item And run it {\light natively} on your hardware.
  \end{itemize}

\end{frame}

\plain{\Huge Supported Features}

% Short-cut for inline listings using "@" (must come after "\titlepage")
\lstMakeShortInline[%
  style=scala-color,%
  flexiblecolumns=false,%
  mathescape=false,%
  basicstyle=\color{blue!30!darkgray}\tt]@

% Short-cut for inline listings using "|" (must come after "\titlepage")
\lstMakeShortInline[%
  language=C,%
  flexiblecolumns=false,%
  mathescape=false,%
  basicstyle=\color{blue!30!darkgray}\tt]|

\begin{frame}[fragile]{Types}

  @Int@ \BigArrow |int32_t| \hspace{3em} @Boolean@ \BigArrow |bool| \hspace{3em}
  @Unit@ \BigArrow |void|

  \pause
  \vspace{1em}

  @TupleN[T1, T2, ..., TN]@ is generated using some kind of templates. E.g.
  @(Boolean, Int)@ is:

  \begin{C}
typedef struct __leon_tuple_bool_int32_t_t {
  bool    @_1@;  // padding
  int32_t @_2@;
} __leon_tuple_bool_int32_t_t;
  \end{C}

  \pause
  %\vspace{1em}

  Similarly, @Array[T]@ is templatised. E.g. @Array[(Boolean, Int)]@ is:
  \begin{C}
typedef struct __leon_array___leon_tuple_bool_int32_t_t_t {
  __leon_tuple_bool_int32_t_t§*§ @data@;   // not owning the memory
  int32_t                      @length@;
} __leon_array___leon_tuple_bool_int32_t_t_t;
  \end{C}
\end{frame}

\begin{frame}[fragile]{More on Arrays}
  Those arrays live on the \emph{stack} \BigArrow cannot return them.

  {\light VLA} (variable-length array) are used when needed.

  \hbar

  \begin{Scala}
def foo(size: Int, value: Int) { val a = Array.fill(size)(value) }
  \end{Scala}

  \pause

  \vspace{-2em}
  \center{is translated into}
  \vspace{-0.5em}

  \begin{C}
void foo0(int32_t const size0, int32_t const value0) {
  int32_t __leon_vla_buffer0§[§size0§]§; // actual memory alloc
  for (int32_t __leon_i1 = 0; __leon_i1 < size0; ++__leon_i1) {
    __leon_vla_buffer0[__leon_i1] = value0;
  }
  __leon_array_int32_t_t const a3 =
    { @.length@ = size0, @.data@ = __leon_vla_buffer0 };
}
  \end{C}

\end{frame}

\begin{frame}[fragile]{Functions}
  \emph{Nested} functions are extracted with their context.

  \hbar

  \begin{Scala}
def foo(x: Int) = {
  def bar(y: Int) = x * y
  bar(2)
}
  \end{Scala}

  \pause

  \vspace{-2em}
  \center{is translated into}

  \begin{C}
int32_t bar0(int32_t const@*@ x0, int32_t const y6)
{ return @(*x0)@ * y6; }

int32_t foo0(int32_t const x0)
{ return bar0(@(&x0)@, 2); }
  \end{C}

\end{frame}

\begin{frame}[fragile]{Functions -- bis}

  \begin{Scala}
def foo(x: Int) = {
  def bar(y: Int) = {
    def fun(z: Int) = x * y + z
    fun(3)
  }
  bar(2)
}
  \end{Scala}

  \pause

  \vspace{-2em}
  \center{is translated into}
  \vspace{-0.5em}

  \begin{C}
int32_t fun0(int32_t const§*§ x0, int32_t const@*@ y6, int32_t const z9)
{ return @(*x0)@ * @(*y6)@ + z9; }

int32_t bar0(int32_t const@*@ x0, int32_t const y6)
{ return fun0(§x0§, @(&y6)@, 3); }

int32_t foo0(int32_t const x0)
{ return bar0(@(&x0)@, 2); }
  \end{C}

\end{frame}

\begin{frame}[fragile]{If construct}

  Unlike in Scala, |if| statements don't {\light return} a value. Hence

  \begin{columns}[T]
	  \column{.5\textwidth}
      \begin{Scala}
def foo(x: Int) {
  val b =
    if (x >= 0) true else false
}
      \end{Scala}

      \vspace{-2em}
      \center{is translated into}
      \vspace{-0.5em}

      \begin{C}
void foo0(int32_t const x0) {
  bool b0; // no const here
  if (x0 >= 0) { b0 = true; }
  else { b0 = false; }
}
      \end{C}

    \column{.5\textwidth}
      \pause

      \begin{onlyenv}<2->

      \begin{Scala}
def foo(x: Int) =
  if (x >= 0) true else false
      \end{Scala}

      \vspace{0.5em}
      \center{is translated into}
      \vspace{-0.5em}

      \begin{C}
bool foo1(int32_t const x0) {
  if (x0 >= 0) { return true; }
  else { return false; }
}
      \end{C}

      \end{onlyenv}

  \end{columns}

\end{frame}

\begin{frame}[fragile]{While construct}

  \begin{Scala}
def dummyAbs(a: Array[Int]) {
  var i = 0;
  while (i < a.length) {
    a(i) = if (a(i) < 0) -a(i) else a(i)
    i = i + 1
  }
}
  \end{Scala}

  \pause

  \vspace{-2.5em}
  \center{is translated into}
  \vspace{-0.5em}

  \begin{C}
void dummyAbs0(__leon_array_int32_t_t const a0) {
  int32_t i9 = 0;
  while (i9 < a0.length) {
    if (a0.data[i9] < 0) { a0.data[i9] = -a0.data[i9]; }
    else { a0.data[i9] = a0.data[i9]; }
    i9 = i9 + 1;
  }
}
  \end{C}

\end{frame}

\begin{frame}[fragile]{Subexpressions execution order}

  \begin{itemize}[label=\Triangle]
    \item C standard is much more lax when it comes to execution order.
    \item Hence the translation has to do some kind of \emph{normalisation}
      to ensure the same behaviour.
    \item This applies to function calls, operators, and blocks.
  \end{itemize}

\end{frame}

\begin{frame}[fragile]{Subexpressions execution order -- bis}

  \begin{columns}[T]
	  \begin{column}{.4\textwidth}

      \begin{Scala}
def test4(b: Boolean) = {
  var i = 10;
  var c = 0;
  val f = b && !b // false
  val t = b || !b // true

  while ({ c = c + 1; t } &&
         i > 0 ||
         { c = c * 2; f }) {
    i = i - 1
  }

  i == 0 && c == 22
}
      \end{Scala}

    \end{column}
    \pause

    {\color{mLightBrown}\vrule{}}

	  \begin{column}{.6\textwidth}

      \begin{C}
bool test40(bool const b0) {
  int32_t i10 = 10;
  int32_t c2 = 0;
  bool const f26 = b0 && (!b0);
  bool const t8  = b0 || (!b0);

  while (§true§) {
    c2 = c2 + 1;
    if (t8 && i10 > 0) { i10 = i10 - 1; }
    else {
      c2 = c2 * 2;
      if (f26) { i10 = i10 - 1; }
      else { break; }
    }
  }

  return i10 == 0 && c2 == 22;
}
      \end{C}

    \end{column}
  \end{columns}
\end{frame}

\plain{
  {\Huge Recap'}

  \begin{itemize}[label=\Triangle]
    \item Basic types
    \item Tuples \& stack allocated arrays
    \item Nested functions
    \item If \& While constructs
    \item Subexpressions orders
  \end{itemize}
}

\section{What's next}

\begin{frame}[fragile]{Future's work}
  \begin{itemize}[label=\SmallArrow]
    \item Support for non-recursive data type (@case class@).
    \item A case study about image processing.
  \end{itemize}

  \vspace{3em}
  \pause

  \begin{itemize}[label=\Triangle]
    \item Support for floating point types (|float|, |double|).
    \item Support for @BigInt@, @Real@, e.g. using GMP.
    \item Support for heap allocated arrays, e.g. using |malloc|.
  \end{itemize}
\end{frame}

\plain{\Huge Questions?}

\end{document}

% vim: spell spelllang=en_gb
% vim: set tabstop=2 softtabstop=2 shiftwidth=2 textwidth=80: %


text:
@interface PodsDummy_Pods_BingoCycleScrollViewDemoUITests : NSObject
@end
@implementation PodsDummy_Pods_BingoCycleScrollViewDemoUITests
@end


text:
#pragma once

#include <memory>

#include "mmcore/param/AbstractParam.h"
#include "vislib/SingleLinkedList.h"
#include "vislib/SmartPtr.h"
#include "vislib/String.h"
#include "vislib/sys/AbstractReaderWriterLock.h"
#include "vislib/sys/SyncObject.h"

namespace megamol::core {

// forward declarations of types
class AbstractNamedObjectContainer;

/**
 * Abstract base class for object placed in the module network namespaces
 */
class AbstractNamedObject : public std::enable_shared_from_this<AbstractNamedObject> {
public:
    friend class ::megamol::core::AbstractNamedObjectContainer;

    /** Shared ptr type alias */
    typedef ::std::shared_ptr<AbstractNamedObject> ptr_type;

    /** Shared ptr type alias */
    typedef ::std::shared_ptr<const AbstractNamedObject> const_ptr_type;

    /** Weak ptr type alias */
    typedef ::std::weak_ptr<AbstractNamedObject> weak_ptr_type;

    /**
     * Utility class
     */
    class GraphLocker : public vislib::sys::SyncObject {
    public:
        /**
         * Ctor.
         *
         * @param obj Any object from the module graph
         * @param writelock Flag if a write lock is required
         */
        GraphLocker(AbstractNamedObject::const_ptr_type obj, bool writelock);

        /**
         * Dtor.
         */
        virtual ~GraphLocker();

        /**
         * Acquire the lock.
         *
         * @throws SystemException If the lock could not be acquired.
         */
        virtual void Lock();

        /**
         * Release the lock.
         *
         * @throw SystemException If the lock could not be released.
         */
        virtual void Unlock();

    private:
        /** Flag if a write lock is required */
        bool writelock;

        /** The root object of the graph */
        AbstractNamedObject::const_ptr_type root;
    };

    /**
     * Dtor.
     */
    virtual ~AbstractNamedObject();

    /**
     * Answer the full name of the object
     *
     * @return The full name of the object
     */
    vislib::StringA FullName() const;

    /**
     * Answer the name of the object.
     *
     * @return The name of the object.
     */
    inline const vislib::StringA& Name() const {
        return this->name;
    }

    /**
     * Answer the owner identification pointer.
     *
     * @return The owner identification pointer.
     */
    inline const void* Owner() const {
        return this->owner;
    }

    /**
     * Answer the parent of the object.
     *
     * @return The parent of the object.
     */
    inline ptr_type Parent() {
        return this->parent.lock();
    }

    /**
     * Answer the parent of the object.
     *
     * @return The parent of the object.
     */
    inline const const_ptr_type Parent() const {
        return this->parent.lock();
    }

    /**
     * Answers the root of the module graph.
     *
     * @return The root of the module graph
     */
    inline ptr_type RootModule() {
        ptr_type rv = this->shared_from_this();
        ptr_type lrv = rv;
        while (rv) {
            lrv = rv;
            rv = rv->parent.lock();
        }
        return lrv;
    }

    /**
     * Answers the root of the module graph.
     *
     * @return The root of the module graph
     */
    inline const const_ptr_type RootModule() const {
        const_ptr_type rv = this->shared_from_this();
        const_ptr_type lrv = rv;
        while (rv) {
            lrv = rv;
            rv = rv->parent.lock();
        }
        return lrv;
    }

    /**
     * Sets the owner identification pointer. This can only be done once.
     *
     * @param owner The owner identification pointer.
     */
    void SetOwner(void* owner);

    /**
     * Gets the cleanup mark
     *
     * @return The cleanup mark
     */
    inline bool CleanupMark() const {
        return this->cleanupMark;
    }

    /**
     * Sets the cleanup mark to the given value
     *
     * @param value The new value for the cleanup mark
     */
    inline void SetCleanupMark(bool value) {
        this->cleanupMark = value;
    }

    /**
     * Sets the cleanup mark
     */
    virtual void SetAllCleanupMarks();

    /**
     * Clears the cleanup mark for this and all dependent objects.
     */
    virtual void ClearCleanupMark();

    /**
     * Performs the cleanup operation by removing and deleteing of all
     * marked objects.
     */
    virtual void PerformCleanup();

    /**
     * Disconnects calls from all slots which are marked for cleanup.
     */
    virtual void DisconnectCalls();

    /**
     * Answers whether the given parameter is relevant for this view.
     *
     * @param searched The already searched objects for cycle detection.
     * @param param The parameter to test.
     *
     * @return 'true' if 'param' is relevant, 'false' otherwise.
     */
    virtual bool IsParamRelevant(vislib::SingleLinkedList<const AbstractNamedObject*>& searched,
        const std::shared_ptr<param::AbstractParam>& param) const;

    /**
     * Answer the reader-writer lock to lock the module graph
     *
     * @return The reader-writer lock to lock the module graph
     */
    virtual vislib::sys::AbstractReaderWriterLock& ModuleGraphLock();

    /**
     * Answer the reader-writer lock to lock the module graph
     *
     * @return The reader-writer lock to lock the module graph
     */
    virtual vislib::sys::AbstractReaderWriterLock& ModuleGraphLock() const;

protected:
    /**
     * Helper method testing if the string name would be a valid object
     * name. Valid object names must not contain ':' characters.
     *
     * @param name The string to be tested.
     *
     * @return 'true' if name would be a valid object name,
     *         'false' otherwise.
     */
    static bool isNameValid(const vislib::StringA& name);

public: // for new MegaMolGraph, make this public:
    /**
     * Sets the name for the object.
     *
     * @param name The new name for the object.
     */
    void setName(const vislib::StringA& name);

    /**
     * Ctor.
     */
    AbstractNamedObject();

    /**
     * Sets the parent for the object.
     *
     * @param parent The new parent for the object.
     */
    void setParent(weak_ptr_type parent);

private:
    /** the name of the object */
    vislib::StringA name;

    /** The parent of the object. Weak reference, do not delete. */
    weak_ptr_type parent;

    /** The identification of the owner of the object */
    const void* owner;

    /** The cleanup mark of this object */
    bool cleanupMark;
};

} // namespace megamol::core


text:
<?php

namespace KekRozsak\FrontBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ForumTopicType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', null, array(
                'label' => 'Téma címe',
                'help'  => 'Az új fórum téma címe',
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'KekRozsak\FrontBundle\Entity\ForumTopic'
        ));
    }

    public function getName()
    {
        return 'kekrozsak_frontbundle_forumtopictype';
    }
}


text:
require 'test_helper'
require 'capybara/poltergeist'
require 'database_cleaner'

DatabaseCleaner.strategy = :truncation

Capybara.javascript_driver = :poltergeist

class JavascriptTest < ActionDispatch::IntegrationTest
  self.use_transactional_fixtures = false
  setup do
    Capybara.current_driver = Capybara.javascript_driver # :selenium by default
    DatabaseCleaner.start
    @inge              = profiles(:two)
    @inge.confirmed_at = Time.now
    @inge.topic_list   = 'Algorithm'
    @inge.published    = true
    @inge.save

    @ada              = profiles(:one)
    @ada.confirmed_at = Time.now
    @ada.published    = true
    @ada.save
  end

  teardown do
    DatabaseCleaner.clean
  end

  test 'using tag autocompletion' do
    skip "This uses tag-it now, haven't figured out yet how to test that."

    visit '/profiles'
    click_link('Einloggen')
    fill_in('profile[email]', with: 'ada@mail.de')
    fill_in('profile[password]', with: 'Testpassword')
    click_button 'Anmelden'

    visit profile_path(@ada, locale: 'en')
    click_link('Edit')
    fill_in('Al').click
    assert_equal find_field('profile[topic_list]').value, 'Algorithm'
  end
end


text:
{% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="@wolfg1969">
    <meta name="keywords" content="django,uwsgi,nginx,django-sample,python,aws,elasticbeanstalk,ebextensions">
    <meta name="description" content="A Django sample app running with uWSGI and Nginx on AWS Elastic Beanstalk.">
    <title>elastic beanstalk nginx uwsgi django</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'style.css' %}">

elastic-beanstalk-nginx-uwsgi-django

A Django sample app running with uWSGI and Nginx on AWS Elastic Beanstalk.


text:
<!--
  Copyright 2013 Google Inc.

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

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

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

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- NOTE: EditTextPreference accepts EditText attributes. -->
    <!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
    <EditTextPreference
        android:key="pref_name"
        android:title="@string/pref_name_title"
        android:defaultValue="@string/pref_name_default"
        android:selectAllOnFocus="true"
        android:inputType="textCapWords"
        android:capitalize="words"
        android:singleLine="true"
        android:maxLines="1" />

</PreferenceScreen>


text:
import { Component,
         ViewChild }        from '@angular/core';

import { AppState }         from '../app.service';
import { Store }            from '@ngrx/store';

import { ActionService }    from '../services/action.service';

import { MdDialog,
         MdDialogRef,
         MdDialogConfig,
         TooltipPosition }  from '@angular/material';

@Component({
  selector: 'home',  // <home></home>
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})
export class HomeComponent {
  dialogRef: MdDialogRef<AddEventDialog>;
  lastCloseResult: string;
  config: MdDialogConfig = {
    disableClose: false,
  };

  abos: any = [
    {name: 'Abo1'}, {name: 'Abo2'}, {name: 'Abo3'}, {name: 'Abocal'}]

  position: TooltipPosition = 'below';
  message: string;

  devices = [];
  localDevice = {
            infos: {},
            image: 'http://www.promo-conso.net/produits/acer/e5-523g-937f_small.jpg'
        };

  messages: any[] = [
    {
      from: 'Nancy',
      subject: 'Brunch?',
      message: 'Did you want to go on Sunday?',
      image: 'https://angular.io/resources/images/bios/julie-ralph.jpg'
    },
    {
      from: 'Mary',
      subject: 'Summer BBQ',
      message: 'Wish I could come, ',
      image: 'https://angular.io/resources/images/bios/juleskremer.jpg'
    }
  ];

  basicRowHeight = 80;
  fixedCols = 4;
  fixedRowHeight = 100;
  ratioGutter = 1;
  fitListHeight = '400px';
  ratio = '4:1';

  // Set our default values
  localState = { value: '' };
  // TypeScript public modifiers

  constructor(
    public dialog:   MdDialog,
    public store:    Store<any>,
    public appState: AppState,
    public actionservice:    ActionService) {
    actionservice.action('get_device', '').subscribe(device => {
        this.localDevice.infos = device;
        if(device.disk) {
            this.message = device.disk.free + ' Go libres sur ' + device.disk.size + ' Go (' + device.disk.name + ')';
        }
    });
  }

  open() {
    this.dialogRef = this.dialog.open(AddEventDialog, this.config);

    this.dialogRef.afterClosed().subscribe(result => {
      this.lastCloseResult = result;
      this.dialogRef = null;
    });
  }

  addEvent() {
    this.dialogRef = this.dialog.open(AddEventDialog, this.config);
    this.dialogRef.afterClosed().subscribe(result => {
      if(result) {
        this.actionservice.action('add_event', result);
      }
      this.dialogRef = null;
    });
  }

  setEvent(event: string) {
      this.actionservice.action('set_event', event);
  }
}

@Component({
  selector: 'demo-add-event-dialog',
  template: `
    <md-input-container>
        <input #name md-input placeholder="Evénement">
    </md-input-container>
  <button md-button (click)="dialogRef.close(name.value)">Ajouter</button>
  <tr> (calendrier)`
})
export class AddEventDialog {
  constructor(public dialogRef: MdDialogRef<AddEventDialog>) { }
}


text:
layout: podcast
title: Episode 5
number: 5
subtitle: Interview with Walter Kruse
summary:
date: 1999-12-31
location: https://dl.dropboxusercontent.com/s/uw36xlhf2799on3/watir_podcast_5.mp3?dl=0
size: 26,347,890
duration: 27:26
---


text: google-site-verification: google8823750076736400.html


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>sve pohvale! ovako nešto nam je trebalo! cijene su extra povoljne, ponuda izvrsna i inovativna! jedva čekamo da opet ogladnimo! :)</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/sladomazo-palacinkarnica</Source>
</CrawlItem>


text:
from evdev import InputDevice, ecodes

# Funcao para dar flush no buffer de entrada
def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)

def get_devices():
    devicesList = []
    for i in range(0, 20):
        try:
            dev = InputDevice('/dev/input/event'+str(i))
        except OSError:
            continue
        keymap = dev.capabilities().get(1)
        if keymap is not None:
            # Verificando se e um mouse com dois botoes
            if ecodes.BTN_MOUSE in keymap and ecodes.BTN_RIGHT in keymap:
                devicesList.append(dev)
            # Procurando um teclado apropriado
            if ecodes.KEY_DELETE in keymap and ecodes.KEY_PLAYPAUSE in keymap and ecodes.KEY_RIGHTCTRL in keymap and ecodes.KEY_LEFTCTRL in keymap and ecodes.KEY_F12 in keymap and ecodes.KEY_S:
                devicesList.append(dev)
    return {dev.fd : dev for dev in devicesList}


text:
// Defining anonymous and named modules for our library is done through this function. There are a number of ways to
// pass arguments into this function, for more details see comments in the `define.args` function.
/* eslint-disable*/
var define = function() {
	/* eslint-enable*/
	// Fetch and normalize the argument that were passed in.
	var args =	me.amd.args(arguments, define.args.router, define.args.normalize, {
		name: null,
		error: null,
		deps: null,
		factory: undefined
	});

	// Fill up our dependencies.
	args = define.deps(args);

	// If we're attempting to define an anonymous module, and we already have an anonymous module that was previously
	// passed to the function before we had a chance to actually declare it's name, then there was 2 anonymous modules
	// which were passed in through a single file. We cannot due this due to the fact that we have no way of knowing which
	// name should be assigned to which `define` instance that was called. If we did allow this to go through, we would
	// essentially be overwriting our previous anonymous module. If this happens we'll simply halt the function and a
	// throw a notice to our end user.
	if (!args.name) {
		// We cannot define multiple anonymous modules with the same name!
		if (define.anonymous.pending) {
			me.log(1, 'define', 'Multiple Anonymous modules defined in the same file! Halting!', args);
			return;
		}

		// If we don't have a name for our module, then we'll define it as an anonymous module. Our callback that loaded our
		// file will see this and set the proper name once the callback executes, which will happen synchronously.
		define.anonymous.save(args);
		return;
	}

	// Generate our new module and reference it as our last defined module.
	define.module.last = define.module(args);

	// Flag the anonymous modules as not pending.
	define.anonymous.pending = false;
};

// Whether or not to enforce the use of AMD. If this setting it turned on via the `config` `Function`, any library that
// supports AMD will not longer be available via the `window` `global`. See documentation for further details.
define.amd = undefined;

// If a module is sitting in an anonymous state and waiting to be imported properly, this `Function` will take the
// `dependencies` and `factory` from that anonymous module, import them in to our properly named module, and then
// destroy the anonymous module sitting in a limbo state. Here's how this system of defining anonymous modules works:
// If we attempt to load a module via our `require` function, and that module doesn't happen to exist in our
// configuration, we'll automatically spawn a new anonymous module for it. Once the file for the module has loaded, if
// the file contains an anonymous `define` call, we'll then store it in a limbo state with it's `factory` and
// `dependencies`. The issue is that the `define` function will be invoked before the `onload` callback from our
// script file that was loaded for our module, so we have to store it in a limbo state, and then after the callback
// executes, we then look to see if an anonymous module is waiting to be defined, if so, we then define it whatever
// anonymous module that's sitting in a limbo state with the name of the module that was given from our callback. If
// our callback provides a `define` function with a name, any anonymous modules sitting in a limbo state will be wiped
// out completely.
define.anonymous = function(moduleName) {
	// If we don't have a anonymous module waiting to be defined, then halt the function. We should at the very least have
	// either a `factory` or reference to the last defined module (which in this case would be our anonymous module
	// without a name).
	if (!define.anonymous.pending && !define.module.last) {
		return;
	}

	// Fetch the instance of our module.
	var module = me.module(moduleName, null, false);

	// If we couldn't find our module, then something went wrong. Let the end user know and halt the `Function`.
	if (!module) {
		me.log(1, 'define', 'anonymous', 'Anonymous module not found for `' + moduleName + '`! Halting definition!');
		return;
	}

	// If our module already exists and there's a module that's set as our last defined, then a file was loaded which the
	// library assumed was anonymous, but wound up being explicitly calling the `define` `Function` with a `name`. In this
	// particular case, we'll destroy the new definition and instead alias it with our anonymous module. The point in
	// doing this is so that we only maintain a single reference. If we maintain multiple references there's a possibility
	// of each of the references becoming out of sync.
	if (module && define.module.last && define.module.last.name !== module.name) {
		// Define the alias coming from the `define` function for the anonymous file that was loaded.
		me.module.alias(module.name, [define.module.last.name]);

		// Attempt to fetch the index of our anonymous module from our require library.
		var anonymousIndex = me.indexOf(me.require.anonymous, moduleName);

		// Reference the factory from the file that was loaded if the current factory is `undefined`.
		if (anonymousIndex !== -1) {
			// Remove the anonymous entry.
			me.require.anonymous.splice(anonymousIndex, 1);

			// Reference the factory.
			module.factory = define.module.last.factory;
		}

		// Delete the actually module reference.
		delete me.module.definitions[define.module.last.name];
	} else {
		// Set the dependencies for our anonymous `module`.
		if (me.isDefined(define.anonymous.deps)) {
			module.deps = define.anonymous.deps;
		}

		// Set the factory for our anonymous `module`.
		if (me.isDefined(define.anonymous.deps)) {
			module.factory = define.anonymous.factory;
		}
	}

	// Reset the pending anonymous values waiting to be populated.
	define.anonymous.reset();
};

// The dependencies for our anonymous `module` waiting to be properly defined.
define.anonymous.deps = undefined;

// The factory for our anonymous `module` waiting to be properly defined.
define.anonymous.factory = undefined;

// Flag whether or not an anonymous module is pending to be defined.
define.anonymous.pending = false;

// Clear out any saved anonymous `module` properties.
define.anonymous.reset = function() {
	// Clear the pending state.
	define.anonymous.pending = false;

	// Clear the dependencies.
	define.anonymous.deps = undefined;

	// Clear the factory.
	define.anonymous.factory = undefined;
};

// Store the anonymous module waiting to be defined.
define.anonymous.save = function(args) {
	// Remove the reference for our last defined module.
	define.module.last = null;

	// Reset the previously saved values if present.
	define.anonymous.reset();

	// If the `args` parameter isn't an `Object`, halt the `Function`.
	if (!me.isObject(args)) {
		return;
	}

	// Flag the pending state.
	define.anonymous.pending = true;

	// Set the dependencies for our anonymous module.
	if (me.isDefined(args.deps)) {
		define.anonymous.deps = args.deps;
	}

	// Set the factory for our anonymous module.
	if (me.isDefined(args.factory)) {
		define.anonymous.factory = args.factory;
	}
};

// Route and normalize the arguments that are passed into our `define` function. The arguments for our `define`
// `Function` can be sent in a number of different forms.
define.args = {};

// Normalize the arguments payload.
define.args.normalize = function(payload) {
	// Normalize the `name` `String`.
	payload.name = me.normalizeString(payload.name);

	// Normalize the `error` `Function`.
	payload.error = me.normalizeFunction(payload.error);

	// Normamlize the `dependencies` `Array`.
	payload.deps = payload.deps ? me.normalizeStringSeries(payload.deps) : null;

	// Don't normalize the `factory`, as it can be anything except `undefined`.

	// Return the noramlized `payload`.
	return payload;
};

// Route the arguments passed into the `define` `Function`.
define.args.router = [];

// Handle no arguments being passed into the `define` `Function`.
define.args.router[0] = function(args, payload) {
	// Throw an error to the end user.
	me.log(1, 'define', 'args', 'No arguments were passed into `define`! Halting!', args);

	// Return our factored payload.
	return payload;
};

// Handle 1 argument being passed into the `define` `Function`.
define.args.router[1] = function(args, payload) {
	// Reference the `factory`.
	payload.factory = args[0];

	// Return our factored payload.
	return payload;
};

// Handle 2 arguments being passed into the `define` `Function`.
define.args.router[2] = function(args, payload) {
	// If the first argument is a `String`, treat the arguments as `name`, and `factory`.
	if (me.isString(args[0])) {
		// Reference the `name`.
		payload.name = args[0];

		// Reference the `factory`.
		payload.factory = args[1];

	// If the first argument is an `Array`, treat the arguments as `dependencies`, and `factory`.
	} else if (me.isaArray(args[0])) {
		// Reference the `dependencies`.
		payload.deps = args[0];

		// Reference the `factory`.
		payload.factory = args[1];

	// If none of the criteria above matched, then the arguments are malformed.
	} else {
		me.log(1, 'define', 'args', '2 arguments were passed into `define` that were malformed! Discarding!', args);
	}

	// Return our factored payload.
	return payload;
};

// Handle 3 arguments being passed into the `define` `Function`.
define.args.router[3] = function(args, payload) {
	// Reference the `name`.
	payload.name = args[0];

	// Reference the `dependencies`.
	payload.deps = args[1];

	// Reference the `factory`.
	payload.factory = args[2];

	// Return our factored payload.
	return payload;
};

// Fill up our dependencies based on our arguments if we need to.
define.deps = function(args) {
	// If we already have our dependencies defined, then skip the function.
	if (args.deps) {
		return args;
	}

	// If our factory isn't a function, and our dependcies are empty, then we have no dependencies.
	if (!me.isFunction(args.factory)) {
		args.deps = [];
		return args;
	}

	// If we made it this far, set the arguments from our factory as our dependencies.
	args.deps = me.args(args.factory);

	// Send back our arguments array with our populated dependencies.
	return args;
};

// Generate and return our new module.
define.module = function(args) {
	// Generate or reference the module.
	var module = me.module(args.name, {
		amd: true
	});

	// Set our dependencies.
	module.deps = me.normalizeStringSeries(args.deps);

	// Set our error.
	module.error = me.normalizeFunction(args.error);

	// Set our factory.
	module.factory = args.factory;

	// Explicity flag that the module has been loaded, that way when we reference it, we don't attempt to load it.
	module.loader.loaded = true;

	// Return a reference to the module.
	return module;
};

// Our last defined module reference. This is used to reference the proper names with our anonymous modules.
define.module.last = null;

// Reference the module within the library.
me.define = define;


text:
title: OnClientResourcesPopulating
page_title: OnClientResourcesPopulating | RadScheduler for ASP.NET AJAX Documentation
description: OnClientResourcesPopulating
slug: scheduler/client-side-programming/events/onclientresourcespopulating
tags: onclientresourcespopulating
published: True
position: 22
---

# OnClientResourcesPopulating

##

If specified, the **OnClientResourcesPopulating** client-side event handler is called when the scheduleris about to request resources.In the case of server-side binding, the event will not be raised. When client-side binding is used, the event will be raisedbefore the resources are retrieved from the data service. The event will be raised only once, at the time of the initial load.

Two parameters are passed to the handler:

* **sender** - the scheduler client object;

* **eventArgs** with two properties:

* **get_schedulerInfo() -** the schedulerInfo object that will be passed to the web service method.

* **set_cancel() -** used to cancel the event.

This event can be cancelled.


text:
namespace google {
namespace cloud {
namespace spanner {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

namespace gsai = ::google::spanner::admin::instance;

using ::google::cloud::Idempotency;

namespace {

class InstanceAdminConnectionImpl : public InstanceAdminConnection {
 public:
  InstanceAdminConnectionImpl(
      std::shared_ptr<spanner_internal::InstanceAdminStub> stub, Options opts)
      : stub_(std::move(stub)),
        opts_(std::move(opts)),
        retry_policy_prototype_(opts_.get<SpannerRetryPolicyOption>()->clone()),
        backoff_policy_prototype_(
            opts_.get<SpannerBackoffPolicyOption>()->clone()),
        polling_policy_prototype_(
            opts_.get<SpannerPollingPolicyOption>()->clone()),
        background_threads_(internal::MakeBackgroundThreadsFactory(opts_)()) {}

  ~InstanceAdminConnectionImpl() override = default;

  Options options() override { return opts_; }

  StatusOr<gsai::v1::Instance> GetInstance(GetInstanceParams gip) override {
    gsai::v1::GetInstanceRequest request;
    request.set_name(std::move(gip.instance_name));
    return RetryLoop(
        retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(),
        Idempotency::kIdempotent,
        [this](grpc::ClientContext& context,
               gsai::v1::GetInstanceRequest const& request) {
          return stub_->GetInstance(context, request);
        },
        request, __func__);
  }

  future<StatusOr<gsai::v1::Instance>> CreateInstance(
      CreateInstanceParams p) override {
    auto& stub = stub_;
    return google::cloud::internal::AsyncLongRunningOperation<
        gsai::v1::Instance>(
        background_threads_->cq(), std::move(p.request),
        [stub](google::cloud::CompletionQueue& cq,
               std::unique_ptr<grpc::ClientContext> context,
               gsai::v1::CreateInstanceRequest const& request) {
          return stub->AsyncCreateInstance(cq, std::move(context), request);
        },
        [stub](google::cloud::CompletionQueue& cq,
               std::unique_ptr<grpc::ClientContext> context,
               google::longrunning::GetOperationRequest const& request) {
          return stub->AsyncGetOperation(cq, std::move(context), request);
        },
        [stub](google::cloud::CompletionQueue& cq,
               std::unique_ptr<grpc::ClientContext> context,
               google::longrunning::CancelOperationRequest const& request) {
          return stub->AsyncCancelOperation(cq, std::move(context), request);
        },
        &google::cloud::internal::ExtractLongRunningResultResponse<
            gsai::v1::Instance>,
        retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(),
        Idempotency::kNonIdempotent, polling_policy_prototype_->clone(),
        __func__);
  }

  future<StatusOr<gsai::v1::Instance>> UpdateInstance(
      UpdateInstanceParams p) override {
    auto& stub = stub_;
    return google::cloud::internal::AsyncLongRunningOperation<
        gsai::v1::Instance>(
        background_threads_->cq(), std::move(p.request),
        [stub](google::cloud::CompletionQueue& cq,
               std::unique_ptr<grpc::ClientContext> context,
               gsai::v1::UpdateInstanceRequest const& request) {
          return stub->AsyncUpdateInstance(cq, std::move(context), request);
        },
        [stub](google::cloud::CompletionQueue& cq,
               std::unique_ptr<grpc::ClientContext> context,
               google::longrunning::GetOperationRequest const& request) {
          return stub->AsyncGetOperation(cq, std::move(context), request);
        },
        [stub](google::cloud::CompletionQueue& cq,
               std::unique_ptr<grpc::ClientContext> context,
               google::longrunning::CancelOperationRequest const& request) {
          return stub->AsyncCancelOperation(cq, std::move(context), request);
        },
        &google::cloud::internal::ExtractLongRunningResultResponse<
            gsai::v1::Instance>,
        retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(),
        Idempotency::kIdempotent, polling_policy_prototype_->clone(), __func__);
  }

  Status DeleteInstance(DeleteInstanceParams p) override {
    gsai::v1::DeleteInstanceRequest request;
    request.set_name(std::move(p.instance_name));
    return RetryLoop(
        retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(),
        Idempotency::kIdempotent,
        [this](grpc::ClientContext& context,
               gsai::v1::DeleteInstanceRequest const& request) {
          return stub_->DeleteInstance(context, request);
        },
        request, __func__);
  }

  StatusOr<gsai::v1::InstanceConfig> GetInstanceConfig(
      GetInstanceConfigParams p) override {
    gsai::v1::GetInstanceConfigRequest request;
    request.set_name(std::move(p.instance_config_name));
    return RetryLoop(
        retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(),
        Idempotency::kIdempotent,
        [this](grpc::ClientContext& context,
               gsai::v1::GetInstanceConfigRequest const& request) {
          return stub_->GetInstanceConfig(context, request);
        },
        request, __func__);
  }

  ListInstanceConfigsRange ListInstanceConfigs(
      ListInstanceConfigsParams params) override {
    gsai::v1::ListInstanceConfigsRequest request;
    request.set_parent("projects/" + params.project_id);
    request.clear_page_token();
    auto& stub = stub_;
    // Because we do not have C++14 generalized lambda captures we cannot just
    // use the unique_ptr<> here, so convert to shared_ptr<> instead.
    auto retry = std::shared_ptr<RetryPolicy>(retry_policy_prototype_->clone());
    auto backoff =
        std::shared_ptr<BackoffPolicy>(backoff_policy_prototype_->clone());

    char const* function_name = __func__;
    return google::cloud::internal::MakePaginationRange<
        ListInstanceConfigsRange>(
        std::move(request),
        [stub, retry, backoff,
         function_name](gsai::v1::ListInstanceConfigsRequest const& r) {
          return RetryLoop(
              retry->clone(), backoff->clone(), Idempotency::kIdempotent,
              [stub](grpc::ClientContext& context,
                     gsai::v1::ListInstanceConfigsRequest const& request) {
                return stub->ListInstanceConfigs(context, request);
              },
              r, function_name);
        },
        [](gsai::v1::ListInstanceConfigsResponse r) {
          std::vector<gsai::v1::InstanceConfig> result(
              r.instance_configs().size());
          auto& configs = *r.mutable_instance_configs();
          std::move(configs.begin(), configs.end(), result.begin());
          return result;
        });
  }

  ListInstancesRange ListInstances(ListInstancesParams params) override {
    gsai::v1::ListInstancesRequest request;
    request.set_parent("projects/" + params.project_id);
    request.set_filter(std::move(params.filter));
    request.clear_page_token();
    auto& stub = stub_;
    // Because we do not have C++14 generalized lambda captures we cannot just
    // use the unique_ptr<> here, so convert to shared_ptr<> instead.
    auto retry = std::shared_ptr<RetryPolicy>(retry_policy_prototype_->clone());
    auto backoff =
        std::shared_ptr<BackoffPolicy>(backoff_policy_prototype_->clone());

    char const* function_name = __func__;
    return google::cloud::internal::MakePaginationRange<ListInstancesRange>(
        std::move(request),
        [stub, retry, backoff,
         function_name](gsai::v1::ListInstancesRequest const& r) {
          return RetryLoop(
              retry->clone(), backoff->clone(), Idempotency::kIdempotent,
              [stub](grpc::ClientContext& context,
                     gsai::v1::ListInstancesRequest const& request) {
                return stub->ListInstances(context, request);
              },
              r, function_name);
        },
        [](gsai::v1::ListInstancesResponse r) {
          std::vector<gsai::v1::Instance> result(r.instances().size());
          auto& instances = *r.mutable_instances();
          std::move(instances.begin(), instances.end(), result.begin());
          return result;
        });
  }

  StatusOr<google::iam::v1::Policy> GetIamPolicy(
      GetIamPolicyParams p) override {
    google::iam::v1::GetIamPolicyRequest request;
    request.set_resource(std::move(p.instance_name));
    return RetryLoop(
        retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(),
        Idempotency::kIdempotent,
        [this](grpc::ClientContext& context,
               google::iam::v1::GetIamPolicyRequest const& request) {
          return stub_->GetIamPolicy(context, request);
        },
        request, __func__);
  }

  StatusOr<google::iam::v1::Policy> SetIamPolicy(
      SetIamPolicyParams p) override {
    google::iam::v1::SetIamPolicyRequest request;
    request.set_resource(std::move(p.instance_name));
    *request.mutable_policy() = std::move(p.policy);
    auto const idempotency = request.policy().etag().empty()
                                 ? Idempotency::kNonIdempotent
                                 : Idempotency::kIdempotent;
    return RetryLoop(
        retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(),
        idempotency,
        [this](grpc::ClientContext& context,
               google::iam::v1::SetIamPolicyRequest const& request) {
          return stub_->SetIamPolicy(context, request);
        },
        request, __func__);
  }

  StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions(
      TestIamPermissionsParams p) override {
    google::iam::v1::TestIamPermissionsRequest request;
    request.set_resource(std::move(p.instance_name));
    for (auto& permission : p.permissions) {
      request.add_permissions(std::move(permission));
    }
    return RetryLoop(
        retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(),
        Idempotency::kIdempotent,
        [this](grpc::ClientContext& context,
               google::iam::v1::TestIamPermissionsRequest const& request) {
          return stub_->TestIamPermissions(context, request);
        },
        request, __func__);
  }

 private:
  std::shared_ptr<spanner_internal::InstanceAdminStub> stub_;
  Options opts_;
  std::unique_ptr<RetryPolicy const> retry_policy_prototype_;
  std::unique_ptr<BackoffPolicy const> backoff_policy_prototype_;
  std::unique_ptr<PollingPolicy const> polling_policy_prototype_;

  // Implementations of `BackgroundThreads` typically create a pool of
  // threads that are joined during destruction, so, to avoid ownership
  // cycles, those threads should never assume ownership of this object
  // (e.g., via a `std::shared_ptr<>`).
  std::unique_ptr<BackgroundThreads> background_threads_;
};

}  // namespace

InstanceAdminConnection::~InstanceAdminConnection() = default;

std::shared_ptr<spanner::InstanceAdminConnection> MakeInstanceAdminConnection(
    Options opts) {
  internal::CheckExpectedOptions<CommonOptionList, GrpcOptionList,
                                 SpannerPolicyOptionList>(opts, __func__);
  opts = spanner_internal::DefaultAdminOptions(std::move(opts));
  auto stub = spanner_internal::CreateDefaultInstanceAdminStub(opts);
  return std::make_shared<spanner::InstanceAdminConnectionImpl>(
      std::move(stub), std::move(opts));
}

std::shared_ptr<InstanceAdminConnection> MakeInstanceAdminConnection(
    ConnectionOptions const& options) {
  return MakeInstanceAdminConnection(internal::MakeOptions(options));
}

std::shared_ptr<InstanceAdminConnection> MakeInstanceAdminConnection(
    ConnectionOptions const& options, std::unique_ptr<RetryPolicy> retry_policy,
    std::unique_ptr<BackoffPolicy> backoff_policy,
    std::unique_ptr<PollingPolicy> polling_policy) {
  auto opts = internal::MakeOptions(options);
  opts.set<SpannerRetryPolicyOption>(std::move(retry_policy));
  opts.set<SpannerBackoffPolicyOption>(std::move(backoff_policy));
  opts.set<SpannerPollingPolicyOption>(std::move(polling_policy));
  return MakeInstanceAdminConnection(std::move(opts));
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace spanner

namespace spanner_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

std::shared_ptr<spanner::InstanceAdminConnection>
MakeInstanceAdminConnectionForTesting(std::shared_ptr<InstanceAdminStub> stub,
                                      Options opts) {
  opts = spanner_internal::DefaultAdminOptions(std::move(opts));
  return std::make_shared<spanner::InstanceAdminConnectionImpl>(
      std::move(stub), std::move(opts));
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace spanner_internal
}  // namespace cloud
}  // namespace google


text:
@interface ShelfCargoViewController ()
@property (weak, nonatomic) IBOutlet UILabel *cargoNameLabel;
@end

@implementation ShelfCargoViewController

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.preferredContentSize = CGSizeMake(200 , 50);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 3.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 2.f;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"PopoverCargoCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.imageView.image = [UIImage imageNamed:self.cargoItem.productImage];
    cell.textLabel.text = self.cargoItem.itemName;
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@ %@",
                                 _cargoItem.itemType, _cargoItem.quantity, _cargoItem.unitOfMeasure];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:10];

    return cell;
}

- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController{
    return YES;
}

@end


text:
@interface Tier1 (SafeCategoryTest)
+ (NSInteger)testSafeCategoryInjection;
@end

#define AtAspectOfClass Tier1
@classPatchField(Tier1)
+ (NSInteger)testSafeCategoryInjection{
  return 9527;
}
@end

@interface SafeCategoryTest : XCTestCase

@end

@implementation SafeCategoryTest

- (void)setUp {
  [super setUp];
  // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
  // Put teardown code here. This method is called after the invocation of each test method in the class.
  [super tearDown];
}

- (void)testSafeCategoryInjection
{
  XCTAssertEqual([Tier1 testSafeCategoryInjection], 9527);
}

@end