text:
#ifndef INCLUDE_buffer_h__
#define INCLUDE_buffer_h__

#include <stdbool.h>
#include <stddef.h>
#include <stdarg.h>
#include <sys/types.h>
#include <stdint.h>

typedef struct {
	char *ptr;
	size_t asize, size;
} gh_buf;

extern char gh_buf__initbuf[];
extern char gh_buf__oom[];

#define GH_BUF_INIT { gh_buf__initbuf, 0, 0 }

/**
 * Initialize a gh_buf structure.
 *
 * For the cases where GH_BUF_INIT cannot be used to do static
 * initialization.
 */
extern void gh_buf_init(gh_buf *buf, size_t initial_size);

/**
 * Attempt to grow the buffer to hold at least `target_size` bytes.
 *
 * If the allocation fails, this will return an error.  If mark_oom is true,
 * this will mark the buffer as invalid for future operations; if false,
 * existing buffer content will be preserved, but calling code must handle
 * that buffer was not expanded.
 */
extern int gh_buf_try_grow(gh_buf *buf, size_t target_size, bool mark_oom);

/**
 * Grow the buffer to hold at least `target_size` bytes.
 *
 * If the allocation fails, this will return an error and the buffer will be
 * marked as invalid for future operations, invaliding contents.
 *
 * @return 0 on success or -1 on failure
 */
static inline int gh_buf_grow(gh_buf *buf, size_t target_size)
{
	return gh_buf_try_grow(buf, target_size, true);
}

extern void gh_buf_free(gh_buf *buf);
extern void gh_buf_swap(gh_buf *buf_a, gh_buf *buf_b);

/**
 * Test if there have been any reallocation failures with this gh_buf.
 *
 * Any function that writes to a gh_buf can fail due to memory allocation
 * issues.  If one fails, the gh_buf will be marked with an OOM error and
 * further calls to modify the buffer will fail.  Check gh_buf_oom() at the
 * end of your sequence and it will be true if you ran out of memory at any
 * point with that buffer.
 *
 * @return false if no error, true if allocation error
 */
static inline bool gh_buf_oom(const gh_buf *buf)
{
	return (buf->ptr == gh_buf__oom);
}

static inline size_t gh_buf_len(const gh_buf *buf)
{
	return buf->size;
}

extern int gh_buf_cmp(const gh_buf *a, const gh_buf *b);

extern void gh_buf_attach(gh_buf *buf, char *ptr, size_t asize);
extern char *gh_buf_detach(gh_buf *buf);
extern void gh_buf_copy_cstr(char *data, size_t datasize, const gh_buf *buf);

static inline const char *gh_buf_cstr(const gh_buf *buf)
{
	return buf->ptr;
}

/*
 * Functions below that return int value error codes will return 0 on
 * success or -1 on failure (which generally means an allocation failed).
 * Using a gh_buf where the allocation has failed with result in -1 from
 * all further calls using that buffer.  As a result, you can ignore the
 * return code of these functions and call them in a series then just call
 * gh_buf_oom at the end.
 */
extern int gh_buf_set(gh_buf *buf, const char *data, size_t len);
extern int gh_buf_sets(gh_buf *buf, const char *string);
extern int gh_buf_putc(gh_buf *buf, char c);
extern int gh_buf_put(gh_buf *buf, const void *data, size_t len);
extern int gh_buf_puts(gh_buf *buf, const char *string);
extern int gh_buf_printf(gh_buf *buf, const char *format, ...)
	__attribute__((format (printf, 2, 3)));
extern int gh_buf_vprintf(gh_buf *buf, const char *format, va_list ap);
extern void gh_buf_clear(gh_buf *buf);

#define gh_buf_PUTS(buf, str) gh_buf_put(buf, str, sizeof(str) - 1)

#endif


text:
<!DOCTYPE html>

		<title>three.js webgl - materials - bump map [Lee Perry-Smith]</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js - Normal Post Processing Pass by Ben Houston -
			Lee Perry-Smith head

redpajama_set_name: RedPajamaGithub


text:
/*
 *
 *
 *
 */

#include <gst/gst.h>
#include "MediaPipeline.hpp"
#include <TelmateFrameGrabberImplFactory.hpp>
#include "TelmateFrameGrabberImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include "MediaPipelineImpl.hpp"

#define GST_CAT_DEFAULT kurento_telmate_frame_grabber_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoTelmateFrameGrabberImpl"

namespace kurento
{
namespace module
{
namespace telmateframegrabber
{

TelmateFrameGrabberImpl::TelmateFrameGrabberImpl (const boost::property_tree::ptree &config, std::shared_ptr<MediaPipeline> mediaPipeline) : OpenCVFilterImpl (config, std::dynamic_pointer_cast<MediaPipelineImpl> (mediaPipeline) )

{
}

int TelmateFrameGrabberImpl::cleanup ()
{
  return TelmateFrameGrabberOpenCVImpl::cleanup ();
}

int TelmateFrameGrabberImpl::getSnapInterval ()
{
  return TelmateFrameGrabberOpenCVImpl::getSnapInterval ();
}

void TelmateFrameGrabberImpl::setSnapInterval (int snapInterval)
{
  return TelmateFrameGrabberOpenCVImpl::setSnapInterval(snapInterval);
}

std::string TelmateFrameGrabberImpl::getStoragePath ()
{
  return TelmateFrameGrabberOpenCVImpl::getStoragePath ();
}

void TelmateFrameGrabberImpl::setStoragePath (const std::string &path)
{
  return TelmateFrameGrabberOpenCVImpl::setStoragePath (path);
}

void TelmateFrameGrabberImpl::setWebRtcEpName (const std::string &epName)
{
  return TelmateFrameGrabberOpenCVImpl::setWebRtcEpName (epName);
}

void TelmateFrameGrabberImpl::setOutputFormat (int outputFormat)
{
  return TelmateFrameGrabberOpenCVImpl::setOutputFormat (outputFormat);
}

int TelmateFrameGrabberImpl::getMonitorTimeoutSec ()
{
  return TelmateFrameGrabberOpenCVImpl::getMonitorTimeoutSec();
}

void TelmateFrameGrabberImpl::setMonitorTimeoutSec (const int timeout)
{
  return TelmateFrameGrabberOpenCVImpl::setMonitorTimeoutSec (timeout);
}

std::string TelmateFrameGrabberImpl::getSessionUUID ()
{
  return TelmateFrameGrabberOpenCVImpl::getSessionUUID ();
}

void TelmateFrameGrabberImpl::setSessionUUID (const std::string &puuid)
{
  return TelmateFrameGrabberOpenCVImpl::setSessionUUID (puuid);
}

MediaObjectImpl *
TelmateFrameGrabberImplFactory::createObject (const boost::property_tree::ptree &config, std::shared_ptr<MediaPipeline> mediaPipeline) const
{
  return new TelmateFrameGrabberImpl (config, mediaPipeline);
}

TelmateFrameGrabberImpl::StaticConstructor TelmateFrameGrabberImpl::staticConstructor;

TelmateFrameGrabberImpl::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} /* telmateframegrabber */
} /* module */
} /* kurento */


text:
<?php

/**
 *
 * @license See LICENSE in source root
 * @version 1.0
 * @since   1.0
 */

namespace Cspray\Telluris\Config;

class Config {

    private $data;
    private $secrets;

    public function __construct(array $data, array $secrets = []) {
        $this->data = $data;
        $this->secrets = $secrets;
    }

    /**
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    public function get($key, $default = null) {
        $val = $this->resolveDotNotation($this->data, $key, $default);
        return $this->parseForPossibleSecret($val);
    }

    private function resolveDotNotation(array $data, $key, $default = null) {
        $current = $data;
        $p = strtok($key, '.');

        while ($p !== false) {
            if (!isset($current[$p])) {
                return $default;
            }
            $current = $current[$p];
            $p = strtok('.');
        }

        return $current;
    }

    private function parseForPossibleSecret($val) {
        $secretStrLen = 7;
        if (substr($val, 0, $secretStrLen) === 'secret(' && $val[strlen($val) -1] === ')') {
            $secretKey = substr(substr($val, 0, -1), $secretStrLen);
            $val = $this->resolveDotNotation($this->secrets, $secretKey);
        }
        return $val;
    }

}


text:
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::env;
use toml;

use error::{Error, Result};

#[derive(Deserialize)]
pub struct KafkaConfig {
    pub hosts: Vec<String>,
    pub ack_timeout: u64,
    pub topic: String
}

#[derive(Deserialize)]
pub struct Config {
    /// kafka broker related configuration
    pub kafka: KafkaConfig
}

/// Reads the configuration descriptor from the TOML file. It first scans the list of well known
/// locations to find a valid configuration file. If non existing path is found, it fallbacks to
/// resolve the configuration file path from `CUBOSTRATUSC_CONFIG` environment variable.
///
/// If the configuration descriptor can be loaded from any of the available paths and is parsed
/// correctly, this function returns `Result::Ok(config)` where `config` references [Config](struct.
/// Config.html). On error it returns `Result::Err(e)`.
///
pub fn read_config() -> Result<Config> {
    let mut content = String::new();
    let locations = vec!["/etc/cubostratusc.toml", "/var/lib/cubostratusc/cubostratusc.toml"];
    let mut path = locations.iter()
            .find(|loco| Path::new(*loco).exists())
            .map(|l| l.to_string());
    if path == None {
        path = env::var("CUBOSTRATUSC_CONFIG").map(|e| Some(e)).unwrap_or(None);
    }
    if let Some(path) = path {
        File::open(path)
                .unwrap()
                .read_to_string(&mut content)
                .expect("unable to open configuration file");
        toml::from_str(&content).map_err(|e| Error::ConfigParseError(e.to_string()))
    } else {
        Err(Error::UnknownConfigPathError)
    }
}


text:
package org.apache.commons.jcs.auxiliary.disk.jdbc.mysql;

import org.apache.commons.jcs.auxiliary.disk.jdbc.JDBCDiskCachePoolAccess;
import org.apache.commons.jcs.auxiliary.disk.jdbc.TableState;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * The MySQL Table Optimizer can optimize MySQL tables. It knows how to optimize for MySQL datbases
 * in particular and how to repair the table if it is corrupted in the process.
 *

 * We will probably be able to abstract out a generic optimizer interface from this class in the
 * future.
 *

 * @author Aaron Smuts
 */
public class MySQLTableOptimizer
{
    /** The logger */
    private static final Log log = LogFactory.getLog( MySQLTableOptimizer.class );

    /** The pool */
    private JDBCDiskCachePoolAccess poolAccess = null;

    /** The name of the table. */
    private String tableName = null;

    /** optimizing, etc. */
    private TableState tableState;

    /**
     * This constructs an optimizer with the disk cacn properties.
     *

     * @param attributes
     * @param tableState We mark the table status as optimizing when this is happening.
     * @param poolAccess access to the database
     */
    public MySQLTableOptimizer( MySQLDiskCacheAttributes attributes, TableState tableState,
                                JDBCDiskCachePoolAccess poolAccess )
    {
        setTableName( attributes.getTableName() );

        this.tableState = tableState;

        this.poolAccess = poolAccess;
    }

    /**
     * A scheduler will call this method. When it is called the table state is marked as optimizing.
     * TODO we need to verify that no deletions are running before we call optimize. We should wait
     * if a deletion is in progress.
     *

     * This restores when there is an optimization error. The error output looks like this:
     *
     *

     *           mysql> optimize table JCS_STORE_FLIGHT_OPTION_ITINERARY;
     *               +---------------------------------------------+----------+----------+---------------------+
     *               | Table                                       | Op       | Msg_type | Msg_text            |
     *               +---------------------------------------------+----------+----------+---------------------+
     *               | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | optimize | error    | 2 when fixing table |
     *               | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | optimize | status   | Operation failed    |
     *               +---------------------------------------------+----------+----------+---------------------+
     *               2 rows in set (51.78 sec)
     *

     *
     * A successful repair response looks like this:
     *
     *

     *        mysql> REPAIR TABLE JCS_STORE_FLIGHT_OPTION_ITINERARY;
     *            +---------------------------------------------+--------+----------+----------------------------------------------+
     *            | Table                                       | Op     | Msg_type | Msg_text                                     |
     *            +---------------------------------------------+--------+----------+----------------------------------------------+
     *            | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | repair | error    | 2 when fixing table                          |
     *            | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | repair | warning  | Number of rows changed from 131276 to 260461 |
     *            | jcs_cache.JCS_STORE_FLIGHT_OPTION_ITINERARY | repair | status   | OK                                           |
     *            +---------------------------------------------+--------+----------+----------------------------------------------+
     *            3 rows in set (3 min 5.94 sec)
     *

     *
     * A successful optimization looks like this:
     *
     *

     *       mysql> optimize table JCS_STORE_DEFAULT;
     *           +-----------------------------+----------+----------+----------+
     *           | Table                       | Op       | Msg_type | Msg_text |
     *           +-----------------------------+----------+----------+----------+
     *           | jcs_cache.JCS_STORE_DEFAULT | optimize | status   | OK       |
     *           +-----------------------------+----------+----------+----------+
     *           1 row in set (1.10 sec)
     *

     * @return true if it worked
     */
    public boolean optimizeTable()
    {
        long start = System.currentTimeMillis();
        boolean success = false;

        if ( tableState.getState() == TableState.OPTIMIZATION_RUNNING )
        {
            log
                .warn( "Skipping optimization.  Optimize was called, but the table state indicates that an optimization is currently running." );
            return false;
        }

        try
        {
            tableState.setState( TableState.OPTIMIZATION_RUNNING );
            if ( log.isInfoEnabled() )
            {
                log.info( "Optimizing table [" + this.getTableName() + "]" );
            }

            Connection con;
            try
            {
                con = poolAccess.getConnection();
            }
            catch ( SQLException e )
            {
                log.error( "Problem getting connection.", e );
                return false;
            }

            try
            {
                // TEST
                Statement sStatement = null;
                try
                {
                    sStatement = con.createStatement();

                    ResultSet rs = sStatement.executeQuery( "optimize table " + this.getTableName() );

                    // first row is error, then status
                    // if there is only one row in the result set, everything
                    // should be fine.
                    // This may be mysql version specific.
                    if ( rs.next() )
                    {
                        String status = rs.getString( "Msg_type" );
                        String message = rs.getString( "Msg_text" );

                        if ( log.isInfoEnabled() )
                        {
                            log.info( "Message Type: " + status );
                            log.info( "Message: " + message );
                        }

                        if ( "error".equals( status ) )
                        {
                            log.warn( "Optimization was in erorr.  Will attempt to repair the table.  Message: "
                                + message );

                            // try to repair the table.
                            success = repairTable( sStatement );
                        }
                        else
                        {
                            success = true;
                        }
                    }

                    // log the table status
                    String statusString = getTableStatus( sStatement );
                    if ( log.isInfoEnabled() )
                    {
                        log.info( "Table status after optimizing table [" + this.getTableName() + "]\n" + statusString );
                    }
                }
                catch ( SQLException e )
                {
                    log.error( "Problem optimizing table [" + this.getTableName() + "]", e );
                    return false;
                }
                finally
                {
                    if (sStatement != null)
                    {
                        try
                        {
                            sStatement.close();
                        }
                        catch ( SQLException e )
                        {
                            log.error( "Problem closing statement.", e );
                        }
                    }
                }
            }
            finally
            {
                try
                {
                    con.close();
                }
                catch ( SQLException e )
                {
                    log.error( "Problem closing connection.", e );
                }
            }
        }
        finally
        {
            tableState.setState( TableState.FREE );

            long end = System.currentTimeMillis();
            if ( log.isInfoEnabled() )
            {
                log.info( "Optimization of table [" + this.getTableName() + "] took " + ( end - start ) + " ms." );
            }
        }

        return success;
    }

    /**
     * This calls show table status and returns the result as a String.
     *

     * @param sStatement
     * @return String
     * @throws SQLException
     */
    protected String getTableStatus( Statement sStatement )
        throws SQLException
    {
        ResultSet statusResultSet = sStatement.executeQuery( "show table status" );
        StringBuilder statusString = new StringBuilder();
        int numColumns = statusResultSet.getMetaData().getColumnCount();
        while ( statusResultSet.next() )
        {
            statusString.append( "\n" );
            for ( int i = 1; i <= numColumns; i++ )
            {
                statusString.append( statusResultSet.getMetaData().getColumnLabel( i ) + " ["
                    + statusResultSet.getString( i ) + "]  |  " );
            }
        }
        return statusString.toString();
    }

    /**
     * This is called if the optimizatio is in error.
     *

     * It looks for "OK" in response. If it find "OK" as a message in any result set row, it returns
     * true. Otherwise we assume that the repair failed.
     *

     * @param sStatement
     * @return true if successful
     * @throws SQLException
     */
    protected boolean repairTable( Statement sStatement )
        throws SQLException
    {
        boolean success = false;

        // if( message != null && message.indexOf( ) )
        ResultSet repairResult = sStatement.executeQuery( "repair table " + this.getTableName() );
        StringBuilder repairString = new StringBuilder();
        int numColumns = repairResult.getMetaData().getColumnCount();
        while ( repairResult.next() )
        {
            for ( int i = 1; i <= numColumns; i++ )
            {
                repairString.append( repairResult.getMetaData().getColumnLabel( i ) + " [" + repairResult.getString( i )
                    + "]  |  " );
            }

            String message = repairResult.getString( "Msg_text" );
            if ( "OK".equals( message ) )
            {
                success = true;
            }
        }
        if ( log.isInfoEnabled() )
        {
            log.info( repairString );
        }

        if ( !success )
        {
            log.warn( "Failed to repair the table. " + repairString );
        }
        return success;
    }

    /**
     * @param tableName The tableName to set.
     */
    public void setTableName( String tableName )
    {
        this.tableName = tableName;
    }

    /**
     * @return Returns the tableName.
     */
    public String getTableName()
    {
        return tableName;
    }
}


text:
import sys
import subprocess
import re
import os
import xml.etree.ElementTree as ET
from email.utils import parseaddr
import sh
import logging
import argparse
#from check_identity import verify_signed_off

if "ZEPHYR_BASE" not in os.environ:
    logging.error("$ZEPHYR_BASE environment variable undefined.\n")
    exit(1)

logger = None
DOCS_WARNING_FILE = "doc.warnings"

repository_path = os.environ['ZEPHYR_BASE']
sh_special_args = {
    '_tty_out': False,
    '_cwd': repository_path
}

def init_logs():
    global logger
    log_lev = os.environ.get('LOG_LEVEL', None)
    level = logging.INFO
    if log_lev == "DEBUG":
        level = logging.DEBUG
    elif log_lev == "ERROR":
        level = logging.ERROR

    console = logging.StreamHandler()
    format = logging.Formatter('%(levelname)-8s: %(message)s')
    console.setFormatter(format)
    logger = logging.getLogger('')
    logger.addHandler(console)
    logger.setLevel(level)

    logging.debug("Log init completed")

def parse_args():
    parser = argparse.ArgumentParser(
                description="Check for coding style and documentation warnings.")
    parser.add_argument('-c', '--commits', default=None,
            help="Commit range in the form: a..b")
    return parser.parse_args()

def get_shas(refspec):

    sha_list = sh.git("rev-list",
        '--max-count={0}'.format(-1 if "." in refspec else 1),
        refspec, **sh_special_args).split()

    return sha_list

def run_gitlint(tc, commit_range):
    proc = subprocess.Popen('gitlint --commits %s' %(commit_range),
                shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    msg = ""
    if proc.wait() != 0:
        msg = proc.stdout.read()

    if msg != "":
        failure = ET.SubElement(tc, 'failure', type="failure", message="commit message error on range: %s" %commit_range)
        failure.text = (msg.decode('utf8'))
        return 1

    return 0

def run_checkpatch(tc, commit_range):
    output = None
    out = ""

    diff = subprocess.Popen(('git', 'diff', '%s' %(commit_range)), stdout=subprocess.PIPE)
    try:
        output = subprocess.check_output(('%s/scripts/checkpatch.pl' %repository_path,
            '--mailback', '--no-tree', '-'), stdin=diff.stdout,
            stderr=subprocess.STDOUT, shell=True)

    except subprocess.CalledProcessError as ex:
        m = re.search("([1-9][0-9]*) errors,", ex.output.decode('utf8'))
        if m:
            failure = ET.SubElement(tc, 'failure', type="failure", message="checkpatch issues")
            failure.text = (ex.output.decode('utf8'))
            return 1

    return 0

def verify_signed_off(tc, commit):

    signed = []
    author = ""
    sha = ""
    parsed_addr = None
    for line in commit.split("\n"):
        match = re.search("^commit\s([^\s]*)", line)
        if match:
            sha = match.group(1)
        match = re.search("^Author:\s(.*)", line)
        if match:
            author = match.group(1)
            parsed_addr = parseaddr(author)
        match = re.search("signed-off-by:\s(.*)", line, re.IGNORECASE)
        if match:
            signed.append(match.group(1))

    error1 = "%s: author email (%s) needs to match one of the signed-off-by entries." %(sha, author)
    error2 = "%s: author email (%s) does not follow the syntax: First Last <email>." %(sha, author)
    error = 0
    failure = None
    if author not in signed:
        failure = ET.SubElement(tc, 'failure', type="failure", message="identity error")
        failure.text = error1
        error = 1
    if not parsed_addr or len(parsed_addr[0].split(" ")) < 2:
        if not failure:
            failure = ET.SubElement(tc, 'failure', type="failure", message="identity error")
            failure.text = error2
        else:
            failure.text = failure.text + "\n" + error2
        error = 1

    return error

def run_check_identity(tc, range):
    error = 0
    for f in get_shas(range):
        commit = sh.git("log","--decorate=short", "-n 1", f, **sh_special_args)
        error += verify_signed_off(tc, commit)

    return error

def check_doc(tc, range):

    if os.path.exists(DOCS_WARNING_FILE) and os.path.getsize(DOCS_WARNING_FILE) > 0:
        with open(DOCS_WARNING_FILE, "rb") as f:
            log = f.read()
            failure = ET.SubElement(tc, 'failure', type="failure",
                        message="documentation issues")
            failure.text = (log.decode('utf8'))
        return 1

    return 0

tests = {
        "gitlint": {
            "call": run_gitlint,
            "name": "Commit message style",
            },
        "identity": {
            "call": run_check_identity,
            "name": "Author Identity verification",
            },
        "checkpatch": {
            "call": run_checkpatch,
            "name": "Code style check using checkpatch",
            },
        "documentation": {
            "call": check_doc,
            "name": "New warnings and errors when building documentation",
            }
        }

def run_tests(range):
    run = "Commit Message / Documentation / Coding Style"
    eleTestsuite = None
    fails = 0
    passes = 0
    errors = 0
    total = 0
    filename = "compliance.xml"

    eleTestsuites = ET.Element('testsuites')
    eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="0",
            tests="%d" %(errors + passes + fails),  failures="%d" %fails,  errors="%d" %errors, skip="0")

    for test in tests.keys():

        total += 1
        eleTestcase = ET.SubElement(eleTestsuite, 'testcase', classname="%s"
                %(test), name="%s" %(tests[test]['name']), time="0")

        fails += tests[test]['call'](eleTestcase, range)

    eleTestsuite.set("tests", "%s" %total)
    eleTestsuite.set("failures",  "%s" %fails)

    result = ET.tostring(eleTestsuites)
    f = open(filename, 'wb')
    f.write(result)
    f.close()
    return fails

def main():
    args = parse_args()
    if not args.commits:
        exit(1)
    fails = run_tests(args.commits)
    print(fails)
    sys.exit(fails)

if __name__ == "__main__":
    #init_logs()
    main()


text:
import { shallowMount } from '@vue/test-utils';
import { GlIcon } from '@gitlab/ui';
import DiffStats from '~/diffs/components/diff_stats.vue';

const TEST_ADDED_LINES = 100;
const TEST_REMOVED_LINES = 200;
const DIFF_FILES_COUNT = '300';
const DIFF_FILES_COUNT_TRUNCATED = '300+';

describe('diff_stats', () => {
  let wrapper;

  const createComponent = (props = {}) => {
    wrapper = shallowMount(DiffStats, {
      propsData: {
        addedLines: TEST_ADDED_LINES,
        removedLines: TEST_REMOVED_LINES,
        ...props,
      },
    });
  };

  describe('diff stats group', () => {
    const findDiffStatsGroup = () => wrapper.findAll('.diff-stats-group');

    it('is not rendered if diffFilesCountText is empty', () => {
      createComponent();

      expect(findDiffStatsGroup().length).toBe(2);
    });

    it('is not rendered if diffFilesCountText is not a number', () => {
      createComponent({
        diffFilesCountText: null,
      });

      expect(findDiffStatsGroup().length).toBe(2);
    });
  });

  describe('line changes', () => {
    const findFileLine = name => wrapper.find(name);

    it('shows the amount of lines added', () => {
      expect(findFileLine('.js-file-addition-line').text()).toBe(TEST_ADDED_LINES.toString());
    });

    it('shows the amount of lines removed', () => {
      expect(findFileLine('.js-file-deletion-line').text()).toBe(TEST_REMOVED_LINES.toString());
    });
  });

  describe('files changes', () => {
    const findIcon = name =>
      wrapper
        .findAll(GlIcon)
        .filter(c => c.attributes('name') === name)
        .at(0).element.parentNode;

    it('shows amount of file changed with plural "files" when 0 files has changed', () => {
      const oneFileChanged = '0';

      createComponent({
        diffFilesCountText: oneFileChanged,
      });

      expect(findIcon('doc-code').textContent.trim()).toBe(`${oneFileChanged} files`);
    });

    it('shows amount of file changed with singular "file" when 1 file is changed', () => {
      const oneFileChanged = '1';

      createComponent({
        diffFilesCountText: oneFileChanged,
      });

      expect(findIcon('doc-code').textContent.trim()).toBe(`${oneFileChanged} file`);
    });

    it('shows amount of files change with plural "files" when multiple files are changed', () => {
      createComponent({
        diffFilesCountText: DIFF_FILES_COUNT,
      });

      expect(findIcon('doc-code').textContent.trim()).toContain(`${DIFF_FILES_COUNT} files`);
    });

    it('shows amount of files change with plural "files" when files changed is truncated', () => {
      createComponent({
        diffFilesCountText: DIFF_FILES_COUNT_TRUNCATED,
      });

      expect(findIcon('doc-code').textContent.trim()).toContain(
        `${DIFF_FILES_COUNT_TRUNCATED} files`,
      );
    });
  });
});


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path("../dummy/config/environment", __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
#require 'factory_girl_rails'

ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../')
Dir[File.join(ENGINE_RAILS_ROOT, "spec/factories/**/*.rb")].each {|f| require f }
Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f }

# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
# ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.include FactoryGirl::Syntax::Methods
  config.include ::HmacAuthHelper, type: :controller
end


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

/**
 * This is a convenience renderer which can be used by section based formats
 * to reduce code duplication. It is not necessary for all course formats to
 * use this and its likely to change in future releases.
 *
 * @package core
 * @copyright 2012 Dan Poltawski
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.3
 */
abstract class format_section_renderer_base extends plugin_renderer_base {

    /**
     * Generate the starting container html for a list of sections
     * @return string HTML to output.
     */
    abstract protected function start_section_list();

    /**
     * Generate the closing container html for a list of sections
     * @return string HTML to output.
     */
    abstract protected function end_section_list();

    /**
     * Generate the title for this section page
     * @return string the page title
     */
    abstract protected function page_title();

    /**
     * Generate the section title
     *
     * @param stdClass $section The course_section entry from DB
     * @param stdClass $course The course entry from DB
     * @return string HTML to output.
     */
    public function section_title($section, $course) {
        $title = get_section_name($course, $section);
        $url = course_get_url($course, $section->section, array('navigation' => true));
        if ($url) {
            $title = html_writer::link($url, $title);
        }
        return $title;
    }

    /**
     * Generate the content to displayed on the right part of a section
     * before course modules are included
     *
     * @param stdClass $section The course_section entry from DB
     * @param stdClass $course The course entry from DB
     * @param bool $onsectionpage true if being printed on a section page
     * @return string HTML to output.
     */
    protected function section_right_content($section, $course, $onsectionpage) {
        $o = $this->output->spacer();

        if ($section->section != 0) {
            $controls = $this->section_edit_controls($course, $section, $onsectionpage);
            if (!empty($controls)) {
                $o = implode('<br />', $controls);
            }
        }

        return $o;
    }

    /**
     * Generate the content to displayed on the left part of a section
     * before course modules are included
     *
     * @param stdClass $section The course_section entry from DB
     * @param stdClass $course The course entry from DB
     * @param bool $onsectionpage true if being printed on a section page
     * @return string HTML to output.
     */
    protected function section_left_content($section, $course, $onsectionpage) {
        $o = $this->output->spacer();

        if ($section->section != 0) {
            // Only in the non-general sections.
            if (course_get_format($course)->is_section_current($section)) {
                $o = get_accesshide(get_string('currentsection', 'format_'.$course->format));
            }
        }

        return $o;
    }

    /**
     * Generate the display of the header part of a section before
     * course modules are included
     *
     * @param stdClass $section The course_section entry from DB
     * @param stdClass $course The course entry from DB
     * @param bool $onsectionpage true if being printed on a single-section page
     * @param int $sectionreturn The section to return to after an action
     * @return string HTML to output.
     */
    protected function section_header($section, $course, $onsectionpage, $sectionreturn=null) {
        global $PAGE;

        $o = '';
        $currenttext = '';
        $sectionstyle = '';

        if ($section->section != 0) {
            // Only in the non-general sections.
            if (!$section->visible) {
                $sectionstyle = ' hidden';
            } else if (course_get_format($course)->is_section_current($section)) {
                $sectionstyle = ' current';
            }
        }

        $o.= html_writer::start_tag('li', array('id' => 'section-'.$section->section,
            'class' => 'section main clearfix'.$sectionstyle));

        $leftcontent = $this->section_left_content($section, $course, $onsectionpage);
        $o.= html_writer::tag('div', $leftcontent, array('class' => 'left side'));

        $rightcontent = $this->section_right_content($section, $course, $onsectionpage);
        $o.= html_writer::tag('div', $rightcontent, array('class' => 'right side'));
        $o.= html_writer::start_tag('div', array('class' => 'content'));

        // When not on a section page, we display the section titles except the general section if null
        $hasnamenotsecpg = (!$onsectionpage && ($section->section != 0 || !is_null($section->name)));

        // When on a section page, we only display the general section title, if title is not the default one
        $hasnamesecpg = ($onsectionpage && ($section->section == 0 && !is_null($section->name)));

        if ($hasnamenotsecpg || $hasnamesecpg) {
            $o.= $this->output->heading($this->section_title($section, $course), 3, 'sectionname');
        }

        $o.= html_writer::start_tag('div', array('class' => 'summary'));
        $o.= $this->format_summary_text($section);

        $context = context_course::instance($course->id);
        if ($PAGE->user_is_editing() && has_capability('moodle/course:update', $context)) {
            $url = new moodle_url('/course/editsection.php', array('id'=>$section->id, 'sr'=>$sectionreturn));
            $o.= html_writer::link($url,
                html_writer::empty_tag('img', array('src' => $this->output->pix_url('t/edit'),
                    'class' => 'iconsmall edit', 'alt' => get_string('edit'))),
                array('title' => get_string('editsummary')));
        }
        $o.= html_writer::end_tag('div');

        $o .= $this->section_availability_message($section,
                has_capability('moodle/course:viewhiddensections', $context));

        return $o;
    }

    /**
     * Generate the display of the footer part of a section
     *
     * @return string HTML to output.
     */
    protected function section_footer() {
        $o = html_writer::end_tag('div');
        $o.= html_writer::end_tag('li');

        return $o;
    }

    /**
     * Generate the edit controls of a section
     *
     * @param stdClass $course The course entry from DB
     * @param stdClass $section The course_section entry from DB
     * @param bool $onsectionpage true if being printed on a section page
     * @return array of links with edit controls
     */
    protected function section_edit_controls($course, $section, $onsectionpage = false) {
        global $PAGE;

        if (!$PAGE->user_is_editing()) {
            return array();
        }

        $coursecontext = context_course::instance($course->id);

        if ($onsectionpage) {
            $baseurl = course_get_url($course, $section->section);
        } else {
            $baseurl = course_get_url($course);
        }
        $baseurl->param('sesskey', sesskey());

        $controls = array();

        $url = clone($baseurl);
        if (has_capability('moodle/course:sectionvisibility', $coursecontext)) {
            if ($section->visible) { // Show the hide/show eye.
                $strhidefromothers = get_string('hidefromothers', 'format_'.$course->format);
                $url->param('hide', $section->section);
                $controls[] = html_writer::link($url,
                    html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/hide'),
                    'class' => 'icon hide', 'alt' => $strhidefromothers)),
                    array('title' => $strhidefromothers, 'class' => 'editing_showhide'));
            } else {
                $strshowfromothers = get_string('showfromothers', 'format_'.$course->format);
                $url->param('show',  $section->section);
                $controls[] = html_writer::link($url,
                    html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/show'),
                    'class' => 'icon hide', 'alt' => $strshowfromothers)),
                    array('title' => $strshowfromothers, 'class' => 'editing_showhide'));
            }
        }

        if (!$onsectionpage && has_capability('moodle/course:movesections', $coursecontext)) {
            $url = clone($baseurl);
            if ($section->section > 1) { // Add a arrow to move section up.
                $url->param('section', $section->section);
                $url->param('move', -1);
                $strmoveup = get_string('moveup');

                $controls[] = html_writer::link($url,
                    html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/up'),
                    'class' => 'icon up', 'alt' => $strmoveup)),
                    array('title' => $strmoveup, 'class' => 'moveup'));
            }

            $url = clone($baseurl);
            if ($section->section < $course->numsections) { // Add a arrow to move section down.
                $url->param('section', $section->section);
                $url->param('move', 1);
                $strmovedown =  get_string('movedown');

                $controls[] = html_writer::link($url,
                    html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/down'),
                    'class' => 'icon down', 'alt' => $strmovedown)),
                    array('title' => $strmovedown, 'class' => 'movedown'));
            }
        }

        return $controls;
    }

    /**
     * Generate a summary of a section for display on the 'coruse index page'
     *
     * @param stdClass $section The course_section entry from DB
     * @param stdClass $course The course entry from DB
     * @param array    $mods (argument not used)
     * @return string HTML to output.
     */
    protected function section_summary($section, $course, $mods) {
        $classattr = 'section main section-summary clearfix';
        $linkclasses = '';

        // If section is hidden then display grey section link
        if (!$section->visible) {
            $classattr .= ' hidden';
            $linkclasses .= ' dimmed_text';
        } else if (course_get_format($course)->is_section_current($section)) {
            $classattr .= ' current';
        }

        $o = '';
        $o .= html_writer::start_tag('li', array('id' => 'section-'.$section->section, 'class' => $classattr));

        $o .= html_writer::tag('div', '', array('class' => 'left side'));
        $o .= html_writer::tag('div', '', array('class' => 'right side'));
        $o .= html_writer::start_tag('div', array('class' => 'content'));

        $title = get_section_name($course, $section);
        if ($section->uservisible) {
            $title = html_writer::tag('a', $title,
                    array('href' => course_get_url($course, $section->section), 'class' => $linkclasses));
        }
        $o .= $this->output->heading($title, 3, 'section-title');

        $o.= html_writer::start_tag('div', array('class' => 'summarytext'));
        $o.= $this->format_summary_text($section);
        $o.= html_writer::end_tag('div');
        $o.= $this->section_activity_summary($section, $course, null);

        $context = context_course::instance($course->id);
        $o .= $this->section_availability_message($section,
                has_capability('moodle/course:viewhiddensections', $context));

        $o .= html_writer::end_tag('div');
        $o .= html_writer::end_tag('li');

        return $o;
    }

    /**
     * Generate a summary of the activites in a section
     *
     * @param stdClass $section The course_section entry from DB
     * @param stdClass $course the course record from DB
     * @param array    $mods (argument not used)
     * @return string HTML to output.
     */
    private function section_activity_summary($section, $course, $mods) {
        $modinfo = get_fast_modinfo($course);
        if (empty($modinfo->sections[$section->section])) {
            return '';
        }

        // Generate array with count of activities in this section:
        $sectionmods = array();
        $total = 0;
        $complete = 0;
        $cancomplete = isloggedin() && !isguestuser();
        $completioninfo = new completion_info($course);
        foreach ($modinfo->sections[$section->section] as $cmid) {
            $thismod = $modinfo->cms[$cmid];

            if ($thismod->modname == 'label') {
                // Labels are special (not interesting for students)!
                continue;
            }

            if ($thismod->uservisible) {
                if (isset($sectionmods[$thismod->modname])) {
                    $sectionmods[$thismod->modname]['name'] = $thismod->modplural;
                    $sectionmods[$thismod->modname]['count']++;
                } else {
                    $sectionmods[$thismod->modname]['name'] = $thismod->modfullname;
                    $sectionmods[$thismod->modname]['count'] = 1;
                }
                if ($cancomplete && $completioninfo->is_enabled($thismod) != COMPLETION_TRACKING_NONE) {
                    $total++;
                    $completiondata = $completioninfo->get_data($thismod, true);
                    if ($completiondata->completionstate == COMPLETION_COMPLETE) {
                        $complete++;
                    }
                }
            }
        }

        if (empty($sectionmods)) {
            // No sections
            return '';
        }

        // Output section activities summary:
        $o = '';
        $o.= html_writer::start_tag('div', array('class' => 'section-summary-activities mdl-right'));
        foreach ($sectionmods as $mod) {
            $o.= html_writer::start_tag('span', array('class' => 'activity-count'));
            $o.= $mod['name'].': '.$mod['count'];
            $o.= html_writer::end_tag('span');
        }
        $o.= html_writer::end_tag('div');

        // Output section completion data
        if ($total > 0) {
            $a = new stdClass;
            $a->complete = $complete;
            $a->total = $total;

            $o.= html_writer::start_tag('div', array('class' => 'section-summary-activities mdl-right'));
            $o.= html_writer::tag('span', get_string('progresstotal', 'completion', $a), array('class' => 'activity-count'));
            $o.= html_writer::end_tag('div');
        }

        return $o;
    }

    /**
     * If section is not visible, display the message about that ('Not available
     * until...', that sort of thing). Otherwise, returns blank.
     *
     * For users with the ability to view hidden sections, it shows the
     * information even though you can view the section and also may include
     * slightly fuller information (so that teachers can tell when sections
     * are going to be unavailable etc). This logic is the same as for
     * activities.
     *
     * @param stdClass $section The course_section entry from DB
     * @param bool $canviewhidden True if user can view hidden sections
     * @return string HTML to output
     */
    protected function section_availability_message($section, $canviewhidden) {
        global $CFG;
        $o = '';
        if (!$section->uservisible) {
            $o .= html_writer::start_tag('div', array('class' => 'availabilityinfo'));
            // Note: We only get to this function if availableinfo is non-empty,
            // so there is definitely something to print.
            $o .= $section->availableinfo;
            $o .= html_writer::end_tag('div');
        } else if ($canviewhidden && !empty($CFG->enableavailability) && $section->visible) {
            $ci = new condition_info_section($section);
            $fullinfo = $ci->get_full_information();
            if ($fullinfo) {
                $o .= html_writer::start_tag('div', array('class' => 'availabilityinfo'));
                $o .= get_string(
                        ($section->showavailability ? 'userrestriction_visible' : 'userrestriction_hidden'),
                        'condition', $fullinfo);
                $o .= html_writer::end_tag('div');
            }
        }
        return $o;
    }

    /**
     * Show if something is on on the course clipboard (moving around)
     *
     * @param stdClass $course The course entry from DB
     * @param int $sectionno The section number in the coruse which is being dsiplayed
     * @return string HTML to output.
     */
    protected function course_activity_clipboard($course, $sectionno = null) {
        global $USER;

        $o = '';
        // If currently moving a file then show the current clipboard.
        if (ismoving($course->id)) {
            $url = new moodle_url('/course/mod.php',
                array('sesskey' => sesskey(),
                      'cancelcopy' => true,
                      'sr' => $sectionno,
                )
            );

            $o.= html_writer::start_tag('div', array('class' => 'clipboard'));
            $o.= strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
            $o.= ' ('.html_writer::link($url, get_string('cancel')).')';
            $o.= html_writer::end_tag('div');
        }

        return $o;
    }

    /**
     * Generate next/previous section links for naviation
     *
     * @param stdClass $course The course entry from DB
     * @param array $sections The course_sections entries from the DB
     * @param int $sectionno The section number in the coruse which is being dsiplayed
     * @return array associative array with previous and next section link
     */
    protected function get_nav_links($course, $sections, $sectionno) {
        // FIXME: This is really evil and should by using the navigation API.
        $course = course_get_format($course)->get_course();
        $canviewhidden = has_capability('moodle/course:viewhiddensections', context_course::instance($course->id))
            or !$course->hiddensections;

        $links = array('previous' => '', 'next' => '');
        $back = $sectionno - 1;
        while ($back > 0 and empty($links['previous'])) {
            if ($canviewhidden || $sections[$back]->uservisible) {
                $params = array();
                if (!$sections[$back]->visible) {
                    $params = array('class' => 'dimmed_text');
                }
                $previouslink = html_writer::tag('span', $this->output->larrow(), array('class' => 'larrow'));
                $previouslink .= get_section_name($course, $sections[$back]);
                $links['previous'] = html_writer::link(course_get_url($course, $back), $previouslink, $params);
            }
            $back--;
        }

        $forward = $sectionno + 1;
        while ($forward <= $course->numsections and empty($links['next'])) {
            if ($canviewhidden || $sections[$forward]->uservisible) {
                $params = array();
                if (!$sections[$forward]->visible) {
                    $params = array('class' => 'dimmed_text');
                }
                $nextlink = get_section_name($course, $sections[$forward]);
                $nextlink .= html_writer::tag('span', $this->output->rarrow(), array('class' => 'rarrow'));
                $links['next'] = html_writer::link(course_get_url($course, $forward), $nextlink, $params);
            }
            $forward++;
        }

        return $links;
    }

    /**
     * Generate the header html of a stealth section
     *
     * @param int $sectionno The section number in the coruse which is being dsiplayed
     * @return string HTML to output.
     */
    protected function stealth_section_header($sectionno) {
        $o = '';
        $o.= html_writer::start_tag('li', array('id' => 'section-'.$sectionno, 'class' => 'section main clearfix orphaned hidden'));
        $o.= html_writer::tag('div', '', array('class' => 'left side'));
        $o.= html_writer::tag('div', '', array('class' => 'right side'));
        $o.= html_writer::start_tag('div', array('class' => 'content'));
        $o.= $this->output->heading(get_string('orphanedactivities'), 3, 'sectionname');
        return $o;
    }

    /**
     * Generate footer html of a stealth section
     *
     * @return string HTML to output.
     */
    protected function stealth_section_footer() {
        $o = html_writer::end_tag('div');
        $o.= html_writer::end_tag('li');
        return $o;
    }

    /**
     * Generate the html for a hidden section
     *
     * @param int $sectionno The section number in the coruse which is being dsiplayed
     * @return string HTML to output.
     */
    protected function section_hidden($sectionno) {
        $o = '';
        $o.= html_writer::start_tag('li', array('id' => 'section-'.$sectionno, 'class' => 'section main clearfix hidden'));
        $o.= html_writer::tag('div', '', array('class' => 'left side'));
        $o.= html_writer::tag('div', '', array('class' => 'right side'));
        $o.= html_writer::start_tag('div', array('class' => 'content'));
        $o.= get_string('notavailable');
        $o.= html_writer::end_tag('div');
        $o.= html_writer::end_tag('li');
        return $o;
    }

    /**
     * Output the html for a single section page .
     *
     * @param stdClass $course The course entry from DB
     * @param array $sections (argument not used)
     * @param array $mods (argument not used)
     * @param array $modnames (argument not used)
     * @param array $modnamesused (argument not used)
     * @param int $displaysection The section number in the course which is being displayed
     */
    public function print_single_section_page($course, $sections, $mods, $modnames, $modnamesused, $displaysection) {
        global $PAGE;

        $modinfo = get_fast_modinfo($course);
        $course = course_get_format($course)->get_course();

        // Can we view the section in question?
        if (!($sectioninfo = $modinfo->get_section_info($displaysection))) {
            // This section doesn't exist
            print_error('unknowncoursesection', 'error', null, $course->fullname);
            return;
        }

        if (!$sectioninfo->uservisible) {
            if (!$course->hiddensections) {
                echo $this->start_section_list();
                echo $this->section_hidden($displaysection);
                echo $this->end_section_list();
            }
            // Can't view this section.
            return;
        }

        // Copy activity clipboard..
        echo $this->course_activity_clipboard($course, $displaysection);
        $thissection = $modinfo->get_section_info(0);
        if ($thissection->summary or !empty($modinfo->sections[0]) or $PAGE->user_is_editing()) {
            echo $this->start_section_list();
            echo $this->section_header($thissection, $course, true, $displaysection);
            print_section($course, $thissection, null, null, true, "100%", false, $displaysection);
            if ($PAGE->user_is_editing()) {
                print_section_add_menus($course, 0, null, false, false, $displaysection);
            }
            echo $this->section_footer();
            echo $this->end_section_list();
        }

        // Start single-section div
        echo html_writer::start_tag('div', array('class' => 'single-section'));

        // The requested section page.
        $thissection = $modinfo->get_section_info($displaysection);

        // Title with section navigation links.
        $sectionnavlinks = $this->get_nav_links($course, $modinfo->get_section_info_all(), $displaysection);
        $sectiontitle = '';
        $sectiontitle .= html_writer::start_tag('div', array('class' => 'section-navigation header headingblock'));
        $sectiontitle .= html_writer::tag('span', $sectionnavlinks['previous'], array('class' => 'mdl-left'));
        $sectiontitle .= html_writer::tag('span', $sectionnavlinks['next'], array('class' => 'mdl-right'));
        // Title attributes
        $titleattr = 'mdl-align title';
        if (!$thissection->visible) {
            $titleattr .= ' dimmed_text';
        }
        $sectiontitle .= html_writer::tag('div', get_section_name($course, $displaysection), array('class' => $titleattr));
        $sectiontitle .= html_writer::end_tag('div');
        echo $sectiontitle;

        // Now the list of sections..
        echo $this->start_section_list();

        echo $this->section_header($thissection, $course, true, $displaysection);
        // Show completion help icon.
        $completioninfo = new completion_info($course);
        echo $completioninfo->display_help_icon();

        print_section($course, $thissection, null, null, true, '100%', false, $displaysection);
        if ($PAGE->user_is_editing()) {
            print_section_add_menus($course, $displaysection, null, false, false, $displaysection);
        }
        echo $this->section_footer();
        echo $this->end_section_list();

        // Display section bottom navigation.
        $courselink = html_writer::link(course_get_url($course), get_string('returntomaincoursepage'));
        $sectionbottomnav = '';
        $sectionbottomnav .= html_writer::start_tag('div', array('class' => 'section-navigation mdl-bottom'));
        $sectionbottomnav .= html_writer::tag('span', $sectionnavlinks['previous'], array('class' => 'mdl-left'));
        $sectionbottomnav .= html_writer::tag('span', $sectionnavlinks['next'], array('class' => 'mdl-right'));
        $sectionbottomnav .= html_writer::tag('div', $courselink, array('class' => 'mdl-align'));
        $sectionbottomnav .= html_writer::end_tag('div');
        echo $sectionbottomnav;

        // close single-section div.
        echo html_writer::end_tag('div');
    }

    /**
     * Output the html for a multiple section page
     *
     * @param stdClass $course The course entry from DB
     * @param array $sections (argument not used)
     * @param array $mods (argument not used)
     * @param array $modnames (argument not used)
     * @param array $modnamesused (argument not used)
     */
    public function print_multiple_section_page($course, $sections, $mods, $modnames, $modnamesused) {
        global $PAGE;

        $modinfo = get_fast_modinfo($course);
        $course = course_get_format($course)->get_course();

        $context = context_course::instance($course->id);
        // Title with completion help icon.
        $completioninfo = new completion_info($course);
        echo $completioninfo->display_help_icon();
        echo $this->output->heading($this->page_title(), 2, 'accesshide');

        // Copy activity clipboard..
        echo $this->course_activity_clipboard($course, 0);

        // Now the list of sections..
        echo $this->start_section_list();

        foreach ($modinfo->get_section_info_all() as $section => $thissection) {
            if ($section == 0) {
                // 0-section is displayed a little different then the others
                if ($thissection->summary or !empty($modinfo->sections[0]) or $PAGE->user_is_editing()) {
                    echo $this->section_header($thissection, $course, false, 0);
                    print_section($course, $thissection, null, null, true, "100%", false, 0);
                    if ($PAGE->user_is_editing()) {
                        print_section_add_menus($course, 0, null, false, false, 0);
                    }
                    echo $this->section_footer();
                }
                continue;
            }
            if ($section > $course->numsections) {
                // activities inside this section are 'orphaned', this section will be printed as 'stealth' below
                continue;
            }
            // Show the section if the user is permitted to access it, OR if it's not available
            // but showavailability is turned on (and there is some available info text).
            $showsection = $thissection->uservisible ||
                    ($thissection->visible && !$thissection->available && $thissection->showavailability
                    && !empty($thissection->availableinfo));
            if (!$showsection) {
                // Hidden section message is overridden by 'unavailable' control
                // (showavailability option).
                if (!$course->hiddensections && $thissection->available) {
                    echo $this->section_hidden($section);
                }

                continue;
            }

            if (!$PAGE->user_is_editing() && $course->coursedisplay == COURSE_DISPLAY_MULTIPAGE) {
                // Display section summary only.
                echo $this->section_summary($thissection, $course, null);
            } else {
                echo $this->section_header($thissection, $course, false, 0);
                if ($thissection->uservisible) {
                    print_section($course, $thissection, null, null, true, "100%", false, 0);
                    if ($PAGE->user_is_editing()) {
                        print_section_add_menus($course, $section, null, false, false, 0);
                    }
                }
                echo $this->section_footer();
            }
        }

        if ($PAGE->user_is_editing() and has_capability('moodle/course:update', $context)) {
            // Print stealth sections if present.
            foreach ($modinfo->get_section_info_all() as $section => $thissection) {
                if ($section <= $course->numsections or empty($modinfo->sections[$section])) {
                    // this is not stealth section or it is empty
                    continue;
                }
                echo $this->stealth_section_header($section);
                print_section($course, $thissection, null, null, true, "100%", false, 0);
                echo $this->stealth_section_footer();
            }

            echo $this->end_section_list();

            echo html_writer::start_tag('div', array('id' => 'changenumsections', 'class' => 'mdl-right'));

            // Increase number of sections.
            $straddsection = get_string('increasesections', 'moodle');
            $url = new moodle_url('/course/changenumsections.php',
                array('courseid' => $course->id,
                      'increase' => true,
                      'sesskey' => sesskey()));
            $icon = $this->output->pix_icon('t/switch_plus', $straddsection);
            echo html_writer::link($url, $icon.get_accesshide($straddsection), array('class' => 'increase-sections'));

            if ($course->numsections > 0) {
                // Reduce number of sections sections.
                $strremovesection = get_string('reducesections', 'moodle');
                $url = new moodle_url('/course/changenumsections.php',
                    array('courseid' => $course->id,
                          'increase' => false,
                          'sesskey' => sesskey()));
                $icon = $this->output->pix_icon('t/switch_minus', $strremovesection);
                echo html_writer::link($url, $icon.get_accesshide($strremovesection), array('class' => 'reduce-sections'));
            }

            echo html_writer::end_tag('div');
        } else {
            echo $this->end_section_list();
        }

    }

    /**
     * Generate html for a section summary text
     *
     * @param stdClass $section The course_section entry from DB
     * @return string HTML to output.
     */
    protected function format_summary_text($section) {
        $context = context_course::instance($section->course);
        $summarytext = file_rewrite_pluginfile_urls($section->summary, 'pluginfile.php',
            $context->id, 'course', 'section', $section->id);

        $options = new stdClass();
        $options->noclean = true;
        $options->overflowdiv = true;
        return format_text($summarytext, $section->summaryformat, $options);
    }

    /**
     * Is the section passed in the current section?
     *
     * @deprecated since 2.4
     * @see format_base::is_section_current()
     *
     * @param stdClass $course The course entry from DB
     * @param stdClass $section The course_section entry from the DB
     * @return bool true if the section is current
     */
    protected final function is_section_current($section, $course) {
        debugging('Function format_section_renderer_base::is_section_current() is deprecated. '.
                'Use course_get_format($course)->is_section_current($section) instead', DEBUG_DEVELOPER);
        return course_get_format($course)->is_section_current($section);
    }
}


text:
/**
 * Created by xubt on 9/24/16.
 */
kanbanApp.factory('invitationService', ['$http', '$q', 'httpServices',
    function ($http, $q, httpServices) {
        return {
            loadInvitationByLink: function (_invitationLink) {
                return httpServices.get(_invitationLink);
            },
            acceptInvitation: function (_invitationLink) {
                return httpServices.putWithNoBody(_invitationLink);
            }
        };
    }]);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea satakuntensis f. athallina O. Behr

### Remarks
null


text:
package com.googlecode.objectify.guice.processor;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;

/**
 * User: jamestalmage
 * Date: 10/6/11
 * Time: 2:22 AM
 */
class WriterUtils {
    static void print(PrintWriter out, String string){
        if(unemptyString(string)) out.print(string);
    }
    static boolean unemptyString(String string){
        return string !=null && !string.isEmpty();
    }
    static void join(PrintWriter out, String prefix, String suffix, Iterable vals){
        join(out,prefix,suffix,",",true,vals);
    }
    static void join(PrintWriter out, String prefix, String suffix, Object ... vals){
        join(out,prefix,suffix,",",true,Arrays.asList(vals));
    }
    static void join(PrintWriter out, String prefix, String suffix, String delim, boolean newLineDelim, Object ... vals){
        join(out,prefix,suffix,delim,newLineDelim, Arrays.asList(vals));
    }
    static void join(PrintWriter out, String prefix, String suffix, String delim, boolean newLineDelim, Iterable vals){
        Iterator iter = vals.iterator();
        while (iter.hasNext()){
            Object val = iter.next();
            print(out,prefix);
            out.print(val);
            print(out,suffix);
            if(iter.hasNext()){
                print(out,delim);
            }
            if(newLineDelim) out.println();
        }
    }

    static void printClassHeader(PrintWriter out, String pkg, String className, String extnds, String ... implmts){
        if(unemptyString(pkg)){
            out.print("package ");
            out.print(pkg);
            out.println(";");
            out.println();
        }
        out.println("/** Generated by guice-ify */");
        out.print("public final class ");
        out.print(className);
        if(unemptyString(extnds)){
            out.print(" extends ");
            out.print(extnds);
        }
        if(implmts != null && implmts.length > 0){
            out.print(" implements");
            for(int i= 0; i < implmts.length; i++){
                if(i != 0) out.print(",");
                out.print(" ");
                out.print(implmts[i]);
            }
        }
        out.println(" {");
        out.println();
    }

    static void printModuleEqualsAndHashCode(PrintWriter out, String className) {
        out.println("  @Override");
        out.println("  public boolean equals(Object obj){");
        out.print("    return obj instanceof ");
        out.print(className);
        out.println(";");
        out.println("  }");

        out.println("  @Override");
        out.println("  public int hashCode(){");
        out.print("    return ");
        out.print(className);
        out.println(".class.hashCode();");
        out.println("  }");
    }

    static void printProvidesQueryMethod(PrintWriter out, String name) {
       out.println("  @com.google.inject.Provides");
       out.print("  public com.googlecode.objectify.Query<");
       out.print(name);
       out.print("> get");
       out.print(name);
       out.println("Query(com.googlecode.objectify.Objectify ofy){");
       out.print("    return ofy.query(");
       out.print(name);
       out.println(".class);");
       out.println("  }");
       out.println();
   }

    static String capitalize(String s){
        StringBuilder sb = new StringBuilder();
        sb.append(Character.toUpperCase(s.charAt(0)));
        sb.append(s.substring(1));
        return sb.toString();
    }

    static String uniqueNameFromPackage(String pkg, String suffix){
        return capitalize(pkg.substring(pkg.lastIndexOf(".") + 1))+suffix;
    }
}


text:
package com.leonti.slickpm.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.leonti.slickpm.domain.TaskType;
import com.leonti.slickpm.domain.dto.TaskTypeDTO;
import com.leonti.slickpm.service.TaskTypeService;

@Controller
@Secured("ROLE_USER")
@RequestMapping("/taskType")
public class TaskTypeController {

	@Resource(name = "TaskTypeService")
	TaskTypeService taskTypeService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public @ResponseBody
	List<TaskTypeDTO> RESTList(Model model) {

		List<TaskTypeDTO> taskTypeDTOList = new ArrayList<TaskTypeDTO>();

		for (TaskType taskType : taskTypeService.getList()) {
			taskTypeDTOList.add(taskType.getDTO());
		}

		return taskTypeDTOList;
	}
}


text:
import {SystemMemoryGaugeSet} from '../../../../src/metrics/os/SystemMemoryGaugeSet';
import {expect} from 'chai';

const path = require('path');

describe('/test/unit/metrics/os/SystemMemoryGaugeSet.test.ts', () => {

  it('should get system memory statistics', () => {
    let gaugeset = new SystemMemoryGaugeSet(5, path.join(__dirname, '../resources/meminfo'));
    let gauges = gaugeset.getMetrics();

    expect(gauges[0].name.key).to.equal('mem.total');
    expect(gauges[0].metric.getValue()).to.equal(99163816);

    expect(gauges[1].name.key).to.equal('mem.used');
    expect(gauges[1].metric.getValue()).to.equal(3361884);

    expect(gauges[2].name.key).to.equal('mem.free');
    expect(gauges[2].metric.getValue()).to.equal(89847992);

    expect(gauges[3].name.key).to.equal('mem.buffers');
    expect(gauges[3].metric.getValue()).to.equal(1459900);

    expect(gauges[4].name.key).to.equal('mem.cached');
    expect(gauges[4].metric.getValue()).to.equal(4494040);

    expect(gauges[5].name.key).to.equal('mem.swap.total');
    expect(gauges[5].metric.getValue()).to.equal(2097144);

    expect(gauges[6].name.key).to.equal('mem.swap.used');
    expect(gauges[6].metric.getValue()).to.equal(0);

    expect(gauges[7].name.key).to.equal('mem.swap.free');
    expect(gauges[7].metric.getValue()).to.equal(2097144);

  });
});


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

<rootTag>
  <Award>
    <AwardTitle>PostDoctoral Research Fellowship</AwardTitle>
    <AwardEffectiveDate>07/01/2014</AwardEffectiveDate>
    <AwardExpirationDate>06/30/2018</AwardExpirationDate>
    <AwardAmount>150000</AwardAmount>
    <AwardInstrument>
      <Value>Fellowship</Value>
    </AwardInstrument>
    <Organization>
      03040000
      <Directorate>
        <LongName>Direct For Mathematical & Physical Scien</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Mathematical Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Bruce P. Palka</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award is made as part of the FY 2014 Mathematical Sciences Postdoctoral Research Fellowships Program. Each of the fellowships supports a research and training project at a host institution in the mathematical sciences, including applications to other disciplines, under the mentorship of a sponsoring scientist. The title of the project for this fellowship to Tobias L. Johnson is "Random Combinatorial Structures and Stein's Method." The host institution for the fellowship is the University of Southern California, and the sponsoring scientist is Dr. Larry Goldstein.</AbstractNarration>
    <MinAmdLetterDate>04/02/2014</MinAmdLetterDate>
    <MaxAmdLetterDate>04/02/2014</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1401479</AwardID>
    <Investigator>
      <FirstName>Tobias</FirstName>
      <LastName>Johnson</LastName>
      <EmailAddress/>
      <StartDate>04/02/2014</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Johnson Tobias L</Name>
      <CityName>Seattle</CityName>
      <ZipCode>981954350</ZipCode>
      <PhoneNumber/>
      <StreetAddress/>
      <CountryName>United States</CountryName>
      <StateName>Washington</StateName>
      <StateCode>WA</StateCode>
    </Institution>
    <ProgramElement>
      7335
      <Text>WORKFORCE IN THE MATHEMAT SCI</Text>
    </ProgramElement>
    <ProgramReference>
      9219
      <Text>POSTDOCTORAL FELLOWSHIPS IN MATH SCIENCE</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Pterostegia fruticosa Greene

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CREATE-WEALTH-HISTOGRAM</title>

I set up and maintain a histogram of the distribution of sugar in the

	population.

	Begin micro-behaviour

CREATE-WEALTH-HISTOGRAM

	Begin NetLogo code:

create-histogram
  "270" "450" ; lower left corner
  "520" "709" ; upper right corner
  "Wealth Histogram" ; unique name (and label) for this plot
  "Wealth (tens of sugar)" ; X axis label
  "Number of individuals" ; Y axis label
  all-individuals
  (round (my-sugar / 10)) ; value being displayed
  "0" ; minimum x value
  "20" ; maximum x value
  "0"  ; minimum y value
  "100" ; maximum y value

	End NetLogo code

Variants

All the labels and parameters can be changed.

Note that currently the system is limited to interpreting calls to

	create-histogram where each argument is on a different line.

How this works

It computes the number of tens of sugar units each individual has by

	dividing the sugar by ten and rounding.

Related Micro-behaviours

	CREATE-POPULATION-PLOT creates a plot of the population.

History

This was implemented by Ken Kahn.


text:
package io.vertx.blueprint.microservice.payment;

import io.vertx.core.json.JsonObject;
import io.vertx.core.json.JsonArray;

/**
 * Converter for {@link io.vertx.blueprint.microservice.payment.Payment}.
 *
 * NOTE: This class has been automatically generated from the {@link io.vertx.blueprint.microservice.payment.Payment} original class using Vert.x codegen.
 */
public class PaymentConverter {

  public static void fromJson(JsonObject json, Payment obj) {
    if (json.getValue("payAmount") instanceof Number) {
      obj.setPayAmount(((Number)json.getValue("payAmount")).doubleValue());
    }
    if (json.getValue("payId") instanceof String) {
      obj.setPayId((String)json.getValue("payId"));
    }
    if (json.getValue("paySource") instanceof Number) {
      obj.setPaySource(((Number)json.getValue("paySource")).shortValue());
    }
    if (json.getValue("paymentTime") instanceof Number) {
      obj.setPaymentTime(((Number)json.getValue("paymentTime")).longValue());
    }
  }

  public static void toJson(Payment obj, JsonObject json) {
    if (obj.getPayAmount() != null) {
      json.put("payAmount", obj.getPayAmount());
    }
    if (obj.getPayId() != null) {
      json.put("payId", obj.getPayId());
    }
    if (obj.getPaySource() != null) {
      json.put("paySource", obj.getPaySource());
    }
    if (obj.getPaymentTime() != null) {
      json.put("paymentTime", obj.getPaymentTime());
    }
  }
}


text:
  <mat-card class="settings-card">
    <mat-card-title>

        admin.general-settings

    </mat-card-title>
    <mat-progress-bar color="warn" mode="indeterminate" *ngIf="isLoading$ | async">
    </mat-progress-bar>

    <mat-card-content style="padding-top: 16px;">
      <form [formGroup]="generalSettings" (ngSubmit)="save()">
        <fieldset [disabled]="isLoading$ | async">
          <mat-form-field class="mat-block">
            <mat-label translate>admin.base-url</mat-label>
            <input matInput formControlName="baseUrl" required/>
            <mat-error *ngIf="generalSettings.get('baseUrl').hasError('required')">
              {{ 'admin.base-url-required' | translate }}
            </mat-error>
          </mat-form-field>
          <tb-checkbox formControlName="prohibitDifferentUrl" style="display: block; padding-bottom: 16px;">
            {{ 'admin.prohibit-different-url' | translate }}
          </tb-checkbox>

admin.prohibit-different-url-hint

            <button mat-button mat-raised-button color="primary" [disabled]="(isLoading$ | async) || generalSettings.invalid || !generalSettings.dirty"
                    type="submit">{{'action.save' | translate}}
            </button>

        </fieldset>
      </form>
    </mat-card-content>
  </mat-card>


text:
title: AJAX updates
page_title: AJAX updates | RadSplitter for ASP.NET AJAX Documentation
description: AJAX updates
slug: splitter/how-to/ajax-updates
tags: ajax,updates
published: True
position: 0
---

# AJAX updates

**RadSlidingPane**, **RadPane,** and **RadSplitBar** controls can not be updated directly with an **Ajax Manager** control.

When you want to update the content of a **RadPane** (or **RadSlidingPane**) control, just add an **asp:Panel** control (or any other container control that runs on the server) inside the pane and update the panel instead the **RadPane** (or **RadSlidingPane**).

When you want to change the **RadSlidingPane**, **RadPane** or **RadSplitBar** properties, you can do it with the [client-side API]({%slug splitter/client-side-programming/overview%}) or you can update the whole **Splitter** or **RadSlidingZone** with the **Ajax Manager** control or with an **Ajax Panel** control.

## See Also

 * [Structure]({%slug splitter/getting-started/structure%})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Igneel.Graphics
{
    /// <summary>
    /// build a cylindre center at (0,0,0)
    /// </summary>
    public class CylindreBuilder : ShapeBuilder<MeshVertex>
    {
        public int slices;
        public int stacks;
        public float radius;
        public float height;
        public bool open;

        public CylindreBuilder(int stacks, int slices, float radius, float height, bool open)
        {
            this.stacks = stacks;
            this.slices = slices;
            this.radius = radius;
            this.height = height;
            this.open = open;
            Build();
        }

        private void Build()
        {
            vertices = new MeshVertex[(stacks + 1) * (slices + 1) + (open ? 0 : 2 * (slices + 1) + 2)];
            indices = new ushort[stacks * slices * 6 + (open ? 0 : slices * 6)];

            float dTheta = Numerics.TwoPI / (float)slices;
            float dy = height / stacks;
            int vidx = 0;
            int iIdx = 0;
            float halfHeight = height * 0.5f;
            CyCoord coords = new CyCoord(0, halfHeight, radius);
            if (!open)
            {
                CreateCap(dTheta, ref vidx, ref iIdx, new Vector3(0, 1, 0), coords.Y);
                CreateCap(dTheta, ref vidx, ref iIdx, new Vector3(0, -1, 0), -coords.Y);
            }
            ushort offset = (ushort)vidx;

            for (int i = 0; i <= stacks; i++)
            {
                coords.Y = halfHeight - i * dy;
                for (int j = 0; j <= slices; j++)
                {
                    coords.Theta = j * dTheta;
                    vertices[vidx++] = CreateVertex(coords, dTheta);
                }
            }
            int numRingVertices = slices + 1;
            for (int i = 0; i < stacks; i++)
            {
                for (int j = 0; j < slices; j++)
                {
                    indices[iIdx++] = (ushort)(offset + (ushort)(i * numRingVertices + j));
                    indices[iIdx++] = (ushort)(offset + (ushort)(i * numRingVertices + j + 1));
                    indices[iIdx++] = (ushort)(offset + (ushort)((i + 1) * numRingVertices + j));

                    indices[iIdx++] = (ushort)(offset + (ushort)((i + 1) * numRingVertices + j));
                    indices[iIdx++] = (ushort)(offset + (ushort)(i * numRingVertices + j + 1));
                    indices[iIdx++] = (ushort)(offset + (ushort)((i + 1) * numRingVertices + j + 1));
                }
            }
        }

        private void CreateCap(float dTheta, ref int vidx, ref int iIdx, Vector3 normal, float y)
        {
            int start = vidx;
            CyCoord coords = new CyCoord(0, y, radius);
            //pole
            vertices[vidx++] = new MeshVertex(position: new Vector3(0, coords.Y, 0),
                                            normal: normal,
                                            tangent: new Vector3(1, 0, 0),
                                            texCoord: new Vector2(0.5f, 0.5f));
            for (int i = 0; i <= slices; i++)
            {
                coords.Theta = i * dTheta;
                vertices[vidx++] = CreateVertex(coords, dTheta);
            }

            for (int i = 0; i < slices; i++)
            {
                //create triangle
                if (normal.Y == 1)
                {
                    indices[iIdx++] = (ushort)(start + i + 1);
                    indices[iIdx++] = (ushort)(start);
                    indices[iIdx++] = (ushort)(start + i + 2);
                }
                else
                {
                    indices[iIdx++] = (ushort)start;
                    indices[iIdx++] = (ushort)(start + i + 1);
                    indices[iIdx++] = (ushort)(start + i + 2);
                }

            }
        }

        private unsafe MeshVertex CreateVertex(CyCoord coords, float dTheta)
        {
            Vector3* pos = stackalloc Vector3[3];
            CyCoord tcoord = coords;
            for (int i = 0; i < 3; i++)
            {
                //compute 3 positions for computing the derivate respect theta
                pos[i] = tcoord.ToCartesian();
                tcoord.Theta += dTheta;
            }

            var tangent = Vector3.Normalize(Numerics.DerivateForward1(pos, dTheta));
            var normal = Vector3.Normalize(Vector3.Cross(tangent, new Vector3(0, -1, 0)));
            var texCoord = new Vector2(coords.Theta / Numerics.TwoPI, 0.5f - coords.Y / height);

            return new MeshVertex(pos[0], normal, tangent, texCoord);
        }
    }
}


text:
waitvid.2048
============
A collection of video drivers for the [Parallax P8X32A](http://parallax.com).

Primary design goals are minimal core usage and/or full colour mode. Sometimes though, just proving a point.


text:
package store

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command

import (
	"errors"
	"net/url"
	golangswaggerpaths "path"
	"strings"

	"github.com/go-openapi/swag"
)

// OrderDeleteURL generates an URL for the order delete operation
type OrderDeleteURL struct {
	OrderID int64

	_basePath string
	// avoid unkeyed usage
	_ struct{}
}

// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *OrderDeleteURL) WithBasePath(bp string) *OrderDeleteURL {
	o.SetBasePath(bp)
	return o
}

// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *OrderDeleteURL) SetBasePath(bp string) {
	o._basePath = bp
}

// Build a url path and query string
func (o *OrderDeleteURL) Build() (*url.URL, error) {
	var _result url.URL

	var _path = "/store/order/{orderId}"

	orderID := swag.FormatInt64(o.OrderID)
	if orderID != "" {
		_path = strings.Replace(_path, "{orderId}", orderID, -1)
	} else {
		return nil, errors.New("orderId is required on OrderDeleteURL")
	}

	_basePath := o._basePath
	if _basePath == "" {
		_basePath = "/api/v2"
	}
	_result.Path = golangswaggerpaths.Join(_basePath, _path)

	return &_result, nil
}

// Must is a helper function to panic when the url builder returns an error
func (o *OrderDeleteURL) Must(u *url.URL, err error) *url.URL {
	if err != nil {
		panic(err)
	}
	if u == nil {
		panic("url can't be nil")
	}
	return u
}

// String returns the string representation of the path with query string
func (o *OrderDeleteURL) String() string {
	return o.Must(o.Build()).String()
}

// BuildFull builds a full url with scheme, host, path and query string
func (o *OrderDeleteURL) BuildFull(scheme, host string) (*url.URL, error) {
	if scheme == "" {
		return nil, errors.New("scheme is required for a full url on OrderDeleteURL")
	}
	if host == "" {
		return nil, errors.New("host is required for a full url on OrderDeleteURL")
	}

	base, err := o.Build()
	if err != nil {
		return nil, err
	}

	base.Scheme = scheme
	base.Host = host
	return base, nil
}

// StringFull returns the string representation of a complete url
func (o *OrderDeleteURL) StringFull(scheme, host string) string {
	return o.Must(o.BuildFull(scheme, host)).String()
}


text:
//
//  CATDogTabViewController.m
//  CATNavigationController
//
//  Created by lben on 6/15/16.
//  Copyright © 2016 lbencs. All rights reserved.
//

#import "CATDogTabViewController.h"
#import "CATDogChildViewController.h"
#import "UINavigationBar+CATCustom.h"
#import "CATNavigationController.h"

@interface CATDogTabViewController ()

@end

@implementation CATDogTabViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	self.view.backgroundColor = [UIColor whiteColor];
	self.title = @"More";
	self.at_showTabBar = YES;
	[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
	[self.navigationController.navigationBar at_setBottomLineColor:[UIColor redColor]];
}

- (void)viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
	[self.navigationController setNavigationBarHidden:NO animated:animated];
	self.navigationController.tabBarController.tabBar.hidden = NO;

	[self.navigationController.navigationBar at_setBackgroundColor:[UIColor whiteColor]];
//	self.hidesBottomBarWhenPushed = YES;
//	self.tabBarController.tabBar.hidden = NO;
//	self.tabBarController.hidesBottomBarWhenPushed = YES;
//	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//		[self.navigationController.navigationBar at_undo];
//	});
}
- (void)viewWillDisappear:(BOOL)animated{
	[super viewWillDisappear:animated];
//	self.accessibilityElementsHidden = NO;
	[self.navigationController.navigationBar at_undo];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
	cell.textLabel.text = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
	// Configure the cell...

	return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	NSLog(@"%@",self.navigationController);
	CATDogChildViewController *nvc = [[CATDogChildViewController alloc] init];
	if (indexPath.row == 0) {
		[self.navigationController  at_pushViewController:nvc animated:YES];
	}else{
		nvc.view.backgroundColor = [UIColor yellowColor];
		[self.navigationController at_pushViewController:nvc animated:YES];
	}
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
define(function (require, exports, module) {var React = require('react');
var joinClasses = require('./utils/joinClasses');
var BootstrapMixin = require('./BootstrapMixin');
var classSet = require('./utils/classSet');
var cloneWithProps = require('./utils/cloneWithProps');

var ValidComponentChildren = require('./utils/ValidComponentChildren');

var ListGroupItem = React.createClass({displayName: "ListGroupItem",
  mixins: [BootstrapMixin],

  propTypes: {
    bsStyle: React.PropTypes.oneOf(['danger','info','success','warning']),
    active: React.PropTypes.any,
    disabled: React.PropTypes.any,
    header: React.PropTypes.node,
    onClick: React.PropTypes.func,
    eventKey: React.PropTypes.any,
    href: React.PropTypes.string,
    target: React.PropTypes.string
  },

  getDefaultProps: function () {
    return {
      bsClass: 'list-group-item'
    };
  },

  render: function () {
    var classes = this.getBsClassSet();

    classes['active'] = this.props.active;
    classes['disabled'] = this.props.disabled;

    if (this.props.href || this.props.target || this.props.onClick) {
      return this.renderAnchor(classes);
    } else {
      return this.renderSpan(classes);
    }
  },

  renderSpan: function (classes) {
    return (
      React.createElement("span", React.__spread({},  this.props, {className: joinClasses(this.props.className, classSet(classes))}),
        this.props.header ? this.renderStructuredContent() : this.props.children
      )
    );
  },

  renderAnchor: function (classes) {
    return (
      React.createElement("a", React.__spread({},
        this.props,
        {className: joinClasses(this.props.className, classSet(classes)),
        onClick: this.handleClick}),
        this.props.header ? this.renderStructuredContent() : this.props.children
      )
    );
  },

  renderStructuredContent: function () {
    var header;
    if (React.isValidElement(this.props.header)) {
      header = cloneWithProps(this.props.header, {
        className: 'list-group-item-heading'
      });
    } else {
      header = (
        React.createElement("h4", {className: "list-group-item-heading"},
          this.props.header
        )
      );
    }

    var content = (
      React.createElement("p", {className: "list-group-item-text"},
        this.props.children
      )
    );

    return {
      header: header,
      content: content
    };
  },

  handleClick: function (e) {
    if (this.props.onClick) {
      e.preventDefault();
      this.props.onClick(this.props.eventKey, this.props.href, this.props.target);
    }
  }
});

module.exports = ListGroupItem;

});


text:
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class SiteController extends Controller
{
    // got idea from https://github.com/yiisoft/yii2/issues/3890
    public $theme = "";

    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            $this->theme = Yii::$app->getRequest()->getQueryParam('theme');
            Yii::$app->view->theme = new \yii\base\Theme([
                'pathMap' => ['@app/views' => 'themes/'.$this->theme],
                'baseUrl' => 'themes/'.$this->theme,

            ]);
            return true;  // or false if needed
        } else {
            return false;
        }
    }

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    public function actionAbout()
    {
        return $this->render('about');
    }
}


text:
require 'pathname'
require 'fattr'
require 'fileutils'

# SourcePath represents an article source file on disk.
class Germinate::SourceFile
  fattr :path
  fattr(:backup_path) { Pathname(path.to_s + ".germ.bak") }
  fattr(:log) { Germinate.logger }

  def initialize(path)
    @path = Pathname(path)
  end

  def write!(lines)
    log.debug "Writing #{lines.size} lines to #{path}"
    file = File.new(path)
    flock_result = file.flock(File::LOCK_EX)
    if flock_result != 0
      raise "Unable to lock file #{path}"
    end
    FileUtils.cp(path, backup_path)
    unless path.read == backup_path.read
      raise "Error backup up #{path} to #{backup_path}"
    end
    begin
      path.open('w+') do |output|
        lines.each do |line|
          output.write(line)
        end
      end
    rescue Exception => error
      FileUtils.cp(backup_path, path)
      raise
    end
    log.info "Changes saved to #{path}."
    log.info "Previous state saved as #{backup_path}."
  ensure
    file.flock(File::LOCK_UN)
  end
end


text:
package logan.actors

import akka.actor.ActorRef
import akka.pattern.pipe
import logan.core.Node

import scala.concurrent.Future

class StdinActor(node: Node, consumers: Seq[ActorRef])
  extends NodeActor(node, consumers) {

  case class ReadLine()
  case class SendLine(line: String)

  override def preStart(): Unit = {
    self ! ReadLine
  }

  implicit val ec = context.dispatcher

  def receive = {
    case RequestMore =>
      self ! ReadLine

    case ReadLine =>
      Future {
        SendLine(Console.in.readLine())
      } pipeTo self

    case SendLine(line) =>
      consumers.foreach({ s => s ! line})
      self ! ReadLine
  }
}