text:
package org.apache.usergrid.rest.filters;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * Filter for setting default accept and Content-Type as application/json when undefined by client
 *
 * @author tnine
 */
public class ContentTypeFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger( ContentTypeFilter.class );

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init( FilterConfig filterConfig ) throws ServletException {
        logger.info( "Starting content type filter" );
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @Override
    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
            throws IOException, ServletException {

        if ( !( request instanceof HttpServletRequest ) ) {
            chain.doFilter( request, response );
            return;
        }

        HttpServletRequest origRequest = ( HttpServletRequest ) request;

        HeaderWrapperRequest newRequest = new HeaderWrapperRequest( origRequest );
        newRequest.adapt();

        chain.doFilter( newRequest, response );
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.Filter#destroy()
     */
    @Override
    public void destroy() {
    }

    private class HeaderWrapperRequest extends HttpServletRequestWrapper {
        private PushbackInputStream inputStream = null;
        private ServletInputStream servletInputStream = null;
        private HttpServletRequest origRequest = null;
        private BufferedReader reader = null;

        private final Map<String, String> newHeaders = new HashMap<String, String>();

        /**
         * @param request
         * @throws IOException
         */
        public HeaderWrapperRequest( HttpServletRequest request ) throws IOException {
            super( request );
            origRequest = request;
            inputStream = new PushbackInputStream( request.getInputStream() );
            servletInputStream = new DelegatingServletInputStream( inputStream );
        }

        /**
         * @throws IOException
         *
         */
        private void adapt() throws IOException {

            //check if the accept header was set
            @SuppressWarnings( "rawtypes" ) Enumeration contentType = origRequest.getHeaders( HttpHeaders.ACCEPT );

            if ( !contentType.hasMoreElements() ) {
                setHeader( HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON );
            }

            String path = origRequest.getRequestURI();

            logger.debug( "Content path is '{}'", path );

            int initial = inputStream.read();

            String method = origRequest.getMethod();

            // nothing to read, check if it's a put or a post. If so set the
            // content type to json to create an empty json request
            if ( initial == -1 ) {
                if ( ( HttpMethod.POST.equals( method ) || HttpMethod.PUT.equals( method ) ) && !MediaType
                        .APPLICATION_FORM_URLENCODED.equals( getContentType() ) ) {

                    logger.debug(
                            "Setting content type to application/json for POST or PUT with no content at path '{}'",
                            path );

                    setHeader( HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON );
                    setHeader( HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON );
                }

                return;
            }

            char firstChar = ( char ) initial;

            // its json, make it so
            if ( firstChar == '{' || firstChar == '[' ) {
                logger.debug( "Setting content type to application/json for POST or PUT with json content at path '{}'",
                        path );

                setHeader( HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON );
                setHeader( HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON );
            }

            inputStream.unread( initial );
        }

        /**
         * @throws IOException
         *
         */
        public void setHeader( String name, String value ) {
            newHeaders.put( name, value );
        }

        /*
         * (non-Javadoc)
         *
         * @see
         * javax.servlet.http.HttpServletRequestWrapper#getHeader(java.lang.
         * String)
         */
        @Override
        public String getHeader( String name ) {
            String header = newHeaders.get( name );

            if ( header != null ) {
                return header;
            }

            return super.getHeader( name );
        }

        /*
         * (non-Javadoc)
         *
         * @see
         * javax.servlet.http.HttpServletRequestWrapper#getHeaders(java.lang
         * .String)
         */
        @Override
        public Enumeration getHeaders( String name ) {
            Set<String> headers = new LinkedHashSet<String>();

            String overridden = newHeaders.get( name );

            if ( overridden != null ) {
                headers.add( overridden );
            }
            else {
                for ( Enumeration e = super.getHeaders( name ); e.hasMoreElements(); ) {
                    headers.add( e.nextElement().toString() );
                }
            }

            return Collections.enumeration( headers );
        }

        /*
         * (non-Javadoc)
         *
         * @see javax.servlet.http.HttpServletRequestWrapper#getHeaderNames()
         */
        @Override
        public Enumeration getHeaderNames() {
            Set<String> headers = new LinkedHashSet<String>();

            for ( Enumeration e = super.getHeaderNames(); e.hasMoreElements(); ) {
                headers.add( e.nextElement().toString() );
            }

            headers.addAll( newHeaders.keySet() );

            return Collections.enumeration( headers );
        }

        /*
         * (non-Javadoc)
         *
         * @see javax.servlet.ServletRequestWrapper#getInputStream()
         */
        @Override
        public ServletInputStream getInputStream() throws IOException {
            return servletInputStream;
        }

        /*
         * (non-Javadoc)
         *
         * @see javax.servlet.ServletRequestWrapper#getReader()
         */
        @Override
        public BufferedReader getReader() throws IOException {
            if ( reader != null ) {
                return reader;
            }

            reader = new BufferedReader( new InputStreamReader( servletInputStream ) );

            return reader;
        }

        // NOTE, for full override we need to implement the other getHeader
        // methods. We won't use it, so I'm not implementing it here
    }

    /**
     * Delegating implementation of {@link javax.servlet.ServletInputStream}.
     *
     * @author Juergen Hoeller, Todd Nine
     * @since 1.0.2
     */
    private static class DelegatingServletInputStream extends ServletInputStream {

        private final InputStream sourceStream;

        /**
         * Create a DelegatingServletInputStream for the given source stream.
         *
         * @param sourceStream the source stream (never null)
         */
        public DelegatingServletInputStream( InputStream sourceStream ) {
            Assert.notNull( sourceStream, "Source InputStream must not be null" );
            this.sourceStream = sourceStream;
        }

        /** Return the underlying source stream (never null). */
        public final InputStream getSourceStream() {
            return this.sourceStream;
        }

        public int read() throws IOException {
            return this.sourceStream.read();
        }

        public void close() throws IOException {
            super.close();
            this.sourceStream.close();
        }
    }
}


text:
import React from 'react';
import { Link } from '@curi/react';

import LogoutLink from 'components/auth/LogoutLink';

const BaseProfile = () => (

      <LogoutLink />

      <Link to='Change Password'>Change Password</Link>

);

export default BaseProfile;

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ignite;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.testframework.ListeningTestLogger;
import org.apache.ignite.testframework.LogListener;
import org.apache.ignite.testframework.junits.WithSystemProperty;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

import static org.apache.ignite.IgniteSystemProperties.IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_QUIET;

/**
 *
 */
@WithSystemProperty(key = IGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP, value = "true")
@WithSystemProperty(key = IGNITE_QUIET, value = "false")
public class ClassPathContentLoggingTest extends GridCommonAbstractTest {
    /** */
    private final ListeningTestLogger listeningLog = new ListeningTestLogger(log);

    /** */
    private String javaClassPath;

    /** */
    private static String javaHome = System.getenv("JAVA_HOME");

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        return super.getConfiguration(igniteInstanceName)
            .setGridLogger(listeningLog);
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        javaClassPath = System.getProperty("java.class.path", ".");

        assertNotNull(javaHome);

        StringBuilder jarPath = new StringBuilder(javaHome)
            .append(javaHome.endsWith(File.separator) ? "" : File.separator)
            .append("lib")
            .append(File.separator)
            .append("*");

        System.setProperty("java.class.path", javaClassPath + File.pathSeparator + jarPath.toString());
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        System.setProperty("java.class.path", javaClassPath);

        super.afterTestsStopped();
    }

    /**
     * Checks the presence of class path content message in log when enabled.
     *
     * @throws Exception if failed.
     */
    @Test
    public void testClassPathContentLogging() throws Exception {
        String javaClassPath = System.getProperty("java.class.path", ".");

        LogListener lsnr = LogListener
            .matches("List of files containing in classpath")
            .build();

        LogListener clsPathValuelsnr = LogListener
            .matches("Classpath value")
            .build();

        LogListener errLsnr = LogListener
            .matches("Could not log class path entry")
            .build();

        LogListener.Builder contenLsnrBuilder = LogListener.builder();

        String jarPath = new StringBuilder(javaHome)
            .append(javaHome.endsWith(File.separator) ? "" : File.separator)
            .append("lib")
            .append(File.separator)
            .toString();

        Iterable<Path> jars = Files.newDirectoryStream(Paths.get(jarPath), "*.jar");

        for (Path jar : jars)
            contenLsnrBuilder.andMatches(jar.getFileName().toString());

        Arrays.stream(javaClassPath.split(File.separator))
            .filter(fileName -> new File(fileName).isDirectory())
            .forEach(contenLsnrBuilder::andMatches);

        LogListener contentLsnr = contenLsnrBuilder.build();

        listeningLog.registerListener(lsnr);
        listeningLog.registerListener(clsPathValuelsnr);
        listeningLog.registerListener(errLsnr);
        listeningLog.registerListener(contentLsnr);

        startGrid(0);

        assertTrue(lsnr.check());
        assertTrue(clsPathValuelsnr.check());
        assertTrue(contentLsnr.check());

        assertFalse(errLsnr.check());
    }
}


text:
<form id="filter_form" class="form-search" method="get">

            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            {{_("Add Filter")}}

            </button>

                    {[ label_columns[col] ]}

                    ×
                    {[active_filter.label]}

                    <select class="my_select2 form-control ng-scope" data-placeholder="Select Value" id="{[active_filter.col]}" name="{[active_filter.col]}" style="width:250px">
                    <option ng-repeat="(key, value) in active_filter.options" value="{[key]}">{[value]}</option>
                    </select>
                        <ab-select data="active_filter.options"></ab-select>
                    <ab-date format="yyyy-MM-dd" ></ab-date>

    </form>


text:
#include "communication.h"
#include "debug.h"

uint32_t packetIndex = 0;

uint8_t packetBuffer[PACKET_BUF_SIZE];
uint8_t packet_buffer_size = 0;

void communication_init() {
    iwrap_callback_rxdata = communication_rx_callback;
    //lastReceivedChannel = 128;
    packetIndex = 0;
}

//Called upon receiving data
//Looks for JSON-formatted requests, and parses them
void communication_rx_callback(uint8_t packet_channel, uint16_t, const unsigned char *data) {
    LOG(F("========\nReceived data: "));
    LOG((const char *)data);
    LOG(F("\n========\n"));
    surefire_connection_id = packet_channel; //Client software is expected to spam some line of data.

    LOG("Received packet!");

    bool send_config = false;
    //creating a scope for static buffers
    {
        char buf[256];
        strncpy(buf, (const char*)data, 255);

        LOG(F("Begin parsing JSON from received data"));
        StaticJsonBuffer<30> jsonBuffer;
        JsonObject &root = jsonBuffer.parseObject(buf);

        //Give information as requested, change parameters as requested
        if (root.success()) {
            LOG(F("JSON was valid!"));
            if (root.containsKey("request")) {
                LOG(F("Contains a request."));
                if (strcmp(root["request"], "configuration") == 0) {
                    send_config = true;
                }
                LOG(F("lol"));
            }
            if (root.containsKey("configuration-set")) {
                const JsonObject& cset = root["configuration-set"].as<const JsonObject&>();
                if (cset.containsKey("name")) {
                    set_friendly_name(cset["name"]);
                }
            }
        }
    }
    if (send_config) {
        LOG(F("Sending config"));
        send_configuration();
    }
}

//Called upon connection
void my_iwrap_evt_ring(uint8_t link_id, const iwrap_address_t *address, uint16_t channel, const char *profile) {
    //add_mapped_connection(link_id, address, profile, channel);
    iwrap_active_connections++;
    surefire_connection_id = link_id;
}

void send_data(char* output) {
    iwrap_send_data(surefire_connection_id, strlen(output), (uint8_t*)output, IWRAP_MODE_MUX);
    Serial1.flush();
}

void build_data_json(char *buffer, int len) {
    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& dump = jsonBuffer.createObject();
    //dump["packetID"] = packetIndex++;
    //JsonObject& data = dump.createNestedObject("sensorData");
    JsonArray& data = dump.createNestedArray("sensorData");

    for (int i=0; i < NUM_SENSORS; i++) {
        //sensorList[i]->dump_data(dump);
        //field["value"]  = sensorList[i].value.out;
        //data[sensorList[i].name] = sensorList[i].value.out;
    }
    packetIndex++;
    dump.printTo(buffer, len);
    //BluetoothStream b;
    //dump.printTo(b);
    //b.println();;
    //b.println("lolwhat");
    //iwrap_send_data(surefire_connection_id, 4, (const uint8_t*)"wtf\n", IWRAP_MODE_MUX);

}

void build_single_data_json(int sensor_index, char *buffer, int len) {
    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& dump = jsonBuffer.createObject();
    JsonObject& data = dump.createNestedObject("sensorData");
    /*
    dump[sensorList[sensor_index].name] = sensorList[sensor_index].value.out;
    */
    //sensorList[sensor_index]->dump_data(data);
    data["name"]    = sensorList[sensor_index].name;
    data["value"]   = sensorList[sensor_index].value.out;
    dump.printTo(buffer, len);
}

size_t BluetoothStream::write(uint8_t data) {
    if (packet_buffer_size == 0) {
      //Serial1.flush();
    }
    packetBuffer[packet_buffer_size++] = data;
    if (data == '\n' || packet_buffer_size == PACKET_BUF_SIZE) {
        iwrap_send_data(surefire_connection_id,packet_buffer_size, packetBuffer, IWRAP_MODE_MUX);
        Serial1.flush();
        //memset(packetBuffer, 0, PACKET_BUF_SIZE);
        packet_buffer_size = 0;
    }
    return 1;
}
/*
size_t BluetoothStream::write(const uint8_t *data) {
    unsigned int len = strlen(data);
    iwrap_send_data(surefire_connection_id, len, (const uint8_t*)data, IWRAP_MODE_MUX);
    return len;
}*/

void send_sensor_data() {
    if (surefire_connection_id == 0xFF) {return;}

    /*char output[512];
    build_data_json(output, sizeof(output));
    //build_data_json();
    strncat(output, "\n", sizeof(output));

    //Serial.println(output);
    iwrap_send_data(surefire_connection_id, strlen(output), (uint8_t*)output, IWRAP_MODE_MUX);
    Serial1.flush();
    */

    for (int i=0; i < NUM_SENSORS; i++) {
        char output[256];
        build_single_data_json(i, output, sizeof(output));
        //build_data_json();
        strncat(output, "\n", sizeof(output));
        send_data(output);
    }
    Serial.print("Current connections: ");
    Serial.println(iwrap_active_connections);
}

void send_configuration() {
    char output[200];
    Serial.println("kek");
    {
        StaticJsonBuffer<50> buffer;
        Serial.println("kok");
        JsonObject& dump = buffer.createObject();
        JsonObject& config = dump.createNestedObject("configuration");
        config["uuid"]  = DEVICE_UUID_STR;
        config["pin"]   = DEVICE_PIN_STR;
        config["name"]  = DEVICE_FRIENDLY_NAME;

        Serial.println("kekkek");
        dump.printTo(output, sizeof(output));
    }
    Serial.println("keks");
    strncat(output, "\n", sizeof(output));
    Serial.println(output);
    send_data(output);
}


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class ClusterAction extends DynamicData
{
  public String type;
  public ManagedObjectReference target;

  public String getType()
  {
    return this.type;
  }

  public ManagedObjectReference getTarget()
  {
    return this.target;
  }

  public void setType(String type)
  {
    this.type=type;
  }

  public void setTarget(ManagedObjectReference target)
  {
    this.target=target;
  }
}


text:
/** Full Logger implementation that logs plain text messages to `stderr`.
 * The format of the messages is suitable for processing in popular text editors like EMacs or Vim.
 * It is the same as that of error messages yielded by most popular compilers like gcc or javac.
 * The format is:
 *
<var>filename</var>:<var>linenumber</var>: error: in <var>symbolnname</var>: <var>message</var>

 * For example:
 *
<samp>foo.c:30: error: Expected X to be 15 but was 13.</samp>

 * @author Christian Hujer
 * @file FullPlainLogger.c
 */

#include <stdio.h>

#include "AceUnit.h"
#include "AceUnitLogging.h"

extern char *__progname;

/** Logs a message using this logger.
 * @param recentError Error to log.
 */
void FullPlainLoggerLog(const AssertionError_t *const recentError) {
#ifdef ACEUNIT_EMBEDDED
#error "FullPlainLogger does not support embedded AceUnit."
#else
    fprintf(stderr, "%s:%d: error: in %d: %s\n", recentError->assertionId.filename, (int) recentError->assertionId.lineNumber, (int) recentError->testId, recentError->assertionId.message);
#endif
}

void FullPlainLoggerRunnerStarted(void) {
    fprintf(stderr, "%s: info: Testing Started.\n", __progname);
}

void FullPlainLoggerSuiteStarted(SuiteId_t const suiteId) {
    fprintf(stderr, "%s: info: Suite %d started.\n", __progname, suiteId);
}

void FullPlainLoggerFixtureStarted(const FixtureId_t fixtureId) {
    fprintf(stderr, "%s: info: Fixture %d started.\n", __progname, fixtureId);
}

void FullPlainLoggerTestCaseStarted(TestCaseId_t testCaseId) {
    fprintf(stderr, "%s: info: Test Case %d started.\n", __progname, testCaseId);
}

void FullPlainLoggerTestCaseEnded(TestCaseId_t testCaseId) {
    fprintf(stderr, "%s: info: Test Case %d ended.\n", __progname, testCaseId);
}

void FullPlainLoggerFixtureEnded(FixtureId_t fixtureId) {
    fprintf(stderr, "%s: info: Fixture %d ended.\n", __progname, fixtureId);
}

void FullPlainLoggerSuiteEnded(SuiteId_t const suiteId) {
    fprintf(stderr, "%s: info: Suite %s ended.\n", __progname, suiteId);
}

void FullPlainLoggerRunnerEnded(void) {
    fprintf(stderr, "%s: info: Runner ended.\n", __progname);
}

/** This Logger. */
AceUnitNewLogger(
    FullPlainLogger,
    FullPlainLoggerRunnerStarted,
    FullPlainLoggerSuiteStarted,
    FullPlainLoggerFixtureStarted,
    FullPlainLoggerTestCaseStarted,
    FullPlainLoggerLog,
    FullPlainLoggerTestCaseEnded,
    FullPlainLoggerFixtureEnded,
    FullPlainLoggerSuiteEnded,
    FullPlainLoggerRunnerEnded
);

TestLogger_t *globalLogger = &FullPlainLogger; /* XXX Hack. Remove. */


text:
#include "../../SDL_internal.h"

#if SDL_JOYSTICK_VITA

/* This is the PSVita implementation of the SDL joystick API */
#include <psp2/types.h>
#include <psp2/ctrl.h>
#include <psp2/kernel/threadmgr.h>

#include <stdio.h>      /* For the definition of NULL */
#include <stdlib.h>

#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"

#include "SDL_events.h"
#include "SDL_error.h"
#include "SDL_thread.h"
#include "SDL_mutex.h"
#include "SDL_timer.h"

/* Current pad state */
static SceCtrlData pad0 = { .lx = 0, .ly = 0, .rx = 0, .ry = 0, .lt = 0, .rt = 0, .buttons = 0 };
static SceCtrlData pad1 = { .lx = 0, .ly = 0, .rx = 0, .ry = 0, .lt = 0, .rt = 0, .buttons = 0 };
static SceCtrlData pad2 = { .lx = 0, .ly = 0, .rx = 0, .ry = 0, .lt = 0, .rt = 0, .buttons = 0 };
static SceCtrlData pad3 = { .lx = 0, .ly = 0, .rx = 0, .ry = 0, .lt = 0, .rt = 0, .buttons = 0 };

static int port_map[4]= { 0, 2, 3, 4 }; //index: SDL joy number, entry: Vita port number
static int ext_port_map[4]= { 1, 2, 3, 4 }; //index: SDL joy number, entry: Vita port number. For external controllers

static int SDL_numjoysticks = 1;

static const unsigned int button_map[] = {
    SCE_CTRL_TRIANGLE,
    SCE_CTRL_CIRCLE,
    SCE_CTRL_CROSS,
    SCE_CTRL_SQUARE,
    SCE_CTRL_LTRIGGER,
    SCE_CTRL_RTRIGGER,
    SCE_CTRL_DOWN,
    SCE_CTRL_LEFT,
    SCE_CTRL_UP,
    SCE_CTRL_RIGHT,
    SCE_CTRL_SELECT,
    SCE_CTRL_START
};

static const unsigned int ext_button_map[] = {
    SCE_CTRL_TRIANGLE,
    SCE_CTRL_CIRCLE,
    SCE_CTRL_CROSS,
    SCE_CTRL_SQUARE,
    SCE_CTRL_L1,
    SCE_CTRL_R1,
    SCE_CTRL_DOWN,
    SCE_CTRL_LEFT,
    SCE_CTRL_UP,
    SCE_CTRL_RIGHT,
    SCE_CTRL_SELECT,
    SCE_CTRL_START,
    SCE_CTRL_L2,
    SCE_CTRL_R2,
    SCE_CTRL_L3,
    SCE_CTRL_R3
};

static int analog_map[256];  /* Map analog inputs to -32768 -> 32767 */

typedef struct
{
  int x;
  int y;
} point;

/* 4 points define the bezier-curve. */
/* The Vita has a good amount of analog travel, so use a linear curve */
static point a = { 0, 0 };
static point b = { 0, 0  };
static point c = { 128, 32767 };
static point d = { 128, 32767 };

/* simple linear interpolation between two points */
static SDL_INLINE void lerp (point *dest, point *first, point *second, float t)
{
    dest->x = first->x + (second->x - first->x) * t;
    dest->y = first->y + (second->y - first->y) * t;
}

/* evaluate a point on a bezier-curve. t goes from 0 to 1.0 */
static int calc_bezier_y(float t)
{
    point ab, bc, cd, abbc, bccd, dest;
    lerp (&ab, &a, &b, t);           /* point between a and b */
    lerp (&bc, &b, &c, t);           /* point between b and c */
    lerp (&cd, &c, &d, t);           /* point between c and d */
    lerp (&abbc, &ab, &bc, t);       /* point between ab and bc */
    lerp (&bccd, &bc, &cd, t);       /* point between bc and cd */
    lerp (&dest, &abbc, &bccd, t);   /* point on the bezier-curve */
    return dest.y;
}

/* Function to scan the system for joysticks.
 * Joystick 0 should be the system default joystick.
 * It should return number of joysticks, or -1 on an unrecoverable fatal error.
 */
int VITA_JoystickInit(void)
{
    int i;
    SceCtrlPortInfo myPortInfo;

    /* Setup input */
    sceCtrlSetSamplingMode(SCE_CTRL_MODE_ANALOG_WIDE);
    sceCtrlSetSamplingModeExt(SCE_CTRL_MODE_ANALOG_WIDE);

    /* Create an accurate map from analog inputs (0 to 255)
       to SDL joystick positions (-32768 to 32767) */
    for (i = 0; i < 128; i++)
    {
        float t = (float)i/127.0f;
        analog_map[i+128] = calc_bezier_y(t);
        analog_map[127-i] = -1 * analog_map[i+128];
    }

    // Assume we have at least one controller, even when nothing is paired
    // This way the user can jump in, pair a controller
    // and control things immediately even if it is paired
    // after the app has already started.

    SDL_numjoysticks = 1;
    SDL_PrivateJoystickAdded(0);
    // How many additional paired controllers are there?
    sceCtrlGetControllerPortInfo(&myPortInfo);

    // On Vita TV, port 0 and 1 are the same controller
    // and that is the first one, so start at port 2
    for (i=2; i<=4; i++)
    {
        if (myPortInfo.port[i]!=SCE_CTRL_TYPE_UNPAIRED)
        {
            SDL_PrivateJoystickAdded(SDL_numjoysticks);
            SDL_numjoysticks++;
        }
    }
    return SDL_numjoysticks;
}

int VITA_JoystickGetCount()
{
    return SDL_numjoysticks;
}

void VITA_JoystickDetect()
{
}

/* Function to perform the mapping from device index to the instance id for this index */
SDL_JoystickID VITA_JoystickGetDeviceInstanceID(int device_index)
{
    return device_index;
}

/* Function to get the device-dependent name of a joystick */
const char *VITA_JoystickGetDeviceName(int index)
{
    if (index == 0)
        return "PSVita Controller";

    if (index == 1)
        return "PSVita Controller";

    if (index == 2)
        return "PSVita Controller";

    if (index == 3)
        return "PSVita Controller";

    SDL_SetError("No joystick available with that index");
    return(NULL);
}

static int
VITA_JoystickGetDevicePlayerIndex(int device_index)
{
    return -1;
}

static void
VITA_JoystickSetDevicePlayerIndex(int device_index, int player_index)
{
}

/* Function to open a joystick for use.
   The joystick to open is specified by the device index.
   This should fill the nbuttons and naxes fields of the joystick structure.
   It returns 0, or -1 if there is an error.
 */
int VITA_JoystickOpen(SDL_Joystick *joystick, int device_index)
{
    joystick->nbuttons = SDL_arraysize(ext_button_map);
    joystick->naxes = 6;
    joystick->nhats = 0;
    joystick->instance_id = device_index;

    return 0;
}

/* Function to update the state of a joystick - called as a device poll.
 * This function shouldn't update the joystick structure directly,
 * but instead should call SDL_PrivateJoystick*() to deliver events
 * and update joystick device state.
 */
static void VITA_JoystickUpdate(SDL_Joystick *joystick)
{
    int i;
    unsigned int buttons;
    unsigned int changed;
    unsigned char lx, ly, rx, ry, lt, rt;
    static unsigned int old_buttons[] = { 0, 0, 0, 0 };
    static unsigned char old_lx[] = { 0, 0, 0, 0 };
    static unsigned char old_ly[] = { 0, 0, 0, 0 };
    static unsigned char old_rx[] = { 0, 0, 0, 0 };
    static unsigned char old_ry[] = { 0, 0, 0, 0 };
    static unsigned char old_lt[] = { 0, 0, 0, 0 };
    static unsigned char old_rt[] = { 0, 0, 0, 0 };
    SceCtrlData *pad = NULL;
    SDL_bool fallback = SDL_FALSE;

    int index = (int) SDL_JoystickInstanceID(joystick);

    if (index == 0) pad = &pad0;
    else if (index == 1) pad = &pad1;
    else if (index == 2) pad = &pad2;
    else if (index == 3) pad = &pad3;
    else return;

    if (index == 0) {
        if (sceCtrlPeekBufferPositiveExt2(ext_port_map[index], pad, 1) < 0) {
            // on vita fallback to port 0
            sceCtrlPeekBufferPositive(port_map[index], pad, 1);
            fallback = SDL_TRUE;
        }
    } else {
        sceCtrlPeekBufferPositiveExt2(ext_port_map[index], pad, 1);
    }

    buttons = pad->buttons;

    lx = pad->lx;
    ly = pad->ly;
    rx = pad->rx;
    ry = pad->ry;
    lt = pad->lt;
    rt = pad->rt;

    // Axes

    if (old_lx[index] != lx) {
        SDL_PrivateJoystickAxis(joystick, 0, analog_map[lx]);
        old_lx[index] = lx;
    }
    if (old_ly[index] != ly) {
        SDL_PrivateJoystickAxis(joystick, 1, analog_map[ly]);
        old_ly[index] = ly;
    }
    if (old_rx[index] != rx) {
        SDL_PrivateJoystickAxis(joystick, 2, analog_map[rx]);
        old_rx[index] = rx;
    }
    if (old_ry[index] != ry) {
        SDL_PrivateJoystickAxis(joystick, 3, analog_map[ry]);
        old_ry[index] = ry;
    }

    if (old_lt[index] != lt) {
        SDL_PrivateJoystickAxis(joystick, 4, analog_map[lt]);
        old_lt[index] = lt;
    }
    if (old_rt[index] != rt) {
        SDL_PrivateJoystickAxis(joystick, 5, analog_map[rt]);
        old_rt[index] = rt;
    }

    // Buttons
    changed = old_buttons[index] ^ buttons;
    old_buttons[index] = buttons;

    if (changed) {
        if (fallback) {
            for (i = 0; i < SDL_arraysize(button_map); i++) {
                if (changed & button_map[i]) {
                    SDL_PrivateJoystickButton(
                        joystick, i,
                        (buttons & button_map[i]) ?
                        SDL_PRESSED : SDL_RELEASED);
                }
            }
        } else {
            for (i = 0; i < SDL_arraysize(ext_button_map); i++) {
                if (changed & ext_button_map[i]) {
                    SDL_PrivateJoystickButton(
                        joystick, i,
                        (buttons & ext_button_map[i]) ?
                        SDL_PRESSED : SDL_RELEASED);
                }
            }
        }
    }
}

/* Function to close a joystick after use */
void VITA_JoystickClose(SDL_Joystick *joystick)
{
}

/* Function to perform any system-specific joystick related cleanup */
void VITA_JoystickQuit(void)
{
}

SDL_JoystickGUID VITA_JoystickGetDeviceGUID( int device_index )
{
    SDL_JoystickGUID guid;
    /* the GUID is just the first 16 chars of the name for now */
    const char *name = VITA_JoystickGetDeviceName( device_index );
    SDL_zero( guid );
    SDL_memcpy( &guid, name, SDL_min( sizeof(guid), SDL_strlen( name ) ) );
    return guid;
}

static int
VITA_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
{
    int index = (int) SDL_JoystickInstanceID(joystick);
    SceCtrlActuator act;
    SDL_zero(act);

    act.small = high_frequency_rumble / 256;
    act.large = low_frequency_rumble / 256;
    sceCtrlSetActuator(ext_port_map[index], &act);
    return 0;
}

static int
VITA_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left, Uint16 right)
{
    return SDL_Unsupported();
}

static Uint32
VITA_JoystickGetCapabilities(SDL_Joystick *joystick)
{
    // always return LED and rumble supported for now
    return SDL_JOYCAP_LED | SDL_JOYCAP_RUMBLE;
}

static int
VITA_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
{
    int index = (int) SDL_JoystickInstanceID(joystick);
    sceCtrlSetLightBar(ext_port_map[index], red, green, blue);
    return 0;
}

static int
VITA_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size)
{
    return SDL_Unsupported();
}

static int
VITA_JoystickSetSensorsEnabled(SDL_Joystick *joystick, SDL_bool enabled)
{
    return SDL_Unsupported();
}

SDL_JoystickDriver SDL_VITA_JoystickDriver =
{
    VITA_JoystickInit,
    VITA_JoystickGetCount,
    VITA_JoystickDetect,
    VITA_JoystickGetDeviceName,
    VITA_JoystickGetDevicePlayerIndex,
    VITA_JoystickSetDevicePlayerIndex,
    VITA_JoystickGetDeviceGUID,
    VITA_JoystickGetDeviceInstanceID,

    VITA_JoystickOpen,

    VITA_JoystickRumble,
    VITA_JoystickRumbleTriggers,

    VITA_JoystickGetCapabilities,
    VITA_JoystickSetLED,
    VITA_JoystickSendEffect,
    VITA_JoystickSetSensorsEnabled,

    VITA_JoystickUpdate,
    VITA_JoystickClose,
    VITA_JoystickQuit,
};

#endif /* SDL_JOYSTICK_VITA */

/* vi: set ts=4 sw=4 expandtab: */


text:
package de.huberlin.cuneiform.common;

public class Constant {

	public static final String TOKEN_TASK = "task";
	public static final String TOKEN_ALL = "all";

	@Deprecated public static final String KEY_INVOCATION_OUTPUT = "invoc-output";
	@Deprecated public static final String KEY_USER = "user";
	@Deprecated public static final String KEY_INVOCATION_STAT = "invoc-stat";
	@Deprecated public static final String KEY_INVOCATION_STAGEIN = "invoc-stagein";
	@Deprecated public static final String KEY_INVOCATION_STAGEOUT = "invoc-stageout";
	@Deprecated public static final String KEY_INVOCATION_STDOUT = "invoc-stdout";
	@Deprecated public static final String KEY_INVOCATION_STDERR = "invoc-stderr";

	@Deprecated public static final String VALUE_NIL = "nil";

	public static final int LANG_BASH = 0;

}


text:
//
//  LXCommonDataModel.h
//  LXDataCollection
//
//  Created by junyixin on 2017/10/30.
//  Copyright © 2017年 junyixin. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface LXDeviceInfo: NSObject

+ (instancetype)obtainDeviceInfo;

/**
 运营商
 */
@property (nonatomic, strong) NSString *carrier;

/**
 App版本号
 */
@property (nonatomic, strong) NSString *version;

/**
 App build编号
 */
@property (nonatomic, strong) NSString *build;

/**
 设备类型(0:Android  1:iOS  2:PC)
 */
@property (nonatomic, strong) NSString *deviceType;

/**
 设备型号(eg:iPhone7)
 */
@property (nonatomic, strong) NSString *model;

/**
 手机品牌
 */
@property (nonatomic, strong) NSString *brand;

/**
 系统版本
 */
@property (nonatomic, strong) NSString *osVersion;

/**
 网络类型
 */
@property (nonatomic, strong) NSString *networkType;

/**
 UUID
 */
@property (nonatomic, strong) NSString *uuid;

/**
 IDFA
 */
@property (nonatomic, strong) NSString *adid;

/**
 渠道
 */
@property (nonatomic, strong) NSString *channel;

@end

@interface LXCommonDataModel : NSObject

/**
 设备信息
 */
@property (nonatomic, strong) LXDeviceInfo *deviceInfo;

/**
 用户ID
 */
@property (nonatomic, strong) NSString *userId;

/**
 事件ID
 */
@property (nonatomic, strong) NSString *eventId;

/**
 标识属性
 */
@property (nonatomic, strong) NSDictionary *attributes;

/**
 事件时间
 */
@property (nonatomic, strong) NSString *eventTime;

@end


text:
from contextlib import contextmanager
import datetime

from django.test import TestCase
from django.utils import timezone
import mock

from cla_common.constants import CASE_SOURCE
from cla_common import call_centre_availability
from core.tests.mommy_utils import make_recipe, make_user
from cla_eventlog import event_registry
from cla_eventlog.models import Log
from legalaid.forms import get_sla_time
from reports.forms import MICB1Extract
from call_centre.tests.test_utils import CallCentreFixedOperatingHours

def _make_datetime(year=None, month=None, day=None, hour=0, minute=0, second=0):
    today = datetime.date.today()
    year = year if year else today.year
    month = month if month else today.month
    day = day if day else today.day
    dt = datetime.datetime(year, month, day, hour, minute, second)
    return timezone.make_aware(dt, timezone.get_current_timezone())

def mock_now(dt):
    return dt

@contextmanager
def patch_field(cls, field_name, dt):
    field = cls._meta.get_field(field_name)
    with mock.patch.object(field, "default", new=mock_now(dt)):
        yield

class MiSlaTestCaseBase(CallCentreFixedOperatingHours):
    source = None
    requires_action_at_minutes_offset = 60

    def setUp(self):
        super(MiSlaTestCaseBase, self).setUp()
        self.current_case = None
        self.now = self.get_default_dt()

        self.timezone_mock = mock.patch.object(timezone, "now", lambda: self.now)
        self.timezone_mock.start()

        now_naive = timezone.make_naive(self.now, timezone.get_current_timezone())
        self.cla_common_datetime_mock = mock.patch.object(
            call_centre_availability, "current_datetime", lambda: now_naive
        )
        self.cla_common_datetime_mock.start()

    def tearDown(self):
        super(MiSlaTestCaseBase, self).tearDown()
        self.timezone_mock.stop()
        self.cla_common_datetime_mock.stop()

    def get_default_dt(self):
        raise NotImplementedError()

    def get_requires_action_at(self):
        raise NotImplementedError

    def get_sla1_datetime(self):
        raise NotImplementedError()

    def get_sla2_datetime(self):
        raise NotImplementedError()

    def move_time_forward_minutes_before_sla1(self, minutes):
        return self._move_time_forward(self.get_sla1_datetime(), -minutes)

    def move_time_forward_minutes_after_sla1(self, minutes):
        return self._move_time_forward(self.get_sla1_datetime(), minutes)

    def move_time_forward_minutes_before_sla2(self, minutes):
        return self._move_time_forward(self.get_sla2_datetime(), -minutes)

    def move_time_forward_minutes_after_sla2(self, minutes):
        return self._move_time_forward(self.get_sla2_datetime(), minutes)

    def _move_time_forward(self, dt, minutes_forward):
        self.now = dt + datetime.timedelta(minutes=minutes_forward)
        self.timezone_mock.return_value = self.now
        self.cla_common_datetime_mock.return_value = timezone.make_naive(dt, dt.tzinfo)

        return self.now

    def make_case(self, dt, **kwargs):
        with patch_field(Log, "created", dt - datetime.timedelta(minutes=1)):
            self.current_case = make_recipe("legalaid.case", source=self.source, **kwargs)
            return self.current_case

    def schedule_callback(self, case, user, created, requires_action_at=None):
        requires_action_at = requires_action_at or created + datetime.timedelta(minutes=35)
        sla_base_time = requires_action_at
        if case.source in [CASE_SOURCE.SMS, CASE_SOURCE.VOICEMAIL]:
            sla_base_time = case.created
        event = event_registry.get_event("call_me_back")()
        with patch_field(Log, "created", created):
            event.get_log_code(case=case)
            event.process(
                case,
                created_by=user,
                notes="",
                context={
                    "requires_action_at": requires_action_at,
                    "sla_15": get_sla_time(sla_base_time, 15),
                    "sla_30": get_sla_time(sla_base_time, 30),
                    "sla_120": get_sla_time(sla_base_time, 120),
                    "sla_480": get_sla_time(sla_base_time, 480),
                    "sla_72h": get_sla_time(sla_base_time, 4320),
                },
            )
            case.set_requires_action_at(requires_action_at)

    def start_call(self, case, user, created):
        event = event_registry.get_event("case")()
        with patch_field(Log, "created", created):
            event.process(case, status="call_started", created_by=user, notes="Call started")

    def get_report(self, date_range):
        with mock.patch("reports.forms.MICB1Extract.date_range", date_range):
            report = MICB1Extract()

            qs = report.get_queryset()
            headers = report.get_headers()

        return {k: v for k, v in zip(headers, qs[0])}

    def create_and_get_report(self, callback_minutes_after, case=None):
        created = case.created if case else _make_datetime(2015, 1, 2, 9, 1, 0)
        case = case or self.make_case(created)
        user = make_user()
        make_recipe("call_centre.operator", user=user)

        requires_action_at = created + datetime.timedelta(minutes=self.requires_action_at_minutes_offset)
        self.schedule_callback(case, user, created, requires_action_at)
        self.start_call(case, user, requires_action_at + datetime.timedelta(minutes=callback_minutes_after))

        date_range = (
            created.replace(hour=0, minute=0),
            created.replace(hour=0, minute=0) + datetime.timedelta(days=1),
        )
        return self.get_report(date_range)

    def test_current_time_within_sla1(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)

        # Create a callback that is due now 1 hour from now
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Move current time to 1 minute before SLA1
        now_tz = self.move_time_forward_minutes_before_sla1(minutes=1)

        # Generate report without a callback
        date_range = (now_tz - datetime.timedelta(days=2), now_tz + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertFalse(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, now_tz)
        # Generate report with a successful callback
        date_range = (now_tz - datetime.timedelta(days=2), now_tz + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertFalse(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

    def test_current_time_after_sla1(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)

        # Create a callback that is due now 1 hour from now
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Move current time to 1 minute after SLA1
        now_tz = self.move_time_forward_minutes_after_sla1(minutes=1)

        # Generate report without a callback
        date_range = (now_tz - datetime.timedelta(days=2), now_tz + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, now_tz)
        # Generate report with a successful callback
        date_range = (now_tz - datetime.timedelta(days=2), now_tz + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

    def test_current_time_before_sla2(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)

        # Create a callback that is due now 1 hour from now
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Move current time to 1 minute before SLA2
        self.move_time_forward_minutes_before_sla2(minutes=1)

        # Generate report without a callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, self.now)
        # Generate report with a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

    def test_current_time_after_sla2(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)
        # Create a callback that is due now
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Move current time to 1 minute after SLA2
        now_tz = self.move_time_forward_minutes_after_sla2(minutes=1)

        # Generate report without a callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertTrue(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, now_tz)
        # Generate report with a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertTrue(values["missed_sla_2"])

    def test_cb2_current_time_within_sla1(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)
        # Create CB1
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())
        # Move current time to 1 minute before SLA1
        self.move_time_forward_minutes_before_sla1(minutes=1)
        # Create  CB2
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Generate report without a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertFalse(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, self.now)
        # Generate report with a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertFalse(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

    def test_cb2_current_time_after_sla1(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)
        # Create CB1
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())
        # Move current time 1 minute after SLA1
        now_tz = self.move_time_forward_minutes_after_sla1(minutes=1)
        # Create  CB2
        self.schedule_callback(case, user, created=now_tz, requires_action_at=self.get_requires_action_at())

        # Generate report without a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, now_tz)
        # Generate report with a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

    def test_cb2_current_time_before_sla2(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)
        # Create CB1
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())
        # Move current time 1 minute before SLA2
        self.move_time_forward_minutes_before_sla2(minutes=1)
        # Create  CB2
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Generate report without a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, self.now)
        # Generate report with a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

    def test_cb2_current_time_after_sla2(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)

        # Create CB1
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())
        # Move current time 1 minute after SLA2
        self.move_time_forward_minutes_after_sla2(minutes=1)
        # Create  CB2
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Generate report without a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertTrue(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, self.now)
        # Generate report with a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertTrue(values["missed_sla_2"])

    def test_cb3_current_time_within_sla1(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)
        # Create CB1
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Move current time to 2 minute before SLA1
        self.move_time_forward_minutes_before_sla1(minutes=2)
        # Create  CB2
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Move current time to 1 minute before SLA1
        self.move_time_forward_minutes_before_sla1(minutes=1)
        # Create  CB3
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Generate report without a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertFalse(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, self.now)
        # Generate report with a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertFalse(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

class MiSlaTestCaseWeb(MiSlaTestCaseBase, TestCase):
    source = CASE_SOURCE.WEB

    # fmt: off
    """
    CB1
    +--------------+-------------------------------+---------------------------------------------+--------------------------------+
    |              |                               |                                             | Call answered                  |
    |              |                               |                                             | after 30m                      |
    |              | Call answered                 | Call answered                               | AND                            |
    |              | Within 30m window             | before 30m window                           | current time within 72h window |
    +--------------+-------------------------------+---------------------------------------------+--------------------------------+
    | SLA 1 missed |             FALSE             |                     TRUE                    |              TRUE              |
    +--------------+-------------------------------+---------------------------------------------+--------------------------------+
    | SLA 2 missed |             FALSE             |                    FALSE                    |              FALSE             |
    +--------------+-------------------------------+---------------------------------------------+--------------------------------+
    | test         | test_current_time_within_sla1 | test_current_time_before_requires_action_at | test_current_time_after_sla1   |
    +--------------+-------------------------------+---------------------------------------------+--------------------------------+

    CB2
    +--------------+-----------------------------------+-------------------------------------------------+----------------------------------+----------------------------------+----------------------------------+-----------------------------------+
    |              | CB2 Scheduled                     | CB2 Scheduled                                   | CB2 Scheduled                    | CB2 Scheduled                    | Call answered                    | CB2 Scheduled                     |
    |              | within 30m window                 | before 30m window                               | after 30m window                 | after 30m window                 | after 72 window                  | within 30m window                 |
    |              | AND                               | AND                                             | AND                              | AND                              |                                  | AND                               |
    |              | current time within 72h window    | current time within 72h window                  | current time within 72h window   | current time after 72h window    |                                  | call answered within 72 window    |
    +--------------+-----------------------------------+-------------------------------------------------+----------------------------------+----------------------------------+----------------------------------+-----------------------------------+
    | SLA 1 missed |               FALSE               |                       TRUE                      |               TRUE               |               TRUE               |               TRUE               |               FALSE               |
    +--------------+-----------------------------------+-------------------------------------------------+----------------------------------+----------------------------------+----------------------------------+-----------------------------------+
    | SLA 2 missed |               FALSE               |                      FALSE                      |               FALSE              |               TRUE               |               TRUE               |               FALSE               |
    +--------------+-----------------------------------+-------------------------------------------------+----------------------------------+----------------------------------+----------------------------------+-----------------------------------+
    | test         | test_cb2_current_time_within_sla1 | test_cb2_current_time_before_requires_action_at | test_cb2_current_time_after_sla1 | test_cb2_current_time_after_sla2 | test_cb2_current_time_after_sla2 | test_cb2_current_time_within_sla1 |
    +--------------+-----------------------------------+-------------------------------------------------+----------------------------------+----------------------------------+----------------------------------+-----------------------------------+

    CB3
    +--------------+-----------------------------------+
    |              | CB3 Scheduled                     |
    |              | within 30m window                 |
    |              | AND                               |
    |              | call answered within 72 window    |
    +--------------+-----------------------------------+
    | SLA 1 missed |               FALSE               |
    +--------------+-----------------------------------+
    | SLA 2 missed |               FALSE               |
    +--------------+-----------------------------------+
    | test         | test_cb3_current_time_within_sla1 |
    +--------------+-----------------------------------+
    """
    # fmt: on

    def get_default_dt(self):
        return _make_datetime(year=2020, month=9, day=7, hour=9, minute=0)

    def get_requires_action_at(self):
        return self.now + datetime.timedelta(hours=1)

    def get_sla1_datetime(self):
        return self.get_requires_action_at() + datetime.timedelta(minutes=30)

    def get_sla2_datetime(self):
        return _make_datetime(year=2020, month=9, day=15, hour=12, minute=30)

    def test_current_time_before_requires_action_at(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)

        # Create a callback that is due now 1 hour from now
        requires_action_at = self.get_requires_action_at()
        self.schedule_callback(case, user, created=self.now, requires_action_at=requires_action_at)

        # Move current time to 5 minute before requires_action_at
        self._move_time_forward(requires_action_at, minutes_forward=-5)
        # Generate report without a callback
        date_range = (self.now - datetime.timedelta(days=2), self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertFalse(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, self.now)
        # Generate report with a successful callback
        date_range = (self.now - datetime.timedelta(days=2), self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        # Contacting customer before the requires_action_at will result in a failure to meet SLA
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

    def test_cb2_current_time_before_requires_action_at(self):
        case = self.make_case(self.now, created=self.now)
        user = make_user()
        make_recipe("call_centre.operator", user=user)
        # Create CB1
        requires_action_at = self.get_requires_action_at()
        self.schedule_callback(case, user, created=self.now, requires_action_at=requires_action_at)

        # Move current time to 5 minute before requires_action_at
        self._move_time_forward(requires_action_at, minutes_forward=-5)

        # Create  CB2
        self.schedule_callback(case, user, created=self.now, requires_action_at=self.get_requires_action_at())

        # Generate report without a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

        # Start a call
        self.start_call(case, user, self.now)
        # Generate report with a successful callback
        date_range = (case.created, self.now + datetime.timedelta(days=2))
        values = self.get_report(date_range)
        self.assertTrue(values["missed_sla_1"])
        self.assertFalse(values["missed_sla_2"])

class MiSlaTestCasePhone(MiSlaTestCaseWeb):
    source = CASE_SOURCE.PHONE

class MiSlaTestCaseSMS(MiSlaTestCaseBase, TestCase):
    source = CASE_SOURCE.SMS

    # fmt: off
    """
    Rules used to determine if SLA1/SLA2 was missed
    Note: A callback attempt is when the operator has clicked the start call button after successfully contacting the user
    +-----------+--------------+-----------------------------------+--------------------------------------------------------------------+-------------------------------------------------------------------+
    |           |              | Callback attempted within 2 hours | Callback attempted after 2 hours AND current time within 8h window | Callback attempted after 2 hours AND current time after 8h window |
    +-----------+--------------+-----------------------------------+--------------------------------------------------------------------+-------------------------------------------------------------------+
    | SMS       | SLA 1 missed | FALSE                             | TRUE                                                               | TRUE                                                              |
    +-----------+--------------+-----------------------------------+--------------------------------------------------------------------+-------------------------------------------------------------------+
    |           | SLA 2 missed | FALSE                             | FALSE                                                              | TRUE                                                              |
    +-----------+--------------+-----------------------------------+--------------------------------------------------------------------+-------------------------------------------------------------------+
    | Voicemail | SLA 1 missed | FALSE                             | TRUE                                                               | TRUE                                                              |
    +-----------+--------------+-----------------------------------+--------------------------------------------------------------------+-------------------------------------------------------------------+
    |           | SLA 2 missed | FALSE                             | FALSE                                                              | TRUE                                                              |
    +-----------+--------------+-----------------------------------+--------------------------------------------------------------------+-------------------------------------------------------------------+
    """
    # fmt: on

    def get_default_dt(self):
        return _make_datetime(year=2020, month=9, day=7, hour=9, minute=0)

    def get_requires_action_at(self):
        return self.now + datetime.timedelta(hours=1)

    def get_sla1_datetime(self):
        return _make_datetime(year=2020, month=9, day=7, hour=11, minute=0)

    def get_sla2_datetime(self):
        return _make_datetime(year=2020, month=9, day=7, hour=17, minute=0)

class MiSlaTestCaseVoiceMail(MiSlaTestCaseSMS):
    source = CASE_SOURCE.VOICEMAIL


text:
//>>built
define("dojox/mobile/Carousel", [
	"dojo/_base/kernel",
	"dojo/_base/array",
	"dojo/_base/connect",
	"dojo/_base/declare",
	"dojo/_base/event",
	"dojo/_base/lang",
	"dojo/_base/sniff",
	"dojo/dom-class",
	"dojo/dom-construct",
	"dojo/dom-style",
	"dijit/_Contained",
	"dijit/_Container",
	"dijit/_WidgetBase",
	"./PageIndicator",
	"./SwapView",
	"require"
], function(kernel, array, connect, declare, event, lang, has, domClass, domConstruct, domStyle, Contained, Container, WidgetBase, PageIndicator, SwapView, require){

/*=====
	var Contained = dijit._Contained;
	var Container = dijit._Container;
	var WidgetBase = dijit._WidgetBase;
	var PageIndicator = dojox.mobile.PageIndicator;
	var SwapView = dojox.mobile.SwapView;
=====*/

	// module:
	//		dojox/mobile/Carousel
	// summary:
	//		A carousel widget that manages a list of images

	kernel.experimental("dojox.mobile.Carousel");

	return declare("dojox.mobile.Carousel", [WidgetBase, Container, Contained], {
		// summary:
		//		A carousel widget that manages a list of images
		// description:
		//		The carousel widget manages a list of images that can be
		//		displayed horizontally, and allows the user to scroll through
		//		the list and select a single item.

		// numVisible: Number
		//		The number of visible items.
		numVisible: 3,

		// title: String
		//		A title of the carousel to be displayed on the title bar.
		title: "",

		// pageIndicator: Boolean
		//		If true, a page indicator, a series of small dots that indicate
		//		the current page, is displayed on the title bar.
		pageIndicator: true,

		// navButton: Boolean
		//		If true, navigation buttons are displyaed on the title bar.
		navButton: false,

		// height: String
		//		Explicitly specified height of the widget (ex. "300px"). If
		//		"inherit" is specified, the height is inherited from its offset
		//		parent.
		height: "300px",

		// store: Object
		//		Reference to data provider object used by this widget.
		store: null,

		// query: Object
		//		A query that can be passed to 'store' to initially filter the
		//		items.
		query: null,

		// queryOptions: Object
		//		An optional parameter for the query.
		queryOptions: null,

		buildRendering: function(){
			this.inherited(arguments);
			this.domNode.className = "mblCarousel";
			var h;
			if(this.height === "inherit"){
				if(this.domNode.offsetParent){
					h = this.domNode.offsetParent.offsetHeight + "px";
				}
			}else if(this.height){
				h = this.height;
			}
			this.domNode.style.height = h;
			this.headerNode = domConstruct.create("DIV", {className:"mblCarouselHeaderBar"}, this.domNode);

			if(this.navButton){
				this.btnContainerNode = domConstruct.create("DIV", {
					className: "mblCarouselBtnContainer"
				}, this.headerNode);
				domStyle.set(this.btnContainerNode, "float", "right"); // workaround for webkit rendering problem
				this.prevBtnNode = domConstruct.create("BUTTON", {
					className: "mblCarouselBtn",
					title: "Previous",
					innerHTML: "<"
				}, this.btnContainerNode);
				this.nextBtnNode = domConstruct.create("BUTTON", {
					className: "mblCarouselBtn",
					title: "Next",
					innerHTML: ">"
				}, this.btnContainerNode);
				this.connect(this.prevBtnNode, "onclick", "onPrevBtnClick");
				this.connect(this.nextBtnNode, "onclick", "onNextBtnClick");
			}

			if(this.pageIndicator){
				if(!this.title){
					this.title = " ";
				}
				this.piw = new PageIndicator();
				domStyle.set(this.piw, "float", "right"); // workaround for webkit rendering problem
				this.headerNode.appendChild(this.piw.domNode);
			}

			this.titleNode = domConstruct.create("DIV", {
				className: "mblCarouselTitle"
			}, this.headerNode);

			this.containerNode = domConstruct.create("DIV", {className:"mblCarouselPages"}, this.domNode);
			connect.subscribe("/dojox/mobile/viewChanged", this, "handleViewChanged");
		},

		startup: function(){
			if(this._started){ return; }
			if(this.store){
				var store = this.store;
				this.store = null;
				this.setStore(store, this.query, this.queryOptions);
			}
			this.inherited(arguments);
		},

		setStore: function(store, query, queryOptions){
			// summary:
			//		Sets the store to use with this widget.
			if(store === this.store){ return; }
			this.store = store;
			this.query = query;
			this.queryOptions = queryOptions;
			this.refresh();
		},

		refresh: function(){
			if(!this.store){ return; }
			this.store.fetch({
				query: this.query,
				queryOptions: this.queryOptions,
				onComplete: lang.hitch(this, "generate"),
				onError: lang.hitch(this, "onError")
			});
		},

		generate: function(/*Array*/items, /*Object*/ dataObject){
			array.forEach(this.getChildren(), function(child){
				if(child instanceof SwapView){
					child.destroyRecursive();
				}
			});
			this.items = items;
			this.swapViews = [];
			this.images = [];
			var nPages = Math.ceil(items.length / this.numVisible);
			var h = this.domNode.offsetHeight - this.headerNode.offsetHeight;
			for(var i = 0; i < nPages; i++){
				var w = new SwapView({height:h+"px"});
				this.addChild(w);
				this.swapViews.push(w);
				w._carouselImages = [];
				if(i === 0 && this.piw){
					this.piw.refId = w.id;
				}
				for(var j = 0; j < this.numVisible; j++){
					var idx = i * this.numVisible + j;
					var item = idx < items.length ? items[idx] :
						{src:require.toUrl("dojo/resources/blank.gif"), height:"1px"};
					var disp = w.domNode.style.display;
					w.domNode.style.display = ""; // need to be visible during the size calculation
					var box = this.createBox(item, h);
					w.containerNode.appendChild(box);
					box.appendChild(this.createHeaderText(item));
					var img = this.createContent(item, idx);
					box.appendChild(img);
					box.appendChild(this.createFooterText(item));
					this.resizeContent(item, box, img);
					w.domNode.style.display = disp;

					if(item.height !== "1px"){
						this.images.push(img);
						w._carouselImages.push(img);
					}
				}
			}
			if(this.swapViews[0]){
				this.loadImages(this.swapViews[0]);
			}
			if(this.swapViews[1]){
				this.loadImages(this.swapViews[1]); // pre-fetch the next view images
			}
			this.currentView = this.swapViews[0];
			if(this.piw){
				this.piw.reset();
			}
		},

		createBox: function(item, h){
			var width = item.width || (90/this.numVisible + "%");
			var height = item.height || h + "px";
			var m = has("ie") ? 5/this.numVisible-1 : 5/this.numVisible;
			var margin = item.margin || (m + "%");
			var box = domConstruct.create("DIV", {
				className: "mblCarouselBox"
			});
			domStyle.set(box, {
				margin: "0px " + margin,
				width: width,
				height: height
			});
			return box;
		},

		createHeaderText: function(item){
			this.headerTextNode = domConstruct.create("DIV", {
				className: "mblCarouselImgHeaderText",
				innerHTML: item.headerText ? item.headerText : " "
			});
			return this.headerTextNode;
		},

		createContent: function(item, idx){
			var props = {
				alt: item.alt || "",
				tabIndex: "0", // for keyboard navigation on a desktop browser
				className: "mblCarouselImg"
			};
			var img = domConstruct.create("IMG", props);
			img._idx = idx;
			if(item.height !== "1px"){
				this.connect(img, "onclick", "onClick");
				this.connect(img, "onkeydown", "onClick");
				connect.connect(img, "ondragstart", event.stop);
			}else{
				img.style.visibility = "hidden";
			}
			return img;
		},

		createFooterText: function(item){
			this.footerTextNode = domConstruct.create("DIV", {
				className: "mblCarouselImgFooterText",
				innerHTML: item.footerText ? item.footerText : " "
			});
			return this.footerTextNode;
		},

		resizeContent: function(item, box, img){
			if(item.height !== "1px"){
				img.style.height = (box.offsetHeight  - this.headerTextNode.offsetHeight - this.footerTextNode.offsetHeight) + "px";
			}
		},

		onError: function(errText){
		},

		onPrevBtnClick: function(e){
			if(this.currentView){
				this.currentView.goTo(-1);
			}
		},

		onNextBtnClick: function(e){
			if(this.currentView){
				this.currentView.goTo(1);
			}
		},

		onClick: function(e){
			if(e && e.type === "keydown" && e.keyCode !== 13){ return; }
			var img = e.currentTarget;
			for(var i = 0; i < this.images.length; i++){
				if(this.images[i] === img){
					domClass.add(img, "mblCarouselImgSelected");
				}else{
					domClass.remove(this.images[i], "mblCarouselImgSelected");
				}
			}
			domStyle.set(img, "opacity", 0.4);
			setTimeout(function(){
				domStyle.set(img, "opacity", 1);
			}, 1000);
			connect.publish("/dojox/mobile/carouselSelect", [this, img, this.items[img._idx], img._idx]);
		},

		loadImages: function(view){
			if(!view){ return; }
			var imgs = view._carouselImages;
			array.forEach(imgs, function(img){
				if(!img.src){
					var item = this.items[img._idx];
					img.src = item.src;
				}
			}, this);
		},

		handleViewChanged: function(view){
			if(view.getParent() !== this){ return; }
			this.currentView = view;
			// lazy-load images in the next view
			this.loadImages(view.nextView(view.domNode));
		},

		_setTitleAttr: function(/*String*/title){
			this.title = title;
			this.titleNode.innerHTML = this._cv ? this._cv(title) : title;
		}
	});
});


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;
    using Newtonsoft.Json;

    /// <summary>
    /// The type Workbook Chart Gridlines.
    /// </summary>
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    public partial class WorkbookChartGridlines : Entity
    {

        /// <summary>
        /// Gets or sets visible.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "visible", Required = Required.Default)]
        public bool? Visible { get; set; }

        /// <summary>
        /// Gets or sets format.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "format", Required = Required.Default)]
        public WorkbookChartGridlinesFormat Format { get; set; }

    }
}


text:
=======
Credits
=======

Development Lead
----------------

* Christopher Clarke <cclarke@chrisdev.com>

Contributors
------------
* Daniel Andrlik <daniel@anderlik.org>
* Parbhat Puri <me@parbhatpuri.com>


text:
import V = require("./VCL");
import VXC = require("./VXComponent");
import VXD = require("./VXDataset");
export declare class TTextBase extends VXC.TComponent implements V.iTranslatable {
    onClicked: (sender: TTextBase) => void;
    private _rtl;
    Rtl: boolean;
    private _localizable;
    /**
    * In order to localize application each page or component of the application has to have Localizable property set true.
    */
    Localizable: boolean;
    private _textcolor;
    TextColor: string;
    private _textaliggment;
    TextAlignment: V.TextAlignment;
    private _text;
    /**
    * Text specify the text string that labels the control.
    */
    Text: string;
    /**
    @aOwner     Indicates the component that is responsible for streaming and freeing this component.Onwer must be TContainer
    @renderTo   (Optional) the id of the html element that will be the parent node for this component
    @text       (Optional) the initial text value of the component
    **/
    constructor(aOwner: VXC.TComponent, renderTo?: string, text?: string);
    draw(reCreate: boolean): void;
    create(): void;
}
export declare class TDBTextBase extends VXC.TComponent {
    onClicked: () => void;
    private _rtl;
    Rtl: boolean;
    private _textcolor;
    TextColor: string;
    /**
    @aOwner     Indicates the component that is responsible for streaming and freeing this component.Onwer must be TContainer
    @renderTo   (Optional) the id of the html element that will be the parent node for this component
    **/
    constructor(aOwner: VXC.TComponent, renderTo?: string);
    private _dataset;
    /**
    * Specifies the dataset that contains the field it represents.
    */
    Dataset: VXD.TDataset;
    private _datafield;
    /**
    * Specifies the field from which the edit control displays data.
    */
    DataField: string;
    DataValue: any;
}


text:
% Acknowledgements

\pdfbookmark[1]{Acknowledgements}{Acknowledgements} % Bookmark name visible in a PDF viewer
\thispagestyle{scrheadings}

\chapter*{Acknowledgements} % Acknowledgements section text

\paragraph{}\noindent During the creation of this marketing report many persons supported me by giving me crucial information or by pointing my into the right direction along the way.

\paragraph{} First of all, my thanks go the --- who was always ready to provide important feedback and kindly investing her precious time many of the chapters in their draft form.
Equally, I want to thank --- for showing me a different perspective many times during the process and for inspirational discussions about the project and its direction.

\paragraph{}My thanks go also to the participants of the pilot semester of Radio Comem. I enjoyed many exchanges and they helped me tremendously by giving me insight about the most important customer of the project — themselves. They often reassured me about my views on the project and sometimes also changed them quite a bit.

\paragraph{}Additionally, I have to thank --- for providing me with many interesting bits of information who have found their way into this report.


text:
This folder contains miscellaneous SASS files. Unlike `"theme-cupertino/sass/etc"`, these files
need to be used explicitly.


text:
package at.newmedialab.ldpath.template.model.transformers;

import at.newmedialab.ldpath.api.backend.RDFBackend;
import at.newmedialab.ldpath.api.transformers.NodeTransformer;
import at.newmedialab.ldpath.model.transformers.LongTransformer;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;

/**
 * Transform a node into the freemarker long type (TemplateNumberModel).
 * <p/>
 * Author: Sebastian Schaffert
 */
public class TemplateLongTransformer<Node> implements NodeTransformer<TemplateNumberModel,Node> {

    private LongTransformer delegate;

    public TemplateLongTransformer() {
        delegate = new LongTransformer();
    }

    /**
     * Transform the KiWiNode node into the datatype T. In case the node cannot be transformed to
     * the respective datatype, throws an IllegalArgumentException that needs to be caught by the class
     * carrying out the transformation.
     *
     * @param node
     * @return
     */
    @Override
    public TemplateNumberModel transform(final RDFBackend<Node> nodeRDFBackend, final Node node) throws IllegalArgumentException {
        return new TemplateNumberModel() {
            @Override
            public Number getAsNumber() throws TemplateModelException {
                return delegate.transform(nodeRDFBackend, node);
            }
        };
    }
}


text:
#include <stdint.h>

#include "py/nlr.h"
#include "py/objfun.h"
#include "py/compile.h"
#include "py/runtime.h"
#include "py/builtin.h"

#if MICROPY_PY_BUILTINS_COMPILE

typedef struct _mp_obj_code_t {
    mp_obj_base_t base;
    mp_obj_t module_fun;
} mp_obj_code_t;

STATIC const mp_obj_type_t mp_type_code = {
    { &mp_type_type },
    .name = MP_QSTR_code,
};

STATIC mp_obj_t code_execute(mp_obj_code_t *self, mp_obj_dict_t *globals, mp_obj_dict_t *locals) {
    // save context and set new context
    mp_obj_dict_t *old_globals = mp_globals_get();
    mp_obj_dict_t *old_locals = mp_locals_get();
    mp_globals_set(globals);
    mp_locals_set(locals);

    // a bit of a hack: fun_bc will re-set globals, so need to make sure it's
    // the correct one
    if (MP_OBJ_IS_TYPE(self->module_fun, &mp_type_fun_bc)) {
        mp_obj_fun_bc_t *fun_bc = MP_OBJ_TO_PTR(self->module_fun);
        fun_bc->globals = globals;
    }

    // execute code
    nlr_buf_t nlr;
    if (nlr_push(&nlr) == 0) {
        mp_obj_t ret = mp_call_function_0(self->module_fun);
        nlr_pop();
        mp_globals_set(old_globals);
        mp_locals_set(old_locals);
        return ret;
    } else {
        // exception; restore context and re-raise same exception
        mp_globals_set(old_globals);
        mp_locals_set(old_locals);
        nlr_jump(nlr.ret_val);
    }
}

STATIC mp_obj_t mp_builtin_compile(mp_uint_t n_args, const mp_obj_t *args) {
    (void)n_args;

    // get the source
    mp_uint_t str_len;
    const char *str = mp_obj_str_get_data(args[0], &str_len);

    // get the filename
    qstr filename = mp_obj_str_get_qstr(args[1]);

    // create the lexer
    mp_lexer_t *lex = mp_lexer_new_from_str_len(filename, str, str_len, 0);

    // get the compile mode
    qstr mode = mp_obj_str_get_qstr(args[2]);
    mp_parse_input_kind_t parse_input_kind;
    switch (mode) {
        case MP_QSTR_single: parse_input_kind = MP_PARSE_SINGLE_INPUT; break;
        case MP_QSTR_exec: parse_input_kind = MP_PARSE_FILE_INPUT; break;
        case MP_QSTR_eval: parse_input_kind = MP_PARSE_EVAL_INPUT; break;
        default:
            nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad compile mode"));
    }

    mp_obj_code_t *code = m_new_obj(mp_obj_code_t);
    code->base.type = &mp_type_code;
    code->module_fun = mp_parse_compile_execute(lex, parse_input_kind, NULL, NULL);
    return MP_OBJ_FROM_PTR(code);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_compile_obj, 3, 6, mp_builtin_compile);

#endif // MICROPY_PY_BUILTINS_COMPILE

#if MICROPY_PY_BUILTINS_EVAL_EXEC

STATIC mp_obj_t eval_exec_helper(mp_uint_t n_args, const mp_obj_t *args, mp_parse_input_kind_t parse_input_kind) {
    // work out the context
    mp_obj_dict_t *globals = mp_globals_get();
    mp_obj_dict_t *locals = mp_locals_get();
    if (n_args > 1) {
        globals = MP_OBJ_TO_PTR(args[1]);
        if (n_args > 2) {
            locals = MP_OBJ_TO_PTR(args[2]);
        } else {
            locals = globals;
        }
    }

    #if MICROPY_PY_BUILTINS_COMPILE
    if (MP_OBJ_IS_TYPE(args[0], &mp_type_code)) {
        return code_execute(MP_OBJ_TO_PTR(args[0]), globals, locals);
    }
    #endif

    mp_uint_t str_len;
    const char *str = mp_obj_str_get_data(args[0], &str_len);

    // create the lexer
    // MP_PARSE_SINGLE_INPUT is used to indicate a file input
    mp_lexer_t *lex;
    if (MICROPY_PY_BUILTINS_EXECFILE && parse_input_kind == MP_PARSE_SINGLE_INPUT) {
        lex = mp_lexer_new_from_file(str);
        if (lex == NULL) {
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "could not open file '%s'", str));
        }
        parse_input_kind = MP_PARSE_FILE_INPUT;
    } else {
        lex = mp_lexer_new_from_str_len(MP_QSTR__lt_string_gt_, str, str_len, 0);
    }

    return mp_parse_compile_execute(lex, parse_input_kind, globals, locals);
}

STATIC mp_obj_t mp_builtin_eval(mp_uint_t n_args, const mp_obj_t *args) {
    return eval_exec_helper(n_args, args, MP_PARSE_EVAL_INPUT);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_eval_obj, 1, 3, mp_builtin_eval);

STATIC mp_obj_t mp_builtin_exec(mp_uint_t n_args, const mp_obj_t *args) {
    return eval_exec_helper(n_args, args, MP_PARSE_FILE_INPUT);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_exec_obj, 1, 3, mp_builtin_exec);

#endif // MICROPY_PY_BUILTINS_EVAL_EXEC

#if MICROPY_PY_BUILTINS_EXECFILE
STATIC mp_obj_t mp_builtin_execfile(mp_uint_t n_args, const mp_obj_t *args) {
    // MP_PARSE_SINGLE_INPUT is used to indicate a file input
    return eval_exec_helper(n_args, args, MP_PARSE_SINGLE_INPUT);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_execfile_obj, 1, 3, mp_builtin_execfile);
#endif


text:
class BaseController < ApplicationController
	def login_form
		if session[:id]
			redirect_to home_path
		end
	end

	def login
		user = User.where(:email => params[:email]).first
		if (user)
			if (user.password == Digest::SHA256.hexdigest(params[:password]))
				session[:id] = user.id
				redirect_to home_path
				return
			end
		end

		flash[:alert] = "Invalid credentials!"
		redirect_to root_path
	end

	def authorization_check
		unless session[:id]
			redirect_to root_path
		else
			@current_user = User.find(session[:id])
		end
	end
end


text:
module AppPerfRpm
  module Instruments
    module Roda
      def call_with_trace(&block)
        if AppPerfRpm::Tracer.tracing?
          req = ::Rack::Request.new(env)
          request_method = req.request_method.to_s.upcase
          path = req.path

          parts = path.to_s.rpartition("/")
          action = parts.last
          controller = parts.first.sub(/\A\//, '').split("/").collect {|w| w.capitalize }.join("::")
          operation = "#{controller}##{action}"

          span = AppPerfRpm.tracer.start_span(operation, tags: {
            "component" => "Roda",
            "http.url" => path,
            "http.method" => request_method,
            "params" => @_request.params
          })
          AppPerfRpm::Utils.log_source_and_backtrace(span, :roda)
        end

        call_without_trace(&block)
      rescue Exception => e
        if span
          span.set_tag('error', true)
          span.log_error(e)
        end
        raise
      ensure
        span.finish if span
      end
    end
  end
end

if defined?(::Roda) && ::AppPerfRpm.config.instrumentation[:roda][:enabled]
  ::AppPerfRpm.logger.info "Initializing roda tracer."

  ::Roda::RodaPlugins::Base::InstanceMethods.send(:include, AppPerfRpm::Instruments::Roda)
  ::Roda::RodaPlugins::Base::InstanceMethods.class_eval do
    alias_method :call_without_trace, :call
    alias_method :call, :call_with_trace
  end
end


text:
//
//  UIView+LPDLine.h
//  LPDCrowdsource
//
//  Created by 沈强 on 16/3/30.
//  Copyright © 2016年 elm. All rights reserved.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIView (LPDLine)

/**
 *  划各种线 和分割线
 *
 *
 */
- (CAShapeLayer *)addBezierLine:(UIBezierPath *)bezierLine color:(UIColor *)lineColor;

- (CAShapeLayer *)addDottedLine:(CGPoint)startLine endPoint:(CGPoint)endPoint color:(UIColor *)lineColor;

- (CAShapeLayer *)addLine:(CGPoint)startLine endPoint:(CGPoint)endPoint color:(UIColor *)lineColor;

- (CAShapeLayer *)addLine:(CGPoint)startLine endPoint:(CGPoint)endPoint lineWidth:(CGFloat)lineWidth color:(UIColor *)lineColor;

- (CAShapeLayer *)addCornerRadius:(CGFloat)cornerRadius;

- (CAShapeLayer *)addCornerRadius:(CGFloat)cornerRadius color:(UIColor *)borderColor;

- (CAShapeLayer *)addCornerRadius:(CGFloat)cornerRadius lineWidth:(CGFloat)lineWidth color:(UIColor *)borderColor;

- (CAShapeLayer *)addCornerRadius:(CGFloat)cornerRadius lineWidth:(CGFloat)lineWidth color:(UIColor *)borderColor backgroundColor:(UIColor *)backgroundColor;

@end

NS_ASSUME_NONNULL_END


text:
package com.whty.flow.statehandler;

import com.whty.flow.impl.context.FlowMapContext;
import com.whty.flow.impl.context.FlowStateHandler;

public class GetAppBaseInfoHandler extends FlowStateHandler{

	@Override
	public String handle(FlowMapContext context) {
		context.addParam("data",  "GetAppBaseInfoHandler");
		return "1";
	}
}


text:
"""
Various richly-typed exceptions, that also help us deal with string formatting
in python where it's easier.

By putting the formatting in `__str__`, we also avoid paying the cost for
users who silence the exceptions.
"""
from numpy.core.overrides import set_module

def _unpack_tuple(tup):
    if len(tup) == 1:
        return tup[0]
    else:
        return tup

def _display_as_base(cls):
    """
    A decorator that makes an exception class look like its base.

    We use this to hide subclasses that are implementation details - the user
    should catch the base type, which is what the traceback will show them.

    Classes decorated with this decorator are subject to removal without a
    deprecation warning.
    """
    assert issubclass(cls, Exception)
    cls.__name__ = cls.__base__.__name__
    return cls

class UFuncTypeError(TypeError):
    """ Base class for all ufunc exceptions """
    def __init__(self, ufunc):
        self.ufunc = ufunc

@_display_as_base
class _UFuncBinaryResolutionError(UFuncTypeError):
    """ Thrown when a binary resolution fails """
    def __init__(self, ufunc, dtypes):
        super().__init__(ufunc)
        self.dtypes = tuple(dtypes)
        assert len(self.dtypes) == 2

    def __str__(self):
        return (
            "ufunc {!r} cannot use operands with types {!r} and {!r}"
        ).format(
            self.ufunc.__name__, *self.dtypes
        )

@_display_as_base
class _UFuncNoLoopError(UFuncTypeError):
    """ Thrown when a ufunc loop cannot be found """
    def __init__(self, ufunc, dtypes):
        super().__init__(ufunc)
        self.dtypes = tuple(dtypes)

    def __str__(self):
        return (
            "ufunc {!r} did not contain a loop with signature matching types "
            "{!r} -> {!r}"
        ).format(
            self.ufunc.__name__,
            _unpack_tuple(self.dtypes[:self.ufunc.nin]),
            _unpack_tuple(self.dtypes[self.ufunc.nin:])
        )

@_display_as_base
class _UFuncCastingError(UFuncTypeError):
    def __init__(self, ufunc, casting, from_, to):
        super().__init__(ufunc)
        self.casting = casting
        self.from_ = from_
        self.to = to

@_display_as_base
class _UFuncInputCastingError(_UFuncCastingError):
    """ Thrown when a ufunc input cannot be casted """
    def __init__(self, ufunc, casting, from_, to, i):
        super().__init__(ufunc, casting, from_, to)
        self.in_i = i

    def __str__(self):
        # only show the number if more than one input exists
        i_str = "{} ".format(self.in_i) if self.ufunc.nin != 1 else ""
        return (
            "Cannot cast ufunc {!r} input {}from {!r} to {!r} with casting "
            "rule {!r}"
        ).format(
            self.ufunc.__name__, i_str, self.from_, self.to, self.casting
        )

@_display_as_base
class _UFuncOutputCastingError(_UFuncCastingError):
    """ Thrown when a ufunc output cannot be casted """
    def __init__(self, ufunc, casting, from_, to, i):
        super().__init__(ufunc, casting, from_, to)
        self.out_i = i

    def __str__(self):
        # only show the number if more than one output exists
        i_str = "{} ".format(self.out_i) if self.ufunc.nout != 1 else ""
        return (
            "Cannot cast ufunc {!r} output {}from {!r} to {!r} with casting "
            "rule {!r}"
        ).format(
            self.ufunc.__name__, i_str, self.from_, self.to, self.casting
        )

# Exception used in shares_memory()
@set_module('numpy')
class TooHardError(RuntimeError):
    pass

@set_module('numpy')
class AxisError(ValueError, IndexError):
    """ Axis supplied was invalid. """
    def __init__(self, axis, ndim=None, msg_prefix=None):
        # single-argument form just delegates to base class
        if ndim is None and msg_prefix is None:
            msg = axis

        # do the string formatting here, to save work in the C code
        else:
            msg = ("axis {} is out of bounds for array of dimension {}"
                   .format(axis, ndim))
            if msg_prefix is not None:
                msg = "{}: {}".format(msg_prefix, msg)

        super().__init__(msg)

@_display_as_base
class _ArrayMemoryError(MemoryError):
    """ Thrown when an array cannot be allocated"""
    def __init__(self, shape, dtype):
        self.shape = shape
        self.dtype = dtype

    @property
    def _total_size(self):
        num_bytes = self.dtype.itemsize
        for dim in self.shape:
            num_bytes *= dim
        return num_bytes

    @staticmethod
    def _size_to_string(num_bytes):
        """ Convert a number of bytes into a binary size string """

        # https://en.wikipedia.org/wiki/Binary_prefix
        LOG2_STEP = 10
        STEP = 1024
        units = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']

        unit_i = max(num_bytes.bit_length() - 1, 1) // LOG2_STEP
        unit_val = 1 << (unit_i * LOG2_STEP)
        n_units = num_bytes / unit_val
        del unit_val

        # ensure we pick a unit that is correct after rounding
        if round(n_units) == STEP:
            unit_i += 1
            n_units /= STEP

        # deal with sizes so large that we don't have units for them
        if unit_i >= len(units):
            new_unit_i = len(units) - 1
            n_units *= 1 << ((unit_i - new_unit_i) * LOG2_STEP)
            unit_i = new_unit_i

        unit_name = units[unit_i]
        # format with a sensible number of digits
        if unit_i == 0:
            # no decimal point on bytes
            return '{:.0f} {}'.format(n_units, unit_name)
        elif round(n_units) < 1000:
            # 3 significant figures, if none are dropped to the left of the .
            return '{:#.3g} {}'.format(n_units, unit_name)
        else:
            # just give all the digits otherwise
            return '{:#.0f} {}'.format(n_units, unit_name)

    def __str__(self):
        size_str = self._size_to_string(self._total_size)
        return (
            "Unable to allocate {} for an array with shape {} and data type {}"
            .format(size_str, self.shape, self.dtype)
        )


text:
"""
News templatetags
"""
from coffin import template
from anaf.core.rendering import render_to_string
from jinja2 import contextfunction, Markup
from django.template import RequestContext

register = template.Library()

@contextfunction
def news_update_list(context, updates, skip_group=False):
    """Print a list of orders"""
    request = context['request']

    response_format = 'html'
    if 'response_format' in context:
        response_format = context['response_format']

    return Markup(render_to_string('news/tags/update_list',
                                   {'updates': updates},
                                   context_instance=RequestContext(request),
                                   response_format=response_format))

register.object(news_update_list)


text:
<?php
declare(strict_types=1);

namespace Gdbots\Pbj\WellKnown;

use Gdbots\Pbj\Exception\InvalidArgumentException;
use Ramsey\Uuid\Rfc4122\UuidV1;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;

class TimeUuidIdentifier extends UuidIdentifier
{
    private const VALID_REGEX = '/\A[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\z/ms';

    protected function __construct(UuidInterface|string $uuid)
    {
        if ($uuid instanceof UuidInterface && !($uuid instanceof UuidV1)) {
            if (!preg_match(self::VALID_REGEX, $uuid->toString())) {
                throw new InvalidArgumentException('A time based (version 1) uuid is required.');
            }
        }

        parent::__construct($uuid);
    }

    public static function generate(): static
    {
        return new static(Uuid::uuid1());
    }
}


text:
package org.apache.flink.runtime.fs.hdfs;

import org.apache.flink.core.fs.FileSystem;
import org.apache.flink.core.fs.FileSystemKind;
import org.apache.flink.core.fs.Path;
import org.apache.flink.util.TestLogger;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 * Tests for extracting the {@link FileSystemKind} from file systems that Flink accesses through
 * Hadoop's File System interface.
 *
 * <p>This class needs to be in this package, because it accesses package private methods from the
 * HDFS file system wrapper class.
 */
public class HdfsKindTest extends TestLogger {

    @Test
    public void testHdfsKind() throws IOException {
        final FileSystem fs = new Path("hdfs://localhost:55445/my/file").getFileSystem();
        assertEquals(FileSystemKind.FILE_SYSTEM, fs.getKind());
    }

    @Test
    public void testS3fileSystemSchemes() {
        assertEquals(FileSystemKind.OBJECT_STORE, HadoopFileSystem.getKindForScheme("s3"));
        assertEquals(FileSystemKind.OBJECT_STORE, HadoopFileSystem.getKindForScheme("s3n"));
        assertEquals(FileSystemKind.OBJECT_STORE, HadoopFileSystem.getKindForScheme("s3a"));
        assertEquals(FileSystemKind.OBJECT_STORE, HadoopFileSystem.getKindForScheme("EMRFS"));
    }

    @Test
    public void testViewFs() {
        assertEquals(FileSystemKind.FILE_SYSTEM, HadoopFileSystem.getKindForScheme("viewfs"));
    }
}


text:
@interface MeritController : BehaviorViewController
@end


text:
using Newtonsoft.Json;
using System;

namespace RecoTwAPI
{
	public class Status
	{
		/// <summary>
		/// ツイート内容
		/// </summary>
		[JsonProperty("content")]
		public string Content { get; set; }

		/// <summary>
		/// 登録ID
		/// </summary>
		[JsonProperty("id")]
		public long Id { get; set; }

		[JsonProperty("record_date")]
		private string record_date { get; set; }
		/// <summary>
		/// 登録日時
		/// </summary>
		public DateTime RecordedAt
		{
			get { return DateTime.Parse(record_date); }
		}

		/// <summary>
		/// ツイートしたユーザのID
		/// </summary>
		[JsonProperty("target_id")]
		public long TargetId { get; set; }

		/// <summary>
		/// ツイートしたユーザの表示名(ScreenName)
		/// </summary>
		[JsonProperty("target_sn")]
		public string TargetScreenName { get; set; }

		/// <summary>
		/// ツイートのID
		/// </summary>
		[JsonProperty("tweet_id")]
		public long TweetId { get; set; }

		public override string ToString()
		{
			return string.Format("@{0}: {1}", TargetScreenName, Content);
		}
	}
}


text:
package noot.assembly;

import java.util.Stack;

/**
 * The Class InstructionBlock.
 *
 * Stack to represent an instruction block. An instruction block
 * is a list of instructions starting with an instruction with a jump label.
 *
 * The fist Instruction pushed to the block will get the instruction
 * block label assigned to it.
 */
public class InstructionBlock extends Stack<Instruction> {

	/** serialVersionUID used for serialization */
	private static final long serialVersionUID = 9189059759052574955L;

	/** The label identifier. */
	public int labelIdentifier = -1;

	/**
	 * Instantiates a new instruction block.
	 *
	 * The labelIdentifier should be unique, this is will be
	 * used to jump to this instruction block.
	 *
	 * @param labelIdentifier the a labelIdentifier
	 */
	public InstructionBlock(int labelIdentifier)
	{
		this.labelIdentifier = labelIdentifier;
	}

	/* (non-Javadoc)
	 * @see java.util.Stack#push(java.lang.Object)
	 */
	public Instruction push(Instruction instruction)
	{
		if(this.size() == 0) instruction.setLabel("L" + labelIdentifier);
		return super.push(instruction);
	}

	/**
	 * Jump label.
	 *
	 * Get label for use with the JUMP instruction.
	 * An example output could be "L1[CB]".
	 *
	 * @return a string containing the labelIdentifier with needed extra additions
	 */
	public String jumpLabel() // without argument = false
	{
		return "L" + Integer.toString(labelIdentifier) + "[CB]";
	}

}