text:
package com.opengamma.strata.market.curve.node;

import static com.opengamma.strata.basics.date.Tenor.TENOR_10Y;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static com.opengamma.strata.product.common.BuySell.BUY;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.data.Offset.offset;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.Set;

import org.junit.jupiter.api.Test;

import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.StandardId;
import com.opengamma.strata.basics.currency.FxRateProvider;
import com.opengamma.strata.basics.date.Tenor;
import com.opengamma.strata.basics.index.PriceIndices;
import com.opengamma.strata.collect.timeseries.LocalDateDoubleTimeSeries;
import com.opengamma.strata.data.ImmutableMarketData;
import com.opengamma.strata.data.MarketData;
import com.opengamma.strata.data.MarketDataNotFoundException;
import com.opengamma.strata.data.ObservableId;
import com.opengamma.strata.market.ValueType;
import com.opengamma.strata.market.curve.CurveNodeDate;
import com.opengamma.strata.market.observable.IndexQuoteId;
import com.opengamma.strata.market.observable.QuoteId;
import com.opengamma.strata.market.param.DatedParameterMetadata;
import com.opengamma.strata.market.param.ParameterMetadata;
import com.opengamma.strata.market.param.TenorDateParameterMetadata;
import com.opengamma.strata.product.common.BuySell;
import com.opengamma.strata.product.swap.ResolvedSwapTrade;
import com.opengamma.strata.product.swap.SwapTrade;
import com.opengamma.strata.product.swap.type.FixedInflationSwapConventions;
import com.opengamma.strata.product.swap.type.FixedInflationSwapTemplate;

/**
 * Test {@link FixedInflationSwapCurveNode}.
 */
public class FixedInflationSwapCurveNodeTest {

  private static final ReferenceData REF_DATA = ReferenceData.standard();
  private static final LocalDate VAL_DATE = date(2015, 6, 30);

  private static final FixedInflationSwapTemplate TEMPLATE =
      FixedInflationSwapTemplate.of(TENOR_10Y, FixedInflationSwapConventions.EUR_FIXED_ZC_EU_EXT_CPI);
  private static final QuoteId QUOTE_ID = QuoteId.of(StandardId.of("OG-Ticker", "EU-EXT-CPI"));
  private static final double SPREAD = 0.0015;
  private static final String LABEL = "Label";
  private static final String LABEL_AUTO = "10Y";

  private static final double TOLERANCE_GUESS = 1.0E-10;

  @Test
  public void test_builder() {
    FixedInflationSwapCurveNode test = FixedInflationSwapCurveNode.builder()
        .label(LABEL)
        .template(TEMPLATE)
        .rateId(QUOTE_ID)
        .additionalSpread(SPREAD)
        .build();
    assertThat(test.getLabel()).isEqualTo(LABEL);
    assertThat(test.getRateId()).isEqualTo(QUOTE_ID);
    assertThat(test.getAdditionalSpread()).isEqualTo(SPREAD);
    assertThat(test.getTemplate()).isEqualTo(TEMPLATE);
    assertThat(test.getDate()).isEqualTo(CurveNodeDate.END);
  }

  @Test
  public void test_of_noSpread() {
    FixedInflationSwapCurveNode test = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID);
    assertThat(test.getLabel()).isEqualTo(LABEL_AUTO);
    assertThat(test.getRateId()).isEqualTo(QUOTE_ID);
    assertThat(test.getAdditionalSpread()).isEqualTo(0.0d);
    assertThat(test.getTemplate()).isEqualTo(TEMPLATE);
  }

  @Test
  public void test_of_withSpread() {
    FixedInflationSwapCurveNode test = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    assertThat(test.getLabel()).isEqualTo(LABEL_AUTO);
    assertThat(test.getRateId()).isEqualTo(QUOTE_ID);
    assertThat(test.getAdditionalSpread()).isEqualTo(SPREAD);
    assertThat(test.getTemplate()).isEqualTo(TEMPLATE);
  }

  @Test
  public void test_of_withSpreadAndLabel() {
    FixedInflationSwapCurveNode test = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD, LABEL);
    assertThat(test.getLabel()).isEqualTo(LABEL);
    assertThat(test.getRateId()).isEqualTo(QUOTE_ID);
    assertThat(test.getAdditionalSpread()).isEqualTo(SPREAD);
    assertThat(test.getTemplate()).isEqualTo(TEMPLATE);
  }

  @Test
  public void test_requirements() {
    FixedInflationSwapCurveNode test = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    Set<ObservableId> set = test.requirements();
    Iterator<ObservableId> itr = set.iterator();
    assertThat(itr.next()).isEqualTo(QUOTE_ID);
    assertThat(itr.hasNext()).isFalse();
  }

  @Test
  public void test_trade() {
    FixedInflationSwapCurveNode node = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    LocalDate tradeDate = LocalDate.of(2015, 1, 22);
    double rate = 0.125;
    double quantity = -1234.56;
    MarketData marketData = ImmutableMarketData.builder(tradeDate).addValue(QUOTE_ID, rate).build();
    SwapTrade trade = node.trade(quantity, marketData, REF_DATA);
    SwapTrade expected = TEMPLATE.createTrade(tradeDate, BUY, -quantity, rate + SPREAD, REF_DATA);
    assertThat(trade).isEqualTo(expected);
  }

  @Test
  public void test_trade_noMarketData() {
    FixedInflationSwapCurveNode node = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    LocalDate valuationDate = LocalDate.of(2015, 1, 22);
    MarketData marketData = MarketData.empty(valuationDate);
    assertThatExceptionOfType(MarketDataNotFoundException.class)
        .isThrownBy(() -> node.trade(1d, marketData, REF_DATA));
  }

  @Test
  public void test_sampleResolvedTrade() {
    FixedInflationSwapCurveNode node = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    LocalDate valuationDate = LocalDate.of(2015, 1, 22);
    ResolvedSwapTrade trade = node.sampleResolvedTrade(valuationDate, FxRateProvider.minimal(), REF_DATA);
    ResolvedSwapTrade expected = TEMPLATE.createTrade(valuationDate, BuySell.SELL, 1d, SPREAD, REF_DATA).resolve(REF_DATA);
    assertThat(trade).isEqualTo(expected);
  }

  @Test
  public void test_initialGuess() {
    FixedInflationSwapCurveNode node = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    LocalDate valuationDate = LocalDate.of(2015, 1, 22);
    double rate = 0.035;
    double lastPriceIndex = 123.4;
    LocalDateDoubleTimeSeries ts = LocalDateDoubleTimeSeries.builder()
        .put(LocalDate.of(2024, 10, 31), lastPriceIndex).build();
    MarketData marketData = ImmutableMarketData.builder(valuationDate).addValue(QUOTE_ID, rate)
        .addTimeSeries(IndexQuoteId.of(PriceIndices.EU_EXT_CPI), ts).build();
    assertThat(node.initialGuess(marketData, ValueType.ZERO_RATE)).isEqualTo(rate);
    double priceIndexGuess = lastPriceIndex * Math.pow(1.0d + rate, TENOR_10Y.get(ChronoUnit.YEARS));
    assertThat(node.initialGuess(marketData, ValueType.PRICE_INDEX)).isCloseTo(priceIndexGuess, offset(TOLERANCE_GUESS));
  }

  @Test
  public void test_initialGuess_wrongType() {
    FixedInflationSwapCurveNode node = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    MarketData marketData = ImmutableMarketData.builder(VAL_DATE).build();
    assertThatIllegalArgumentException()
        .isThrownBy(() -> node.initialGuess(marketData, ValueType.BLACK_VOLATILITY));
  }

  @Test
  public void test_metadata_end() {
    FixedInflationSwapCurveNode node = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    LocalDate valuationDate = LocalDate.of(2015, 1, 22);
    ParameterMetadata metadata = node.metadata(valuationDate, REF_DATA);
    // 2015-01-22 is Thursday, start is 2015-01-26, but 2025-01-26 is Sunday, so end is 2025-01-27
    assertThat(((TenorDateParameterMetadata) metadata).getDate()).isEqualTo(LocalDate.of(2025, 1, 27));
    assertThat(((TenorDateParameterMetadata) metadata).getTenor()).isEqualTo(Tenor.TENOR_10Y);
  }

  @Test
  public void test_metadata_fixed() {
    FixedInflationSwapCurveNode node =
        FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD, LABEL).withDate(CurveNodeDate.of(VAL_DATE));
    LocalDate valuationDate = LocalDate.of(2015, 1, 22);
    DatedParameterMetadata metadata = node.metadata(valuationDate, REF_DATA);
    assertThat(metadata.getDate()).isEqualTo(VAL_DATE);
    assertThat(metadata.getLabel()).isEqualTo(node.getLabel());
  }

  @Test
  public void test_metadata_last_fixing() {
    FixedInflationSwapCurveNode node =
        FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD, LABEL).withDate(CurveNodeDate.LAST_FIXING);
    LocalDate valuationDate = LocalDate.of(2015, 1, 22);
    LocalDate fixingExpected = LocalDate.of(2024, 10, 31); // Last day of the month
    DatedParameterMetadata metadata = node.metadata(valuationDate, REF_DATA);
    assertThat(metadata.getDate()).isEqualTo(fixingExpected);
    assertThat(metadata.getLabel()).isEqualTo(node.getLabel());
  }

  //-------------------------------------------------------------------------
  @Test
  public void coverage() {
    FixedInflationSwapCurveNode test = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    coverImmutableBean(test);
    FixedInflationSwapCurveNode test2 = FixedInflationSwapCurveNode.of(
        FixedInflationSwapTemplate.of(TENOR_10Y, FixedInflationSwapConventions.USD_FIXED_ZC_US_CPI),
        QuoteId.of(StandardId.of("OG-Ticker", "Deposit2")));
    coverBeanEquals(test, test2);
  }

  @Test
  public void test_serialization() {
    FixedInflationSwapCurveNode test = FixedInflationSwapCurveNode.of(TEMPLATE, QUOTE_ID, SPREAD);
    assertSerialization(test);
  }

}


text:
// Copyright Node.js contributors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

/**
 * Node's lib/internal/util.js modified for Axway Titanium
 *
 * @see https://github.com/nodejs/node/blob/master/lib/internal/util.js
 */

import { isNativeError } from './util/types';

const kNodeModulesRE = /^(.*)[\\/]node_modules[\\/]/;

export const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
export const isBuffer = Symbol.for('titanium.buffer.isBuffer');

const colorRegExp = /\u001b\[\d\d?m/g; // eslint-disable-line no-control-regex

export function removeColors(str) {
	return str.replace(colorRegExp, '');
}

export function isError(e) {
	// An error could be an instance of Error while not being a native error
	// or could be from a different realm and not be instance of Error but still
	// be a native error.
	return isNativeError(e) || e instanceof Error;
}

let getStructuredStack;
class StackTraceError extends Error { }
StackTraceError.prepareStackTrace = (err, trace) => trace;
StackTraceError.stackTraceLimit = Infinity;

export function isInsideNodeModules() {
	if (getStructuredStack === undefined) {
		getStructuredStack = () => new StackTraceError().stack;
	}

	let stack = getStructuredStack();

	// stack is only an array on v8, try to convert manually if string
	if (typeof stack === 'string') {
		const stackFrames = [];
		const lines = stack.split(/\n/);
		for (const line of lines) {
			const lineInfo = line.match(/(.*)@(.*):(\d+):(\d+)/);
			if (lineInfo) {
				const filename = lineInfo[2].replace('file://', '');
				stackFrames.push({ getFileName: () => filename });
			}
		}
		stack = stackFrames;
	}

	// Iterate over all stack frames and look for the first one not coming
	// from inside Node.js itself:
	if (Array.isArray(stack)) {
		for (const frame of stack) {
			const filename = frame.getFileName();
			// If a filename does not start with / or contain \,
			// it's likely from Node.js core.
			if (!/^\/|\\/.test(filename)) {
				continue;
			}
			return kNodeModulesRE.test(filename);
		}
	}

	return false;
}

export function join(output, separator) {
	let str = '';
	if (output.length !== 0) {
		const lastIndex = output.length - 1;
		for (let i = 0; i < lastIndex; i++) {
			// It is faster not to use a template string here
			str += output[i];
			str += separator;
		}
		str += output[lastIndex];
	}
	return str;
}

export function uncurryThis(f) {
	return function () {
		return f.call.apply(f, arguments);
	};
}

const ALL_PROPERTIES = 0;
const ONLY_ENUMERABLE = 2;

export const propertyFilter = {
	ALL_PROPERTIES,
	ONLY_ENUMERABLE
};

export function getOwnNonIndexProperties(obj, filter) {
	const props = [];
	const keys = filter === ONLY_ENUMERABLE ? Object.keys(obj) : Object.getOwnPropertyNames(obj);
	for (var i = 0; i < keys.length; ++i) {
		const key = keys[i];
		if (!isAllDigits(key)) {
			props.push(key);
		}
	}
	return props;
}

function isAllDigits(s) {
	if (s.length === 0) {
		return false;
	}
	for (var i = 0; i < s.length; ++i) {
		const code = s.charCodeAt(i);
		if (code < 48 || code > 57) {
			return false;
		}
	}
	return true;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

	class Task_model extends CI_Model{
		public function __construct(){
			$this->load->database();
		}

		public function get_projects_by_client($id){
			$this->db->join( 'Projects', 'projects.id = Clients_projects.project_id');
			$query = $this->db->get_where( 'Clients_projects', array( 'client_id' => $id));
			return $query->result_array();
		}

		public function get_tasks(){
			$client_id = $this->input->post('client');
			$project_id = $this->input->post('project');
			$from_date = $this->input->post('from_date');
			$to_date =  $this->input->post('to_date');

			$query = $this->db->get_where( 'Clients_projects', array( 'client_id' => $client_id, 'project_id' => $project_id));
			$client_project_id = $query->row()->id;

			$query = $this->db->get_where('Tasks', array('client_project_id' => $client_project_id, 'date >=' => $from_date, 'date <=' => $to_date));

			return $query->result_array();
		}
	}


text:
from __future__ import absolute_import

import random
from itertools import chain

nlnl = '\n', '\n'

def new_key(key, word):
	if word == '\n': return nlnl
	else: return (key[1], word)

def markov_data_from_words(words):
	data = {}
	key = nlnl
	for word in words:
		data.setdefault(key, []).append(word)
		key = new_key(key, word)
	return data

def words_from_markov_data(data, initial_word='\n'):
	key = '\n', initial_word
	if initial_word != '\n':
		yield initial_word
	while 1:
		word = random.choice(data.get(key, nlnl))
		key = new_key(key, word)
		yield word

def words_from_file(f):
	for line in f:
		words = line.split()
		if len(words):
			for word in words:
				yield word
		else:
			yield '\n'
	yield '\n'

def words_from_logger(logger, max=100000):
	return words_from_lines(logger.get_random_logs(max))

def words_from_quotes(quotes):
	return words_from_lines(quotes)

def words_from_lines(lines):
	for line in lines:
		words = line[0].strip().lower().split()
		for word in words:
			yield word
		yield '\n'

def words_from_logger_and_quotes(logger, quotes):
	return chain(
		words_from_logger(logger),
		words_from_quotes(quotes),
		['\n'],
	)

def paragraph_from_words(words):
	result = []
	for word in words:
		if word == '\n': break
		result.append(word)
	return ' '.join(result)

def saysomething_db(db, initial_word='\n'):
	return paragraph_from_words(
			words_from_markov_data(
				markov_data_from_words(
					words_from_db(db)),
				initial_word))

class FastSayer(object):
	def __init__(self, word_factory):
		if not hasattr(self, 'markovdata'):
			words = word_factory()
			# save the markov data in the class for future instances
			self.__class__.markovdata = markov_data_from_words(words)

	def saysomething(self, initial_word='\n'):
		return paragraph_from_words(words_from_markov_data(self.markovdata, initial_word))


text:
layout: documentation
title: "Package asset"
order: 7
subLevel: 1
---

----

##### assetNames
An array of asset names to be added to a package asset.

* Required: `true`
* Default: `[]`
* Possible values: An array of valid asset names.
* Examples of valid asset names:
  * A `file`, `browserify` or `url` asset name, for example:
      * `site.js`
      * `site.css`
      * `jquery.min.js`
  * A file within a `folder` asset name, for example:
      * `vendor/bootstrap.min.css`
      * `vendor/bootstrap.min.js`
  * Another `package` asset name.

----

#### Example `package` asset configuration

{% highlight json %}
{
  "name": "my-project",
  "baseDir": "/path/to/your/project",
  "baseUrl": "/assets",
  "destDir": "./dist",
  "assets": [
    { "type": "file", "name": "site.css", ... },
    { "type": "folder", "name": "vendor", ... },
    { "type": "browserify", "name": "site.js", ... },
    {
      "type": "url",
      "name": "jquery.min.js",
      "url": "http://code.jquery.com/jquery-1.11.1.min.js"
    },
    {
      "type": "package",
      "name": "commonPackage",
      "assetNames": [
        "jquery.min.js",
        "vendor/bootstrap/bootstrap.min.js"
        "vendor/bootstrap/bootstrap.min.css",
      ]
    },
    {
      "type": "package",
      "name": "sitePackage",
      "assetNames": [
        "commonPackage",
        "vendor/bootstrap/bootstrap.min.js",
        "site.css",
        "site.js"
      ]
    }
  ]
}
{% endhighlight %}

The above example will result in two (2) packages:

* `commonPackage` has three (3) assets with the following URLs:

  ```
  http://code.jquery.com/jquery-1.11.1.min.js
  /assets/vendor/bootstrap/bootstrap.min.js
  /assets/vendor/bootstrap/bootstrap.min.css
  ```

* `sitePackage` has five (5) assets with the following URLs:

  ```
  http://code.jquery.com/jquery-1.11.1.min.js
  /assets/vendor/bootstrap/bootstrap.min.js
  /assets/vendor/bootstrap/bootstrap.min.css
  /assets/site.css
  /assets/site.js
  ```

Notes

* `sitePackage` contains another `package` asset `commonPackage`.
* `sitePackage` contains `vendor/bootstrap/bootstrap.min.js` <br/>(a file in a `folder` asset which is already an asset in `commonPackage`)
* The order of the assets in a package is preserved, making managing asset dependencies maintainable.


text:
* Fixes error with long strings in Lua 5.1 (@pgimeno)
* Adds incremental mode (@pgimeno)


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="org.djodjo.comm.jus.examples.BlankFragment">

    <android.support.v7.widget.RecyclerView

        android:id="@+id/list_images"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="7dp"
        android:layout_marginRight="7dp">

    </android.support.v7.widget.RecyclerView>

</FrameLayout>


text:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

import { SERVER_API_URL } from 'app/app.constants';

@Injectable({ providedIn: 'root' })
export class PasswordResetFinishService {
  constructor(private http: HttpClient) {}

  save(keyAndPassword: any): Observable<any> {
    return this.http.post(SERVER_API_URL + 'api/account/reset-password/finish', keyAndPassword);
  }
}


text:
package org.apache.lenya.cms.cocoon.source;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.MalformedURLException;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.cocoon.processing.ProcessInfoProvider;
import org.apache.cocoon.spring.configurator.WebAppContextUtils;
import org.apache.commons.logging.Log;
import org.apache.excalibur.source.ModifiableTraversableSource;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceException;
import org.apache.excalibur.source.SourceNotFoundException;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.AbstractSource;
import org.apache.lenya.cms.publication.Document;
import org.apache.lenya.cms.publication.Publication;
import org.apache.lenya.cms.publication.Session;
import org.apache.lenya.cms.repository.ContentHolder;
import org.apache.lenya.cms.repository.Node;
import org.apache.lenya.cms.repository.NodeFactory;
import org.apache.lenya.cms.repository.RepositoryException;
import org.apache.lenya.cms.repository.SessionHolder;
import org.apache.lenya.util.Query;
import org.apache.lenya.utils.ServletHelper;
import org.apache.lenya.utils.URLInformation;
/**
 * Repository source.
 *
 * @version $Id$
 */
public class RepositorySource extends AbstractSource implements ModifiableTraversableSource {

    private ContentHolder content;
    private Session session;
    private Log logger;
    protected static final String SCHEME = "lenya";

    private NodeFactory nodeFactory;

    /**
     * @param nodeFactory The node factory.
     * @param uri The source URI.
     * @param session The repository session.
     * @param logger The logger.
     * @throws SourceException if an error occurs.
     * @throws MalformedURLException if an error occurs.
     */
    public RepositorySource(NodeFactory nodeFactory, String uri, Session session, Log logger)
            throws SourceException, MalformedURLException {
        this.logger = logger;
        this.nodeFactory = nodeFactory;

        if (getLogger().isDebugEnabled())
            getLogger().debug("Init RepositorySource: " + uri);

        if (session == null) {
            throw new IllegalArgumentException("The repository session must not be null!");
        }
        this.session = session;

        if (uri == null) {
            throw new MalformedURLException("The source URI must not be null!");
        }

        setSystemId(uri);

        // Scheme
        int start = 0;
        int end = uri.indexOf(':');
        if (end == -1)
            throw new MalformedURLException(
                    "Malformed uri for xmodule source (cannot find scheme) : " + uri);

        String scheme = uri.substring(start, end);
        if (!SCHEME.equals(scheme))
            throw new MalformedURLException("Malformed uri for a xmodule source : " + uri);

        setScheme(scheme);

        try {

            String sourceUri;
            int revisionNumber = -1;

            int questionMarkIndex = uri.indexOf("?");
            if (questionMarkIndex > -1) {
                sourceUri = uri.substring(0, questionMarkIndex);
                Query query = new Query(uri.substring(questionMarkIndex + 1));
                String revisionString = query.getValue("rev", null);
                if (revisionString != null) {
                    ProcessInfoProvider process = (ProcessInfoProvider) WebAppContextUtils
                            .getCurrentWebApplicationContext().getBean(ProcessInfoProvider.ROLE);
                    HttpServletRequest request = process.getRequest();
                    String webappUrl = ServletHelper.getWebappURI(request);
                    String pubId = new URLInformation(webappUrl).getPublicationId();
                    Publication pub = this.session.getPublication(pubId);
                    Document currentDoc = pub.getSession().getUriHandler().getDocument(webappUrl);
                    if (currentDoc.getSourceURI().equals(sourceUri)) {
                        revisionNumber = Integer.valueOf(revisionString).intValue();
                    }
                }
            } else {
                sourceUri = uri;
            }

            org.apache.lenya.cms.repository.Session repoSession = ((SessionHolder) session)
                    .getRepositorySession();
            if (revisionNumber == -1) {
                this.content = (ContentHolder) repoSession
                        .getRepositoryItem(nodeFactory, sourceUri);
            } else {
                Node node = (Node) repoSession.getRepositoryItem(nodeFactory, sourceUri);
                this.content = node.getHistory().getRevision(revisionNumber);
            }

        } catch (Exception e) {
            throw new SourceException("Creating repository node failed: ", e);
        }
    }

    /**
     * @return The repository node which is accessed by this source.
     */
    public Node getNode() {

        if (!(this.content instanceof Node)) {
            throw new RuntimeException(
                    "This operation can only be invoked on nodes, not on revisions.");
        }

        return (Node) this.content;
    }

    protected Log getLogger() {
        return this.logger;
    }

    /**
     * @see org.apache.excalibur.source.ModifiableSource#getOutputStream()
     */
    public OutputStream getOutputStream() throws IOException {
        try {
            return getNode().getOutputStream();
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @see org.apache.excalibur.source.ModifiableSource#delete()
     */
    public void delete() {
        try {
            getNode().delete();
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @see org.apache.excalibur.source.ModifiableSource#canCancel(java.io.OutputStream)
     */
    public boolean canCancel(OutputStream arg0) {
        return false;
    }

    /**
     * @see org.apache.excalibur.source.ModifiableSource#cancel(java.io.OutputStream)
     */
    public void cancel(OutputStream arg0) throws IOException {
    }

    /**
     * @see org.apache.excalibur.source.Source#exists()
     */
    public boolean exists() {
        try {
            if (getContent().exists()) {
                return true;
            } else {
                return isCollection();
            }
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @see org.apache.excalibur.source.Source#getInputStream()
     */
    public InputStream getInputStream() throws IOException, SourceNotFoundException {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Get InputStream for " + getURI());
        if (!exists()) {
            throw new SourceNotFoundException("The source [" + getURI() + "] does not exist!");
        }
        try {
            return getContent().getInputStream();
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    protected InputStream convert(org.w3c.dom.Document edoc) throws IOException {

        final org.w3c.dom.Document doc = edoc;
        final PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream();
        pis.connect(pos);

        (new Thread(new Runnable() {

            public void run() {
                try {
                    transform(doc, pos);
                } catch (TransformerException e) {
                    throw new RuntimeException(
                            "Failed to tranform org.w3c.dom.Document to PipedOutputStream", e);
                } finally {
                    try {
                        pos.close();
                    } catch (Exception ignore) {
                        ignore.printStackTrace();
                    }
                }
            }
        }, getClass().getName() + ".convert(org.w3c.dom.Document edoc)")).start();

        return pis;
    }

    void transform(org.w3c.dom.Document edoc, PipedOutputStream pos) throws TransformerException {

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        transformer.setOutputProperty("encoding", "UTF-8");
        transformer.setOutputProperty("indent", "yes");

        transformer.transform(new DOMSource(edoc), new StreamResult(pos));

    }

    /**
     * @return The content of this source.
     */
    public ContentHolder getContent() {
        return this.content;
    }

    /**
     * @see org.apache.excalibur.source.Source#getContentLength()
     */
    public long getContentLength() {
        try {
            return getContent().getContentLength();
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @see org.apache.excalibur.source.Source#getLastModified()
     */
    public long getLastModified() {
        try {
            return getContent().getLastModified();
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @return The source URI.
     */
    public String getSourceURI() {
        return getContent().getSourceURI();
    }

    /**
     * @see org.apache.excalibur.source.Source#getMimeType()
     */
    public String getMimeType() {
        try {
            return getContent().getMimeType();
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     */
    public Source getParent() {
        getLogger().warn("getParent() not implemented yet!");
        return null;
    }

    /**
     *
     */
    public void makeCollection() {
        getLogger().warn("RepositorySource().makeCollection() not implemented yet!");
    }

    /**
     *
     */
    public String getName() {
        // Quick and dirty
        String name = new java.io.File(getURI()).getName();
        if (getLogger().isDebugEnabled())
            getLogger().debug("getName(): URI: " + name);
        return name;
    }

    /**
     *
     */
    public Source getChild(String name) {
        getLogger().warn("getChild() not implemented yet!");
        return null;
    }

    /**
     *
     */
    public Collection getChildren() {
        try {
            Collection children = getNode().getChildren();
            java.util.Iterator iterator = children.iterator();
            java.util.Vector newChildren = new java.util.Vector();
            while (iterator.hasNext()) {
                Node child = (Node) iterator.next();
                newChildren.add(new RepositorySource(getNodeFactory(), child.getSourceURI(),
                        this.session, getLogger()));
            }
            return newChildren;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     */
    public boolean isCollection() {
        try {
            return getNode().isCollection();
        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }
    }

    private SourceValidity validity;

    public SourceValidity getValidity() {
        if (this.validity == null) {
            this.validity = new RepositorySourceValidity(this);
        }
        return this.validity;
    }

    public NodeFactory getNodeFactory() {
        return nodeFactory;
    }

}


text:
#ifndef SETTINGS_H

#define SETTINGS_H

#include "structures/darray.h"

typedef struct _setting {
    /* data */
    char* name;
    char* value;
} setting_t;

typedef struct _settings_t {
    /* data */
    DArray* list;
} setting_arr_t;

// Parse a string into a config value.
setting_t *settings_parseln(char* string);

// Read a file and return a list of settings.
setting_arr_t *settings_read(char* filename);

//settings_t* settings_fill_from_argl(ArgList* argl);
#endif /* end of include guard: SETTINGS */


text:
'use strict';

var FinancialEntity = require('./FinancialEntity');

// ==============================
// CONCRETE ATM
// ==============================

var ATM, bankAccount;

ATM = function (account) {
    bankAccount = account;
};
ATM.prototype = Object.create(FinancialEntity.prototype);
ATM.prototype.constructor = ATM;

ATM.prototype.withdrawMoney = function (code) {
    if (code !== 1337) {
        throw {
            type: "AuthenticationException",
            message: "Invalid code"
        };
    }
    return bankAccount.withdrawMoney();
};

module.exports = ATM;


text:
package com.jakefallin.rhsapp.Objects;

/**
 * Created by Jake on 5/18/2016.
 */

public class Startup {

    private String title, description;
    private boolean cb1, cb2, cb3, cb4;

    public Startup(int day) {

        title = "period" + day;
        description = "";
        cb1 = true;
        cb2 = true;
        cb3 = true;
        cb4 = true;
    }

    public Startup(String t, String d, boolean c1, boolean c2, boolean c3, boolean c4) {
        title = t;
        description = d;
        cb1 = c1;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isCb1() {
        return cb1;
    }

    public void setCb1(boolean cb1) {
        this.cb1 = cb1;
    }

    public boolean isCb2() {
        return cb2;
    }

    public void setCb2(boolean cb2) {
        this.cb2 = cb2;
    }

    public boolean isCb3() {
        return cb3;
    }

    public void setCb3(boolean cb3) {
        this.cb3 = cb3;
    }

    public boolean isCb4() {
        return cb4;
    }

    public void setCb4(boolean cb4) {
        this.cb4 = cb4;
    }

    public String getDescription() {
        return description;
    }
}


text:
Public Class Class1

    Public Const Constant As String = "CodeNav"

    Protected Version As Integer = 1

    Public Field As Boolean = True

    Private _secret As int = 2

    Dim LocalType = "string"

End Class


text:
class Profile;

namespace extensions {

class MediaGalleriesPrivateEventRouter;

// The profile-keyed service that manages the media galleries private extension
// API.
class MediaGalleriesPrivateAPI : public ProfileKeyedAPI,
                                 public EventRouter::Observer {
 public:
  explicit MediaGalleriesPrivateAPI(Profile* profile);
  virtual ~MediaGalleriesPrivateAPI();

  // ProfileKeyedService implementation.
  virtual void Shutdown() OVERRIDE;

  // ProfileKeyedAPI implementation.
  static ProfileKeyedAPIFactory<MediaGalleriesPrivateAPI>* GetFactoryInstance();

  // Convenience method to get the MediaGalleriesPrivateAPI for a profile.
  static MediaGalleriesPrivateAPI* Get(Profile* profile);

  // EventRouter::Observer implementation.
  virtual void OnListenerAdded(const EventListenerInfo& details) OVERRIDE;

  MediaGalleriesPrivateEventRouter* GetEventRouter();
  GalleryWatchStateTracker* GetGalleryWatchStateTracker();

 private:
  friend class ProfileKeyedAPIFactory<MediaGalleriesPrivateAPI>;

  void MaybeInitializeEventRouter();

  // ProfileKeyedAPI implementation.
  static const char* service_name() {
    return "MediaGalleriesPrivateAPI";
  }
  static const bool kServiceIsNULLWhileTesting = true;

  // Current profile.
  Profile* profile_;

  GalleryWatchStateTracker tracker_;

  // Created lazily on first access.
  scoped_ptr<MediaGalleriesPrivateEventRouter>
      media_galleries_private_event_router_;

  DISALLOW_COPY_AND_ASSIGN(MediaGalleriesPrivateAPI);
};

// Implements the chrome.mediaGalleriesPrivate.addGalleryWatch method.
class MediaGalleriesPrivateAddGalleryWatchFunction
    : public AsyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("mediaGalleriesPrivate.addGalleryWatch",
                             MEDIAGALLERIESPRIVATE_ADDGALLERYWATCH);

 protected:
  virtual ~MediaGalleriesPrivateAddGalleryWatchFunction();

  // AsyncExtensionFunction overrides.
  virtual bool RunImpl() OVERRIDE;

 private:
  // Gallery watch request handler.
  void HandleResponse(chrome::MediaGalleryPrefId gallery_id,
                      bool success);
};

// Implements the chrome.mediaGalleriesPrivate.removeGalleryWatch method.
class MediaGalleriesPrivateRemoveGalleryWatchFunction
    : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("mediaGalleriesPrivate.removeGalleryWatch",
                             MEDIAGALLERIESPRIVATE_REMOVEGALLERYWATCH);

 protected:
  virtual ~MediaGalleriesPrivateRemoveGalleryWatchFunction();

  // SyncExtensionFunction overrides.
  virtual bool RunImpl() OVERRIDE;
};

// Implements the chrome.mediaGalleriesPrivate.getAllGalleryWatch method.
class MediaGalleriesPrivateGetAllGalleryWatchFunction
    : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("mediaGalleriesPrivate.getAllGalleryWatch",
                             MEDIAGALLERIESPRIVATE_GETALLGALLERYWATCH);
 protected:
  virtual ~MediaGalleriesPrivateGetAllGalleryWatchFunction();

  // SyncExtensionFunction overrides.
  virtual bool RunImpl() OVERRIDE;
};

// Implements the chrome.mediaGalleriesPrivate.removeAllGalleryWatch method.
class MediaGalleriesPrivateRemoveAllGalleryWatchFunction
    : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("mediaGalleriesPrivate.removeAllGalleryWatch",
                             MEDIAGALLERIESPRIVATE_REMOVEALLGALLERYWATCH);
 protected:
  virtual ~MediaGalleriesPrivateRemoveAllGalleryWatchFunction();

  // SyncExtensionFunction overrides.
  virtual bool RunImpl() OVERRIDE;
};

// Implements the chrome.mediaGalleriesPrivate.ejectDevice method.
class MediaGalleriesPrivateEjectDeviceFunction
    : public AsyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("mediaGalleriesPrivate.ejectDevice",
                             MEDIAGALLERIESPRIVATE_EJECTDEVICE);

 protected:
  virtual ~MediaGalleriesPrivateEjectDeviceFunction();

  // AsyncExtensionFunction overrides.
  virtual bool RunImpl() OVERRIDE;

 private:
  // Eject device request handler.
  void HandleResponse(
      chrome::RemovableStorageNotifications::EjectStatus status);
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_MEDIA_GALLERIES_PRIVATE_MEDIA_GALLERIES_PRIVATE_API_H_


text:
namespace Google.Cloud.PubSub.V1.Snippets
{
    // [START pubsub_v1_generated_SubscriberServiceApi_CreateSubscription_sync]
    using Google.Cloud.PubSub.V1;
    using Google.Protobuf.WellKnownTypes;

    public sealed partial class GeneratedSubscriberServiceApiClientSnippets
    {
        /// <summary>Snippet for CreateSubscription</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void CreateSubscriptionRequestObject()
        {
            // Create client
            SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create();
            // Initialize request argument(s)
            Subscription request = new Subscription
            {
                SubscriptionName = SubscriptionName.FromProjectSubscription("[PROJECT]", "[SUBSCRIPTION]"),
                TopicAsTopicName = TopicName.FromProjectTopic("[PROJECT]", "[TOPIC]"),
                PushConfig = new PushConfig(),
                AckDeadlineSeconds = 0,
                RetainAckedMessages = false,
                MessageRetentionDuration = new Duration(),
                Labels = { { "", "" }, },
                EnableMessageOrdering = false,
                ExpirationPolicy = new ExpirationPolicy(),
                Filter = "",
                DeadLetterPolicy = new DeadLetterPolicy(),
                RetryPolicy = new RetryPolicy(),
                Detached = false,
                EnableExactlyOnceDelivery = false,
                TopicMessageRetentionDuration = new Duration(),
                BigqueryConfig = new BigQueryConfig(),
                State = Subscription.Types.State.Unspecified,
            };
            // Make the request
            Subscription response = subscriberServiceApiClient.CreateSubscription(request);
        }
    }
    // [END pubsub_v1_generated_SubscriberServiceApi_CreateSubscription_sync]
}


text:
import ActionTypes from "redux-arena/ActionTypes";

function addCnt() {
  return {
    type: "ADD_CNT"
  };
}

function clearCnt() {
  return {
    type: ActionTypes.ARENA_SCENE_SET_STATE,
    state: {
      cnt: 0
    }
  };
}

export default { addCnt, clearCnt };


text:
SET @sName = 'bx_timeline';

-- TABLES
CREATE TABLE IF NOT EXISTS `bx_timeline_events` (
  `id` int(11) NOT NULL auto_increment,
  `owner_id` int(11) NOT NULL default '0',
  `system` tinyint(4) NOT NULL default '1',
  `type` varchar(255) NOT NULL,
  `action` varchar(255) NOT NULL,
  `object_id` int(11) NOT NULL default '0',
  `object_owner_id` int(11) NOT NULL default '0',
  `object_privacy_view` varchar(16) NOT NULL default '3',
  `content` text NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `location` text NOT NULL,
  `views` int(11) unsigned NOT NULL default '0',
  `rate` float NOT NULL default '0',
  `votes` int(11) unsigned NOT NULL default '0',
  `rrate` float NOT NULL default '0',
  `rvotes` int(11) NOT NULL default '0',
  `score` int(11) NOT NULL default '0',
  `sc_up` int(11) NOT NULL default '0',
  `sc_down` int(11) NOT NULL default '0',
  `comments` int(11) unsigned NOT NULL default '0',
  `reports` int(11) unsigned NOT NULL default '0',
  `reposts` int(11) unsigned NOT NULL default '0',
  `date` int(11) NOT NULL default '0',
  `published` int(11) NOT NULL default '0',
  `status` enum ('active', 'awaiting', 'failed', 'hidden', 'deleted') NOT NULL DEFAULT 'active',
  `active` tinyint(4) NOT NULL default '1',
  `pinned` int(11) NOT NULL default '0',
  `sticked` int(11) NOT NULL default '0',
  `promoted` int(11) NOT NULL default '0',
  PRIMARY KEY (`id`),
  KEY `owner_id` (`owner_id`),
  KEY `object_id` (`object_id`),
  FULLTEXT KEY `search_fields` (`title`, `description`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_handlers` (
  `id` int(11) NOT NULL auto_increment,
  `group` varchar(64) NOT NULL default '',
  `type` enum('insert','update','delete') NOT NULL DEFAULT 'insert',
  `alert_unit` varchar(64) NOT NULL default '',
  `alert_action` varchar(64) NOT NULL default '',
  `content` text NOT NULL,
  `privacy` varchar(64) NOT NULL default '',
  PRIMARY KEY  (`id`),
  UNIQUE `handler` (`group`, `type`),
  UNIQUE `alert` (`alert_unit`, `alert_action`)
);

INSERT INTO `bx_timeline_handlers`(`group`, `type`, `alert_unit`, `alert_action`, `content`) VALUES
('common_post', 'insert', 'timeline_common_post', '', ''),
('common_repost', 'insert', 'timeline_common_repost', '', ''),

('profile', 'delete', 'profile', 'delete', ''),

('comment', 'insert', 'comment', 'added', 'a:5:{s:11:"module_name";s:6:"system";s:13:"module_method";s:17:"get_timeline_post";s:12:"module_class";s:17:"TemplCmtsServices";s:9:"groupable";i:0;s:8:"group_by";s:0:"";}'),
('comment', 'update', 'comment', 'edited', ''),
('comment', 'delete', 'comment', 'deleted', '');

CREATE TABLE IF NOT EXISTS `bx_timeline_cache` (
  `type` varchar(32) NOT NULL default '',
  `context_id` int(11) NOT NULL default '0',
  `profile_id` int(11) NOT NULL default '0',
  `event_id` int(11) NOT NULL default '0',
  `date` int(11) NOT NULL default '0',
  `important` tinyint(4) NOT NULL default '0',
  PRIMARY KEY `item` (`type`, `context_id`, `profile_id`, `event_id`)
);

-- TABLE: mute
CREATE TABLE IF NOT EXISTS `bx_timeline_mute` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `initiator` int(11) NOT NULL,
  `content` int(11) NOT NULL,
  `mutual` tinyint(4) NOT NULL,
  `added` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `initiator` (`initiator`,`content`),
  KEY `content` (`content`)
);

-- TABLES: STORAGES, TRANSCODERS, UPLOADERS
CREATE TABLE IF NOT EXISTS `bx_timeline_photos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `profile_id` int(10) unsigned NOT NULL,
  `remote_id` varchar(128) NOT NULL,
  `path` varchar(255) NOT NULL,
  `file_name` varchar(255) NOT NULL,
  `mime_type` varchar(128) NOT NULL,
  `ext` varchar(32) NOT NULL,
  `size` bigint(20) NOT NULL,
  `added` int(11) NOT NULL,
  `modified` int(11) NOT NULL,
  `private` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `remote_id` (`remote_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_photos_processed` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `profile_id` int(10) unsigned NOT NULL,
  `remote_id` varchar(128) NOT NULL,
  `path` varchar(255) NOT NULL,
  `file_name` varchar(255) NOT NULL,
  `mime_type` varchar(128) NOT NULL,
  `ext` varchar(32) NOT NULL,
  `size` bigint(20) NOT NULL,
  `added` int(11) NOT NULL,
  `modified` int(11) NOT NULL,
  `private` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `remote_id` (`remote_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_photos2events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_id` int(11) NOT NULL DEFAULT '0',
  `media_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `media` (`event_id`, `media_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_videos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `profile_id` int(10) unsigned NOT NULL,
  `remote_id` varchar(128) NOT NULL,
  `path` varchar(255) NOT NULL,
  `file_name` varchar(255) NOT NULL,
  `mime_type` varchar(128) NOT NULL,
  `ext` varchar(32) NOT NULL,
  `size` bigint(20) NOT NULL,
  `added` int(11) NOT NULL,
  `modified` int(11) NOT NULL,
  `private` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `remote_id` (`remote_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_videos_processed` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `profile_id` int(10) unsigned NOT NULL,
  `remote_id` varchar(128) NOT NULL,
  `path` varchar(255) NOT NULL,
  `file_name` varchar(255) NOT NULL,
  `mime_type` varchar(128) NOT NULL,
  `ext` varchar(32) NOT NULL,
  `size` bigint(20) NOT NULL,
  `added` int(11) NOT NULL,
  `modified` int(11) NOT NULL,
  `private` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `remote_id` (`remote_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_videos2events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_id` int(11) NOT NULL DEFAULT '0',
  `media_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `media` (`event_id`, `media_id`)
);

-- TABLES: LINKS
CREATE TABLE IF NOT EXISTS `bx_timeline_links` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `profile_id` int(10) unsigned NOT NULL,
  `media_id` int(11) NOT NULL DEFAULT '0',
  `url` varchar(255) NOT NULL,
  `title` varchar(255) NOT NULL,
  `text` text NOT NULL,
  `added` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `profile_id` (`profile_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_links2events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_id` int(11) NOT NULL DEFAULT '0',
  `link_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `link` (`link_id`, `event_id`)
);

-- TABLES: REPOSTS
CREATE TABLE IF NOT EXISTS `bx_timeline_reposts_track` (
  `event_id` int(11) NOT NULL default '0',
  `author_id` int(11) NOT NULL default '0',
  `author_nip` int(11) unsigned NOT NULL default '0',
  `reposted_id` int(11) NOT NULL default '0',
  `date` int(11) NOT NULL default '0',
  UNIQUE KEY `event_id` (`event_id`),
  KEY `repost` (`reposted_id`, `author_nip`)
);

-- TABLES: COMMENTS
CREATE TABLE IF NOT EXISTS `bx_timeline_comments` (
  `cmt_id` int(11) NOT NULL AUTO_INCREMENT,
  `cmt_parent_id` int(11) NOT NULL DEFAULT '0',
  `cmt_vparent_id` int(11) NOT NULL DEFAULT '0',
  `cmt_object_id` int(11) NOT NULL DEFAULT '0',
  `cmt_author_id` int(11) NOT NULL DEFAULT '0',
  `cmt_level` int(11) NOT NULL DEFAULT '0',
  `cmt_text` text NOT NULL,
  `cmt_time` int(11) unsigned NOT NULL DEFAULT '0',
  `cmt_replies` int(11) NOT NULL DEFAULT '0',
  `cmt_pinned` int(11) NOT NULL default '0',
  PRIMARY KEY (`cmt_id`),
  KEY `cmt_object_id` (`cmt_object_id`,`cmt_parent_id`),
  FULLTEXT KEY `search_fields` (`cmt_text`)
);

-- TABLE: views
CREATE TABLE IF NOT EXISTS `bx_timeline_views_track` (
  `object_id` int(11) NOT NULL default '0',
  `viewer_id` int(11) NOT NULL default '0',
  `viewer_nip` int(11) unsigned NOT NULL default '0',
  `date` int(11) NOT NULL default '0',
  KEY `id` (`object_id`,`viewer_id`,`viewer_nip`)
);

-- TABLES: VOTES
CREATE TABLE IF NOT EXISTS `bx_timeline_votes` (
  `object_id` int(11) NOT NULL default '0',
  `count` int(11) NOT NULL default '0',
  `sum` int(11) NOT NULL default '0',
  UNIQUE KEY `object_id` (`object_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_votes_track` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `object_id` int(11) NOT NULL default '0',
  `author_id` int(11) NOT NULL default '0',
  `author_nip` int(11) unsigned NOT NULL default '0',
  `value` tinyint(4) NOT NULL default '0',
  `date` int(11) NOT NULL default '0',
  PRIMARY KEY (`id`),
  KEY `vote` (`object_id`, `author_nip`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_reactions` (
  `object_id` int(11) NOT NULL default '0',
  `reaction` varchar(32) NOT NULL default '',
  `count` int(11) NOT NULL default '0',
  `sum` int(11) NOT NULL default '0',
  UNIQUE KEY `reaction` (`object_id`, `reaction`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_reactions_track` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `object_id` int(11) NOT NULL default '0',
  `author_id` int(11) NOT NULL default '0',
  `author_nip` int(11) unsigned NOT NULL default '0',
  `reaction` varchar(32) NOT NULL default '',
  `value` tinyint(4) NOT NULL default '0',
  `date` int(11) NOT NULL default '0',
  PRIMARY KEY (`id`),
  KEY `vote` (`object_id`, `author_nip`)
);

-- TABLE: metas
CREATE TABLE IF NOT EXISTS `bx_timeline_meta_keywords` (
  `object_id` int(10) unsigned NOT NULL,
  `keyword` varchar(255) NOT NULL,
  KEY `object_id` (`object_id`),
  KEY `keyword` (`keyword`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_meta_locations` (
  `object_id` int(10) unsigned NOT NULL,
  `lat` double NOT NULL,
  `lng` double NOT NULL,
  `country` varchar(2) NOT NULL,
  `state` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `zip` varchar(255) NOT NULL,
  `street` varchar(255) NOT NULL,
  `street_number` varchar(255) NOT NULL,
  PRIMARY KEY (`object_id`),
  KEY `country_state_city` (`country`,`state`(8),`city`(8))
);

CREATE TABLE IF NOT EXISTS `bx_timeline_meta_mentions` (
  `object_id` int(10) unsigned NOT NULL,
  `profile_id` int(10) unsigned NOT NULL,
  KEY `object_id` (`object_id`),
  KEY `profile_id` (`profile_id`)
);

-- TABLE: reports
CREATE TABLE IF NOT EXISTS `bx_timeline_reports` (
  `object_id` int(11) NOT NULL default '0',
  `count` int(11) NOT NULL default '0',
  UNIQUE KEY `object_id` (`object_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_reports_track` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `object_id` int(11) NOT NULL default '0',
  `author_id` int(11) NOT NULL default '0',
  `author_nip` int(11) unsigned NOT NULL default '0',
  `type` varchar(32) NOT NULL default '',
  `text` text NOT NULL default '',
  `date` int(11) NOT NULL default '0',
  PRIMARY KEY (`id`),
  KEY `report` (`object_id`, `author_nip`)
);

-- TABLE: hot track
CREATE TABLE IF NOT EXISTS `bx_timeline_hot_track` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `event_id` int(11) NOT NULL default '0',
  `value` int(11) NOT NULL default '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `event_id` (`event_id`)
);

-- TABLE: scores
CREATE TABLE IF NOT EXISTS `bx_timeline_scores` (
  `object_id` int(11) NOT NULL default '0',
  `count_up` int(11) NOT NULL default '0',
  `count_down` int(11) NOT NULL default '0',
  UNIQUE KEY `object_id` (`object_id`)
);

CREATE TABLE IF NOT EXISTS `bx_timeline_scores_track` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `object_id` int(11) NOT NULL default '0',
  `author_id` int(11) NOT NULL default '0',
  `author_nip` int(11) unsigned NOT NULL default '0',
  `type` varchar(8) NOT NULL default '',
  `date` int(11) NOT NULL default '0',
  PRIMARY KEY (`id`),
  KEY `vote` (`object_id`, `author_nip`)
);

-- STORAGES, TRANSCODERS, UPLOADERS
SET @sStorageEngine = (SELECT `value` FROM `sys_options` WHERE `name` = 'sys_storage_default');

INSERT INTO `sys_objects_uploader` (`object`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_timeline_simple_photo', 1, 'BxTimelineUploaderSimpleAttach', 'modules/boonex/timeline/classes/BxTimelineUploaderSimpleAttach.php'),
('bx_timeline_simple_video', 1, 'BxTimelineUploaderSimpleAttach', 'modules/boonex/timeline/classes/BxTimelineUploaderSimpleAttach.php'),
('bx_timeline_html5_photo', 1, 'BxTimelineUploaderHTML5Attach', 'modules/boonex/timeline/classes/BxTimelineUploaderHTML5Attach.php'),
('bx_timeline_html5_video', 1, 'BxTimelineUploaderHTML5Attach', 'modules/boonex/timeline/classes/BxTimelineUploaderHTML5Attach.php'),
('bx_timeline_record_video', 1, 'BxTimelineUploaderRecordVideoAttach', 'modules/boonex/timeline/classes/BxTimelineUploaderRecordVideoAttach.php');

INSERT INTO `sys_objects_storage` (`object`, `engine`, `params`, `token_life`, `cache_control`, `levels`, `table_files`, `ext_mode`, `ext_allow`, `ext_deny`, `quota_size`, `current_size`, `quota_number`, `current_number`, `max_file_size`, `ts`) VALUES
('bx_timeline_photos', @sStorageEngine, '', 360, 2592000, 3, 'bx_timeline_photos', 'allow-deny', 'jpg,jpeg,jpe,gif,png', '', 0, 0, 0, 0, 0, 0),
('bx_timeline_photos_processed', @sStorageEngine, '', 360, 2592000, 3, 'bx_timeline_photos_processed', 'allow-deny', 'jpg,jpeg,jpe,gif,png', '', 0, 0, 0, 0, 0, 0),

('bx_timeline_videos', @sStorageEngine, '', 360, 2592000, 3, 'bx_timeline_videos', 'allow-deny', 'avi,flv,mpg,mpeg,wmv,mp4,m4v,mov,qt,divx,xvid,3gp,3g2,webm,mkv,ogv,ogg,rm,rmvb,asf,drc', '', 0, 0, 0, 0, 0, 0),
('bx_timeline_videos_processed', @sStorageEngine, '', 360, 2592000, 3, 'bx_timeline_videos_processed', 'allow-deny', 'jpg,jpeg,jpe,gif,png,avi,flv,mpg,mpeg,wmv,mp4,m4v,mov,qt,divx,xvid,3gp,3g2,webm,mkv,ogv,ogg,rm,rmvb,asf,drc', '', 0, 0, 0, 0, 0, 0);

INSERT INTO `sys_objects_transcoder` (`object`, `storage_object`, `source_type`, `source_params`, `private`, `atime_tracking`, `atime_pruning`, `ts`, `override_class_name`, `override_class_file`) VALUES
('bx_timeline_photos_preview', 'bx_timeline_photos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_photos";}', 'no', '1', '2592000', '0', '', ''),
('bx_timeline_photos_view', 'bx_timeline_photos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_photos";}', 'no', '1', '2592000', '0', '', ''),
('bx_timeline_photos_medium', 'bx_timeline_photos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_photos";}', 'no', '1', '2592000', '0', '', ''),
('bx_timeline_photos_big', 'bx_timeline_photos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_photos";}', 'no', '1', '2592000', '0', '', ''),

('bx_timeline_videos_poster', 'bx_timeline_videos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_videos";}', 'no', '0', '0', '0', 'BxDolTranscoderVideo', ''),
('bx_timeline_videos_mp4', 'bx_timeline_videos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_videos";}', 'no', '0', '0', '0', 'BxDolTranscoderVideo', ''),
('bx_timeline_videos_mp4_hd', 'bx_timeline_videos_processed', 'Storage', 'a:1:{s:6:"object";s:18:"bx_timeline_videos";}', 'no', '0', '0', '0', 'BxDolTranscoderVideo', '');

INSERT INTO `sys_transcoder_filters` (`transcoder_object`, `filter`, `filter_params`, `order`) VALUES
('bx_timeline_photos_preview', 'Resize', 'a:3:{s:1:"w";s:3:"100";s:1:"h";s:3:"100";s:13:"square_resize";s:1:"1";}', '0'),
('bx_timeline_photos_view', 'Resize', 'a:1:{s:1:"w";s:3:"300";}', '0'),
('bx_timeline_photos_medium', 'Resize', 'a:1:{s:1:"w";s:3:"600";}', '0'),
('bx_timeline_photos_big', 'Resize', 'a:2:{s:1:"w";s:4:"1200";s:1:"h";s:4:"1200";}', '0'),

('bx_timeline_videos_poster', 'Poster', 'a:2:{s:1:"h";s:3:"318";s:10:"force_type";s:3:"jpg";}', 0),
('bx_timeline_videos_mp4', 'Mp4', 'a:2:{s:1:"h";s:3:"318";s:10:"force_type";s:3:"mp4";}', 0),
('bx_timeline_videos_mp4_hd', 'Mp4', 'a:3:{s:1:"h";s:3:"720";s:13:"video_bitrate";s:4:"1536";s:10:"force_type";s:3:"mp4";}', 0);

-- Forms -> Post
INSERT INTO `sys_objects_form` (`object`, `module`, `title`, `action`, `form_attrs`, `submit_name`, `table`, `key`, `uri`, `uri_title`, `params`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_timeline_post', @sName, '_bx_timeline_form_post', '', '', 'tlb_do_submit', 'bx_timeline_events', 'id', '', '', '', 0, 1, 'BxTimelineFormPost', 'modules/boonex/timeline/classes/BxTimelineFormPost.php');

INSERT INTO `sys_form_displays` (`display_name`, `module`, `object`, `title`, `view_mode`) VALUES
('bx_timeline_post_add', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_add', 0),
('bx_timeline_post_add_public', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_add_public', 0),
('bx_timeline_post_add_profile', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_add_profile', 0),

('bx_timeline_post_edit', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_edit', 0),

('bx_timeline_post_view', @sName, 'bx_timeline_post', '_bx_timeline_form_post_display_view', 1);

INSERT INTO `sys_form_inputs` (`object`, `module`, `name`, `value`, `values`, `checked`, `type`, `caption_system`, `caption`, `info`, `required`, `collapsed`, `html`, `attrs`, `attrs_tr`, `attrs_wrapper`, `checker_func`, `checker_params`, `checker_error`, `db_pass`, `db_params`, `editable`, `deletable`) VALUES
('bx_timeline_post', @sName, 'type', 'post', '', 0, 'hidden', '_bx_timeline_form_post_input_sys_type', '', '', 0, 0, 0, '', '', '', '', '', '', 'Xss', '', 0, 0),
('bx_timeline_post', @sName, 'action', '', '', 0, 'hidden', '_bx_timeline_form_post_input_sys_action', '', '', 0, 0, 0, '', '', '', '', '', '', 'Xss', '', 0, 0),
('bx_timeline_post', @sName, 'owner_id', '0', '', 0, 'hidden', '_bx_timeline_form_post_input_sys_owner_id', '', '', 0, 0, 0, '', '', '', '', '', '', 'Int', '', 1, 0),
('bx_timeline_post', @sName, 'text', '', '', 0, 'textarea', '_bx_timeline_form_post_input_sys_text', '_bx_timeline_form_post_input_text', '', 0, 0, 3, 'a:1:{s:12:"autocomplete";s:3:"off";}', '', '', '', '', '', 'XssHtml', '', 1, 0),
('bx_timeline_post', @sName, 'anonymous', '', '', 0, 'switcher', '_sys_form_input_sys_anonymous', '_sys_form_input_anonymous', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'date', '', '', 0, 'datetime', '_bx_timeline_form_post_input_sys_date', '_bx_timeline_form_post_input_date', '', 0, 0, 0, '', '', '', '', '', '', 'DateTimeUtc', '', 1, 0),
('bx_timeline_post', @sName, 'published', '', '', 0, 'datetime', '_bx_timeline_form_post_input_sys_date_published', '_bx_timeline_form_post_input_date_published', '_bx_timeline_form_post_input_date_published_info', 0, 0, 0, '', '', '', '', '', '', 'DateTimeUtc', '', 1, 0),
('bx_timeline_post', @sName, 'object_privacy_view', '', '', 0, 'custom', '_bx_timeline_form_post_input_sys_object_privacy_view', '_bx_timeline_form_post_input_object_privacy_view', '', 1, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_post', @sName, 'location', '', '', 0, 'location', '_sys_form_input_sys_location', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'link', '', '', 0, 'custom', '_bx_timeline_form_post_input_sys_link', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'photo', 'a:1:{i:0;s:23:"bx_timeline_html5_photo";}', 'a:2:{s:24:"bx_timeline_simple_photo";s:26:"_sys_uploader_simple_title";s:23:"bx_timeline_html5_photo";s:25:"_sys_uploader_html5_title";}', 0, 'files', '_bx_timeline_form_post_input_sys_photo', '_bx_timeline_form_post_input_photo', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'video', 'a:2:{i:0;s:23:"bx_timeline_html5_video";i:1;s:24:"bx_timeline_record_video";}', 'a:3:{s:24:"bx_timeline_simple_video";s:26:"_sys_uploader_simple_title";s:23:"bx_timeline_html5_video";s:25:"_sys_uploader_html5_title";s:24:"bx_timeline_record_video";s:32:"_sys_uploader_record_video_title";}', 0, 'files', '_bx_timeline_form_post_input_sys_video', '_bx_timeline_form_post_input_video', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'attachments', '', '', 0, 'custom', '_bx_timeline_form_post_input_sys_attachments', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 1, 0),
('bx_timeline_post', @sName, 'controls', '', 'tlb_do_submit,tlb_do_cancel', 0, 'input_set', '', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_post', @sName, 'tlb_do_submit', '_bx_timeline_form_post_input_do_submit', '', 0, 'submit', '_bx_timeline_form_post_input_sys_do_submit', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_post', @sName, 'tlb_do_cancel', '_bx_timeline_form_post_input_do_cancel', '', 0, 'button', '_bx_timeline_form_post_input_sys_do_cancel', '', '', 0, 0, 0, 'a:2:{s:7:"onclick";s:51:"{js_object_view}.editPostCancel(this, {content_id})";s:5:"class";s:22:"bx-def-margin-sec-left";}', '', '', '', '', '', '', '', 0, 0);

INSERT INTO `sys_form_display_inputs` (`display_name`, `input_name`, `visible_for_levels`, `active`, `order`) VALUES
('bx_timeline_post_add', 'type', 2147483647, 1, 0),
('bx_timeline_post_add', 'action', 2147483647, 1, 1),
('bx_timeline_post_add', 'text', 2147483647, 1, 2),
('bx_timeline_post_add', 'attachments', 2147483647, 1, 3),
('bx_timeline_post_add', 'owner_id', 2147483647, 1, 4),
('bx_timeline_post_add', 'object_privacy_view', 2147483647, 1, 5),
('bx_timeline_post_add', 'published', 192, 1, 6),
('bx_timeline_post_add', 'location', 2147483647, 1, 7),
('bx_timeline_post_add', 'link', 2147483647, 1, 8),
('bx_timeline_post_add', 'photo', 2147483647, 1, 9),
('bx_timeline_post_add', 'video', 2147483647, 1, 10),
('bx_timeline_post_add', 'tlb_do_submit', 2147483647, 1, 11),

('bx_timeline_post_add_public', 'type', 2147483647, 1, 0),
('bx_timeline_post_add_public', 'action', 2147483647, 1, 1),
('bx_timeline_post_add_public', 'owner_id', 2147483647, 1, 2),
('bx_timeline_post_add_public', 'text', 2147483647, 1, 3),
('bx_timeline_post_add_public', 'attachments', 2147483647, 1, 4),
('bx_timeline_post_add_public', 'object_privacy_view', 2147483647, 1, 5),
('bx_timeline_post_add_public', 'published', 192, 1, 6),
('bx_timeline_post_add_public', 'location', 2147483647, 1, 7),
('bx_timeline_post_add_public', 'link', 2147483647, 1, 8),
('bx_timeline_post_add_public', 'photo', 2147483647, 1, 9),
('bx_timeline_post_add_public', 'video', 2147483647, 1, 10),
('bx_timeline_post_add_public', 'tlb_do_submit', 2147483647, 1, 11),

('bx_timeline_post_add_profile', 'type', 2147483647, 1, 0),
('bx_timeline_post_add_profile', 'action', 2147483647, 1, 1),
('bx_timeline_post_add_profile', 'owner_id', 2147483647, 1, 2),
('bx_timeline_post_add_profile', 'text', 2147483647, 1, 3),
('bx_timeline_post_add_profile', 'attachments', 2147483647, 1, 4),
('bx_timeline_post_add_profile', 'object_privacy_view', 2147483647, 1, 5),
('bx_timeline_post_add_profile', 'published', 192, 1, 6),
('bx_timeline_post_add_profile', 'location', 2147483647, 1, 7),
('bx_timeline_post_add_profile', 'link', 2147483647, 1, 8),
('bx_timeline_post_add_profile', 'photo', 2147483647, 1, 9),
('bx_timeline_post_add_profile', 'video', 2147483647, 1, 10),
('bx_timeline_post_add_profile', 'tlb_do_submit', 2147483647, 1, 11),

('bx_timeline_post_edit', 'type', 2147483647, 1, 1),
('bx_timeline_post_edit', 'action', 2147483647, 1, 2),
('bx_timeline_post_edit', 'owner_id', 2147483647, 1, 3),
('bx_timeline_post_edit', 'text', 2147483647, 1, 4),
('bx_timeline_post_edit', 'attachments', 2147483647, 1, 5),
('bx_timeline_post_edit', 'published', 192, 1, 6),
('bx_timeline_post_edit', 'location', 2147483647, 1, 7),
('bx_timeline_post_edit', 'link', 2147483647, 1, 8),
('bx_timeline_post_edit', 'photo', 2147483647, 1, 9),
('bx_timeline_post_edit', 'video', 2147483647, 1, 10),
('bx_timeline_post_edit', 'controls', 2147483647, 1, 11),
('bx_timeline_post_edit', 'tlb_do_submit', 2147483647, 1, 12),
('bx_timeline_post_edit', 'tlb_do_cancel', 2147483647, 1, 13);

-- Forms -> Attach link
INSERT INTO `sys_objects_form` (`object`, `module`, `title`, `action`, `form_attrs`, `submit_name`, `table`, `key`, `uri`, `uri_title`, `params`, `deletable`, `active`, `override_class_name`, `override_class_file`) VALUES
('bx_timeline_attach_link', @sName, '_bx_timeline_form_attach_link', '', '', 'do_submit', 'bx_timeline_links', 'id', '', '', '', 0, 1, '', '');

INSERT INTO `sys_form_displays` (`display_name`, `module`, `object`, `title`, `view_mode`) VALUES
('bx_timeline_attach_link_add', @sName, 'bx_timeline_attach_link', '_bx_timeline_form_attach_link_display_add', 0);

INSERT INTO `sys_form_inputs` (`object`, `module`, `name`, `value`, `values`, `checked`, `type`, `caption_system`, `caption`, `info`, `required`, `collapsed`, `html`, `attrs`, `attrs_tr`, `attrs_wrapper`, `checker_func`, `checker_params`, `checker_error`, `db_pass`, `db_params`, `editable`, `deletable`) VALUES
('bx_timeline_attach_link', @sName, 'event_id', '0', '', 0, 'hidden', '_bx_timeline_form_attach_link_input_sys_event_id', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_attach_link', @sName, 'url', '', '', 0, 'text', '_bx_timeline_form_attach_link_input_sys_url', '_bx_timeline_form_attach_link_input_url', '', 0, 0, 0, '', '', '', 'Preg', 'a:1:{s:4:"preg";s:0:"";}', '_bx_timeline_form_attach_link_input_url_err', '', '', 0, 0),
('bx_timeline_attach_link', @sName, 'controls', '', 'do_submit,do_cancel', 0, 'input_set', '', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_attach_link', @sName, 'do_submit', '_bx_timeline_form_attach_link_input_do_submit', '', 0, 'submit', '_bx_timeline_form_attach_link_input_sys_do_submit', '', '', 0, 0, 0, '', '', '', '', '', '', '', '', 0, 0),
('bx_timeline_attach_link', @sName, 'do_cancel', '_bx_timeline_form_attach_link_input_do_cancel', '', 0, 'button', '_bx_timeline_form_attach_link_input_do_cancel', '', '', 0, 0, 0, 'a:2:{s:7:"onclick";s:45:"$(''.bx-popup-applied:visible'').dolPopupHide()";s:5:"class";s:22:"bx-def-margin-sec-left";}', '', '', '', '', '', '', '', 0, 0);

INSERT INTO `sys_form_display_inputs` (`display_name`, `input_name`, `visible_for_levels`, `active`, `order`) VALUES
('bx_timeline_attach_link_add', 'event_id', 2147483647, 1, 1),
('bx_timeline_attach_link_add', 'url', 2147483647, 1, 2),
('bx_timeline_attach_link_add', 'controls', 2147483647, 1, 3),
('bx_timeline_attach_link_add', 'do_submit', 2147483647, 1, 4),
('bx_timeline_attach_link_add', 'do_cancel', 2147483647, 1, 5);

-- COMMENTS
INSERT INTO `sys_objects_cmts` (`Name`, `Module`, `Table`, `CharsPostMin`, `CharsPostMax`, `CharsDisplayMax`, `Html`, `PerView`, `PerViewReplies`, `BrowseType`, `IsBrowseSwitch`, `PostFormPosition`, `NumberOfLevels`, `IsDisplaySwitch`, `IsRatable`, `ViewingThreshold`, `IsOn`, `RootStylePrefix`, `BaseUrl`, `ObjectVote`, `TriggerTable`, `TriggerFieldId`, `TriggerFieldAuthor`, `TriggerFieldTitle`, `TriggerFieldComments`, `ClassName`, `ClassFile`) VALUES
('bx_timeline', 'bx_timeline', 'bx_timeline_comments', 1, 5000, 1000, 3, 5, 3, 'tail', 1, 'bottom', 1, 1, 1, -3, 1, 'cmt', 'page.php?i=item&id={object_id}', '', 'bx_timeline_events', 'id', 'object_id', 'title', 'comments', '', '');

-- VIEWS
INSERT INTO `sys_objects_view` (`name`, `table_track`, `period`, `is_on`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_count`, `class_name`, `class_file`) VALUES
('bx_timeline', 'bx_timeline_views_track', '86400', '1', 'bx_timeline_events', 'id', 'object_id', 'views', '', '');

-- VOTES
INSERT INTO `sys_objects_vote`(`Name`, `TableMain`, `TableTrack`, `PostTimeout`, `MinValue`, `MaxValue`, `IsUndo`, `IsOn`, `TriggerTable`, `TriggerFieldId`, `TriggerFieldAuthor`, `TriggerFieldRate`, `TriggerFieldRateCount`, `ClassName`, `ClassFile`) VALUES
('bx_timeline', 'bx_timeline_votes', 'bx_timeline_votes_track', '604800', '1', '1', '0', '1', 'bx_timeline_events', 'id', 'object_id', 'rate', 'votes', 'BxTimelineVoteLikes', 'modules/boonex/timeline/classes/BxTimelineVoteLikes.php'),
('bx_timeline_reactions', 'bx_timeline_reactions', 'bx_timeline_reactions_track', '604800', '1', '1', '1', '1', 'bx_timeline_events', 'id', 'object_id', 'rrate', 'rvotes', 'BxTemplVoteReactions', '');

-- SCORES
INSERT INTO `sys_objects_score` (`name`, `module`, `table_main`, `table_track`, `post_timeout`, `is_on`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_score`, `trigger_field_cup`, `trigger_field_cdown`, `class_name`, `class_file`) VALUES
('bx_timeline', 'bx_timeline', 'bx_timeline_scores', 'bx_timeline_scores_track', '604800', '0', 'bx_timeline_events', 'id', 'object_id', 'score', 'sc_up', 'sc_down', '', '');

-- REPORTS
INSERT INTO `sys_objects_report` (`name`, `module`, `table_main`, `table_track`, `is_on`, `base_url`, `trigger_table`, `trigger_field_id`, `trigger_field_author`, `trigger_field_count`, `class_name`, `class_file`) VALUES
('bx_timeline', 'bx_timeline', 'bx_timeline_reports', 'bx_timeline_reports_track', '1', 'page.php?i=item&id={object_id}', 'bx_timeline_events', 'id', 'owner_id', 'reports',  'BxTimelineReport', 'modules/boonex/timeline/classes/BxTimelineReport.php');

-- CONTENT INFO
INSERT INTO `sys_objects_content_info` (`name`, `title`, `alert_unit`, `alert_action_add`, `alert_action_update`, `alert_action_delete`, `class_name`, `class_file`) VALUES
('bx_timeline', '_bx_timeline', 'bx_timeline', 'post_common', '', 'delete', '', ''),
('bx_timeline_cmts', '_bx_timeline_cmts', 'bx_timeline', 'commentPost', 'commentUpdated', 'commentRemoved', 'BxDolContentInfoCmts', '');

-- STUDIO PAGE & WIDGET
INSERT INTO `sys_std_pages`(`index`, `name`, `header`, `caption`, `icon`) VALUES
(3, 'bx_timeline', '_bx_timeline', '_bx_timeline', 'bx_timeline@modules/boonex/timeline/|std-icon.svg');
SET @iPageId = LAST_INSERT_ID();

SET @iParentPageId = (SELECT `id` FROM `sys_std_pages` WHERE `name` = 'home');
SET @iParentPageOrder = (SELECT MAX(`order`) FROM `sys_std_pages_widgets` WHERE `page_id` = @iParentPageId);
INSERT INTO `sys_std_widgets` (`page_id`, `module`, `type`, `url`, `click`, `icon`, `caption`, `cnt_notices`, `cnt_actions`) VALUES
(@iPageId, 'bx_timeline', 'extensions', '{url_studio}module.php?name=bx_timeline', '', 'bx_timeline@modules/boonex/timeline/|std-icon.svg', '_bx_timeline', '', 'a:4:{s:6:"module";s:6:"system";s:6:"method";s:11:"get_actions";s:6:"params";a:0:{}s:5:"class";s:18:"TemplStudioModules";}');
INSERT INTO `sys_std_pages_widgets` (`page_id`, `widget_id`, `order`) VALUES
(@iParentPageId, LAST_INSERT_ID(), IF(ISNULL(@iParentPageOrder), 1, @iParentPageOrder + 1));


text:
local S = factory.S
local gui = factory.gui
factory.vac_sorter_formspec =
	"size[8,5.5]"..
	gui.bg_color..
	gui.bg_img_2..
	gui.slot_colors..
	"list[current_name;sort;3.5,0;1,1;]"..
	"list[current_player;main;0,1.5;8,1;]"..
	"list[current_player;main;0,2.75;8,3;8]"..
	"listring[current_player;main]"..
	"listring[current_name;sort]"

minetest.register_node("factory:upward_vacuum_on", {
	description = S("Vacuum Sorter"),
	tiles = {"factory_machine_steel_dark.png^factory_vent_slates.png",
		"factory_machine_steel_dark.png^factory_ring_green.png", "factory_machine_steel_dark.png",
		"factory_machine_steel_dark.png", "factory_machine_steel_dark.png^factory_8x8_black_square_32x32.png",
		"factory_machine_steel_dark.png"},
	groups = {cracky=3, not_in_creative_inventory=1},
	paramtype = "light",
	paramtype2 = "facedir",
	drop="factory:upward_vacuum_off",
	legacy_facedir_simple = true,
	is_ground_content = false,
	allow_metadata_inventory_put = function(pos, listname, index, stack)
	  -- args: pos, listname, index, stack, player
		local inv = minetest.get_meta(pos):get_inventory()
		stack:set_count(1)
		inv:set_stack(listname, index, stack)
		return 0
	end,
	allow_metadata_inventory_take = function(pos, listname, index)
		local inv = minetest.get_meta(pos):get_inventory()
		inv:set_stack(listname, index, ItemStack(""))
		factory.swap_node(pos,"factory:upward_vacuum_off")
		return 0
	end,
})

minetest.register_node("factory:upward_vacuum_off", {
	description = S("Vacuum Sorter"),
	tiles = {"factory_machine_steel_dark.png^factory_vent_slates.png",
		"factory_machine_steel_dark.png^factory_ring_red.png", "factory_machine_steel_dark.png",
		"factory_machine_steel_dark.png", "factory_machine_steel_dark.png^factory_8x8_black_square_32x32.png",
		"factory_machine_steel_dark.png"},
	groups = {cracky=3},
	paramtype = "light",
	paramtype2 = "facedir",
	legacy_facedir_simple = true,
	is_ground_content = false,
	on_construct = function(pos)
		local meta = minetest.get_meta(pos)
		meta:set_string("formspec", factory.vac_sorter_formspec)
		meta:set_string("infotext", factory.S("Vacuum Sorter"))
		local inv = meta:get_inventory()
		inv:set_size("sort", 1)
	end,
	allow_metadata_inventory_put = function(pos, listname, index, stack)
	  -- args: pos, listname, index, stack, player
		local inv = minetest.get_meta(pos):get_inventory()
		stack:set_count(1)
		inv:set_stack(listname, index, stack)
		factory.swap_node(pos,"factory:upward_vacuum_on")
		return 0
	end,
	allow_metadata_inventory_take = function(pos, listname, index)
		local inv = minetest.get_meta(pos):get_inventory()
		inv:set_stack(listname, index, ItemStack(""))
		return 0
	end,
})

minetest.register_abm({
	nodenames = {"factory:upward_vacuum_on"},
	neighbors = nil,
	interval = 1,
	chance = 1,
	action = function(pos)
		local all_objects = minetest.get_objects_inside_radius({x = pos.x, y = pos.y-1, z = pos.z}, 0.5)
		local inv = minetest.get_meta(pos):get_inventory()
		for _,obj in ipairs(all_objects) do
			if not obj:is_player() and obj:get_luaentity() and obj:get_luaentity().name == "__builtin:item" then
				if ItemStack(obj:get_luaentity().itemstring):get_name() == inv:get_list("sort")[1]:get_name() then
					factory.do_moving_item(obj:get_pos(), obj:get_luaentity().itemstring)
					obj:get_luaentity().itemstring = ""
					obj:remove()
				end
			end
		end
	end,
})


text:
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat)](https://opensource.org/licenses/Apache-2.0)
[![Go Report Card](https://goreportcard.com/badge/github.com/wspl/creeper)](https://goreportcard.com/report/github.com/wspl/creeper)
[![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg)](https://gitter.im/creeper-project/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link)
![Creeper](https://raw.githubusercontent.com/wspl/creeper/master/art/Creeper.png)
## About

Creeper is a *next-generation* crawler which fetches web page by creeper script. As a cross-platform embedded crawler, you can use it for your news app, subscribe program, etc.

**Warning:** At present this project is still under early stage development, please do not use in the production environment.

## Get Started

#### Installation

```
$ go get github.com/wspl/creeper
```

#### Hello World!

Create `hacker_news.crs`

```
page(@page=1) = "https://news.ycombinator.com/news?p={@page}"

news[]: page -> $("tr.athing")
    title: $(".title a.storylink").text
    site: $(".title span.sitestr").text
    link: $(".title a.storylink").href
```

Then, create `main.go`

```go
package main

import "github.com/wspl/creeper"

func main() {
	c := creeper.Open("./hacker_news.crs")
	c.Array("news").Each(func(c *creeper.Creeper) {
		println("title: ", c.String("title"))
		println("site: ", c.String("site"))
		println("link: ", c.String("link"))
		println("===")
	})
}
```

Build and run. Console will print something like:

```
title:  Samsung chief Lee arrested as S.Korean corruption probe deepens
site:  reuters.com
link:  http://www.reuters.com/article/us-southkorea-politics-samsung-group-idUSKBN15V2RD
===
title:  ReactOS 0.4.4 Released
site:  reactos.org
link:  https://reactos.org/project-news/reactos-044-released
===
title:  FeFETs: How this new memory stacks up against existing non-volatile memory
site:  semiengineering.com
link:  http://semiengineering.com/what-are-fefets/
```

## Script Spec

### Town

Town is a lambda like expression for saving (in)mutable string. Most of the time, we used it to store url.

```
page(@page=1, ext) = "https://news.ycombinator.com/news?p={@page}&ext={ext}"
```

When you need town, use it as if you were calling a function:

```
news[]: page(ext="Hello World!") -> $("tr.athing")
```

You might have noticed that the `@page` parameter is not used. Yeah, it is a special parameter.

Expression in town definition line like `name="something"`, represents parameter `name` has a default value `"something"`.

Incidentally, `@page` is a parameter that will automatically increasing when current page has no more content.

### Node

Nodes are tree structure that represent the data structure you are going to crawl.

```
news[]: page -> $("tr.athing")
	title: $(".title a.storylink").text
	site: $(".title span.sitestr").text
	link: $(".title a.storylink").href
```

Like `yaml`, nodes distinguishes the hierarchy by indentation.

#### Node Name

Node has name. `title` is a field name, represents a general string data. `news[]` is a array name, represents a parent structure with multiple sub-data.

#### Page

Page indicates where to fetching the field data. It can be a town expression or field reference.

Field reference is a advanced usage of Node, you can found the details in [./eh.crs](./eh.crs).

If a node owned page and fun at the same time, page should on the left of `->`, fun should on the right of `->`. Which is `page -> fun`

#### Fun

Fun represents the data processing process.

There are all supported funs:

| Name      | Parameters                       | Description                              |
| --------- | -------------------------------- | ---------------------------------------- |
| $         | (selector: string)               | Relative CSS selector (select from parent node)|
| $root     | (selector: string)               | Absolute CSS selector (select from body)|
| html      |                                  | inner HTML                               |
| text      |                                  | inner text                               |
| outerHTML |                                  | outer HTML                               |
| attr      | (attr: string)                   | attribute value                          |
| style     |                                  | style attribute value                    |
| href      |                                  | href attribute value                     |
| src       |                                  | src attribute value                      |
| class     |                                  | class attribute value                    |
| id        |                                  | id attribute value                       |
| calc      | (prec: int)                      | calculate arithmetic expression          |
| match     | (regexp: string)                 | match first sub-string via regular expression |
| expand    | (regexp: string, target: string) | expand matched strings to target string  |

## Author

Plutonist

> [impl.moe](https://impl.moe) · Github [@wspl](https://github.com/wspl)


text:
<?php

namespace backend\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\BackendUser;

/**
 * BackendUserSearch represents the model behind the search form about `backend\models\BackendUser`.
 */
class BackendUserSearch extends BackendUser
{
    public function rules()
    {
        return [
            [['id', 'role', 'created_by', 'updated_by'], 'integer'],
            [['username', 'auth_key', 'password_hash', 'password_reset_token', 'email', 'status', 'created_at', 'updated_at'], 'safe'],
        ];
    }

    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function search($params)
    {
        $query = BackendUser::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
            'pageSize' => 10,
            ],
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'role' => $this->role,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            //'created_by' => $this->created_by,
            //'updated_by' => $this->updated_by,
        ]);

        $query->andFilterWhere(['like', 'username', $this->username])
            ->andFilterWhere(['like', 'auth_key', $this->auth_key])
            ->andFilterWhere(['like', 'password_hash', $this->password_hash])
            ->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'status', $this->status]);

        return $dataProvider;
    }
}


text:
        Checkpoint Event
        Count

        Triggered
        {{ checkpointStats['counts']['total'] }}

        In Progress
        {{ checkpointStats['counts']['in_progress'] }}

        Completed
        {{ checkpointStats['counts']['completed'] }}

        Failed
        {{ checkpointStats['counts']['failed'] }}

        Restored
        {{ checkpointStats['counts']['restored'] }}


text:
import {basename} from 'path';

import {inlineCli} from '../helpers/main_driver.js';

test(`baseline_${basename(import.meta.url)}`, async () => {
  const {actual} = await inlineCli(
    `
<http://schema.org/URL> <http://www.w3.org/2000/01/rdf-schema#comment> "Data type: URL." .
<http://schema.org/URL> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Class> .
<http://schema.org/URL> <http://www.w3.org/2000/01/rdf-schema#label> "URL" .
<http://schema.org/URL> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://schema.org/Text> .
<http://schema.org/Text> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/DataType> .
<http://schema.org/Text> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2000/01/rdf-schema#Class> .
      `,
    ['--ontology', `https://fake.com/${basename(import.meta.url)}.nt`]
  );

  expect(actual).toMatchInlineSnapshot(`
"/** Used at the top-level node to indicate the context for the JSON-LD objects used. The context provided in this type is compatible with the keys and URLs in the rest of this generated file. */
export type WithContext<T extends Thing> = T & {
    \\"@context\\": \\"https://schema.org\\";
};
export interface Graph {
    \\"@context\\": \\"https://schema.org\\";
    \\"@graph\\": readonly Thing[];
}
type SchemaValue<T> = T | readonly T[];
type IdReference = {
    /** IRI identifying the canonical address of this object. */
    \\"@id\\": string;
};

export type Text = URL | string;

/** Data type: URL. */
export type URL = string;

"
`);
});


text:
import { IConnection } from "vscode-languageserver";
import ILogger from "../service/logger/ILogger";
import IFactory from "./IFactory";

/**
 * ILogger factory interface
 *
 * @module vscode-phpmd/server/factory
 * @author Sandhjé Bouw (sandhje@ecodes.io)
 */
interface ILoggerFactory extends IFactory<ILogger> {
    /**
     * Set logger connection
     *
     * @param {IConnection} connection
     * @returns {void}
     */
    setConnection(connection: IConnection): void;

    /**
     * Set logger verbose mode
     *
     * @param {boolean} verbose
     * @returns {void}
     */
    setVerbose(verbose: boolean): void;
}

export default ILoggerFactory;


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const ModuleDependency = require("./ModuleDependency");

class DelegatedSourceDependency extends ModuleDependency {
	constructor(request) {
		super(request);
	}

	get type() {
		return "delegated source";
	}
}

module.exports = DelegatedSourceDependency;