text:
package com.google.security.zynamics.binnavi.Database.PostgreSQL.Functions;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Database.AbstractSQLProvider;
import com.google.security.zynamics.binnavi.Database.CConnection;
import com.google.security.zynamics.binnavi.Database.CTableNames;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntDeleteException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException;
import com.google.security.zynamics.binnavi.Database.PostgreSQL.PostgreSQLHelpers;
import com.google.security.zynamics.binnavi.debug.models.trace.TraceList;
import com.google.security.zynamics.binnavi.debug.models.trace.TraceRegister;
import com.google.security.zynamics.binnavi.debug.models.trace.interfaces.ITraceEvent;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.INaviProject;

public final class PostgreSQLTraceFunctions {
  /**
   * You are not supposed to intantiate this class.
   */
  private PostgreSQLTraceFunctions() {
    // You are not supposed to instantiate this class.
  }

  /**
   * Creates a new trace list object in the database.
   *
   * @param provider The connection to the database.
   * @param tracesTable The traces table where the trace is added.
   * @param tracesColumn Identifies the view container column for which the trace is created.
   * @param containerTable Identifies the view container table.
   * @param containerId ID of the view container for which the trace is created.
   * @param name The name of the new trace.
   * @param description The description of the new trace.
   *
   * @return The created trace list.
   *
   * @throws CouldntSaveDataException Thrown if the trace list could not be created.
   */
  // ESCA-JAVA0138:
  private static TraceList createTrace(final AbstractSQLProvider provider,
      final String tracesTable,
      final String tracesColumn,
      final String containerTable,
      final int containerId,
      final String name,
      final String description) throws CouldntSaveDataException {
    Preconditions.checkNotNull(name, "IE00568: Name argument can not be null");

    Preconditions.checkNotNull(description, "IE00569: Description argument can not be null");

    final CConnection connection = provider.getConnection();

    final String query = "INSERT INTO " + CTableNames.TRACES_TABLE
        + "(view_id, name, description) VALUES(?, ?, ?) RETURNING id";

    try {
      final PreparedStatement statement = connection.getConnection().prepareStatement(query,
          ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

      Integer listId = null;

      try {
        statement.setInt(1, 0);
        statement.setString(2, name);
        statement.setString(3, description);

        final ResultSet resultSet = statement.executeQuery();
        try {
          while (resultSet.next()) {
            if (resultSet.isFirst()) {
              listId = resultSet.getInt(1);
            }
          }
        } finally {
          resultSet.close();
        }
      } finally {
        statement.close();
      }

      connection.executeUpdate("INSERT INTO " + tracesTable + "(" + tracesColumn + ", trace_id) "
          + " VALUES(" + containerId + ", " + listId + ")", true);

      PostgreSQLHelpers.updateModificationDate(connection, containerTable, containerId);

      return new TraceList(listId, name, description, provider);
    } catch (final SQLException exception) {
      throw new CouldntSaveDataException(exception);
    }
  }

  /**
   * Saves the events of a trace.
   *
   * @param connection Connection to the database.
   * @param trace The trace whose events are saved.
   *
   * @throws CouldntSaveDataException Thrown if the events could not be saved.
   */
  private static void saveEvents(final CConnection connection, final TraceList trace)
      throws CouldntSaveDataException {
    final String queryPrefix = "INSERT INTO " + CTableNames.TRACE_EVENT_TABLE
        + "(trace_id, position, tid, module_id, address, type) VALUES";

    final StringBuilder stringBuilder = new StringBuilder(queryPrefix);

    int position = 0;

    for (final ITraceEvent traceEvent : trace) {
      final String moduleString = traceEvent.getOffset().getModule() == null ? "null"
          : String.valueOf(traceEvent.getOffset().getModule().getConfiguration().getId());

      stringBuilder.append(String.format(Locale.ENGLISH,
          "(%d, %d, %d, %s, %s, %d)",
          trace.getId(),
          position,
          traceEvent.getThreadId(),
          moduleString,
          traceEvent.getOffset().getAddress().getAddress().toBigInteger().toString(),
          1));

      ++position;

      if (trace.getEventCount() > position) {
        stringBuilder.append(", ");
      }
    }

    try {
      final PreparedStatement prep =
          connection.getConnection().prepareStatement(stringBuilder.toString());
      try {
        prep.execute();
      } catch (final SQLException exception) {
        throw new CouldntSaveDataException(exception);
      } finally {
        prep.close();
      }
    } catch (final SQLException exception) {
      throw new CouldntSaveDataException(exception);
    }
  }

  /**
   * Creates a new trace in a module.
   *
   * @param provider The SQL provider that provides the connection.
   * @param module The module where the trace is created.
   * @param name The name of the new trace.
   * @param description The description of the new trace.
   *
   * @return The created trace.
   *
   * @throws CouldntSaveDataException Thrown if the trace could not be created.
   */
  public static TraceList createTrace(final AbstractSQLProvider provider, final INaviModule module,
      final String name, final String description) throws CouldntSaveDataException {
    Preconditions.checkNotNull(provider, "IE00570: Provider argument can not be null");
    Preconditions.checkNotNull(module, "IE00571: Module argument can not be null");
    Preconditions.checkNotNull(name, "IE02192: Name argument can not be null");
    Preconditions.checkNotNull(description, "IE02193: Description argument can not be null");
    Preconditions.checkArgument(module.inSameDatabase(provider),
        "IE00572: The given module is not part of this database");
    return createTrace(provider,
        CTableNames.MODULE_TRACES_TABLE,
        "module_id",
        CTableNames.MODULES_TABLE,
        module.getConfiguration().getId(),
        name,
        description);
  }

  /**
   * Creates a new trace in a project.
   *
   * @param provider The SQL provider that provides the connection.
   * @param project The project where the trace is created.
   * @param name The name of the new trace.
   * @param description The description of the new trace.
   *
   * @return The created trace.
   *
   * @throws CouldntSaveDataException Thrown if the trace could not be created.
   */
  public static TraceList createTrace(final AbstractSQLProvider provider,
      final INaviProject project, final String name, final String description)
      throws CouldntSaveDataException {
    Preconditions.checkNotNull(provider, "IE00573: Provider argument can not be null");
    Preconditions.checkNotNull(project, "IE00574: Project argument can not be null");
    Preconditions.checkNotNull(name, "IE00575: Name argument can not be null");
    Preconditions.checkNotNull(description, "IE02194: Description argument can not be null");
    return createTrace(provider,
        CTableNames.PROJECT_TRACES_TABLE,
        "project_id",
        CTableNames.PROJECTS_TABLE,
        project.getConfiguration().getId(),
        name,
        description);
  }

  /**
   * Deletes a trace from the database.
   *
   * @param provider The SQL provider that provides the connection.
   * @param trace The trace to be deleted.
   *
   * @throws CouldntDeleteException Thrown if the trace could not be deleted.
   */
  public static void deleteTrace(final AbstractSQLProvider provider, final TraceList trace)
      throws CouldntDeleteException {
    Preconditions.checkNotNull(provider, "IE00576: Provider argument can not be null");
    Preconditions.checkNotNull(trace, "IE00577: Trace argument can not be null");
    Preconditions.checkArgument(trace.inSameDatabase(provider),
        "IE00578: Trace list is not part of this database");

    final CConnection connection = provider.getConnection();

    final String query = "DELETE FROM " + CTableNames.TRACES_TABLE + " WHERE id = " + trace.getId();

    try {
      connection.executeUpdate(query, true);
    } catch (final SQLException e) {
      throw new CouldntDeleteException(e);
    }
  }

  /**
   * Saves a trace to the database.
   *
   * @param provider The SQL provider that provides the connection.
   * @param trace The trace to save to the database.
   *
   * @throws CouldntSaveDataException Thrown if the trace could not be saved to the database.
   */
  public static void save(final AbstractSQLProvider provider, final TraceList trace)
      throws CouldntSaveDataException {
    Preconditions.checkNotNull(provider, "IE00579: Provider argument can not be null");
    Preconditions.checkNotNull(trace, "IE00580: List argument can not be null");
    Preconditions.checkArgument(trace.inSameDatabase(provider),
        "IE00581: List is not part of this database");

    final CConnection connection = provider.getConnection();

    if (trace.getEventCount() != 0) {
      saveEvents(connection, trace);
      saveEventValues(connection, trace);
    }
  }

  /**
   * Saves the event values of a trace.
   *
   * @param connection Connection to the database.
   * @param trace Trace whose event values are saved.
   *
   * @throws CouldntSaveDataException Thrown if the data could not be saved.
   */
  public static void saveEventValues(final CConnection connection, final TraceList trace)
      throws CouldntSaveDataException {
    Preconditions.checkNotNull(connection, "IE02412: connection argument can not be null");
    Preconditions.checkNotNull(trace, "IE02413: trace argument can not be null");

    final String query = "INSERT INTO " + CTableNames.TRACE_EVENT_VALUES_TABLE
        + "(trace_id, position, register_name, register_value, memory_value) VALUES "
        + "(?, ?, ?, ?, ?)";

    try {
      final PreparedStatement preparedStatement =
          connection.getConnection().prepareStatement(query);

      int position = 0;

      for (final ITraceEvent traceEvent : trace) {
        for (final TraceRegister register : traceEvent.getRegisterValues()) {
          preparedStatement.setInt(1, trace.getId());
          preparedStatement.setInt(2, position);
          preparedStatement.setString(3, register.getName());
          preparedStatement.setLong(4, register.getValue().toLong());
          preparedStatement.setBytes(5, register.getMemory());

          preparedStatement.addBatch();
        }
        ++position;
      }
      preparedStatement.executeBatch();

      preparedStatement.close();
    }
 catch (final SQLException exception) {
      throw new CouldntSaveDataException(exception);
    }
  }

  /**
   * Changes the description of a trace.
   *
   * @param provider The SQL provider that provides the connection.
   * @param trace The trace whose description is changed.
   * @param description The new description of the trace.
   *
   * @throws CouldntSaveDataException Thrown if the description of the trace could not be changed.
   */
  public static void setDescription(final AbstractSQLProvider provider, final TraceList trace,
      final String description) throws CouldntSaveDataException {

    Preconditions.checkNotNull(provider, "IE00582: Provider argument can not be null");
    Preconditions.checkNotNull(trace, "IE00583: Trace list argument can not be null");
    Preconditions.checkNotNull(description, "IE00584: Description argument can not be null");
    Preconditions.checkArgument(trace.inSameDatabase(provider),
        "IE00585: Trace list is not part of this database");

    final CConnection connection = provider.getConnection();
    final String query = "UPDATE " + CTableNames.TRACES_TABLE + " SET description = ? WHERE id = ?";
    try {
      final PreparedStatement statement = connection.getConnection().prepareStatement(query);
      try {
        statement.setString(1, description);
        statement.setInt(2, trace.getId());

        statement.executeUpdate();
      } finally {
        statement.close();
      }

    } catch (final SQLException e) {
      throw new CouldntSaveDataException(e);
    }
  }

  /**
   * Changes the name of a trace.
   *
   * @param provider The SQL provider that provides the connection.
   * @param trace The trace whose name is changed.
   * @param name The new name of the trace.
   *
   * @throws CouldntSaveDataException Thrown if the name of the trace could not be changed.
   */
  public static void setName(final AbstractSQLProvider provider, final TraceList trace,
      final String name) throws CouldntSaveDataException {

    Preconditions.checkNotNull(provider, "IE00586: Provider argument can not be null");
    Preconditions.checkNotNull(trace, "IE00587: Trace list argument can not be null");
    Preconditions.checkNotNull(name, "IE00588: Name argument can not be null");
    Preconditions.checkArgument(trace.inSameDatabase(provider),
        "IE00589: Trace list is not part of this database");

    final CConnection connection = provider.getConnection();
    final String query = "UPDATE " + CTableNames.TRACES_TABLE + " SET name = ? WHERE id = ?";
    try {
      final PreparedStatement statement = connection.getConnection().prepareStatement(query);
      try {
        statement.setString(1, name);
        statement.setInt(2, trace.getId());

        statement.executeUpdate();
      } finally {
        statement.close();
      }
    } catch (final SQLException e) {
      throw new CouldntSaveDataException(e);
    }
  }
}


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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <include android:layout_width="match_parent"
            android:layout_height="45dp"
            android:id="@+id/lifecycle_title"
            layout="@layout/navigationbar"/>
    <LinearLayout android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:id="@+id/tabbar"
            android:layout_below="@id/lifecycle_title"
            android:orientation="horizontal" android:gravity="center">
        <TextView android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android:id="@+id/activity_all"
                android:text="所有"
                android:layout_weight="1"
                android:gravity="center" android:textColor="#000000"/>
        <TextView android:layout_height="wrap_content"
                  android:layout_width="match_parent"
                  android:id="@+id/activity_visible"
                  android:text="可见"
                  android:layout_weight="1" android:gravity="center" android:textColor="#000000"/>
        <TextView android:layout_height="wrap_content"
                  android:layout_width="match_parent"
                  android:id="@+id/activity_foreground"
                  android:text="前台运行"
                  android:layout_weight="1" android:gravity="center" android:textColor="#000000"/>
    </LinearLayout>
    <com.external.maxwin.view.XListView
            android:id="@+id/activitylist"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:layout_below="@+id/tabbar"
            android:divider="#c4c4c4"
            android:dividerHeight="1dp"/>

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
To generate the production files, make sure you have already installed the
dependencies using ````npm install```` and then just use:

````
npm run-script build
````

## Tests

To launch the test suite, make sure you have already installed the dependencies
using ````npm install````.
Tests are launching in all your installed browsers. They're also launched on
Travis CI, in PhantomJS.

````
npm test
````

## License

MIT. See `LICENSE.md`


text:
const execFile = require('child_process').execFile;
const flow = require('flow-bin');

execFile(flow, undefined, (err, stdout) => {
  console.log(stdout);
  process.exitCode = 0;
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using System.Globalization;
using System.Resources;

namespace cn.zuoanqh.open.QingNote
{
  class ZDictionaryFileIO
  {
    public static void writeFile(List<KeyValuePair<string, string>> data, string separator, string fileName)
    {
      writeFile(data, separator, Directory.GetCurrentDirectory(), fileName);
    }

    public static void writeFile(List<KeyValuePair<string, string>> data, string separator, string absolutePath, string fileName)
    {
      string fpath = Path.Combine(absolutePath, fileName);
      using (StreamWriter writer = new StreamWriter(fpath, false, Encoding.UTF8))
      {
        for (int i = 0; i < data.Count; i++)
        {
          if (data[i].Key.Trim().Length != 0)
            writer.WriteLine(data[i].Key + separator + data[i].Value);
          else
            writer.WriteLine(data[i].Value);
        }
      }
    }

    public static List<KeyValuePair<string, string>> readFile(string separator, string fileName)
    {
      return readFile(separator, Directory.GetCurrentDirectory(), fileName);
    }

    public static List<KeyValuePair<string, string>> readFile(string separator, string absolutePath, string fileName)
    {
      List<KeyValuePair<string, string>> data = new List<KeyValuePair<string, string>>();
      List<string> lines = ZByLineFileIO.readFileVerbatim(fileName, absolutePath);
      int l = 0;//line number
      while (true)
      {
        if (l >= lines.Count) break;
        string s = lines[l];
        int ind = s.IndexOf(separator);

        string tails = "";
        while (l + 1 < lines.Count && lines[l + 1].IndexOf(separator) < 0)
        {
          l++;
          tails += "\r\n" + lines[l];
        }

        data.Add(new KeyValuePair<string, string>(s.Substring(0, ind), s.Substring(ind + separator.Length) + tails));
        l++;
      }
      return data;
    }

    public static string peekFile(string fileName)
    {
      return peekFile(Directory.GetCurrentDirectory(), fileName);
    }

    public static string peekFile(string absolutePath, string fileName)
    {
      string fpath = Path.Combine(absolutePath, fileName);
      using (StreamReader reader = new StreamReader(fpath, Encoding.UTF8))
      {
        if (reader.Peek() == -1) return null;
        return reader.ReadLine();
      }
    }

  }
}


text:
from isc_dhcp_leases import IscDhcpLeases
from isc_dhcp_leases import Lease
from isc_dhcp_leases import Lease6

def parse(*files):
    parsed_files = list(map(lambda file: IscDhcpLeases(file).get(), files))
    return Leases(*parsed_files)

class Leases:
    _leases = []
    _iter = None

    def __init__(self, *args):
        l = len(args)
        if l > 1:
            # create a new iterator that can be called again
            def _iter():
                for argument in args:
                    yield from argument

            self._leases = None
            self._iter = _iter
        elif l == 1:
            self._leases = args[0]
        else:
            # fallback to empty list if there are no leases given
            self._leases = []

    @property
    def current(self):
        """
        Leases where the active and valid properties are True
        :return:
        """
        return self.active.valid

    @property
    def active(self):
        """
        Leases where the active property is True
        :return:
        """
        g = (l for l in self if l.active)
        return Leases(g)

    @property
    def inactive(self):
        """
        Leases where the active property is False
        :return:
        """
        g = (l for l in self if not l.active)
        return Leases(g)

    @property
    def valid(self):
        """
        Leases where the valid property is True
        :return:
        """
        g = (l for l in self if l.valid)
        return Leases(g)

    @property
    def invalid(self):
        """
        Leases where the valid property is False
        :return:
        """
        g = (l for l in self if not l.valid)
        return Leases(g)

    @property
    def v4(self):
        """
        Leases that are an instance of Lease
        :return:
        """
        g = (l for l in self if isinstance(l, Lease))
        return Leases(g)

    @property
    def v6(self):
        """
        Leases that are an instance of Lease6
        :return:
        """
        g = (l for l in self if isinstance(l, Lease6))
        return Leases(g)

    def filter(self, filter_func):
        """
        Filter leases by supplied filter function
        :param filter_func: function that returns true for all
                            values that should be accepted
        :return:
        """
        g = (l for l in self if filter_func(l))
        return Leases(g)

    def where_eq(self, key, value=None):
        """
        Filter leases by supplied set-key and value (if provided)
        :param key: the key in the sets dictionary of the lease
        :param value: the value for the supplied key, if None any lease
                      with the key is returned
        :return:
        """
        if value:
            def filter_func(lease):
                return lease.sets.get(key, None) == value
        else:
            def filter_func(lease):
                return key in lease.sets

        g = filter(filter_func, self)

        return Leases(g)

    def count(self):
        """
        Returns the count of leases in the current set of leases
        :return: int count of leases
        """
        return len(self)

    def __iter__(self):
        """
        Returns an iterator for the current set of leases
        :return:
        """
        if self._leases:
            yield from iter(self._leases)
        elif self._iter:
            yield from self._iter()

    def __len__(self):
        """
        Implements __len__
        If we are dealing with a generator we will expand it into `_leases`
        :return:
        """
        if type(self._leases) is list:
            return len(self._leases)
        else:
            l = list(iter(self))
            self._leases = l
            return len(l)


text:
<?php

namespace EscapeWork\LaravelUploader\Providers;

use Illuminate\Support\ServiceProvider;

class LaravelUploaderServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->app->validator->extend(
            'mime_type_array',
            'EscapeWork\LaravelUploader\Validators\MimeTypeArrayValidator@validate'
        );
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
var video = document.getElementById('video');

var tracker = new tracking.ColorTracker(['cyan']);

tracking.track('#video', tracker, {
    camera: true
});

tracker.on('track', function (event) {
    if (event.data.length === 0) {
        showpeppa(true);
    } else {
        event.data.forEach(function (rect) {
            console.log("ok");
            showpeppa(false);
        });
    }
});

function showpeppa(arg) {
    document.getElementById("peppapig").hidden = arg;
}


text:
/**
 */
package COSEM.InterfaceClasses.impl;

import COSEM.InterfaceClasses.InterfaceClassesPackage;
import COSEM.InterfaceClasses.PRIME_NB_OFDM_PLC_MAC_counters;

import org.eclipse.emf.ecore.EClass;

/**
 *
 * An implementation of the model object 'PRIME NB OFDM PLC MAC counters'.
 *
 *
 * @generated
 */
public class PRIME_NB_OFDM_PLC_MAC_countersImpl extends BaseImpl implements PRIME_NB_OFDM_PLC_MAC_counters {
	/**
	 *
	 *
	 * @generated
	 */
	protected PRIME_NB_OFDM_PLC_MAC_countersImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return InterfaceClassesPackage.Literals.PRIME_NB_OFDM_PLC_MAC_COUNTERS;
	}

} //PRIME_NB_OFDM_PLC_MAC_countersImpl


text:
SET planner.width.max_per_node=100;
SET planner.slice_target=1;
SET planner.enable_multiphase_agg=false;
SELECT
stddev_pop(cast(DECIMAL_18_8 as decimal(18, 8))),
stddev_pop(cast(DECIMAL_2_1 as decimal(2, 1))),
stddev_pop(cast(DECIMAL_15_5 as decimal(15, 5)))
FROM dfs.drillTestDir.`decimal/fragments/T_DECIMAL_BIG`;
RESET planner.width.max_per_node;
RESET planner.slice_target;
RESET planner.enable_multiphase_agg;


text:
using namespace gpopt;

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::CPhysicalMotionRoutedDistribute
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CPhysicalMotionRoutedDistribute::CPhysicalMotionRoutedDistribute(
	CMemoryPool *mp, CDistributionSpecRouted *pdsRouted)
	: CPhysicalMotion(mp), m_pdsRouted(pdsRouted), m_pcrsRequiredLocal(nullptr)
{
	GPOS_ASSERT(nullptr != pdsRouted);

	m_pcrsRequiredLocal = GPOS_NEW(mp) CColRefSet(mp);

	// include segment id column
	m_pcrsRequiredLocal->Include(m_pdsRouted->Pcr());
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::~CPhysicalMotionRoutedDistribute
//
//	@doc:
//		Dtor
//
//---------------------------------------------------------------------------
CPhysicalMotionRoutedDistribute::~CPhysicalMotionRoutedDistribute()
{
	m_pdsRouted->Release();
	m_pcrsRequiredLocal->Release();
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::Matches
//
//	@doc:
//		Match operators
//
//---------------------------------------------------------------------------
BOOL
CPhysicalMotionRoutedDistribute::Matches(COperator *pop) const
{
	if (Eopid() != pop->Eopid())
	{
		return false;
	}

	CPhysicalMotionRoutedDistribute *popRoutedDistribute =
		CPhysicalMotionRoutedDistribute::PopConvert(pop);

	return m_pdsRouted->Matches(popRoutedDistribute->m_pdsRouted);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::PcrsRequired
//
//	@doc:
//		Compute required columns of the n-th child;
//
//---------------------------------------------------------------------------
CColRefSet *
CPhysicalMotionRoutedDistribute::PcrsRequired(CMemoryPool *mp,
											  CExpressionHandle &exprhdl,
											  CColRefSet *pcrsRequired,
											  ULONG child_index,
											  CDrvdPropArray *,	 // pdrgpdpCtxt
											  ULONG				 // ulOptReq
)
{
	GPOS_ASSERT(0 == child_index);

	CColRefSet *pcrs = GPOS_NEW(mp) CColRefSet(mp, *m_pcrsRequiredLocal);
	pcrs->Union(pcrsRequired);

	CColRefSet *pcrsChildReqd =
		PcrsChildReqd(mp, exprhdl, pcrs, child_index, gpos::ulong_max);
	pcrs->Release();

	return pcrsChildReqd;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::FProvidesReqdCols
//
//	@doc:
//		Check if required columns are included in output columns
//
//---------------------------------------------------------------------------
BOOL
CPhysicalMotionRoutedDistribute::FProvidesReqdCols(CExpressionHandle &exprhdl,
												   CColRefSet *pcrsRequired,
												   ULONG  // ulOptReq
) const
{
	return FUnaryProvidesReqdCols(exprhdl, pcrsRequired);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::EpetOrder
//
//	@doc:
//		Return the enforcing type for order property based on this operator
//
//---------------------------------------------------------------------------
CEnfdProp::EPropEnforcingType
CPhysicalMotionRoutedDistribute::EpetOrder(CExpressionHandle &,	 // exprhdl
										   const CEnfdOrder *	 // peo
) const
{
	return CEnfdProp::EpetRequired;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::PosRequired
//
//	@doc:
//		Compute required sort order of the n-th child
//
//---------------------------------------------------------------------------
COrderSpec *
CPhysicalMotionRoutedDistribute::PosRequired(CMemoryPool *mp,
											 CExpressionHandle &,  // exprhdl
											 COrderSpec *,		   //posInput
											 ULONG
#ifdef GPOS_DEBUG
												 child_index
#endif	// GPOS_DEBUG
											 ,
											 CDrvdPropArray *,	// pdrgpdpCtxt
											 ULONG				// ulOptReq
) const
{
	GPOS_ASSERT(0 == child_index);

	return GPOS_NEW(mp) COrderSpec(mp);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::PosDerive
//
//	@doc:
//		Derive sort order
//
//---------------------------------------------------------------------------
COrderSpec *
CPhysicalMotionRoutedDistribute::PosDerive(CMemoryPool *mp,
										   CExpressionHandle &	// exprhdl
) const
{
	return GPOS_NEW(mp) COrderSpec(mp);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::OsPrint
//
//	@doc:
//		Debug print
//
//---------------------------------------------------------------------------
IOstream &
CPhysicalMotionRoutedDistribute::OsPrint(IOstream &os) const
{
	os << SzId() << " ";

	return m_pdsRouted->OsPrint(os);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalMotionRoutedDistribute::PopConvert
//
//	@doc:
//		Conversion function
//
//---------------------------------------------------------------------------
CPhysicalMotionRoutedDistribute *
CPhysicalMotionRoutedDistribute::PopConvert(COperator *pop)
{
	GPOS_ASSERT(nullptr != pop);
	GPOS_ASSERT(EopPhysicalMotionRoutedDistribute == pop->Eopid());

	return dynamic_cast<CPhysicalMotionRoutedDistribute *>(pop);
}

// EOF


text:
<?php

/* YallaWebsiteBackendBundle:Event:show.html.twig */
class __TwigTemplate_2f6521919220404521cccd7c75fdd61a62929d9efac3fb6924b25bbe66ba81cb extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("YallaWebsiteBackendBundle:Event:base_event.html.twig", "YallaWebsiteBackendBundle:Event:show.html.twig", 1);
        $this->blocks = array(
            'extraOptions' => array($this, 'block_extraOptions'),
            'controlleraction' => array($this, 'block_controlleraction'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "YallaWebsiteBackendBundle:Event:base_event.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_extraOptions($context, array $blocks = array())
    {
        // line 3
        echo "    env, $this->env->getExtension('routing')->getPath("backend_event_edit", array("id" => $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "id", array()))), "html", null, true);
        echo "\"><button class=\"btn btn-primary create_new\"> Edit</button>
    env, $this->env->getExtension('routing')->getPath("backend_event_delete", array("id" => $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "id", array()))), "html", null, true);
        echo "\"><button class=\"btn btn-primary create_new\"> Delete</button>
";
    }

    // line 7
    public function block_controlleraction($context, array $blocks = array())
    {
        // line 8
        echo "

            Name : ";
        // line 10
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "title", array()), "html", null, true);
        echo "

            ";
        // line 11
        if (($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "isVenue", array()) == false)) {
            // line 12
            echo "                Address : ";
            echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "location", array()), "address", array()), "html", null, true);
            echo "

                Telephone : ";
            // line 13
            echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "location", array()), "telephone", array()), "html", null, true);
            echo "

            ";
        } else {
            // line 15
            echo "                Venue :  ";
            echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "venue", array()), "title", array()), "html", null, true);
            echo "

                Address : ";
            // line 16
            echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "venue", array()), "location", array()), "address", array()), "html", null, true);
            echo "

                Telephone : ";
            // line 17
            echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "venue", array()), "location", array()), "telephone", array()), "html", null, true);
            echo "

            ";
        }
        // line 19
        echo "            ";
        if ((twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "startDate", array()), "F jS") == twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "endDate", array()), "F jS"))) {
            echo "
                Date : ";
            // line 20
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "startDate", array()), "F jS"), "html", null, true);
            echo "

                  Start : ";
            // line 21
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "startDate", array()), "g:ia"), "html", null, true);
            echo "
                  End : ";
            // line 22
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "endDate", array()), "g:ia"), "html", null, true);
            echo "

            ";
        } else {
            // line 24
            echo "                Start Date : ";
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "startDate", array()), "F jS \\a\\t g:ia"), "html", null, true);
            echo "

                End Date : ";
            // line 25
            echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "endDate", array()), "F jS \\a\\t g:ia"), "html", null, true);
            echo "

            ";
        }
        // line 27
        echo "            Description : ";
        echo $this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "content", array());
        echo "

            Tags
            ";
        // line 29
        if ($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "getTags", array(), "method")) {
            // line 30
            echo "                ";
            $context['_parent'] = $context;
            $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "getTags", array()));
            foreach ($context['_seq'] as $context["_key"] => $context["tag"]) {
                // line 31
                echo "                     ";
                echo twig_escape_filter($this->env, $this->getAttribute($context["tag"], "name", array()), "html", null, true);
                echo "
                ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['tag'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 33
            echo "            ";
        }
        echo "

            Similar Artists
            ";
        // line 35
        if ($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "getSimilarArtist", array())) {
            // line 36
            echo "                ";
            $context['_parent'] = $context;
            $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "getSimilarArtist", array()));
            foreach ($context['_seq'] as $context["_key"] => $context["art"]) {
                // line 37
                echo "
 env, $this->env->getExtension('routing')->getPath("backend_artist_show", array("id" => $this->getAttribute($context["art"], "id", array()))), "html", null, true);
                echo "'>";
                echo twig_escape_filter($this->env, $this->getAttribute($context["art"], "title", array()), "html", null, true);
                echo "

                ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['art'], $context['_parent'], $context['loop']);
            $context = array_intersect_key($context, $_parent) + $_parent;
            // line 39
            echo "            ";
        }
        // line 40
        echo "

            ";
        // line 44
        echo $this->env->getExtension('sonata_media')->thumbnail($this->getAttribute((isset($context["entity"]) ? $context["entity"] : null), "media", array()), "medium", array());
        // line 45
        echo "

    ";
    }

    public function getTemplateName()
    {
        return "YallaWebsiteBackendBundle:Event:show.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  165 => 45,  163 => 44,  157 => 40,  154 => 39,  143 => 37,  138 => 36,  136 => 35,  130 => 33,  121 => 31,  116 => 30,  114 => 29,  108 => 27,  103 => 25,  98 => 24,  93 => 22,  89 => 21,  85 => 20,  80 => 19,  75 => 17,  71 => 16,  66 => 15,  61 => 13,  56 => 12,  54 => 11,  50 => 10,  46 => 8,  43 => 7,  37 => 4,  32 => 3,  29 => 2,  11 => 1,);
    }
}
/* {% extends "YallaWebsiteBackendBundle:Event:base_event.html.twig" %}*/
/* {% block extraOptions %}*/
/*     <button class="btn btn-primary create_new"> Edit</button>*/
/*     <button class="btn btn-primary create_new"> Delete</button>*/
/* {% endblock %}*/
/* */
/* {% block controlleraction  %}*/
/*
*/
/*
*/
/*             Name : {{entity.title}}
*/
/*             {% if entity.isVenue == false %}*/
/*                 Address : {{entity.location.address }}
*/
/*                 Telephone : {{entity.location.telephone }}
*/
/*             {% else %}*/
/*                 Venue :  {{entity.venue.title }}
*/
/*                 Address : {{entity.venue.location.address }}
*/
/*                 Telephone : {{entity.venue.location.telephone }}
*/
/*             {% endif %}*/
/*             {% if entity.startDate|date("F jS") ==  entity.endDate|date("F jS") %} */
/*                 Date : {{entity.startDate|date("F jS")}}
*/
/*                   Start : {{entity.startDate|date("g:ia")}}*/
/*                   End : {{entity.endDate|date("g:ia")}}
*/
/*             {% else %}*/
/*                 Start Date : {{entity.startDate|date("F jS \\a\\t g:ia")}}
*/
/*                 End Date : {{entity.endDate|date("F jS \\a\\t g:ia")}}
*/
/*             {% endif %}*/
/*             Description : {{entity.content|raw}}
*/
/*             Tags*/
/*             {% if entity.getTags() %}*/
/*                 {% for tag in entity.getTags %}*/
/*                      {{ tag.name }} */
/*                 {% endfor %}*/
/*             {% endif %}
*/
/*             Similar Artists*/
/*             {% if entity.getSimilarArtist %}*/
/*                 {% for art in entity.getSimilarArtist %}*/
/*
 {{ art.title }}
*/
/*                 {% endfor %}*/
/*             {% endif %}*/
/*             */
/*             */
/*
*/
/*
*/
/*             {% thumbnail  entity.media, 'medium' %}*/
/*
*/
/*     {% endblock %}*/
/* */


text:
import logging
logger = logging.getLogger(__name__)

from itertools import groupby

from django.db.models import Prefetch
from django.db.models import prefetch_related_objects
from data.nlp_hint_types import QUESTION_TYPES

from thresher.models import NLPHints, HighlightGroup

from thresher.serializers import (ProjectSerializer,
                                  ArticleSerializer,
                                  TopicSerializer,
                                  TopicSerializer2,
                                  HighlightGroupSerializer,
                                  NLPQuestionSerializer,
                                  NLPHintSerializer)

def collectNLPTasks(articles=None):
    taskList = [{
                  "article_id": article.id,
                  "Topic Text": article.text,
                  "Questions": QUESTION_TYPES
                }
        for article in articles
    ]
    return taskList

def collectHighlightTasks(articles=None, topics=None, project=None):

    articles = articles.order_by("article_number").distinct()
    logger.info("collectHighlightTasks sorting by article_number: {}".format(
                [article.article_number for article in articles]))
    project_data = ProjectSerializer(project, many=False).data
    topics_data = TopicSerializer(topics, many=True).data
    return [{ "project": project_data,
              "topics": topics_data,
              "article":
                  ArticleSerializer(article, many=False).data
           } for article in articles ]

def collectQuizTasks(articles=None, topics=None, project=None):
    taskList = []
    for topic in topics:
        taskList.extend(collectQuizTasksForTopic(articles, topic, project))
    return taskList

def collectQuizTasksForTopic(articles=None, topic=None, project=None):
    taskList = []

    # getTopicTree returns the topic with all levels of its subtopic tree
    topictree = topic.getTopicTree()

    # Prefetching uses one query per related table to populate caches.
    # This helps us avoid per row queries when looping over rows.
    prefetch_related_objects(topictree, "questions__answers")

    # Set up the prefetch to retrieve all available hints for each article
    allHints = NLPHints.objects.all()
    fetchHints = Prefetch("hints",
                          queryset=allHints,
                          to_attr="allHints")
    logger.info("Found %d hints" % (len(allHints),))

    # Set up Prefetch that will cache just the highlights matching
    # this topic to article.highlight_taskruns[n].highlightsForTopic
    exclude_ids = []

    # Pick the contributor based on what's selected in the GUI.
    contributor_id = project.task_config['contributor_id']
    topicHighlights = HighlightGroup.objects.filter(topic=topic,
        article_highlight__contributor=contributor_id)

    # Filter the highlights based on the min tokens provided on project creation
    min_tokens_per_highlight = project.task_config['min_tokens']
    max_tokens_per_highlight = project.task_config['max_tokens']
    for topic_hlght in topicHighlights:
        total_count = topic_hlght.token_count()
        if (total_count < min_tokens_per_highlight
            or total_count > max_tokens_per_highlight):
            exclude_ids.append(topic_hlght.id)
            logger.info("Excluded HighlightGroup: {} {} {} tokens".
                        format(topic_hlght.id, topic_hlght.topic.name, total_count))

    topicHighlights = topicHighlights.exclude(id__in=exclude_ids)

    fetchHighlights = Prefetch("highlight_taskruns__highlights",
                               queryset=topicHighlights,
                               to_attr="highlightsForTopic")
    # Find articles highlighted with the topic within the provided queryset
    # distinct is essential after prefetch_related chained method
    articles = (articles
                .filter(highlight_taskruns__highlights__topic=topic)
                .prefetch_related(fetchHighlights)
                .prefetch_related(fetchHints)
                .order_by("article_number")
                .distinct())
    logger.info("collectQuizTasks sorting by article_number for topic {}: {}"
                .format(topic.name, [article.article_number for article in articles])
               )

    project_data = ProjectSerializer(project, many=False).data
    topictree_data = TopicSerializer2(topictree, many=True).data

    # With the prefetching config above, the loops below will
    # be hitting caches. Only 8 queries should be issued against 8 tables,
    # i.e. The query count will not be a function of number of rows returned.
    for article in articles:
        # Our prefetched highlightsForTopic is nested under
        # the ArticleHightlight record, in HighlightGroup
        # Not expecting more than one ArticleHighlight record
        # but safest to code as if there could be more than one.

        highlights = [ hg
                       for ah in article.highlight_taskruns.all()
                       for hg in ah.highlightsForTopic
        ]
        # At this point, we are processing one topic for one article
        # All the highlights for a given topic/case need to be in one task.
        # Need to sort here instead of the above prefetch because we want
        # to ignore the potential grouping effect if there was more than one
        # ArticleHighlight in above list comprehension
        # See data.pybossa_api.save_quiz_taskrun for import code
        sortkey = lambda x: x.case_number
        hg_by_case = sorted(highlights, key=sortkey)

        # Although this code can send multiple HighlightGroups, the
        # Quiz task presenter will only use the first one.
        # So when there are multiple highlight taskruns in the database,
        # (for a given article and topic),
        # the taskrun to be processed by a Quiz will essentially be selected
        # at random. There will need to be a way to flag the
        # official "Gold Standard" HighlightGroup that was distilled from
        # multiple Highlighter taskruns, that will be the one sent to the Quiz.
        for case_number, hg_case_group in groupby(hg_by_case, key=sortkey):
            taskList.append({
               "project": project_data,
               "topTopicId": topic.id,
               "topictree": topictree_data,
               "article": ArticleSerializer(article, many=False).data,
               "highlights": HighlightGroupSerializer(
                                 hg_case_group, many=True).data,
               "hints": NLPHintSerializer(article.allHints, many=True).data,
            })

    return taskList


text:
package meta

import (
	"fmt"
	"github.com/sjwhitworth/golearn/base"
)

// OneVsAllModel replaces class Attributes with numeric versions
// and trains n wrapped classifiers. The actual class is chosen
// by whichever is most confident. Only one CategoricalAttribute
// class variable is supported.
type OneVsAllModel struct {
	NewClassifierFunction func(string) base.Classifier
	filters               []*oneVsAllFilter
	classifiers           []base.Classifier
	maxClassVal           uint64
}

// NewOneVsAllModel creates a new OneVsAllModel. The argument
// must be a function which returns a base.Classifier ready for training.
func NewOneVsAllModel(f func(string) base.Classifier) *OneVsAllModel {
	return &OneVsAllModel{
		f,
		nil,
		nil,
		0,
	}
}

func (m *OneVsAllModel) generateAttributes(from base.FixedDataGrid) map[base.Attribute]base.Attribute {
	attrs := from.AllAttributes()
	classAttrs := from.AllClassAttributes()
	if len(classAttrs) != 1 {
		panic("Only 1 class Attribute is supported!")
	}
	ret := make(map[base.Attribute]base.Attribute)
	for _, a := range attrs {
		ret[a] = a
		for _, b := range classAttrs {
			if a.Equals(b) {
				cur := base.NewFloatAttribute(b.GetName())
				ret[a] = cur
			}
		}
	}
	return ret
}

// Fit creates n filtered datasets (where n is the number of values
// a CategoricalAttribute can take) and uses them to train the
// underlying classifiers.
func (m *OneVsAllModel) Fit(using base.FixedDataGrid) {
	var classAttr *base.CategoricalAttribute
	// Do some validation
	classAttrs := using.AllClassAttributes()
	for _, a := range classAttrs {
		if c, ok := a.(*base.CategoricalAttribute); !ok {
			panic("Unsupported ClassAttribute type")
		} else {
			classAttr = c
		}
	}
	attrs := m.generateAttributes(using)

	// Find the highest stored value
	val := uint64(0)
	classVals := classAttr.GetValues()
	for _, s := range classVals {
		cur := base.UnpackBytesToU64(classAttr.GetSysValFromString(s))
		if cur > val {
			val = cur
		}
	}
	if val == 0 {
		panic("Must have more than one class!")
	}
	m.maxClassVal = val

	// Create individual filtered instances for training
	filters := make([]*oneVsAllFilter, val+1)
	classifiers := make([]base.Classifier, val+1)
	for i := uint64(0); i <= val; i++ {
		f := &oneVsAllFilter{
			attrs,
			classAttr,
			i,
		}
		filters[i] = f
		classifiers[i] = m.NewClassifierFunction(classVals[int(i)])
		classifiers[i].Fit(base.NewLazilyFilteredInstances(using, f))
	}

	m.filters = filters
	m.classifiers = classifiers
}

// Predict issues predictions. Each class-specific classifier is expected
// to output a value between 0 (indicating that a given instance is not
// a given class) and 1 (indicating that the given instance is definitely
// that class). For each instance, the class with the highest value is chosen.
// The result is undefined if several underlying models output the same value.
func (m *OneVsAllModel) Predict(what base.FixedDataGrid) (base.FixedDataGrid, error) {
	ret := base.GeneratePredictionVector(what)
	vecs := make([]base.FixedDataGrid, m.maxClassVal+1)
	specs := make([]base.AttributeSpec, m.maxClassVal+1)
	for i := uint64(0); i <= m.maxClassVal; i++ {
		f := m.filters[i]
		c := base.NewLazilyFilteredInstances(what, f)
		p, err := m.classifiers[i].Predict(c)
		if err != nil {
			return nil, err
		}
		vecs[i] = p
		specs[i] = base.ResolveAttributes(p, p.AllClassAttributes())[0]
	}
	_, rows := ret.Size()
	spec := base.ResolveAttributes(ret, ret.AllClassAttributes())[0]
	for i := 0; i < rows; i++ {
		class := uint64(0)
		best := 0.0
		for j := uint64(0); j <= m.maxClassVal; j++ {
			val := base.UnpackBytesToFloat(vecs[j].Get(specs[j], i))
			if val > best {
				class = j
				best = val
			}
		}
		ret.Set(spec, i, base.PackU64ToBytes(class))
	}
	return ret, nil
}

//
// Filter implementation
//
type oneVsAllFilter struct {
	attrs        map[base.Attribute]base.Attribute
	classAttr    base.Attribute
	classAttrVal uint64
}

func (f *oneVsAllFilter) AddAttribute(a base.Attribute) error {
	return fmt.Errorf("Not supported")
}

func (f *oneVsAllFilter) GetAttributesAfterFiltering() []base.FilteredAttribute {
	ret := make([]base.FilteredAttribute, len(f.attrs))
	cnt := 0
	for i := range f.attrs {
		ret[cnt] = base.FilteredAttribute{i, f.attrs[i]}
		cnt++
	}
	return ret
}

func (f *oneVsAllFilter) String() string {
	return "oneVsAllFilter"
}

func (f *oneVsAllFilter) Transform(old, to base.Attribute, seq []byte) []byte {
	if !old.Equals(f.classAttr) {
		return seq
	}
	val := base.UnpackBytesToU64(seq)
	if val == f.classAttrVal {
		return base.PackFloatToBytes(1.0)
	}
	return base.PackFloatToBytes(0.0)
}

func (f *oneVsAllFilter) Train() error {
	return fmt.Errorf("Unsupported")
}


text:
import { prependProtocol } from '../../../helpers/prepend-protocol';
import { module, test } from 'qunit';

module('Unit | Helper | prepend protocol');

// Replace this with your real tests.
test('it works', function(assert) {
  let result = prependProtocol(42);
  assert.ok(result);
});


text:
from collections import OrderedDict
from pprint import pprint

def equal_dicts(d1, d2):
    ''' Devolve True se dicionários são iguais.
    Só funciona se todos os valores forem serializáveis.
    '''
    return len(d1.items() ^ d2.items()) == 0

def update_dict(original, adding):
    result = original.copy()
    for key in adding.keys():
        if adding[key] is None:
            continue
        if isinstance(adding[key], dict):
            if key not in result or not isinstance(result[key], dict):
                result[key] = adding[key].copy()
            else:
                result[key] = update_dict(result[key], adding[key])
        else:
            result[key] = adding[key]
    return result

def dict_firsts(adict, firsts):
    eh_ordered = isinstance(adict, OrderedDict)
    if not eh_ordered:
        adict = OrderedDict(adict)
    keys = list(adict.keys())
    for key in keys:
        if key not in firsts:
            adict.move_to_end(key)
    if eh_ordered:
        return adict
    else:
        return dict(adict)

def dict_get_none(dic, key, tpl="{v}"):
    default = dic.get(None)
    if isinstance(default, dict):
        tpl = default.get('tpl', tpl)
        default = default.get(None)

    try:
        value = dic[key]
    except KeyError:
        value = default

    if tpl:
        return tpl.format(k=key, v=value)
    else:
        return value


text:
class QuestionSetsController < ApplicationController
  before_action :set_question_set, only: [:show, :edit, :update, :destroy]
  before_action :set_class_group
  respond_to :json
  before_action :require_login

  # GET /question_sets
  # GET /question_sets.json
  def index
    @question_sets = @class_group.question_sets
  end

  # GET /question_sets/1
  # GET /question_sets/1.json
  def show
    if @current_user.enrolled?(@class_group.id)
      if @current_user.teacher?(@class_group.id)
        render "teacher_show"
      else
        render "student_show"
      end
    else
      redirect_to class_groups_path
      return
    end
  end

  # POST /question_sets
  # POST /question_sets.json
  def create
    # return render :json => { :id => 99, :name => "Hello Class", :class_group_id => 1 }
    if current_user.teacher?(@class_group.id)
      @question_set = QuestionSet.new(question_set_params)
      @question_set.class_group_id = @class_group.id

      respond_to do |format|
        if @question_set.save
          format.html { redirect_to [@class_group, @question_set], notice: 'Question set was successfully created.' }
          format.json { render :show, status: :created, location: [@class_group, @question_set] }
        else
          format.html { render :new }
          format.json { render json: @question_set.errors, status: :unprocessable_entity }
        end
      end
    else
      flash[:error_not_teacher] = "You must be a teacher to perform this action."
      redirect_to class_groups_path
    end
  end

  # PATCH/PUT /question_sets/1
  # PATCH/PUT /question_sets/1.json
  def update
    if current_user.teacher?(@class_group.id)
      respond_to do |format|
        if @question_set.update(question_set_params)
          @question_set = QuestionSet.new(question_set_params)
          @question_set.class_group_id = @class_group.id

          format.html { redirect_to [@class_group, @question_set], notice: 'Question set was successfully updated.' }
          format.json { render :show, status: :ok, location: [@class_group, @question_set] }
        else
          format.html { render :edit }
          format.json { render json: @question_set.errors, status: :unprocessable_entity }
        end
      end
    else
      flash[:error_not_teacher] = "You must be a teacher to perform this action."
      redirect_to class_groups_path
    end
  end

  # DELETE /question_sets/1
  # DELETE /question_sets/1.json
  def destroy
    if current_user.teacher?(@class_group.id)
      @question_set.destroy
      respond_to do |format|
        format.html { redirect_to class_group_question_sets_url, notice: 'Question set was successfully destroyed.' }
        format.json { head :no_content }
      end
    else
      flash[:error_not_teacher] = "You must be a teacher to perform this action."
      redirect_to class_groups_path
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_question_set
      @question_set = QuestionSet.find(params[:id])
    end

    def set_class_group
      @class_group = ClassGroup.find(params[:class_group_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def question_set_params
      params.require(:question_set).permit!
    end
end


text:
package com.billing;

public interface SubscriptionServiceListener extends BillingServiceListener{

    /**
     * Callback will be triggered upon owned subscription restore
     *
     * @param sku - specificator of owned subscription
     */
    void onSubscriptionRestored(String sku);

    /**
     * Callback will be triggered when a subscription purchased successfully
     *
     * @param sku - specificator of purchased subscription
     */
    void onSubscriptionPurchased(String sku);
}


text:
namespace BeardedManStudios.Forge.Networking
{
	public interface IInterpolator<T>
	{
		float LerpT { get; set; }
		bool Enabled { get; set; }
		ulong Timestep { get; set; }

		T Interpolate();
	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Tabl. analyt. Fung. France (Paris) 25 (1883)

#### Original name
Pistillaria cardiospora Quél., 1883

### Remarks
null


text:
`$ npm install react-native-app-metadata --save`

### Mostly automatic installation

`$ react-native link react-native-app-metadata`

### Manual installation

#### iOS

1. In XCode, in the project navigator, right click `Libraries` ➜ `Add Files to [your project's name]`
2. Go to `node_modules` ➜ `react-native-app-metadata` and add `RNAppMetadata.xcodeproj`
3. In XCode, in the project navigator, select your project. Add `libRNAppMetadata.a` to your project's `Build Phases` ➜ `Link Binary With Libraries`
4. Run your project (`Cmd+R`)<

#### Android

1. Open up `android/app/src/main/java/[...]/MainApplication.java`
  - Add `import io.wj.rnappmetadata.RNAppMetadataPackage;` to the imports at the top of the file
  - Add `new RNAppMetadataPackage()` to the list returned by the `getPackages()` method
2. Append the following lines to `android/settings.gradle`:
  	```
  	include ':react-native-app-metadata'
  	project(':react-native-app-metadata').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-app-metadata/android')
  	```
3. Insert the following lines inside the dependencies block in `android/app/build.gradle`:
  	```
      compile project(':react-native-app-metadata')
  	```

## Usage
```javascript
import AppMetadata from 'react-native-app-metadata';

// constant
console.log("     Version: " + AppMetadata.Version);
console.log("ShortVersion: " + AppMetadata.ShortVersion);
console.log("    BundleId: " + AppMetadata.BundleIdentifier);
console.log("  BundleName: " + AppMetadata.BundleName);

// method: getAppMetadataBy
AppMetadata.getAppMetadataBy("somekey")
.then((value)=>{
    console.log(value);
})
.catch((err)=>{
    console.log(err);
});
```


text:
set -o nounset
set -o errexit

SCRIPT=$(basename $0)
SCRIPTDIR=$(dirname $0)

source $SCRIPTDIR/project_properties.sh
source $SCRIPTDIR/common_utils.sh

readonly HDFS_CMD="sudo -u $HADOOP_USER -i $HADOOP_HOME/bin/hadoop fs"
readonly HDFS_ROOT_USER="$HADOOP_USER"

function hdfs_mkdir () {
  local dir=$1
  local owner=${2:-}
  local permissions=${3:-}

  emit "  Checking directory $dir"
  if ! $HDFS_CMD -test -d $dir 2> /dev/null; then
    emit "    Creating directory $dir"
    $HDFS_CMD -mkdir $dir
  fi

  if [[ -n "$owner" ]]; then
    emit "    Ensuring owner $owner"
    $HDFS_CMD -chown $owner $dir
  fi

  if [[ -n "$permissions" ]]; then
    emit "    Ensuring permissions $permissions"
    $HDFS_CMD -chmod $permissions $dir
  fi
}
readonly -f hdfs_mkdir

emit ""
emit "*** Begin: $SCRIPT running on master $(hostname) ***"

# Ensure that /tmp exists (it should) and is fully accessible
hdfs_mkdir "$HDFS_TMP_DIR" "$HDFS_ROOT_USER" "777"

# Create a hive-specific scratch space in /tmp for the hdpuser
hdfs_mkdir "$HDFS_TMP_DIR/hive-$HDP_USER" "$HDP_USER"

# Create a warehouse directory (hive) for the hdpuser
hdfs_mkdir "/user" "$HDFS_ROOT_USER"
hdfs_mkdir "/user/$HDP_USER" "$HDP_USER"
hdfs_mkdir "/user/$HDP_USER/warehouse" "$HDP_USER"

# Create a mapreduce staging directory for the hdpuser
if [[ "${HADOOP_MAJOR_VERSION}" == "2" ]]; then
  hdfs_mkdir "/hadoop/mapreduce" "$HADOOP_USER" "o+rw"
  hdfs_mkdir "/hadoop/mapreduce/staging" "$HADOOP_USER" "o+rw"
  hdfs_mkdir "/hadoop/mapreduce/staging/history" "$HADOOP_USER" "777"
  hdfs_mkdir "/hadoop/mapreduce/staging/$HDP_USER" "$HDP_USER"
else
  hdfs_mkdir "$HADOOP_TMP_DIR/mapred/staging/$HDP_USER" "$HDP_USER"
fi

emit ""
emit "*** End: $SCRIPT running on master $(hostname) ***"
emit ""


text:
package io.shaka.http

import java.io.InputStream
import scala.collection.mutable.ListBuffer

object IO {
  def inputStreamToByteArray(is: InputStream): Array[Byte] = {
    val buf = ListBuffer[Byte]()
    var b = is.read()
    while (b != -1) {
      buf.append(b.byteValue)
      b = is.read()
    }
    buf.toArray
  }
}


text:
package org.onosproject.drivers.fujitsu.cli;

import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.drivers.fujitsu.behaviour.VoltNeConfig;
import org.onosproject.net.DeviceId;
import org.onosproject.net.driver.DriverHandler;
import org.onosproject.net.driver.DriverService;

/**
 * Gets all available data in vOLT.
 */
@Command(scope = "onos", name = "volt-all",
        description = "Gets all available data in vOLT")
public class VoltGetAllCommand extends AbstractShellCommand {

    @Argument(index = 0, name = "uri", description = "Device ID",
            required = true, multiValued = false)
    String uri = null;

    private DeviceId deviceId;

    @Override
    protected void execute() {
        DriverService service = get(DriverService.class);
        deviceId = DeviceId.deviceId(uri);
        DriverHandler h = service.createHandler(deviceId);
        VoltNeConfig volt = h.behaviour(VoltNeConfig.class);
        String reply = volt.getAll();
        if (reply != null) {
            print("%s", reply);
        } else {
            print("No reply from %s", deviceId.toString());
        }
    }

}


text:
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test

def TestCommand(test):
    def run(self):
        import pytest
        from blognajd.tests import setup_django_settings
        setup_django_settings()
        pytest.main(['-v',])

# def run_tests(*args):
#     from blognajd.tests import run_tests, delete_tmp_dirs
#     errors = run_tests()
#     delete_tmp_dirs()
#     if errors:
#         sys.exit(1)
#     else:
#         sys.exit(0)

# test.run_tests = run_tests

setup(
    name = "blognajd",
    version = "1.1.1",
    packages = find_packages(),
    keywords = "django apps",
    license = "MIT",
    description = "Simple django blogging application",
    long_description = "A simple pluggable well maintained django blogging application, tested and fully compatible with Django 1.8 and Python 3.4.",
    author = "Daniel Rus Morales",
    author_email = "mbox@danir.us",
    maintainer = "Daniel Rus Morales",
    maintainer_email = "mbox@danir.us",
    url = "http://pypi.python.org/pypi/blognajd/",
    classifiers = [
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: News/Diary',
        'Framework :: Django',
        'Framework :: Django :: 1.7',
        'Framework :: Django :: 1.8',
    ],
    include_package_data = True,
    package_data = {
        'blognajd': ['*.css', '*.js', '*.html']
    },
    cmdclass={'test': TestCommand},
)


text:
package types

// ServerRoute description goes here.
type ServerRoute struct {
	Name        string   `json:"name,omitempty"`
	RouteParams []string `json:"route_params,omitempty"`
	Path        string   `json:"path,omitempty"`
	SourceFile  string   `json:"source_file,omitempty"`
}

// Example data.
var route = ServerRoute{
	Name:        "name",
	RouteParams: []string{"route", "params"},
	Path:        "path",
	SourceFile:  "source_file",
}

var routes = []ServerRoute{route}


text:
/*

 CEEditPaneController.m

 CotEditor
 http://coteditor.com

 Created by 1024jp on 2014-04-18.

 ------------------------------------------------------------------------------

 © 2004-2007 nakamuxu
 © 2014-2015 1024jp

 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.

 */

#import "CEEditPaneController.h"
#import "CEUtils.h"
#import "Constants.h"

@interface CEEditPaneController ()

@property (nonatomic, nullable, weak) IBOutlet NSButton *smartQuoteCheckButton;

@property (nonatomic, nonnull, copy) NSArray *invisibleSpaces;
@property (nonatomic, nonnull, copy) NSArray *invisibleTabs;
@property (nonatomic, nonnull, copy) NSArray *invisibleNewLines;
@property (nonatomic, nonnull, copy) NSArray *invisibleFullWidthSpaces;

@end

#pragma mark -

@implementation CEEditPaneController

#pragma mark Superclass Methods

// ------------------------------------------------------
/// initialize
- (nullable instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil
// ------------------------------------------------------
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // setup popup menu items for invisible characters
        NSMutableArray *spaces = [NSMutableArray arrayWithCapacity:kSizeOfInvisibleSpaceCharList];
        for (NSUInteger i = 0; i < kSizeOfInvisibleSpaceCharList; i++) {
            [spaces addObject:[NSString stringWithFormat:@"%C", [CEUtils invisibleSpaceChar:i]]];
        }
        _invisibleSpaces = spaces;

        NSMutableArray *tabs = [NSMutableArray arrayWithCapacity:kSizeOfInvisibleTabCharList];
        for (NSUInteger i = 0; i < kSizeOfInvisibleTabCharList; i++) {
            [tabs addObject:[NSString stringWithFormat:@"%C", [CEUtils invisibleTabChar:i]]];
        }
        _invisibleTabs = tabs;

        NSMutableArray *newLines = [NSMutableArray arrayWithCapacity:kSizeOfInvisibleNewLineCharList];
        for (NSUInteger i = 0; i < kSizeOfInvisibleNewLineCharList; i++) {
            [newLines addObject:[NSString stringWithFormat:@"%C", [CEUtils invisibleNewLineChar:i]]];
        }
        _invisibleNewLines = newLines;

        NSMutableArray *fullWidthSpaces = [NSMutableArray arrayWithCapacity:kSizeOfInvisibleFullwidthSpaceCharList];
        for (NSUInteger i = 0; i < kSizeOfInvisibleFullwidthSpaceCharList; i++) {
            [fullWidthSpaces addObject:[NSString stringWithFormat:@"%C", [CEUtils invisibleFullwidthSpaceChar:i]]];
        }
        _invisibleFullWidthSpaces = fullWidthSpaces;
    }
    return self;
}

// ------------------------------------------------------
/// setup UI
- (void)loadView
// ------------------------------------------------------
{
    [super loadView];

    // disable Smart Quotes/Dashes setting on under Mavericks
    if (NSAppKitVersionNumber < NSAppKitVersionNumber10_9) {
        [[self smartQuoteCheckButton] setEnabled:NO];
        [[self smartQuoteCheckButton] setState:NSOffState];
        [[self smartQuoteCheckButton] setTitle:[NSString stringWithFormat:@"%@%@", [[self smartQuoteCheckButton] title],
                                                NSLocalizedString(@" (on Mavericks and later)", nil)]];
    }
}

@end


text:
// Copyright 2010 Google Inc. All Rights Reserved.

package com.google.appinventor.blocklyeditor;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Utility class for command execution and I/O redirection.
 *
 * @author halabelson@google.com (Hal Abelson)
 */
public final class CodeBlocksProcessHelper {

  private static final boolean DEBUG = false;

  /*
   * Input stream handler used for stdout and stderr redirection.
   */
  private static class RedirectStreamHandler extends Thread {
    // Streams to redirect from and to
    private final InputStream input;
    private final StringBuffer output;

    RedirectStreamHandler(InputStream input, StringBuffer output) {
      this.input = input;
      this.output = output;
      start();
    }

    @Override
    public void run() {
      try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line;
        while ((line = reader.readLine()) != null) {
          if (output != null) {
            output.append(line).append("\n");
          }
        }
        reader.close();
      } catch (IOException ioe) {
        // OK to ignore...
      }
    }
  }

  private CodeBlocksProcessHelper() {
  }

  /**
   * Executes a command as a separate process.
   *
   * @param workingDir  working directory for the command, can be null
   * @param command  command to execute and its arguments
   * @param out  where to redirect standard output, can be null
   * @param err  where to redirect standard error, can be null
   * @param waitForOutput whether to wait for the output stream process
   * @return  {@code true} if the command succeeds, {@code false} otherwise
   */

  private synchronized static boolean exec(File workingDir, String[] command, StringBuffer out,
      StringBuffer err, boolean waitForOutput) {

    try {
      if (DEBUG) {
        System.out.println("CodeBlocksProcessHelper exec private method on command");
      }

      Process process = Runtime.getRuntime().exec(command, null, workingDir);
      // We create the out and err stream handlers even in the case where we don't wait
      // for (or want) the output.  The reason is that on (some?) Windows, if you
      // don't handle stdout and stderr, a process that writes more than about
      // 128 bytes will hang.

      Thread outHandler = new RedirectStreamHandler(process.getInputStream(), out);
      Thread errHandler = new RedirectStreamHandler(process.getErrorStream(), err);
      int exitCode =  process.waitFor();
      if (DEBUG) {
        System.out.println("exit code = " + exitCode);
      }

      if (waitForOutput) {
        outHandler.join();
        errHandler.join();
      }
      process.exitValue();
      return exitCode == 0;
    } catch (Exception e) {
      System.out.println("CodeBlocksProcessHelper: " +
          "Error trying to exec command: " + e.getMessage());
      return false;
    }
  }

  /**
   * Executes a command as a separate process.
   *
   * @param command  command to execute and its arguments
   * @param waitForOutput whether to wait for the output stream process
   * @return the process output.  NOTE: The returned value and
   * the thrown error message may be incorrect if waitForOutput is false
   */
  public synchronized static String exec(String[] command, boolean waitForOutput) throws IOException {
    StringBuffer out = null;
    StringBuffer err = null;
    if (DEBUG) {
      System.out.println("CodeBlocksProcessHelper exec public method on command");
    }
    out = new StringBuffer();
    err = new StringBuffer();
    boolean result = exec(null, command, out, err, waitForOutput);
    if (DEBUG) {
      printIfNotEmpty(out.toString(), "command process response");
      printIfNotEmpty(err.toString(), "command process error");
      printIfNotEmpty(Boolean.toString(result), "command process result");
    }
    if (!result) {
      throw new IOException(err.toString());
    }
    return out.toString();
  }

  static private void printIfNotEmpty(String output, String prefix) {
    if (output.length() != 0) {
      System.out.println(prefix + ": " + output);
    }
  }

  // We can't just send a bare command string for Windows to exec.  We need to
  // explicitly invoke the command processor with cmd.exe
  public static String execOnWindows(String commandString, boolean waitForOutput)
      throws IOException {
    String[] command = new String[] {"cmd.exe", "/C", commandString};
    if (DEBUG) {
      System.out.println("CodeBlocksProcessHelper execOnWindows: " + commandString);
    }
    return exec(command, waitForOutput);
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>AssemblyInfoParams - FAKE - F# Make</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">

    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">

    <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />

fsharp.org

github page

FAKE - F# Make

AssemblyInfoParams

Record Fields

Record Field	Description

            AssemblyCompany

            Signature: string

            AssemblyConfiguration

            Signature: string

            AssemblyCopyright

            Signature: string

            AssemblyCulture

            Signature: string

            AssemblyDelaySign

            Signature: bool option

            AssemblyDescription

            Signature: string

            AssemblyFileVersion

            Signature: string

            AssemblyInformationalVersion

            Signature: string

            AssemblyKeyFile

            Signature: string

            AssemblyKeyName

            Signature: string

            AssemblyProduct

            Signature: string

            AssemblyTitle

            Signature: string

            AssemblyTrademark

            Signature: string

            AssemblyVersion

            Signature: string

            CLSCompliant

            Signature: bool option

            CodeLanguage

            Signature: CodeLanguage

            ComVisible

            Signature: bool option

            GenerateClass

            Signature: bool

            Guid

            Signature: string

            OutputFileName

            Signature: string

FAKE - F# Make

Home page

Get FAKE - F# Make via NuGet

Source Code on GitHub

License (Apache 2)

Release Notes

Contributing to FAKE - F# Make

Who is using FAKE?

Ask a question

Tutorials

Getting started

NuGet package restore

Using FxCop in a build

Generating AssemblyInfo

Create NuGet packages

Running specific targets

Running FAKE from command line

Running targets in parallel

Using the F# compiler from FAKE

Creating custom tasks

TeamCity integration

Running canopy tests

Octopus Deploy

TypeScript support

Azure WebJobs support

Azure Cloud Services support

Android publisher

File Watcher

Fake.Deploy

Reference

API Reference


text:
#pragma once

#include "../../Flare.h"
#include "FlareSpacecraftWeaponsSystemInterface.generated.h"

/** Status of the ship */
UENUM()
namespace EFlareWeaponGroupType
{
	enum Type
	{
		WG_NONE,
		WG_GUN,
		WG_BOMB,
		WG_TURRET,
		WG_MISSILE
	};
}

/** Interface wrapper */
UINTERFACE(MinimalAPI, meta=(CannotImplementInterfaceInBlueprint))
class UFlareSpacecraftWeaponsSystemInterface  : public UInterface
{
	GENERATED_UINTERFACE_BODY()
};

/** Actual interface */
class IFlareSpacecraftWeaponsSystemInterface
{
	GENERATED_IINTERFACE_BODY()

public:

		/*----------------------------------------------------
			System Interface
		----------------------------------------------------*/

		virtual int32 GetWeaponGroupCount() const = 0;

		virtual EFlareWeaponGroupType::Type GetActiveWeaponType() const = 0;

		FText GetWeaponModeInfo() const;

};