text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.jason</groupId>
	<artifactId>jason-util</artifactId>
	<version>1.0</version>

	<name>jason-utils</name>
	<url>http://www.jason-zhang.org/jason-utils</url>

	<licenses>
		<license>
			<name>Apache 2</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
			<comments>A business-friendly OSS license</comments>
		</license>
	</licenses>

	<developers>
		<developer>
			<id>jason.zhang</id>
			<name>jason.zhang</name>
			<email>zclok236@gmail.com</email>
			<url>http://www.jason-zhang.org</url>
			<organization>techgarden</organization>
			<organizationUrl>http://www.techgarden.com</organizationUrl>
			<roles>
				<role>developer</role>
			</roles>
			<timezone>-6</timezone>
		</developer>
	</developers>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<powermock.version>1.4.10</powermock.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>maven</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.7-20060614</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4</artifactId>
			<version>${powermock.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-mockito</artifactId>
			<version>${powermock.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.3.1</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
			</plugin>
		</plugins>
	</build>
</project>


text:
<!DOCTYPE html>

	<title>GitHub Explained</title>
	<link rel="stylesheet" type="text/css" href="stylesheets/githubexplained.css"/>

Local Repo

(folders on your computer)

The .git "hidden" folder needs to be inside the highest level folder so it can track all changes that happen inside that folder and all subfolders of that folder.

*** It's imperative that you only have ONE .git folder in your whole local repository!! ***

If you have a .git folder in your [username].github.io folder and one in [username].github.io/[folder with html files] you will be tracking changes twice, have 2 different HEADs with different checksum sequences, resulting in errors.

If this is how you have your local repo currently setup, you will have to:

Locally, on your computer - move all files and folders from your [username].github.io folder to a different directory on your computer, like your desktop

remove ALL .git folders

In your github account online (www.github.com), delete your [username].github.io repository completely

Go through the steps to create the [username].github.io again (on github.com, under repositories, click "new" and name it [username].github.io).

Move the files and folders from your desktop back into where they were previously.

Open your terminal, navigate to your local [username].github.io, and run "git init".  This is the ONLY time you will have to run "git init".

Local Repo

(folders on your computer)

Remote Repo

(folders on your GitHub account)

Your HTML files should be in the same local folder as how they are placed in your remote repository.

You should be able to open a browser and type in the full path to your local html file and your site should appear. For example, in firefox, I can type in C:/Users/drennena/Documents/GitHub/drennen42.github.io/misc/githubexplained.html and this site will appear.

To emphasize and test that the paths in my local repo and my remote repo are the same, as long as the html file has been pushed properly to my github account (remote repo) I should be able to remove "C:/Users/drennena/Documents/GitHub/" from the address bar in firefox, leaving me with just "drennen42.github.io/misc/githubexplained.html" in the address bar, and hit Enter.  If I don't get a 404 error, I am now viewing this page remotely.

redpajama_set_name: RedPajamaGithub


text:
<application>
  <component name="FileTypeManager" version="17">
    <ignoreFiles list="*.hprof;*.pyc;*.pyo;*.rbc;*~;.DS_Store;.git;.hg;.svn;CVS;RCS;SCCS;__pycache__;_svn;rcs;vssver.scc;vssver2.scc;" />
    <extensionMap>
      <mapping pattern="www" type="ActionScript" />
      <mapping ext="vm" type="HTML" />
      <mapping pattern=".gitkeep" type="PLAIN_TEXT" />
    </extensionMap>
  </component>
</application>


text:
require 'paperclip'
require "dynamic_paperclip/errors"
require "dynamic_paperclip/config"
require "dynamic_paperclip/attachment"
require "dynamic_paperclip/has_attached_file"
require "dynamic_paperclip/paperclip_shim"
require "dynamic_paperclip/url_security"
require "dynamic_paperclip/style_naming"
require "dynamic_paperclip/attachment_registry"

require 'dynamic_paperclip/railtie' if defined?(Rails)

require 'active_support'
require 'active_support/core_ext/string/inflections'

module DynamicPaperclip
  extend self

  def config
    @@config ||= Config.new
  end
end


text:
module TypeStation
  class AdminBarPresenter < Presenter
    presents :page

    form_field :title, type: :text, label: 'Title'
    form_field :status, type: :select, label: 'Status', options: [['Hidden', 'hidden'], ['Draft', 'draft'], ['Published', 'published']]

  end
end


text:
package online.babylove.www.io.demo4;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class DataInputStreamDemo1 {
	public static void main(String[] args) throws IOException{
		String file = "demo/dataOutputStreamDemo.dat";
		IOUtil.printHex(file);
		DataInputStream dis = new DataInputStream(new FileInputStream(file));
		/*
		 * 这组类,是对"流"功能的扩展,可以更加方便的读取int,long,字符等类型数据
		 * DataInputStream会有一些更加方便的方法,如readInt()/readDouble()/readUTF()等
		 */
		int i = dis.readInt();
		System.out.println(i);
		i = dis.readInt();
		System.out.println(i);

		long l = dis.readLong();
		System.out.println(l);

		double d = dis.readDouble();
		System.out.println(d);

		String s = dis.readUTF();
		System.out.println(s);

		dis.close();
	}
}


text:
"""Contain all zeromq devices needed by OCT
"""
from __future__ import print_function, unicode_literals
import zmq

def forwarder(frontend, backend):
    """Simple pub/sub forwarder

    :param int frontend: fontend zeromq port
    :param int backend: backend zeromq port
    """
    try:
        context = zmq.Context()

        front_sub = context.socket(zmq.SUB)
        front_sub.bind("tcp://*:%d" % frontend)

        front_sub.setsockopt_string(zmq.SUBSCRIBE, "")

        back_pub = context.socket(zmq.PUB)
        back_pub.bind("tcp://*:%d" % backend)

        print("forwarder started, backend on port : %d\tfrontend on port: %d" % (backend, frontend))
        zmq.proxy(front_sub, back_pub)
    except Exception as e:
        print(e)
    finally:
        front_sub.close()
        back_pub.close()
        context.term()

def streamer(frontend, backend):
    """Simple push/pull streamer

    :param int frontend: fontend zeromq port
    :param int backend: backend zeromq port
    """
    try:
        context = zmq.Context()

        front_pull = context.socket(zmq.PULL)
        front_pull.set_hwm(0)
        front_pull.bind("tcp://*:%d" % frontend)

        back_push = context.socket(zmq.PUSH)
        back_push.bind("tcp://*:%d" % backend)

        print("streamer started, backend on port : %d\tfrontend on port: %d" % (backend, frontend))
        zmq.proxy(front_pull, back_push)
    except Exception as e:
        print(e)
    finally:
        front_pull.close()
        back_push.close()
        context.term()


text:
import Xhr from '../../../utils/xhr';

export default class ChartService {
    constructor($q, $http, localStorageService) {
        this.$q = $q;
        this.$http = $http;
        this.localStorageService = localStorageService;

        this.settings = {
            baseUrl: '/api/beatport/chart',
            ttl: 60 * 60 * 24 * 12
        };
    }

    getList(category) {
        return (new Xhr(this.$q, this.$http, this.localStorageService))
            .setTTL(this.settings.ttl)
            .setBaseUrl(this.settings.baseUrl)
            .get(category);
    }
}

ChartService.$inject = ['$q', '$http', 'localStorageService'];


text: <link rel="import" href="src/iron-selector/iron-selection.html">


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/gray_f0f0f0" android:state_pressed="true" />
    <item android:drawable="@color/gray_f0f0f0" android:state_focused="true" />
    <item android:drawable="@color/item_normal" />
</selector>


text:
package org.elasticsearch.painless;

import java.util.ArrayList;
import java.util.HashMap;

public class ConditionalTests extends ScriptTestCase {
    public void testBasic() {
        assertEquals(2, exec("boolean x = true; return x ? 2 : 3;"));
        assertEquals(3, exec("boolean x = false; return x ? 2 : 3;"));
        assertEquals(3, exec("boolean x = false, y = true; return x && y ? 2 : 3;"));
        assertEquals(2, exec("boolean x = true, y = true; return x && y ? 2 : 3;"));
        assertEquals(2, exec("boolean x = true, y = false; return x || y ? 2 : 3;"));
        assertEquals(3, exec("boolean x = false, y = false; return x || y ? 2 : 3;"));
    }

    public void testPrecedence() {
        assertEquals(4, exec("boolean x = false, y = true; return x ? (y ? 2 : 3) : 4;"));
        assertEquals(2, exec("boolean x = true, y = true; return x ? (y ? 2 : 3) : 4;"));
        assertEquals(3, exec("boolean x = true, y = false; return x ? (y ? 2 : 3) : 4;"));
        assertEquals(2, exec("boolean x = true, y = true; return x ? y ? 2 : 3 : 4;"));
        assertEquals(4, exec("boolean x = false, y = true; return x ? y ? 2 : 3 : 4;"));
        assertEquals(3, exec("boolean x = true, y = false; return x ? y ? 2 : 3 : 4;"));
        assertEquals(3, exec("boolean x = false, y = true; return x ? 2 : y ? 3 : 4;"));
        assertEquals(2, exec("boolean x = true, y = false; return x ? 2 : y ? 3 : 4;"));
        assertEquals(4, exec("boolean x = false, y = false; return x ? 2 : y ? 3 : 4;"));
        assertEquals(4, exec("boolean x = false, y = false; return (x ? true : y) ? 3 : 4;"));
        assertEquals(4, exec("boolean x = true, y = false; return (x ? false : y) ? 3 : 4;"));
        assertEquals(3, exec("boolean x = false, y = true; return (x ? false : y) ? 3 : 4;"));
        assertEquals(2, exec("boolean x = true, y = false; return (x ? false : y) ? (x ? 3 : 4) : x ? 2 : 1;"));
        assertEquals(2, exec("boolean x = true, y = false; return (x ? false : y) ? x ? 3 : 4 : x ? 2 : 1;"));
        assertEquals(4, exec("boolean x = false, y = true; return x ? false : y ? x ? 3 : 4 : x ? 2 : 1;"));
    }

    public void testAssignment() {
        assertEquals(4D, exec("boolean x = false; double z = x ? 2 : 4.0F; return z;"));
        assertEquals((byte)7, exec("boolean x = false; int y = 2; byte z = x ? (byte)y : 7; return z;"));
        assertEquals((byte)7, exec("boolean x = false; int y = 2; byte z = (byte)(x ? y : 7); return z;"));
        assertEquals(ArrayList.class, exec("boolean x = false; Object z = x ? new HashMap() : new ArrayList(); return z;").getClass());
    }

    public void testNullArguments() {
        assertEquals(null, exec("boolean b = false, c = true; Object x; Map y; return b && c ? x : y;"));
        assertEquals(HashMap.class,
                exec("boolean b = false, c = true; Object x; Map y = new HashMap(); return b && c ? x : y;").getClass());
    }

    public void testPromotion() {
        assertEquals(false, exec("boolean x = false; boolean y = true; return (x ? 2 : 4.0F) == (y ? 2 : 4.0F);"));
        assertEquals(false, exec("boolean x = false; boolean y = true; " +
            "return (x ? new HashMap() : new ArrayList()) == (y ? new HashMap() : new ArrayList());"));
    }

    public void testIncompatibleAssignment() {
        expectScriptThrows(ClassCastException.class, () -> {
            exec("boolean x = false; byte z = x ? 2 : 4.0F; return z;");
        });

        expectScriptThrows(ClassCastException.class, () -> {
            exec("boolean x = false; Map z = x ? 4 : (byte)7; return z;");
        });

        expectScriptThrows(ClassCastException.class, () -> {
            exec("boolean x = false; Map z = x ? new HashMap() : new ArrayList(); return z;");
        });

        expectScriptThrows(ClassCastException.class, () -> {
            exec("boolean x = false; int y = 2; byte z = x ? y : 7; return z;");
        });
    }
}


text:
import { Http, Response } from '@angular/http';
import { ApiSettings } from '../settings';
import { Observable } from 'rxjs';

export class BaseService {
    constructor(public _http: Http, public _apiSettings: ApiSettings) {
    }

    protected getData<T>(urlFragment: string, queryParams?: any): Observable<T[]> {
        return this._http.get(this.createApiUrl(urlFragment, queryParams))
            .map((res: Response) => res.json().results as T[])
            .catch(this.handleError);
    }

    protected getDataItem<T>(urlFragment: string, queryParams?: any): Observable<T> {
        return this._http.get(this.createApiUrl(urlFragment, queryParams))
            .map((res: Response) => res.json() as T)
            .catch(this.handleError);
    }

    protected encodeQueryParams(queryParams: any): string {
        let queryUrl: string[] = [];
        for (let qp in queryParams) {
            queryUrl.push(encodeURIComponent(qp) + '=' + encodeURIComponent(queryParams[qp]));
        }
        return '?' + queryUrl.join('&');
    }

    private createApiUrl(urlFragment: string, queryParams: any): string {
        return this._apiSettings.apiUrl.replace('{resource}', urlFragment)
            + (queryParams ? this.encodeQueryParams(queryParams) : '');
    }

    private handleError(error: Response) {
        return Observable.throw(error.json().error || 'Server error');
    }
}


text:
'use strict';

var request = require('request');
var AuthService = require('./authService');

function SapHelper(credentials) {
	this.credentials = credentials;

	this.httpUri = 'https://api-eu.sapanywhere.com:443';
	this.version = 'v1';

	this.authService = new AuthService(this.credentials);
}

SapHelper.prototype.execute = function (args, callback) {
	var that = this;
	var requestParams = formatParams(args.params);

	that.authService.accessToken()
		.then(function (accessToken) {
			var options = {
				method: args.method,
				url: that.httpUri + '/' + that.version + '/' + args.path
					+ '?' + requestParams + 'access_token=' + accessToken,
				headers: {
					'content-type': 'application/json',
				},
				body: JSON.stringify(args.body),
			};

			request(options, function (err, res, body) {
				var data;

				if (err && !res) return callback(err);

				if (body) { data = JSON.parse(body); }

				if (!err && res.statusCode >= 400) {
					err = new Error(res.statusCode + ' error' +
						(data && data.errorCode ? ': ' + data.message : ''));
				}

				return callback(err, data, res.statusCode, res.headers);
			});
		})
		.catch(callback);
}

function formatParams(params) {
	var requestParams = '';

	for (var key in params) {
		if (params.hasOwnProperty(key)) {
			requestParams += key + '=' + params[key] + '&';
		}
	}

	return requestParams;
}

module.exports = SapHelper;


text:
=============
exec-wrappers
=============

.. image:: https://img.shields.io/pypi/v/exec-wrappers.svg
    :target: https://pypi.python.org/pypi/exec-wrappers

.. image:: https://img.shields.io/pypi/pyversions/exec-wrappers.svg
    :target: https://pypi.python.org/pypi/exec-wrappers

.. image:: https://img.shields.io/pypi/l/exec-wrappers.svg
    :target: https://pypi.python.org/pypi/exec-wrappers

.. image:: https://travis-ci.org/gqmelo/exec-wrappers.svg?branch=master
    :target: https://travis-ci.org/gqmelo/exec-wrappers
    :alt: See Build Status on Travis CI

.. image:: https://ci.appveyor.com/api/projects/status/github/gqmelo/exec-wrappers?branch=master
    :target: https://ci.appveyor.com/project/gqmelo/exec-wrappers/branch/master
    :alt: See Build Status on AppVeyor

.. image:: https://codecov.io/gh/gqmelo/exec-wrappers/branch/master/graph/badge.svg
  :target: https://codecov.io/gh/gqmelo/exec-wrappers

.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
    :target: https://github.com/ambv/black

A command line tool to create wrappers around executable files

Rationale
---------

``exec-wrappers`` is useful whenever you need a single executable file, but have to do some setup
before executing it.

If you develop using some kind of environment isolation like ``conda``, ``schroot``,
``virtualenv`` you probably wanted to configure a GUI application like an IDE to use the executables
available inside these environments.

But you normally have to create a script that do some setup/activation step and then run the command
but creating such a script for each executable is tedious.

``exec-wrappers`` helps automating that as it detects executable files and create a wrapper for each
of them. It also already provides some wrappers for common tools.

Also, as the wrappers are intended to be used non-interactively, they are normally much simpler than
the interactive counterpart.

For example, the conda wrappers are much faster than doing an activate and executing the command:

- Regular activate:

.. code-block:: bash

    $ echo 'source activate test 2> /dev/null; "$@"' > /tmp/activate-and-run && chmod a+x /tmp/activate-and-run
    $ time /tmp/activate-and-run python --version
    Python 2.7.11 :: Continuum Analytics, Inc.

    real    0m0.354s
    user    0m0.288s
    sys 0m0.040s

- Using python wrapper created by ``exec-wrappers``:

.. code-block:: bash

    $ time /tmp/conda_wrappers/python --version
    Python 2.7.11 :: Continuum Analytics, Inc.

    real    0m0.003s
    user    0m0.000s
    sys 0m0.000s

Having a low overhead is very important if you are executing the command non-interactively.

Features
--------

- automatically detect executables in a given directory
- wrappers written in plain shell and batch scripts
- low overhead (as low as possible)
- built-in wrappers for common tools

Requirements
------------

``python`` is the only dependency to create wrappers.
To properly use the generated wrappers you need the tool used by the wrapper (conda, schroot, etc.).

Installation
------------

.. code-block::

    $ python setup.py install

How it works
------------

Creating `conda`_ wrappers:

.. code-block:: bash

    $ create-wrappers  -t conda --bin-dir ~/miniconda/envs/test/bin --dest-dir /tmp/conda_wrappers --conda-env-dir ~/miniconda/envs/test

This will create in ``/tmp/conda_wrappers`` a wrapper for each executable found in
``~/miniconda/envs/test/bin``.
So if you run the python wrapper:

.. code-block:: bash

    $ /tmp/conda_wrappers/python -c "import sys; print(sys.executable)"
    /home/username/miniconda/envs/test/bin/python

It will actually activate the conda environment and set necessary variables, and then execute the
real ``python`` interpreter. So you can use the wrapper to configure you IDE, for example.

Also a ``run-in`` script will be created, which you can use to run any arbitrary command:

.. code-block:: bash

    $ /tmp/conda_wrappers/run-in bash -c 'echo $CONDA_DEFAULT_ENV'
    /home/username/miniconda/envs/test

Examples
--------

- conda:

.. code-block:: bash

    $ create-wrappers  -t conda -b ~/miniconda/envs/test/bin -d /tmp/conda_wrappers --conda-env-dir ~/miniconda/envs/test

- virtualenv:

.. code-block:: bash

    $ create-wrappers  -t virtualenv -b ~/python3-env/bin -d /tmp/virtualenv_wrappers --virtual-env-dir ~/python3-env

- schroot:

.. code-block:: bash

    $ create-wrappers  -t schroot -b ~/chroots/centos5/bin -d /tmp/schroot_wrappers --schroot-name centos5

.. code-block:: bash

    $ create-wrappers  -t schroot -b ~/chroots/centos5/bin -d /tmp/schroot_wrappers --schroot-name centos5 --schroot-options="-p -d /"

- custom:

.. code-block:: bash

    $ echo -e '#!/bin/sh\necho "$@"' > /tmp/custom-script && chmod a+x /tmp/custom-script
    $ create-wrappers  -t custom --custom-script=/tmp/custom-script -b /usr/bin -d /tmp/custom_wrappers

- wrap only specified files:

.. code-block:: bash

    $ create-wrappers  -t schroot -f gcc:gdb -d /tmp/schroot_wrappers --schroot-name centos5

- chain multiple wrappers:

.. code-block:: bash

    $ create-wrappers  -t conda -b ~/miniconda/envs/test/bin -d /tmp/conda_wrappers --conda-env-dir ~/miniconda/envs/test
    $ create-wrappers  -t schroot -b /tmp/conda_wrappers -d /tmp/schroot_wrappers --schroot-name centos5

License
-------

Distributed under the terms of the `MIT`_ license, ``exec-wrappers`` is free and open source software

Issues
------

If you encounter any problems, please `file an issue`_ along with a detailed description.

.. _`MIT`: http://opensource.org/licenses/MIT
.. _`file an issue`: https://github.com/gqmelo/exec-wrappers/issues
.. _`conda`: http://conda.pydata.org/miniconda.html


text:
import os

if os.environ['GENERATOR3_VERSION'] == '0.1':
    raise RuntimeError

del os


text:
'use strict';

var F8SessionCell = require('F8SessionCell');
var FilterSessions = require('./filterSessions');
var Navigator = require('Navigator');
var React = require('React');
var SessionsSectionHeader = require('./SessionsSectionHeader');
var PureListView = require('../../common/PureListView');
var groupSessions = require('./groupSessions');

import type {Session} from '../../reducers/sessions';

type Props = {
  day: number;
  sessions: Array<Session>;
  navigator: Navigator;
  renderEmptyList?: (day: number) => ReactElement;
};

class ScheduleListView extends React.Component {
  props: Props;
  _innerRef: ?PureListView;

  constructor(props: Props) {
    super(props);
    this.state = {
      todaySessions: groupSessions(FilterSessions.byDay(props.sessions, props.day)),
    };

    this._innerRef = null;

    this.renderSectionHeader = this.renderSectionHeader.bind(this);
    this.renderRow = this.renderRow.bind(this);
    this.renderEmptyList = this.renderEmptyList.bind(this);
    this.storeInnerRef = this.storeInnerRef.bind(this);
  }

  componentWillReceiveProps(nextProps: Props) {
    if (nextProps.sessions !== this.props.sessions ||
        nextProps.day !== this.props.day) {
      this.setState({
        todaySessions: groupSessions(FilterSessions.byDay(nextProps.sessions, nextProps.day)),
      });
    }
  }

  render() {
    return (
      <PureListView
        ref={this.storeInnerRef}
        data={this.state.todaySessions}
        renderRow={this.renderRow}
        renderSectionHeader={this.renderSectionHeader}
        {...this.props}
        renderEmptyList={this.renderEmptyList}
      />
    );
  }

  renderSectionHeader(sectionData: any, sectionID: string) {
    return <SessionsSectionHeader title={sectionID} />;
  }

  renderRow(session: Session, day: number) {
    return (
      <F8SessionCell
        onPress={() => this.openSession(session, day)}
        session={session}
      />
    );
  }

  renderEmptyList(): ?ReactElement {
    const {renderEmptyList} = this.props;
    return renderEmptyList && renderEmptyList(this.props.day);
  }

  openSession(session: Session, day: number) {
    this.props.navigator.push({
      day,
      session,
      allSessions: this.state.todaySessions,
    });
  }

  storeInnerRef(ref: ?PureListView) {
    this._innerRef = ref;
  }

  scrollTo(...args: Array<any>) {
    this._innerRef && this._innerRef.scrollTo(...args);
  }

  getScrollResponder(): any {
    return this._innerRef && this._innerRef.getScrollResponder();
  }
}

module.exports = ScheduleListView;


text:
@implementation TwitterPostXibTableViewCell

-(void) setDataFromTwitterXib :(TwitterPost*) twitterItems
{
    TwitterCellXib * customView = _twitterCustomView;
    customView.userNameLabel.text = twitterItems.username;
    customView.timeLabel.text = twitterItems.created_at;
    customView.textPostView.text = twitterItems.text;
    NSString * commentCount = [NSString stringWithFormat:@"%ld",(long)twitterItems.commentsCount];
    NSString * likesCount = [NSString stringWithFormat:@"%ld",(long)twitterItems.likesCount];
    NSString * retweetCount = [NSString stringWithFormat:@"%ld",(long)twitterItems.retweetCount];
    customView.commentsCountLabel.text = commentCount;
    customView.repostsCountLabel.text = retweetCount;
    customView.likesCountLabel.text  = likesCount;

    [customView.avatarView sd_setImageWithURL:twitterItems.avatarURL placeholderImage:[UIImage imageNamed:@"avatar.png"]];
    if (twitterItems.isLiked == YES) {
        [customView.likeButton setImage:[UIImage imageNamed:@"LikeRedMini"] forState:UIControlStateNormal];
    }else{
        [customView.likeButton setImage:[UIImage imageNamed:@"LikeBlueMini"] forState:UIControlStateNormal];
    }
    if (twitterItems.isRetweeted == YES) {
        [customView.repostButton setImage:[UIImage imageNamed:@"RepostRedMini"] forState:UIControlStateNormal];
    }
    else
    {
        [customView.repostButton setImage:[UIImage imageNamed:@"RepostBlueMini"] forState:UIControlStateNormal];

    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    TwitterCellXib * customCellView  = [TwitterCellXib loadFromNib];
    customCellView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:customCellView];
    _twitterCustomView = customCellView;
    customCellView.textPostView.delegate=self;
//    customCellView.textPostView.editable = NO;
//    customCellView.textPostView.selectable = YES;
//    customCellView.textPostView.userInteractionEnabled = NO;
//    customCellView.textPostView.dataDetectorTypes = UIDataDetectorTypeLink;
    [self.contentView.topAnchor constraintEqualToAnchor:customCellView.topAnchor].active = YES;
    [self.contentView.layoutMarginsGuide.bottomAnchor constraintEqualToAnchor:customCellView.bottomAnchor].active = YES;
    [self.contentView.readableContentGuide.leadingAnchor constraintEqualToAnchor:customCellView.leadingAnchor].active = YES;
    [self.contentView.readableContentGuide.trailingAnchor constraintEqualToAnchor:customCellView.trailingAnchor].active = YES;

    [customCellView.commentButton addTarget:self action:@selector(comment) forControlEvents:UIControlEventTouchUpInside];
    [customCellView.repostButton addTarget:self action:@selector(repost) forControlEvents:UIControlEventTouchUpInside];
    [customCellView.likeButton addTarget:self action:@selector(like) forControlEvents:UIControlEventTouchUpInside];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)comment {
    id<TwitterPostXibTableViewCellDelegate> delegate = self.delegate;
    if ([delegate respondsToSelector:@selector(twitterPostTableViewCellDidTapCommentButton:)]) {
        [delegate twitterPostTableViewCellDidTapCommentButton:self];
    }
}

- (void)repost {
    id<TwitterPostXibTableViewCellDelegate> delegate = self.delegate;
    if ([delegate respondsToSelector:@selector(twitterPostTableViewCellDidTapRepostButton:)]) {
        [delegate twitterPostTableViewCellDidTapRepostButton:self];
    }
}

- (void)like {
    id<TwitterPostXibTableViewCellDelegate> delegate = self.delegate;
    if ([delegate respondsToSelector:@selector(twitterPostTableViewCellDidTapLikeButton:)]) {
        [delegate twitterPostTableViewCellDidTapLikeButton:self];
    }
}

-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    return YES;
}
@end


text:
package kieker.test.common.junit.api.flow.trace;

import java.nio.ByteBuffer;

import org.junit.Assert;
import org.junit.Test;

import kieker.common.record.flow.trace.ConstructionEvent;
import kieker.common.util.registry.IRegistry;
import kieker.common.util.registry.Registry;

import kieker.test.common.junit.AbstractKiekerTest;
import kieker.test.common.junit.util.APIEvaluationFunctions;

/**
 * Test API of {@link kieker.common.record.flow.trace.ConstructionEvent}.
 *
 * @author API Checker
 *
 * @since 1.12
 */
public class TestConstructionEventPropertyOrder extends AbstractKiekerTest {

	/**
	 * All numbers and values must be pairwise unequal. As the string registry also uses integers,
	 * we must guarantee this criteria by starting with 1000 instead of 0.
	 */
	/** Constant value parameter for timestamp. */
	private static final long PROPERTY_TIMESTAMP = 2L;
	/** Constant value parameter for traceId. */
	private static final long PROPERTY_TRACE_ID = 3L;
	/** Constant value parameter for orderIndex. */
	private static final int PROPERTY_ORDER_INDEX = 1001;
	/** Constant value parameter for classSignature. */
	private static final String PROPERTY_CLASS_SIGNATURE = "<classSignature>";
	/** Constant value parameter for objectId. */
	private static final int PROPERTY_OBJECT_ID = 1002;

	/**
	 * Empty constructor.
	 */
	public TestConstructionEventPropertyOrder() {
		// Empty constructor for test class.
	}

	/**
	 * Test property order processing of {@link kieker.common.record.flow.trace.ConstructionEvent} constructors and
	 * different serialization routines.
	 */
	@Test
	public void testConstructionEventPropertyOrder() { // NOPMD
		final IRegistry<String> stringRegistry = this.makeStringRegistry();
		final Object[] values = {
			PROPERTY_TIMESTAMP,
			PROPERTY_TRACE_ID,
			PROPERTY_ORDER_INDEX,
			PROPERTY_CLASS_SIGNATURE,
			PROPERTY_OBJECT_ID,
		};
		final ByteBuffer inputBuffer = APIEvaluationFunctions.createByteBuffer(ConstructionEvent.SIZE,
			this.makeStringRegistry(), values);

		final ConstructionEvent recordInitParameter = new ConstructionEvent(
			PROPERTY_TIMESTAMP,
			PROPERTY_TRACE_ID,
			PROPERTY_ORDER_INDEX,
			PROPERTY_CLASS_SIGNATURE,
			PROPERTY_OBJECT_ID
		);
		final ConstructionEvent recordInitBuffer = new ConstructionEvent(inputBuffer, this.makeStringRegistry());
		final ConstructionEvent recordInitArray = new ConstructionEvent(values);

		this.assertConstructionEvent(recordInitParameter);
		this.assertConstructionEvent(recordInitBuffer);
		this.assertConstructionEvent(recordInitArray);

		// test to array
		final Object[] valuesParameter = recordInitParameter.toArray();
		Assert.assertArrayEquals("Result array of record initialized by parameter constructor differs from predefined array.", values, valuesParameter);
		final Object[] valuesBuffer = recordInitBuffer.toArray();
		Assert.assertArrayEquals("Result array of record initialized by buffer constructor differs from predefined array.", values, valuesBuffer);
		final Object[] valuesArray = recordInitArray.toArray();
		Assert.assertArrayEquals("Result array of record initialized by parameter constructor differs from predefined array.", values, valuesArray);

		// test write to buffer
		final ByteBuffer outputBufferParameter = ByteBuffer.allocate(ConstructionEvent.SIZE);
		recordInitParameter.writeBytes(outputBufferParameter, stringRegistry);
		Assert.assertArrayEquals("Byte buffer do not match (parameter).", inputBuffer.array(), outputBufferParameter.array());

		final ByteBuffer outputBufferBuffer = ByteBuffer.allocate(ConstructionEvent.SIZE);
		recordInitParameter.writeBytes(outputBufferBuffer, stringRegistry);
		Assert.assertArrayEquals("Byte buffer do not match (buffer).", inputBuffer.array(), outputBufferBuffer.array());

		final ByteBuffer outputBufferArray = ByteBuffer.allocate(ConstructionEvent.SIZE);
		recordInitParameter.writeBytes(outputBufferArray, stringRegistry);
		Assert.assertArrayEquals("Byte buffer do not match (array).", inputBuffer.array(), outputBufferArray.array());
	}

	/**
	 * Assertions for ConstructionEvent.
	 */
	private void assertConstructionEvent(final ConstructionEvent record) {
		Assert.assertEquals("'timestamp' value assertion failed.", record.getTimestamp(), PROPERTY_TIMESTAMP);
		Assert.assertEquals("'traceId' value assertion failed.", record.getTraceId(), PROPERTY_TRACE_ID);
		Assert.assertEquals("'orderIndex' value assertion failed.", record.getOrderIndex(), PROPERTY_ORDER_INDEX);
		Assert.assertEquals("'classSignature' value assertion failed.", record.getClassSignature(), PROPERTY_CLASS_SIGNATURE);
		Assert.assertEquals("'objectId' value assertion failed.", record.getObjectId(), PROPERTY_OBJECT_ID);
	}

	/**
	 * Build a populated string registry for all tests.
	 */
	private IRegistry<String> makeStringRegistry() {
		final IRegistry<String> stringRegistry = new Registry<String>();
		// get registers string and returns their ID
		stringRegistry.get(PROPERTY_CLASS_SIGNATURE);

		return stringRegistry;
	}
}


text:
module Softlayer
  module Scale
    class Policy
      class Trigger
        class ResourceUse < Softlayer::Scale::Policy::Trigger
          SERVICE = 'SoftLayer_Scale_Policy_Trigger_ResourceUse'
          autoload :Watch, 'softlayer/scale/policy/trigger/resource_use/watch'
          attr_accessor :watch_count
          attr_accessor :watches

          # template_object
          def self.create_object(message)
            request(:create_object, Softlayer::Scale::Policy::Trigger::ResourceUse, message)
          end

          def delete_object
            request(:delete_object, Boolean)
          end

          # template_object
          def edit_object(message)
            request(:edit_object, Boolean, message)
          end

          def get_object
            request(:get_object, Softlayer::Scale::Policy::Trigger::ResourceUse)
          end

          def get_scale_policy
            request(:get_scale_policy, Softlayer::Scale::Policy)
          end

          def get_type
            request(:get_type, Softlayer::Scale::Policy::Trigger::Type)
          end

          def get_watches
            request(:get_watches, Array[Softlayer::Scale::Policy::Trigger::ResourceUse::Watch])
          end

          class Representer < Softlayer::Scale::Policy::Trigger::Representer
            include Representable::Hash
            include Representable::Coercion
            property :watch_count, type: BigDecimal
          end
        end
      end
    end
  end
end


text:
package com.izforge.izpack.installer;

import com.izforge.izpack.*;
import com.izforge.izpack.event.InstallerListener;
import com.izforge.izpack.io.CorruptVolumeException;
import com.izforge.izpack.io.FileSpanningInputStream;
import com.izforge.izpack.io.FileSpanningOutputStream;
import com.izforge.izpack.io.VolumeNotFoundException;
import com.izforge.izpack.panels.NextMediaDialog;
import com.izforge.izpack.util.*;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

/**
 * Unpacker class for a multi volume installation.
 *
 * @author Dennis Reil, <izpack@reil-online.de>
 */
public class MultiVolumeUnpacker extends UnpackerBase
{
    public MultiVolumeUnpacker(AutomatedInstallData idata, AbstractUIProgressHandler handler)
    {
        super(idata, handler);
    }

    protected File enterNextMediaMessage(String volumename, boolean lastcorrupt)
    {
        if (lastcorrupt)
        {
            Component parent = null;
            if ((this.handler != null) && (this.handler instanceof IzPanel))
            {
                parent = ((IzPanel) this.handler).getInstallerFrame();
            }
            JOptionPane.showMessageDialog(parent, idata.langpack
                    .getString("nextmedia.corruptmedia"), idata.langpack
                    .getString("nextmedia.corruptmedia.title"), JOptionPane.ERROR_MESSAGE);
        }
        Debug.trace("Enter next media: " + volumename);

        File nextvolume = new File(volumename);
        NextMediaDialog nmd = null;

        while (!nextvolume.exists() || lastcorrupt)
        {
            if ((this.handler != null) && (this.handler instanceof IzPanel))
            {
                InstallerFrame installframe = ((IzPanel) this.handler).getInstallerFrame();
                nmd = new NextMediaDialog(installframe, idata, volumename);
            }
            else
            {
                nmd = new NextMediaDialog(null, idata, volumename);
            }
            nmd.setVisible(true);
            String nextmediainput = nmd.getNextMedia();
            if (nextmediainput != null)
            {
                nextvolume = new File(nextmediainput);
            }
            else
            {
                Debug.trace("Input from NextMediaDialog was null");
                nextvolume = new File(volumename);
            }
            // selection equal to last selected which was corrupt?
            if (!(volumename.equals(nextvolume.getAbsolutePath()) && lastcorrupt))
            {
                lastcorrupt = false;
            }
        }
        return nextvolume;
    }

    protected File enterNextMediaMessage(String volumename)
    {
        return enterNextMediaMessage(volumename, false);
    }

    /**
     * The run method.
     */
    public void run()
    {
        addToInstances();
        try
        {
            //
            // Initialisations
            FileOutputStream out = null;
            ArrayList<ParsableFile> parsables = new ArrayList<ParsableFile>();
            ArrayList<ExecutableFile> executables = new ArrayList<ExecutableFile>();
            ArrayList<UpdateCheck> updatechecks = new ArrayList<UpdateCheck>();
            List packs = idata.selectedPacks;
            int npacks = packs.size();
            Debug.trace("Unpacker starting");
            handler.startAction("Unpacking", npacks);
            udata = UninstallData.getInstance();
            // Custom action listener stuff --- load listeners ----
            List[] customActions = getCustomActions();
            // Custom action listener stuff --- beforePacks ----
            informListeners(customActions, InstallerListener.BEFORE_PACKS, idata, npacks, handler);
            // vs = new VariableSubstitutor(idata.getVariables());
            packs = idata.selectedPacks;
            npacks = packs.size();
            if (npacks == 0)
            {
                if (performInterrupted())
                { // Interrupt was initiated; perform it.
                    return;
                }

                // Custom action listener stuff --- afterPacks ----
                informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
                if (performInterrupted())
                { // Interrupt was initiated; perform it.
                    return;
                }

                // The end :-)
                handler.stopAction();
                return;
            }
            InputStream in = MultiVolumeUnpacker.class
                    .getResourceAsStream(FileSpanningOutputStream.VOLUMES_INFO);
            // get volumes metadata
            ObjectInputStream metadataobj = new ObjectInputStream(in);
            // TODO: create MetadataObject
            int volumes = metadataobj.readInt();
            String volumename = metadataobj.readUTF();
            Debug.trace("Reading from " + volumes + " volumes with basename " + volumename + " ");
            metadataobj.close();
            String mediadirectory = MultiVolumeInstaller.getMediadirectory();
            if ((mediadirectory == null) || (mediadirectory.length() <= 0))
            {
                Debug.trace("Mediadirectory wasn't set.");
                mediadirectory = System.getProperty("java.io.tmpdir"); // try the temporary
                // directory
            }
            Debug.trace("Using mediadirectory = " + mediadirectory);
            File volume = new File(mediadirectory + File.separator + volumename);
            if (!volume.exists())
            {
                volume = enterNextMediaMessage(volume.getAbsolutePath());
            }
            FileSpanningInputStream fin = new FileSpanningInputStream(volume, volumes);

            // We unpack the selected packs
            for (int i = 0; i < npacks; i++)
            {
                // We get the pack stream
                int n = idata.allPacks.indexOf(packs.get(i));

                in = MultiVolumeUnpacker.class.getResourceAsStream("/packs/pack" + n);

                // Custom action listener stuff --- beforePack ----
                informListeners(customActions, InstallerListener.BEFORE_PACK, packs.get(i),
                        npacks, handler);
                // find next Entry
                ObjectInputStream objIn = new ObjectInputStream(in);
                // We unpack the files
                int nfiles = objIn.readInt();

                // We get the internationalized name of the pack
                final Pack pack = ((Pack) packs.get(i));
                // evaluate condition
                if (pack.hasCondition() && (rules != null))
                {
                    if (!rules.isConditionTrue(pack.getCondition()))
                    {
                        // skip pack, condition is not fullfilled.
                        continue;
                    }
                }
                String stepname = pack.name;// the message to be passed to the
                // installpanel
                if (langpack != null && !(pack.id == null || "".equals(pack.id)))
                {

                    final String name = langpack.getString(pack.id);
                    if (name != null && !"".equals(name))
                    {
                        stepname = name;
                    }
                }
                handler.nextStep(stepname, i + 1, nfiles);
                for (int j = 0; j < nfiles; j++)
                {
                    // We read the header
                    XPackFile pf = (XPackFile) objIn.readObject();
                    if (pf.hasCondition() && (rules != null))
                    {
                        if (!rules.isConditionTrue(pf.getCondition()))
                        {
                            // skip file, condition is false
                            continue;
                        }
                    }
                    if (OsConstraint.oneMatchesCurrentSystem(pf.osConstraints()))
                    {
                        // We translate & build the path
                        String path = IoHelper.translatePath(pf.getTargetPath(), vs);
                        File pathFile = new File(path);
                        File dest = pathFile;
                        if (!pf.isDirectory())
                        {
                            dest = pathFile.getParentFile();
                        }

                        if (!dest.exists())
                        {
                            // If there are custom actions which would be called
                            // at
                            // creating a directory, create it recursively.
                            List fileListeners = customActions[customActions.length - 1];
                            if (fileListeners != null && fileListeners.size() > 0)
                            {
                                mkDirsWithEnhancement(dest, pf, customActions);
                            }
                            else
                            // Create it in on step.
                            {
                                if (!dest.mkdirs())
                                {
                                    handler.emitError("Error creating directories",
                                            "Could not create directory\n" + dest.getPath());
                                    handler.stopAction();
                                    this.result = false;
                                    return;
                                }
                            }
                        }

                        if (pf.isDirectory())
                        {
                            continue;
                        }

                        // Custom action listener stuff --- beforeFile ----
                        informListeners(customActions, InstallerListener.BEFORE_FILE, pathFile, pf,
                                null);
                        // We add the path to the log,
                        udata.addFile(path, pack.uninstall);

                        handler.progress(j, path);

                        // if this file exists and should not be overwritten,
                        // check
                        // what to do
                        if ((pathFile.exists()) && (pf.override() != PackFile.OVERRIDE_TRUE))
                        {
                            boolean overwritefile = false;

                            // don't overwrite file if the user said so
                            if (pf.override() != PackFile.OVERRIDE_FALSE)
                            {
                                if (pf.override() == PackFile.OVERRIDE_TRUE)
                                {
                                    overwritefile = true;
                                }
                                else if (pf.override() == PackFile.OVERRIDE_UPDATE)
                                {
                                    // check mtime of involved files
                                    // (this is not 100% perfect, because the
                                    // already existing file might
                                    // still be modified but the new installed
                                    // is just a bit newer; we would
                                    // need the creation time of the existing
                                    // file or record with which mtime
                                    // it was installed...)
                                    overwritefile = (pathFile.lastModified() < pf.lastModified());
                                }
                                else
                                {
                                    int def_choice = -1;

                                    if (pf.override() == PackFile.OVERRIDE_ASK_FALSE)
                                    {
                                        def_choice = AbstractUIHandler.ANSWER_NO;
                                    }
                                    if (pf.override() == PackFile.OVERRIDE_ASK_TRUE)
                                    {
                                        def_choice = AbstractUIHandler.ANSWER_YES;
                                    }

                                    int answer = handler.askQuestion(idata.langpack
                                            .getString("InstallPanel.overwrite.title")
                                            + " - " + pathFile.getName(), idata.langpack
                                            .getString("InstallPanel.overwrite.question")
                                            + pathFile.getAbsolutePath(),
                                            AbstractUIHandler.CHOICES_YES_NO, def_choice);

                                    overwritefile = (answer == AbstractUIHandler.ANSWER_YES);
                                }

                            }

                            if (!overwritefile)
                            {
                                if (!pf.isBackReference() && !((Pack) packs.get(i)).loose)
                                {
                                    // objIn.skip(pf.length());
                                }
                                continue;
                            }

                        }

                        // We copy the file
                        out = new FileOutputStream(pathFile);
                        byte[] buffer = new byte[5120];
                        long bytesCopied = 0;
                        // InputStream pis = objIn;
                        InputStream pis = fin;

                        if (((Pack) packs.get(i)).loose)
                        {
                            pis = new FileInputStream(pf.sourcePath);
                        }

                        // read in the position of this file
                        // long fileposition = objIn.readLong();
                        long fileposition = pf.getArchivefileposition();

                        while (fin.getFilepointer() < fileposition)
                        {
                            // we have to skip some bytes
                            Debug.trace("Skipping bytes to get to file " + pathFile.getName()
                                    + " (" + fin.getFilepointer() + "<" + fileposition
                                    + ") target is: " + (fileposition - fin.getFilepointer()));
                            try
                            {
                                fin.skip(fileposition - fin.getFilepointer());
                                break;
                            }
                            catch (VolumeNotFoundException vnfe)
                            {
                                File nextmedia = enterNextMediaMessage(vnfe.getVolumename());
                                fin.setVolumename(nextmedia.getAbsolutePath());
                            }
                            catch (CorruptVolumeException cve)
                            {
                                Debug.trace("corrupt media found. magic number is not correct");
                                File nextmedia = enterNextMediaMessage(cve.getVolumename(), true);
                                fin.setVolumename(nextmedia.getAbsolutePath());
                            }
                        }

                        if (fin.getFilepointer() > fileposition)
                        {
                            Debug.trace("Error, can't access file in pack.");
                        }

                        while (bytesCopied < pf.length())
                        {
                            try
                            {
                                if (performInterrupted())
                                { // Interrupt was initiated; perform it.
                                    out.close();
                                    if (pis != objIn)
                                    {
                                        pis.close();
                                    }
                                    return;
                                }
                                int maxBytes = (int) Math.min(pf.length() - bytesCopied,
                                        buffer.length);

                                int bytesInBuffer = pis.read(buffer, 0, maxBytes);
                                if (bytesInBuffer == -1)
                                {
                                    Debug.trace("Unexpected end of stream (installer corrupted?)");
                                    throw new IOException(
                                            "Unexpected end of stream (installer corrupted?)");
                                }

                                out.write(buffer, 0, bytesInBuffer);

                                bytesCopied += bytesInBuffer;
                            }
                            catch (VolumeNotFoundException vnfe)
                            {
                                File nextmedia = enterNextMediaMessage(vnfe.getVolumename());
                                fin.setVolumename(nextmedia.getAbsolutePath());
                            }
                            catch (CorruptVolumeException cve)
                            {
                                Debug.trace("corrupt media found. magic number is not correct");
                                File nextmedia = enterNextMediaMessage(cve.getVolumename(), true);
                                fin.setVolumename(nextmedia.getAbsolutePath());
                            }
                        }
                        // Cleanings
                        out.close();
                        // if (pis != objIn) pis.close();

                        // Set file modification time if specified
                        if (pf.lastModified() >= 0)
                        {
                            pathFile.setLastModified(pf.lastModified());
                        }
                        // Custom action listener stuff --- afterFile ----
                        informListeners(customActions, InstallerListener.AFTER_FILE, pathFile, pf,
                                null);
                    }
                    else
                    {
                        if (!pf.isBackReference())
                        {
                            // objIn.skip(pf.length());
                        }
                    }
                }
                // Load information about parsable files
                int numParsables = objIn.readInt();
                Debug.trace("Looking for parsables");
                for (int k = 0; k < numParsables; k++)
                {
                    ParsableFile pf = null;
                    while (true)
                    {
                        try
                        {
                            pf = (ParsableFile) objIn.readObject();
                            break;
                        }
                        catch (VolumeNotFoundException vnfe)
                        {
                            File nextmedia = enterNextMediaMessage(vnfe.getVolumename());
                            fin.setVolumename(nextmedia.getAbsolutePath());
                        }
                        catch (CorruptVolumeException cve)
                        {
                            Debug.trace("corrupt media found. magic number is not correct");
                            File nextmedia = enterNextMediaMessage(cve.getVolumename(), true);
                            fin.setVolumename(nextmedia.getAbsolutePath());
                        }
                        catch (EOFException eofe)
                        {
                            File nextmedia = enterNextMediaMessage("");
                            fin.setVolumename(nextmedia.getAbsolutePath());
                        }
                    }
                    if (pf.hasCondition() && (rules != null))
                    {
                        if (!rules.isConditionTrue(pf.getCondition()))
                        {
                            // skip parsable, condition is false
                            continue;
                        }
                    }
                    pf.path = IoHelper.translatePath(pf.path, vs);
                    Debug.trace("Found parsable: " + pf.path);
                    parsables.add(pf);
                }

                // Load information about executable files
                int numExecutables = objIn.readInt();
                Debug.trace("Looking for executables...");
                for (int k = 0; k < numExecutables; k++)
                {
                    ExecutableFile ef = (ExecutableFile) objIn.readObject();
                    if (ef.hasCondition() && (rules != null))
                    {
                        if (!rules.isConditionTrue(ef.getCondition()))
                        {
                            // skip, condition is false
                            continue;
                        }
                    }
                    ef.path = IoHelper.translatePath(ef.path, vs);
                    if (null != ef.argList && !ef.argList.isEmpty())
                    {
                        String arg = null;
                        for (int j = 0; j < ef.argList.size(); j++)
                        {
                            arg = ef.argList.get(j);
                            arg = IoHelper.translatePath(arg, vs);
                            ef.argList.set(j, arg);
                        }
                    }
                    Debug.trace("Found executable: " + ef.path);
                    executables.add(ef);
                    if (ef.executionStage == ExecutableFile.UNINSTALL)
                    {
                        udata.addExecutable(ef);
                    }
                }
                // Custom action listener stuff --- uninstall data ----
                handleAdditionalUninstallData(udata, customActions);

                // Load information about updatechecks
                int numUpdateChecks = objIn.readInt();
                Debug.trace("Looking for updatechecks");
                for (int k = 0; k < numUpdateChecks; k++)
                {
                    UpdateCheck uc = (UpdateCheck) objIn.readObject();
                    Debug.trace("found updatecheck");
                    updatechecks.add(uc);
                }

                // objIn.close();

                if (performInterrupted())
                { // Interrupt was initiated; perform it.
                    return;
                }

                // Custom action listener stuff --- afterPack ----
                informListeners(customActions, InstallerListener.AFTER_PACK, packs.get(i),
                        i, handler);
            }
            Debug.trace("Trying to parse files");
            // We use the scripts parser
            ScriptParser parser = new ScriptParser(parsables, vs);
            parser.parseFiles();
            Debug.trace("parsed files");
            if (performInterrupted())
            { // Interrupt was initiated; perform it.
                return;
            }
            Debug.trace("Trying to execute files");
            // We use the file executor
            FileExecutor executor = new FileExecutor(executables);
            if (executor.executeFiles(ExecutableFile.POSTINSTALL, handler) != 0)
            {
                handler.emitError("File execution failed", "The installation was not completed");
                this.result = false;
                Debug.trace("File execution failed");
            }

            if (performInterrupted())
            { // Interrupt was initiated; perform it.
                return;
            }
            Debug.trace("Create uninstaller");
            // We put the uninstaller (it's not yet complete...)
            putUninstaller();
            Debug.trace("Uninstaller created");
            // update checks _after_ uninstaller was put, so we don't delete it
            Debug.trace("Perform updateChecks");
            performUpdateChecks(updatechecks);
            Debug.trace("updatechecks performed.");
            if (performInterrupted())
            { // Interrupt was initiated; perform it.
                return;
            }

            // Custom action listener stuff --- afterPacks ----
            informListeners(customActions, InstallerListener.AFTER_PACKS, idata, handler, null);
            if (performInterrupted())
            { // Interrupt was initiated; perform it.
                return;
            }

            // write installation information
            writeInstallationInformation();

            this.writeConfigInformation();
            // The end :-)
            handler.stopAction();
            Debug.trace("Installation complete");
        }
        catch (Exception err)
        {
            // TODO: finer grained error handling with useful error messages
            handler.stopAction();
            handler.emitError("An error occured", err.toString());
            err.printStackTrace();
            Debug.trace("Error while installing: " + err.toString());
            this.result = false;
        }
        finally
        {
            removeFromInstances();
        }
    }

    protected void writeConfigInformation()
    {
        // save the variables
        Properties installerproperties = idata.getVariables();
        Enumeration installerpropertieskeys = installerproperties.keys();
        try
        {
            String installpath = idata.getVariable("INSTALL_PATH");
            PrintWriter pw = new PrintWriter(new FileOutputStream(installpath + File.separator
                    + "installer.properties"));
            pw.println("# Installer properties, written by MultiVolumeUnpacker.");
            while (installerpropertieskeys.hasMoreElements())
            {
                String key = (String) installerpropertieskeys.nextElement();
                if (key.startsWith("SYSTEM_"))
                {
                    // skip
                    continue;
                }
                else if (key.startsWith("password_"))
                {
                    // skip
                    continue;
                }
                pw.println(key + "=" + installerproperties.getProperty(key));
            }
            pw.flush();
            pw.close();
        }
        catch (Exception e)
        {
            Debug.trace("Error while writing config information in MultiVolumeUnpacker: "
                    + e.getMessage());
        }
    }
}


text:
require "logstash/inputs/base"
require "logstash/namespace"
require "socket" # for Socket.gethostname
require "stud/interval"

# Periodically run a shell command and capture the whole output as an event.
#
# Notes:
#
# * The `command` field of this event will be the command run.
# * The `message` field of this event will be the entire stdout of the command.
#
class LogStash::Inputs::Exec < LogStash::Inputs::Base

  config_name "exec"

  default :codec, "plain"

  # Command to run. For example, `uptime`
  config :command, :validate => :string, :required => true

  # Interval to run the command. Value is in seconds.
  config :interval, :validate => :number, :required => true

  def register
    @logger.info("Registering Exec Input", :type => @type, :command => @command, :interval => @interval)
    @hostname = Socket.gethostname
    @io       = nil
  end # def register

  def run(queue)
    while !stop?
      inner_run(queue)
    end # loop
  end # def run

  def inner_run(queue)
    start = Time.now
    execute(@command, queue)
    duration = Time.now - start

    @logger.debug? && @logger.debug("Command completed", :command => @command, :duration => duration)

    wait_until_end_of_interval(duration)
  end

  def stop
    return if @io.nil? || @io.closed?
    @io.close
    @io = nil
  end

  private

  # Wait until the end of the interval
  # @param [Integer] the duration of the last command executed
  def wait_until_end_of_interval(duration)
    # Sleep for the remainder of the interval, or 0 if the duration ran
    # longer than the interval.
    sleeptime = [0, @interval - duration].max
    if sleeptime > 0
      Stud.stoppable_sleep(sleeptime) { stop? }
    else
      @logger.warn("Execution ran longer than the interval. Skipping sleep.",
                   :command => @command, :duration => duration, :interval => @interval)
    end
  end

  # Execute a given command
  # @param [String] A command string
  # @param [Array or Queue] A queue to append events to
  def execute(command, queue)
    @logger.debug? && @logger.debug("Running exec", :command => command)
    begin
      @io = IO.popen(command)
      @codec.decode(@io.read) do |event|
        decorate(event)
        event.set("host", @hostname)
        event.set("command", command)
        queue << event
      end
    rescue StandardError => e
      @logger.error("Error while running command",
        :command => command, :e => e, :backtrace => e.backtrace)
    rescue Exception => e
      @logger.error("Exception while running command",
        :command => command, :e => e, :backtrace => e.backtrace)
    ensure
      stop
    end
  end
end # class LogStash::Inputs::Exec


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[MFLSession sharedInstance] handleDidBecomeActive];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    BOOL canHandle = NO;
    if ([[MFLSession sharedInstance] canHandleOpenUrl:url])
    {
        canHandle = [[MFLSession sharedInstance] handleOpenURL:url];
    }
    //other logic
    return canHandle;
}

@end


text:
Here are the slides for my talk at [London Web Standards](http://londonwebstandards.org/) in October 2013.

* [Interactive view](http://stucox.github.io/lwsprog)

Built with [Reveal.js](http://lab.hakim.se/reveal-js/).


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2022 The Fluent Bit Authors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <fluent-bit/flb_output_plugin.h>

#include "stackdriver.h"
#include "stackdriver_helper.h"
#include "stackdriver_timestamp.h"
#include <fluent-bit/flb_regex.h>

#include <ctype.h>

static int is_integer(char *str, int size) {
    int i;
    for (i = 0; i < size; ++ i) {
        if (!isdigit(str[i])) {
            return FLB_FALSE;
        }
    }
    return FLB_TRUE;
}

static void try_assign_time(long long seconds, long long nanos,
                            struct flb_time *tms)
{
    if (seconds != 0) {
        tms->tm.tv_sec = seconds;
        tms->tm.tv_nsec = nanos;
    }
}

static long long get_integer(msgpack_object obj)
{
    char tmp[32];

    if (obj.type == MSGPACK_OBJECT_POSITIVE_INTEGER) {
        return obj.via.i64;
    }
    else if (obj.type == MSGPACK_OBJECT_STR
             && is_integer((char *) obj.via.str.ptr,
                           obj.via.str.size)) {

        /*
         * use an intermediary buffer to perform the conversion to avoid any
         * overflow by atoll. LLONG_MAX value is +9,223,372,036,854,775,807,
         * so using a 32 bytes buffer is enough.
         */
        if (obj.via.str.size > sizeof(tmp) - 1) {
            return 0;
        }

        memcpy(tmp, obj.via.str.ptr, obj.via.str.size);
        tmp[obj.via.str.size] = '\0';

        return atoll(tmp);
    }

    return 0;
}

static int extract_format_timestamp_object(msgpack_object *obj,
                                           struct flb_time *tms)
{
    int seconds_found = FLB_FALSE;
    int nanos_found = FLB_FALSE;
    long long seconds = 0;
    long long nanos = 0;

    msgpack_object_kv *p;
    msgpack_object_kv *pend;
    msgpack_object_kv *tmp_p;
    msgpack_object_kv *tmp_pend;

    if (obj->via.map.size == 0) {
        return FLB_FALSE;
    }
    p = obj->via.map.ptr;
    pend = obj->via.map.ptr + obj->via.map.size;

    for (; p < pend; ++p) {
        if (!validate_key(p->key, "timestamp", 9)
            || p->val.type != MSGPACK_OBJECT_MAP) {
            continue;
        }

        tmp_p = p->val.via.map.ptr;
        tmp_pend = p->val.via.map.ptr + p->val.via.map.size;

        for (; tmp_p < tmp_pend; ++tmp_p) {
            if (validate_key(tmp_p->key, "seconds", 7)) {
                seconds_found = FLB_TRUE;
                seconds = get_integer(tmp_p->val);

                if (nanos_found == FLB_TRUE) {
                    try_assign_time(seconds, nanos, tms);
                    return FLB_TRUE;
                }
            }
            else if (validate_key(tmp_p->key, "nanos", 5)) {
                nanos_found = FLB_TRUE;
                nanos = get_integer(tmp_p->val);

                if (seconds_found == FLB_TRUE) {
                    try_assign_time(seconds, nanos, tms);
                    return FLB_TRUE;
                }
            }
        }
    }
    return FLB_FALSE;
}

static int extract_format_timestamp_duo_fields(msgpack_object *obj,
                                               struct flb_time *tms)
{
    int seconds_found = FLB_FALSE;
    int nanos_found = FLB_FALSE;
    long long seconds = 0;
    long long nanos = 0;

    msgpack_object_kv *p;
    msgpack_object_kv *pend;

    if (obj->via.map.size == 0) {
        return FLB_FALSE;
    }
    p = obj->via.map.ptr;
    pend = obj->via.map.ptr + obj->via.map.size;

    for (; p < pend; ++p) {
        if (validate_key(p->key, "timestampSeconds", 16)) {
            seconds_found = FLB_TRUE;
            seconds = get_integer(p->val);

            if (nanos_found == FLB_TRUE) {
                try_assign_time(seconds, nanos, tms);
                return FLB_TRUE;
            }
        }
        else if (validate_key(p->key, "timestampNanos", 14)) {
            nanos_found = FLB_TRUE;
            nanos = get_integer(p->val);

            if (seconds_found == FLB_TRUE) {
                try_assign_time(seconds, nanos, tms);
                return FLB_TRUE;
            }
        }
    }

    return FLB_FALSE;
}

timestamp_status extract_timestamp(msgpack_object *obj,
                                   struct flb_time *tms)
{
    if (extract_format_timestamp_object(obj, tms)) {
        return FORMAT_TIMESTAMP_OBJECT;
    }
    if (extract_format_timestamp_duo_fields(obj, tms)) {
        return FORMAT_TIMESTAMP_DUO_FIELDS;
    }
    return TIMESTAMP_NOT_PRESENT;
}


text:
module TieredValidation
  class ValidationTier
    DEFAULT_ACTION_VALIDATION_MAP = {
      :save => :validate,
      :update => :validate_on_update,
      :create => :validate_on_create
    }.freeze

    DEFAULT_VALIDATIONS = DEFAULT_ACTION_VALIDATION_MAP.values.freeze

    def self.for(name, klass, includes = [], exclusive = true)
      tier_class = uses_callbacks?(klass) ?
        ValidationTierWithCallbacks : ValidationTierWithoutCallbacks

      tier_class.new(name, klass, includes, exclusive)
    end

    def initialize(name, klass, includes = [], exclusive = true)
      @name = name
      @klass = klass
      @included_tiers = includes.is_a?(Array) ? includes : [includes].compact
      @exclusive = exclusive
      define_validation_chains
    end

    def run_callbacks
    end

    def setup_alias_methods
      DEFAULT_VALIDATIONS.each do |default_callback|
        if @exclusive
          # def self.validate_with_tier(*methods, &block)
          #   validate_for_admin *methods, &block
          # end
          @klass.class_eval <<-BLOCK, __FILE__, __LINE__ + 1
            def self.#{validation_with_tier_name(default_callback)}(*methods, &block)
              #{validation_name(default_callback)} *methods, &block
            end
          BLOCK
        else
          # def self.validate_with_tier(*methods, &block)
          #   validate_for_admin *methods, &block
          #   validate_without_tier *methods, &block
          # end
          @klass.class_eval <<-BLOCK, __FILE__, __LINE__ + 1
            def self.#{validation_with_tier_name(default_callback)}(*methods, &block)
              #{validation_name(default_callback)} *methods, &block
              #{validation_without_tier_name(default_callback)} *methods, &block
            end
          BLOCK
        end

        # class << self
        #   alias_method :validate_without_tier, :validate
        #   alias_method :validate, :validate_with_tier
        # end
        @klass.class_eval <<-BLOCK, __FILE__, __LINE__ + 1
          class << self
            alias_method :#{validation_without_tier_name(default_callback)}, :#{default_callback}
            alias_method :#{default_callback}, :#{validation_with_tier_name(default_callback)}
          end
        BLOCK
      end
    end

    def teardown_alias_methods
      DEFAULT_VALIDATIONS.each do |default_callback|
        # class << self
        #   alias_method :validate, :validate_without_tier
        #
        #   remove_method :validate_with_tier
        #   remove_method :validate_without_tier
        # end
        @klass.class_eval  <<-BLOCK, __FILE__, __LINE__ + 1
          class << self
            alias_method :#{default_callback}, :#{validation_without_tier_name(default_callback)}

            remove_method :#{validation_with_tier_name(default_callback)}
            remove_method :#{validation_without_tier_name(default_callback)}
          end
        BLOCK
      end
    end

    def add_convenience_methods
      # def self.create_with_admin_validation!(attributes = nil, &block)
      #   create_with_tier_validation!(:admin, attributes, &block)
      # end
      #
      # def save_with_admin_validation
      #   save_with_tier_validation(:admin)
      # end
      #
      # def save_with_admin_validation
      #   save_with_tier_validation!(:admin)
      # end
      #
      # def valid_for_admin?
      #   valid_for_tier?(:admin)
      # end
      #
      # def invalid_for_admin?
      #   !valid_for_tier?(:admin)
      # end
      @klass.class_eval <<-BLOCK, __FILE__, __LINE__ + 1
        def self.create_with_#{@name}_validation!(attributes = nil, &block)
          create_with_tier_validation!(:#{@name}, attributes, &block)
        end

        def save_with_#{@name}_validation
          save_with_tier_validation(:#{@name})
        end

        def save_with_#{@name}_validation!
          save_with_tier_validation!(:#{@name})
        end

        def valid_for_#{@name}?
          valid_for_tier?(:#{@name})
        end

        def invalid_for_#{@name}?
          !valid_for_tier?(:#{@name})
        end
      BLOCK
    end

    protected
      def define_validation_chains
      end

      def validation_name(default_callback)
        "#{default_callback}_for_#{@name}"
      end

      def validation_with_tier_name(default_callback)
        "#{default_callback}_with_tier"
      end

      def validation_without_tier_name(default_callback)
        "#{default_callback}_without_tier"
      end

    private
      def self.uses_callbacks?(klass)
        klass.respond_to?(:define_callbacks)
      end
  end
end


text:
<?php

declare(strict_types=1);

/**
 * This file is part of Narrowspark Framework.
 *
 * (c) Daniel Bannert <d.bannert@anolilab.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Viserio\Component\HttpFoundation\Console\Command;

use Throwable;
use Viserio\Component\Console\Command\AbstractCommand;
use Viserio\Contract\Console\Kernel as ConsoleKernelContract;

class UpCommand extends AbstractCommand
{
    /**
     * {@inheritdoc}
     */
    protected static $defaultName = 'app:up';

    /**
     * {@inheritdoc}
     */
    protected $description = 'Bring the application out of maintenance mode';

    /**
     * {@inheritdoc}
     */
    public function handle(ConsoleKernelContract $kernel): int
    {
        try {
            $downFilePath = $kernel->getStoragePath('framework' . \DIRECTORY_SEPARATOR . 'down');

            if (! file_exists($downFilePath)) {
                $this->comment('Application is already up.');

                return 0;
            }

            \unlink($downFilePath);
        } catch (Throwable $exception) {
            $this->error('Application is failed to up.');
            $this->error($exception->getMessage());

            return 1;
        }

        $this->info('Application is now live.');

        return 0;
    }
}


text:
function verifyTablePrimaryField(schema, key) {
    "use strict";
    var table = schema[key];

    if (table.primary && typeof table.primary === "string") {
        if (table.fields[table.primary]) {
            return true;
        } else {
            throw new ReferenceError("Primary key '" + table.primary + "' of table '" + key + "' is not present in the table's fields");
        }
    } else {
        throw new SyntaxError("Missing primary key for table " + key + "\nexample:\n{\n  tableName: {\n\tprimary:'id',\n\tfields:{}\n  }\n}" );
    }
}

module.exports = verifyTablePrimaryField;


text:
Testing class alias with is_subclass_of()
--FILE--
<?php

class foo {
}

class_alias('foo', 'bar');

class baz extends bar {
}

var_dump(is_subclass_of(new foo, 'foo'));
var_dump(is_subclass_of(new foo, 'bar'));
var_dump(is_subclass_of(new foo, 'baz'));

var_dump(is_subclass_of(new bar, 'foo'));
var_dump(is_subclass_of(new bar, 'bar'));
var_dump(is_subclass_of(new bar, 'baz'));

var_dump(is_subclass_of(new baz, 'foo'));
var_dump(is_subclass_of(new baz, 'bar'));
var_dump(is_subclass_of(new baz, 'baz'));

?>
--EXPECT--
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)


text:
package org.apache.hadoop.mapred;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.hadoop.http.HtmlQuoting;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.TaskID;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.util.*;
import java.text.SimpleDateFormat;
import org.apache.hadoop.mapreduce.jobhistory.*;

public final class jobtaskshistory_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static SimpleDateFormat dateFormat =
                                    new SimpleDateFormat("d/MM HH:mm:ss") ;

	private static final long serialVersionUID = 1L;

  private void printTask(String logFile,
    JobHistoryParser.TaskAttemptInfo attempt, JspWriter out) throws IOException{
    out.print("
");
    out.print("" + "" +
          attempt.getAttemptId().getTaskID() + "	");
    out.print("" + StringUtils.getFormattedTimeWithDiff(dateFormat,
          attempt.getStartTime(), 0 ) + "	");
    out.print("" + StringUtils.getFormattedTimeWithDiff(dateFormat,
          attempt.getFinishTime(),
          attempt.getStartTime() ) + "	");
    out.print(""+ HtmlQuoting.quoteHtmlChars(attempt.getError()) +"	");
    out.print("
");
  }

  private static java.util.List _jspx_dependants;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html; charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\n');
      out.write('\n');
      out.write('\n');
      out.write('\n');
      out.write('\n');
      out.write('\n');

  String logFile = request.getParameter("logFile");
  String taskStatus = request.getParameter("status");
  String taskType = request.getParameter("taskType");

  FileSystem fs = (FileSystem) application.getAttribute("fileSys");
  JobTracker jobTracker = (JobTracker) application.getAttribute("job.tracker");
  JobHistoryParser.JobInfo job = JSPUtil.checkAccessAndGetJobInfo(request,
      response, jobTracker, fs, new Path(logFile));
  if (job == null) {
    return;
  }
  Map<TaskID, JobHistoryParser.TaskInfo> tasks = job.getAllTasks();

      out.write("\n\n\n
");
      out.print(taskStatus);
      out.write(' ');
      out.print(taskType );
      out.write(" task list for ');
      out.print(job.getJobId() );
      out.write("
\n\n
\n
Task Id	Start Time	Finish Time
	Error
\n");

  for (JobHistoryParser.TaskInfo task : tasks.values()) {
    if (taskType.equalsIgnoreCase(task.getTaskType().toString())) {
      Map <TaskAttemptID, JobHistoryParser.TaskAttemptInfo> taskAttempts = task.getAllTaskAttempts();
      for (JobHistoryParser.TaskAttemptInfo taskAttempt : taskAttempts.values()) {
        if (taskStatus.equals(taskAttempt.getTaskStatus()) ||
          taskStatus.equalsIgnoreCase("all")){
          printTask(logFile, taskAttempt, out);
        }
      }
    }
  }

      out.write("\n
\n");
      out.write("\n\n\n\n");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}


text:
import gulp from 'gulp'
import browserSync from 'browser-sync'

// js
import sourcemaps from 'gulp-sourcemaps'
import babel from 'gulp-babel'
import concat from 'gulp-concat'

// sass
import autoprefixer from 'gulp-autoprefixer'
import sass from 'gulp-sass'
import minifyCss from 'gulp-minify-css'

const baseDir = './'
const srcDir = `${baseDir}src`
const distDir = `${baseDir}/dist`
const modules = 'ignore'

// initialize browserSync
browserSync.create()

gulp.task('build:js', () => {
   return gulp.src(`${ srcDir }/**/*.js`)
     .pipe(sourcemaps.init())
     .pipe(babel({modules}))
     .pipe(concat('all.js'))
     .pipe(sourcemaps.write('.'))
     .pipe(gulp.dest(distDir))
})

gulp.task('build:sass', () => {
  return gulp.src([`${ srcDir }/**/*.scss`])
    .pipe(autoprefixer('last 2 versions'))
    .pipe(sass())
    .pipe(gulp.dest(distDir))
    .pipe(browserSync.stream())
})

gulp.task('serve', () => {
    browserSync.init({ server: { baseDir }})
    gulp.watch(`${ srcDir }/**/*.js`, ['watch:js'])
    gulp.watch(`${ srcDir }/**/*.scss`, ['build:sass'])
    gulp.watch('./**/*.html', browserSync.reload)
})

gulp.task('watch:js', ['build:js'], browserSync.reload)
gulp.task('build', ['build:js', 'build:sass'])
gulp.task('default', ['build', 'serve'])


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('empleados', '0004_cajero'),
        ('operacion', '0017_auto_20161005_1330'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='servicio',
            name='empleado',
        ),
        migrations.AddField(
            model_name='orden',
            name='cajero',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='cajero', to='empleados.Cajero'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='orden',
            name='fin',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name='orden',
            name='recepcionista',
            field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='recepcionista', to='empleados.Recepcionista'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='servicio',
            name='operario',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='operario', to='empleados.Empleado'),
        ),
    ]


text:
"""Contains utilities for holding and formatting install information.

This is useful for the output of 'gcloud info', which in turn is extremely
useful for debugging issues related to weird installations, out-of-date
installations, and so on.
"""

import datetime
import os
import re
import StringIO
import sys
import textwrap

from googlecloudsdk.core import config
from googlecloudsdk.core import log
from googlecloudsdk.core import named_configs
from googlecloudsdk.core import properties
from googlecloudsdk.core.updater import update_manager
from googlecloudsdk.core.util import platforms

class InfoHolder(object):
  """Base object to hold all the configuration info."""

  def __init__(self):
    self.basic = BasicInfo()
    self.installation = InstallationInfo()
    self.config = ConfigInfo()
    self.logs = LogsInfo()

  def __str__(self):
    out = StringIO.StringIO()
    out.write(str(self.basic) + '\n')
    out.write(str(self.installation) + '\n')
    out.write(str(self.config) + '\n')
    out.write(str(self.logs) + '\n')
    return out.getvalue()

class BasicInfo(object):
  """Holds basic information about your system setup."""

  def __init__(self):
    platform = platforms.Platform.Current()
    self.version = config.CLOUD_SDK_VERSION
    self.operating_system = platform.operating_system
    self.architecture = platform.architecture
    self.python_version = sys.version
    self.site_packages = 'site' in sys.modules

  def __str__(self):
    return textwrap.dedent("""\
        Google Cloud SDK [{version}]

        Platform: [{os}, {arch}]
        Python Version: [{python_version}]
        Python Location: [{python_location}]
        Site Packages: [{site_packages}]
        """.format(
            version=self.version,
            os=self.operating_system.name,
            arch=self.architecture.name,
            python_location=sys.executable,
            python_version=self.python_version.replace('\n', ' '),
            site_packages='Enabled' if self.site_packages else 'Disabled'))

class InstallationInfo(object):
  """Holds information about your Cloud SDK installation."""

  def __init__(self):
    self.sdk_root = config.Paths().sdk_root
    self.release_channel = config.INSTALLATION_CONFIG.release_channel
    self.repo_url = config.INSTALLATION_CONFIG.snapshot_url
    repos = properties.VALUES.component_manager.additional_repositories.Get(
        validate=False)
    self.additional_repos = repos.split(',') if repos else []
    self.path = os.environ.get('PATH', '')

    if self.sdk_root:
      manager = update_manager.UpdateManager()
      self.components = manager.GetCurrentVersionsInformation()
      self.old_tool_paths = manager.FindAllOldToolsOnPath()
      paths = [os.path.realpath(p) for p in self.path.split(os.pathsep)]
      this_path = os.path.realpath(
          os.path.join(self.sdk_root,
                       update_manager.UpdateManager.BIN_DIR_NAME))
      # TODO(user): Validate symlinks in /usr/local/bin when we start
      # creating them.
      self.on_path = this_path in paths
    else:
      self.components = {}
      self.old_tool_paths = []
      self.on_path = False

  def __str__(self):
    out = StringIO.StringIO()
    out.write('Installation Root: [{0}]\n'.format(
        self.sdk_root if self.sdk_root else 'N/A'))
    if config.INSTALLATION_CONFIG.IsAlternateReleaseChannel():
      out.write('Release Channel: [{0}]\n'.format(self.release_channel))
      out.write('Repository URL: [{0}]\n'.format(self.repo_url))
    if self.additional_repos:
      out.write('Additional Repositories:\n  {0}\n'.format(
          '\n  '.join(self.additional_repos)))

    if self.components:
      components = ['{0}: [{1}]'.format(name, value) for name, value in
                    self.components.iteritems()]
      out.write('Installed Components:\n  {0}\n'.format(
          '\n  '.join(components)))

    out.write('System PATH: [{0}]\n'.format(self.path))
    out.write('Cloud SDK on PATH: [{0}]\n'.format(self.on_path))

    if self.old_tool_paths:
      out.write('\nWARNING: There are old versions of the Google Cloud '
                'Platform tools on your system PATH.\n  {0}\n'
                .format('\n  '.join(self.old_tool_paths)))
    return out.getvalue()

class ConfigInfo(object):
  """Holds information about where config is stored and what values are set."""

  def __init__(self):
    self.paths = config.Paths()
    self.active_config_name = named_configs.GetNameOfActiveNamedConfig()
    if self.active_config_name is not None:
      self.active_config_path = named_configs.GetFileForActiveNamedConfig()
    self.account = properties.VALUES.core.account.Get(validate=False)
    self.project = properties.VALUES.core.project.Get(validate=False)
    self.properties = properties.VALUES.AllValues()

  def __str__(self):
    out = StringIO.StringIO()
    out.write('Installation Properties: [{0}]\n'
              .format(self.paths.installation_properties_path))
    out.write('User Config Directory: [{0}]\n'
              .format(self.paths.global_config_dir))
    if self.active_config_name is not None:
      out.write('Active Configuration Name: [{0}]\n'
                .format(self.active_config_name))
      out.write('Active Configuration Path: [{0}]\n\n'
                .format(self.active_config_path))
    else:
      out.write('User Properties: [{0}]\n\n'
                .format(self.paths.user_properties_path))

    out.write('Account: [{0}]\n'.format(self.account))
    out.write('Project: [{0}]\n\n'.format(self.project))

    out.write('Current Properties:\n')
    for section, props in self.properties.iteritems():
      out.write('  [{section}]\n'.format(section=section))
      for name, value in props.iteritems():
        out.write('    {name}: [{value}]\n'.format(
            name=name, value=value))
    return out.getvalue()

def RecentLogFiles(logs_dir, num=1):
  """Finds the most recent (not current) gcloud log files.

  Args:
    logs_dir: str, The path to the logs directory being used.
    num: the number of log files to find

  Returns:
    A list of full paths to the latest num log files, excluding the current
    log file. If there are fewer than num log files, include all of
    them. They will be in chronological order.
  """
  date_dirs = FilesSortedByName(logs_dir)
  if not date_dirs:
    return []

  found_files = []
  for date_dir in reversed(date_dirs):
    log_files = reversed(FilesSortedByName(date_dir) or [])
    found_files.extend(log_files)
    if len(found_files) >= num + 1:
      return found_files[1:num+1]

  return found_files[1:]

def LastLogFile(logs_dir):
  """Finds the last (not current) gcloud log file.

  Args:
    logs_dir: str, The path to the logs directory being used.

  Returns:
    str, The full path to the last (but not the currently in use) log file
    if it exists, or None.
  """
  files = RecentLogFiles(logs_dir)
  if files:
    return files[0]
  return None

def FilesSortedByName(directory):
  """Gets the list of files in the given directory, sorted by name.

  Args:
    directory: str, The path to the directory to list.

  Returns:
    [str], The full paths of the files, sorted by file name, or None.
  """
  if not os.path.isdir(directory):
    return None
  dates = os.listdir(directory)
  if not dates:
    return None
  return [os.path.join(directory, date) for date in sorted(dates)]

class LogData(object):
  """Representation of a log file.

  Stores information such as the name of the log file, its contents, and the
  command run.
  """

  # This precedes the traceback in the log file.
  TRACEBACK_MARKER = 'BEGIN CRASH STACKTRACE\n'

  # This shows the command run in the log file
  COMMAND_REGEXP = r'Running (gcloud\.[a-z.]+)'

  def __init__(self, filename, command, contents, traceback):
    self.filename = filename
    self.command = command
    self.contents = contents
    self.traceback = traceback

  def __str__(self):
    crash_detected = ' (crash detected)' if self.traceback else ''
    return '[{0}]: [{1}]{2}'.format(self.relative_path, self.command,
                                    crash_detected)

  @property
  def relative_path(self):
    logs_dir = config.Paths().logs_dir
    if not self.filename.startswith(logs_dir):
      return self.filename
    return self.filename[len(logs_dir + os.path.sep):]

  @property
  def date(self):
    """Return the date that this log file was created, based on its filename.

    Returns:
      datetime.datetime that the log file was created or None, if the filename
        pattern was not recognized.
    """
    datetime_string = ':'.join(os.path.split(self.relative_path))
    datetime_format = (log.DAY_DIR_FORMAT + ':' + log.FILENAME_FORMAT +
                       log.LOG_FILE_EXTENSION)
    try:
      return datetime.datetime.strptime(datetime_string, datetime_format)
    except ValueError:
      # This shouldn't happen, but it's better not to crash because of it.
      return None

  @classmethod
  def FromFile(cls, log_file):
    """Parse the file at the given path into a LogData.

    Args:
      log_file: str, the path to the log file to read

    Returns:
      LogData, representation of the log file
    """
    with open(log_file) as log_fp:
      contents = log_fp.read()
      traceback = None
      command = None
      match = re.search(cls.COMMAND_REGEXP, contents)
      if match:
        # ex. gcloud.group.subgroup.command
        dotted_cmd_string, = match.groups()
        command = ' '.join(dotted_cmd_string.split('.'))
      if cls.TRACEBACK_MARKER in contents:
        traceback = (contents.split(cls.TRACEBACK_MARKER)[-1])
        # Trim any log lines that follow the traceback
        traceback = re.split(log.LOG_PREFIX_PATTERN, traceback)[0]
        traceback = traceback.strip()
      return cls(log_file, command, contents, traceback)

class LogsInfo(object):
  """Holds information about where logs are located."""

  NUM_RECENT_LOG_FILES = 5

  def __init__(self):
    paths = config.Paths()
    self.logs_dir = paths.logs_dir
    self.last_log = LastLogFile(self.logs_dir)
    self.last_logs = RecentLogFiles(self.logs_dir, self.NUM_RECENT_LOG_FILES)

  def __str__(self):
    return textwrap.dedent("""\
        Logs Directory: [{logs_dir}]
        Last Log File: [{log_file}]
        """.format(logs_dir=self.logs_dir, log_file=self.last_log))

  def LastLogContents(self):
    if not self.last_log:
      return ''
    with open(self.last_log) as fp:
      return fp.read()

  def GetRecentRuns(self):
    """Return the most recent runs, as reported by info_holder.LogsInfo.

    Returns:
      A list of LogData
    """
    return [LogData.FromFile(log_file) for log_file in self.last_logs]


text: void reverse_array(int *a, int n)


text:
using LibrarySystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LibrarySystem.Admin
{
    public partial class EditBooks : System.Web.UI.Page
    {
        public LibraryDbContext dbContext;

        public EditBooks()
        {
            this.dbContext = new LibraryDbContext();
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable<Book> GridViewBooks_GetData()
        {
            return this.dbContext.Books.OrderBy(b => b.ID);
        }

        // The id parameter name should match the DataKeyNames value set on the control
        public void GridViewBooks_UpdateItem(int id)
        {
            Book item = this.dbContext.Books.Find(id);
            if (item == null)
            {
                // The item wasn't found
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                this.dbContext.SaveChanges();
            }
        }

        // The id parameter name should match the DataKeyNames value set on the control
        public void GridViewBooks_DeleteItem(int id)
        {
            Book item = this.dbContext.Books.Find(id);
            if (item == null)
            {
                // The item wasn't found
                ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
                return;
            }

            this.dbContext.Books.Remove(item);
            this.dbContext.SaveChanges();
        }

        public void FormViewIsertBook_InsertItem()
        {
            var item = new LibrarySystem.Models.Book();
            TryUpdateModel(item);
            if (ModelState.IsValid)
            {
                this.dbContext.Books.Add(item);
                this.dbContext.SaveChanges();
            }
        }
        public IQueryable<Category> DropDownListCategoriesCreate_GetData()
        {
            return this.dbContext.Categories.OrderBy(b => b.Name);
        }

        protected void DropDownListCategoriesCreate_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void LinkButtonInsert_Click(object sender, EventArgs e)
        {
            this.btnWrapper.Visible = false;

            var fv = this.UpdatePanelInsertBook.FindControl("FormViewIsertBook") as FormView;
            fv.Visible = true;
        }
    }
}