text:
require 'test_helper'

class Kirpich::BrainTest < Minitest::Test
  def setup
    @brain = Kirpich::Brain
  end

  def test_texts
    assert_answer('паш, 300', :text)
    assert_answer('паш, триста', :text)
    assert_answer('паш, ладно', :text)
  end

  def test_uebyvay_v_svoy_chat
    assert_answer('паш, что нужно делать если чат заебал?', :appeal_text)
  end

  def test_kak_dela
    request = build_request('паш как дела?')
    answer = @brain.respond_on(request)
    assert_equal(:appeal_text, answer.type)
    assert { Kirpich::Dict::KAK_DELA.include?(answer.args.first) }
  end

  def test_random_user
    assert_answer('кирпич, кто охуел?', :random_user)
    assert_answer('кирпич, кто тут всех заебал?', :random_user)
  end

  def test_again
    assert_answer('кирпич, еще раз', :last_answer)
    assert_answer('кирпич, повторика', :last_answer)
  end

  def test_explain
    assert_answer('КиРпиЧ, РазЪясни что', :lurk_search)
    assert_answer('кирпич, разъясни что', :lurk_search)
    assert_answer('кирпич, разъясни что такое гопник', :lurk_search)
    assert_answer('кирпич, что такое гопник', :lurk_search)
  end

  def test_poh
    assert_answer('среда', :appeal_text)
  end

  def test_ladno
    assert_answer('да ладно', :text)
  end

  def test_trista
    assert_answer('использовали константу - 300', :text)
    assert_answer('делали так раз триста', :text)
  end

  def test_hello
    assert_answer('Кипич, привет', :appeal_text)
  end

  def test_currency
    assert_answer('Паш, курс', :currency)
  end

  def test_main
    assert_answer('Паш, кто главный', :appeal_text)
  end

  def test_good
    assert_answer('паштет красава', :appeal_text)
    assert_answer('пашок красавчик', :appeal_text)
    assert_answer('пашок молодчик', :appeal_text)
  end

  def test_choose
    assert_answer('пашок, красное, синее или зеленое?', :choose_text, [%w(красное синее зеленое)])
  end

  def test_call
    assert_answer('пашок ты не приуныл ли случаем?', :choose_text)
    assert_answer('пашок ты сидел?', :choose_text)
    assert_answer('Паш, цены на нефть поднимутся?', :choose_text)
  end

  def test_aphorism
    assert_answer('паш афоризм', :aphorism)
  end

  def test_admin
    assert_answer('паш про админов давай', :devopsreactions_image)
  end

  def test_slots_rules
    assert_answer('паш, как поднять бабла?', :slots_rules)
  end

  def test_slots_spin
    request = build_request('спин')
    answer = @brain.respond_on(request)
    assert { answer.type == :spin }
    assert { answer.args == [1, 1] }

    request = build_request('царский спин')
    answer = @brain.respond_on(request)
    assert { answer.args == [1, 2] }

    request = build_request('спин на первую')
    answer = @brain.respond_on(request)
    assert { answer.args == [0, 1] }

    request = build_request('царский спин на третью')
    answer = @brain.respond_on(request)
    assert { answer.args == [2, 2] }

    request = build_request('фартовый спин на третью')
    answer = @brain.respond_on(request)
    assert { answer.args == [2, 3] }
  end

  def assert_answer(text, method, args = [])
    request = build_request(text)
    answer = @brain.respond_on(request)

    assert { method == answer.type }
    if args.any?
      args.each_with_index do |arg, i|
        assert { arg == answer.args[i] }
      end
    end
  end

  def build_request(text)
    Kirpich::Request.new(text: text, channel: 'test')
  end
end


text:
package simulation;

import geometry.Polygon;
import geometry.Vector;
import graphics.WorldMatrix;

/**
 * Classe representant un ensemble de murs avec lesquels le fluide peut entrer en collision.
 *
 * @author Nicolas Ouellet-Payeur
 * @version 20 mars
 */
public class DistanceField {
	// dimensions du monde physique
	private WorldMatrix world;

	// liste de polygones representant les murs
	private Polygon[] walls;

	// rayon entre un mur et une particule pour qu'il y ait collision
	private final double PENETRATION_RADIUS = 10;

	/**
	 * Constructeur principal.
	 *
	 * @param world Dimensions du monde physique.
	 */
	public DistanceField (WorldMatrix world, Polygon... walls) {
		this.world = world;
		this.walls = walls;
	}

	/**
	 * Retourne la force normale exercee sur une particule en un point (x, y).
	 *
	 * @param x x du point.
	 * @param y y du point.
	 * @param softness Amortissement de la collision (facteur entre 0 et 1).
	 * @return La force normale que le monde applique sur cette particule.
	 */
	public Vector getNormalForce(double x, double y, double softness) {
		Vector normal = Vector.NIL;
		if (x < 0) {
			normal = normal.plus(new Vector(1, 0).times(x*softness));
		}
		if (y < 0) {
			normal = normal.plus(new Vector(0, 1).times(y*softness));
		}
		if (x > world.getMaximumX()) {
			normal = normal.plus(new Vector(-1, 0).times((world.getMaximumX()-x) * softness));
		}
		if (y > world.getMaximumY()) {
			normal = normal.plus(new Vector(0, -1).times((world.getMaximumY() - y) * softness));
		}
		int i;
		for (i = 0; i < walls.length; i++) {
			Polygon wall = walls[i];
			if (wall.distance(x, y) < PENETRATION_RADIUS) {
				double penetration = PENETRATION_RADIUS - wall.distance(x, y);
				if (wall.contains(x, y)) {
					penetration = wall.penetrationDepth(x, y) + PENETRATION_RADIUS;
				}
				normal = normal.plus(wall.normal(x,  y).times(penetration * softness));
			}
		}
		return normal;
	}

	/**
	 * Retourne le vecteur normal au mur le plus proche au point (x,y).
	 *
	 * @param x Position en x du point pour la normale.
	 * @param y Position en y du point pour la normale.
	 * @return Un vecteur de norme 1 perpendiculaire au mur oriente vers l'exterieur.
	 */
	public Vector getNormalAt (double x, double y) {
		Vector normal = Vector.NIL;
		if (x < 0)
			normal = normal.plus(new Vector(1, 0));
		if (y < 0)
			normal = normal.plus(new Vector (0, 1));
		//if (x > world.getMaximumX())
			normal = normal.plus(new Vector (-1, 0));
		if (y > world.getMaximumY())
			normal = normal.plus(new Vector(0, -1));
		if (normal.getMagnitude()==0)
			return Vector.NIL;
		if (x > y) {
			normal = normal.plus(new Vector(-1, 1));
		}
		return normal.normalize(1);
	}

	/**
	 * Retourne le tableau des polygones qui representent les murs, ou obstacles.
	 *
	 * @return Les murs qui interagissent avec les particules.
	 */
	public Polygon[] getWalls() {
		return walls;
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.InternalAbstractions;
using NugetProgram = NuGet.CommandLine.XPlat.Program;

namespace Microsoft.DotNet.Tools.NuGet
{
    public class NuGetCommand
    {
        public static int Run(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication(false)
            {
                Name = "dotnet nuget",
                FullName = ".NET NuGet command runner",
                Description = "For running NuGet commands (\"dotnet nuget --help\" for specifics)"
            };

            app.OnExecute(() =>
            {
                try
                {
                    return RunCommand(args, new NuGetCommandRunner());
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);

                    return -1;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);

                    return -2;
                }
            });

            return app.Execute(args);
        }

        public static int RunCommand(IEnumerable<string> args, INuGetCommandRunner commandRunner)
        {
            Debug.Assert(commandRunner != null, "A command runner must be passed to RunCommand");
            if (commandRunner == null)
            {
                throw new InvalidOperationException("No command runner supplied to RunCommand");
            }

            return commandRunner.Run(args.ToArray());
        }

        private class NuGetCommandRunner : INuGetCommandRunner
        {
            public int Run(string[] commandArgs)
            {
                var nugetAsm = typeof(NugetProgram).GetTypeInfo().Assembly;
                var mainMethod = nugetAsm.EntryPoint;
                return (int)mainMethod.Invoke(null, new object[] { commandArgs });
            }
        }
    }
}


text:
#include <af/dim4.hpp>
#include <Array.hpp>
#include <kernel/ArrayIndex.hpp>
#include <ArrayIndex.hpp>
#include <err_opencl.hpp>

namespace opencl
{

template<typename in_t, typename idx_t>
Array<in_t>* arrayIndex(const Array<in_t> &input, const Array<idx_t> &indices, const unsigned dim)
{
    const dim4 iDims = input.dims();

    dim4 oDims(1);
    for (dim_type d=0; d<4; ++d)
        oDims[d] = (d==int(dim) ? indices.elements() : iDims[d]);

    Array<in_t> *out = createEmptyArray<in_t>(oDims);

    dim_type nDims = iDims.ndims();

    switch(dim) {
        case 0: kernel::arrayIndex<in_t, idx_t, 0>(*out, input, indices, nDims); break;
        case 1: kernel::arrayIndex<in_t, idx_t, 1>(*out, input, indices, nDims); break;
        case 2: kernel::arrayIndex<in_t, idx_t, 2>(*out, input, indices, nDims); break;
        case 3: kernel::arrayIndex<in_t, idx_t, 3>(*out, input, indices, nDims); break;
    }

    return out;
}

#define INSTANTIATE(T)  \
    template Array<T> * arrayIndex<T, float   >(const Array<T> &input, const Array<float   > &indices, const unsigned dim); \
    template Array<T> * arrayIndex<T, double  >(const Array<T> &input, const Array<double  > &indices, const unsigned dim); \
    template Array<T> * arrayIndex<T, int     >(const Array<T> &input, const Array<int     > &indices, const unsigned dim); \
    template Array<T> * arrayIndex<T, unsigned>(const Array<T> &input, const Array<unsigned> &indices, const unsigned dim); \
    template Array<T> * arrayIndex<T, uchar   >(const Array<T> &input, const Array<uchar   > &indices, const unsigned dim);

INSTANTIATE(float   );
INSTANTIATE(cfloat  );
INSTANTIATE(double  );
INSTANTIATE(cdouble );
INSTANTIATE(int     );
INSTANTIATE(unsigned);
INSTANTIATE(uchar   );
INSTANTIATE(char    );

}


text:
package net.hardisonbrewing.signingserver.service.store.push;

import net.hardisonbrewing.signingserver.closed.HBCID;
import net.rim.device.api.system.RuntimeStore;

public class PushSIGStatusStore {

    private static final long UID = HBCID.getUUID( PushSIGStatusStore.class );

    public static void put( boolean status ) {

        RuntimeStore.getRuntimeStore().remove( UID );
        RuntimeStore.getRuntimeStore().put( UID, new Boolean( status ) );
    }

    public static boolean get() {

        Boolean _boolean = (Boolean) RuntimeStore.getRuntimeStore().get( UID );
        return _boolean != null && _boolean.booleanValue();
    }
}


text:
=================
API Documentation
=================

.. autoflask:: app:app
   :undoc-static:


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
    <mirrors>
        <mirror>
            <!--This sends everything else to /public -->
            <id>nexus</id>
            <mirrorOf>*</mirrorOf>
            <url>http://nexus:8081/repository/maven-public</url>
        </mirror>
    </mirrors>
    <servers>
        <server>
            <id>nexus-release-repository</id>
            <username>admin</username>
            <password>admin123</password>
        </server>
        <server>
            <id>nexus-snapshot-repository</id>
            <username>admin</username>
            <password>admin123</password>
        </server>
    </servers>
    <profiles>
        <profile>
            <id>nexus</id>
            <!--Enable snapshots for the built in central repo to direct -->
            <!--all requests to nexus via the mirror -->
            <repositories>
                <repository>
                    <id>central</id>
                    <url>http://central</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </repository>
            </repositories>
            <pluginRepositories>
                <pluginRepository>
                    <id>central</id>
                    <url>http://central</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                </pluginRepository>
            </pluginRepositories>
        </profile>
    </profiles>
    <activeProfiles>
        <!--make the profile active all the time -->
        <activeProfile>nexus</activeProfile>
    </activeProfiles>
</settings>


text:
package org.saiku.olap.query;

import org.apache.commons.lang.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.olap4j.Axis;
import org.olap4j.OlapConnection;
import org.olap4j.OlapException;
import org.olap4j.mdx.IdentifierNode;
import org.olap4j.metadata.Catalog;
import org.olap4j.metadata.Cube;
import org.olap4j.metadata.Database;
import org.olap4j.metadata.Hierarchy;
import org.olap4j.metadata.Level;
import org.olap4j.metadata.Schema;
import org.olap4j.query.LimitFunction;
import org.olap4j.query.Query;
import org.olap4j.query.QueryAxis;
import org.olap4j.query.QueryDimension;
import org.olap4j.query.QueryDimension.HierarchizeMode;
import org.olap4j.query.Selection;
import org.olap4j.query.SortOrder;
import org.saiku.olap.dto.SaikuCube;
import org.saiku.olap.util.exception.QueryParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

/**
 * De-Serializes an XML into a PatQuery object
 *
 * @author Paul Stoellberger
 * @created May 27, 2010
 * @since 0.8
 */
public class QueryDeserializer {

  private static final Logger log = LoggerFactory.getLogger(QueryDeserializer.class);

  private static final String QUERY = "Query";
  private static final String CUBE = "cube";
  private static final String CONNECTION = "connection";
  private static final String CATALOG = "catalog";
  private static final String SCHEMA = "schema";
  private static final String SELECTION = "Selection";
  private Document dom;
  private Query qm;
    private OlapConnection connection;
  private InputSource source;

  public IQuery unparse( String xml, OlapConnection connection ) throws Exception {
    this.connection = connection;
      SAXBuilder parser = new SAXBuilder();
    source = new InputSource( ( new ByteArrayInputStream( xml.getBytes( "UTF8" ) ) ) );
    dom = parser.build( source );
    Element child = dom.getRootElement();
    Element qmElement = child.getChild( "QueryModel" );
    Element mdxElement = child.getChild( "MDX" );

    IQuery returnQuery;
    if ( qmElement != null ) {
      returnQuery = createQmQuery();
      return returnQuery;
    } else if ( mdxElement != null ) {
      returnQuery = createMdxQuery();
      return returnQuery;
    }
    throw new Exception( "Cant find <QueryModel> nor <MDX> Query" );
  }

  public SaikuCube getFakeCube( String xml ) throws Exception {
    SAXBuilder parser = new SAXBuilder();
    InputSource source = new InputSource( ( new ByteArrayInputStream( xml.getBytes() ) ) );
    Document dom = parser.build( source );

    Element queryElement = dom.getRootElement();
    if ( queryElement != null && queryElement.getName().equals( QUERY ) ) {

      String cubeName = queryElement.getAttributeValue( CUBE );

      String connectionName = queryElement.getAttributeValue( CONNECTION );
      String catalogName = queryElement.getAttributeValue( CATALOG );
      String schemaName = queryElement.getAttributeValue( SCHEMA );
      return new SaikuCube( connectionName, cubeName, cubeName, cubeName, catalogName, schemaName );
    }
    throw new Exception( "Cant find <QueryModel> nor <MDX> Query" );
  }

  public SaikuCube getCube( String xml, OlapConnection con ) throws Exception {
    this.connection = con;
      SAXBuilder parser = new SAXBuilder();
    source = new InputSource( ( new ByteArrayInputStream( xml.getBytes() ) ) );
    dom = parser.build( source );

    Element queryElement = dom.getRootElement();
    if ( queryElement != null && queryElement.getName().equals( QUERY ) ) {

      String cubeName = queryElement.getAttributeValue( CUBE );

      if ( !StringUtils.isNotBlank( cubeName ) ) {
        throw new QueryParseException( "Cube for query not defined" );
      }
      String connectionName = queryElement.getAttributeValue( CONNECTION );
      String catalogName = queryElement.getAttributeValue( CATALOG );
      String schemaName = queryElement.getAttributeValue( SCHEMA );
      Query tmpQuery = createEmptyQuery( "tmp-1234", catalogName, schemaName, cubeName );
      Cube cub = tmpQuery.getCube();
      return new SaikuCube( connectionName, cub.getUniqueName(), cub.getName(), cub.getCaption(), catalogName,
        schemaName );
    }
    throw new Exception( "Cant find <QueryModel> nor <MDX> Query" );
  }

  private IQuery createQmQuery() throws QueryParseException, SQLException {

    Element queryElement = dom.getRootElement();
    if ( queryElement != null && queryElement.getName().equals( QUERY ) ) {

      String queryName = queryElement.getAttributeValue( "name" );
      String cubeName = queryElement.getAttributeValue( CUBE );

      if ( !StringUtils.isNotBlank( cubeName ) ) {
        throw new QueryParseException( "Cube for query not defined" );
      }
      String connectionName = queryElement.getAttributeValue( CONNECTION );
      String catalogName = queryElement.getAttributeValue( CATALOG );
      String schemaName = queryElement.getAttributeValue( SCHEMA );

      try {
        Element qmElement = queryElement.getChild( "QueryModel" );
        if ( qmElement != null ) {
          qm = createEmptyQuery( queryName, catalogName, schemaName, cubeName );
          manipulateQuery( qmElement );
          SaikuCube cube =
            new SaikuCube( connectionName, cubeName, qm.getCube().getName(), qm.getCube().getCaption(), catalogName,
              schemaName );
          IQuery q = new OlapQuery( qm, connection, cube, false );
          setTotals( q, queryElement );
          Properties p = getProperties( queryElement );
          q.setProperties( p );
          return q;
        } else {
          throw new OlapException( "Can't find child <QueryModel>" );
        }

      } catch ( OlapException e ) {
        throw new QueryParseException( e.getMessage(), e );
      }

    } else {
      throw new QueryParseException(
        "Cannot parse Query Model: Query node not found and/or more than 1 Query node found" );
    }
  }

  private IQuery createMdxQuery() throws QueryParseException {

    Element queryElement = dom.getRootElement();
    if ( queryElement != null && queryElement.getName().equals( QUERY ) ) {

      String queryName = queryElement.getAttributeValue( "name" );
      String cubeName = queryElement.getAttributeValue( CUBE );

      String connectionName = queryElement.getAttributeValue( CONNECTION );
      String catalogName = queryElement.getAttributeValue( CATALOG );
      String schemaName = queryElement.getAttributeValue( SCHEMA );
      Properties props = getProperties( queryElement );
      try {
        Element mdxElement = queryElement.getChild( "MDX" );
        if ( mdxElement != null ) {
          SaikuCube cube = new SaikuCube( connectionName, cubeName, cubeName, cubeName, catalogName, schemaName );
          IQuery q = new MdxQuery( connection, cube, queryName, mdxElement.getText() );
          q.setProperties( props );
          return q;
        } else {
          throw new OlapException( "Can't find child <MDX>" );
        }

      } catch ( OlapException e ) {
        throw new QueryParseException( e.getMessage(), e );
      }

    } else {
      throw new QueryParseException(
        "Cannot parse Query Model: Query node not found and/or more than 1 Query node found" );
    }
  }

  private void setTotals( IQuery q, Element queryElement ) {
    final Element totals = queryElement.getChild( "Totals" );
    if ( null != totals ) {
      final List totalList = totals.getChildren( "Total" );
      for ( Element function : (List<Element>) totalList ) {
        final String uniqueLevelName = function.getAttributeValue( "uniqueLevelName" );
        final String functionName = function.getAttributeValue( "functionName" );
        q.setTotalFunction( uniqueLevelName, functionName );
      }
    }
  }

  private Properties getProperties( Element queryElement ) {
    Properties props = new Properties();
    try {

      Element propertiesElement = queryElement.getChild( "Properties" );
      if ( propertiesElement != null ) {
        for ( int i = 0; i < propertiesElement.getChildren( "Property" ).size(); i++ ) {
          Element p = (Element) propertiesElement.getChildren( "Property" ).get( i );
          String k = p.getAttributeValue( "name" );
          String v = p.getAttributeValue( "value" );
          props.put( k, v );
        }

      }
    } catch ( Exception e ) {
      log.error("Exception", e.getCause());
    }
    return props;
  }

  private void manipulateQuery( Element qmElement ) throws OlapException {
    moveDims2Axis( qmElement );

  }

  private void moveDims2Axis( Element qmElement ) throws OlapException {
    Element axesElement = qmElement.getChild( "Axes" );
    if ( axesElement != null ) {

      for ( int i = 0; i < axesElement.getChildren( "Axis" ).size(); i++ ) {
        Element axisElement = (Element) axesElement.getChildren( "Axis" ).get( i );

        String location = axisElement.getAttributeValue( "location" );
        if ( !StringUtils.isNotBlank( location ) ) {
          throw new OlapException( "Location for Axis Element can't be null" );
        }

        QueryAxis qAxis = qm.getAxes().get( getAxisName( location ) );

        String nonEmpty = axisElement.getAttributeValue( "nonEmpty" );
        if ( StringUtils.isNotBlank( nonEmpty ) ) {
          qAxis.setNonEmpty( Boolean.parseBoolean( nonEmpty ) );
        }

        String sortOrder = axisElement.getAttributeValue( "sortOrder" );
        String sortEvaluationLiteral = axisElement.getAttributeValue( "sortEvaluationLiteral" );

        if ( StringUtils.isNotBlank( sortOrder ) ) {
          if ( StringUtils.isNotBlank( sortEvaluationLiteral ) ) {
            qAxis.sort( SortOrder.valueOf( sortOrder ), sortEvaluationLiteral );
          } else {
            qAxis.sort( SortOrder.valueOf( sortOrder ) );
          }
        }

        String limitFunction = axisElement.getAttributeValue( "limitFunction" );
        String limitFunctionN = axisElement.getAttributeValue( "limitFunctionN" );
        String limitFunctionSortLiteral = axisElement.getAttributeValue( "limitFunctionSortLiteral" );
        String filterCondition = axisElement.getAttributeValue( "filterCondition" );
        try {
          if ( StringUtils.isNotBlank( limitFunction ) ) {
            LimitFunction func = LimitFunction.valueOf( limitFunction );
            BigDecimal n = new BigDecimal( limitFunctionN );
            qAxis.limit( func, n, limitFunctionSortLiteral );
          }
          if ( StringUtils.isNotBlank( filterCondition ) ) {
            qAxis.filter( filterCondition );
          }
        } catch ( Error e ) {
            log.error("ERROR", e);
        }

        Element dimensions = axisElement.getChild( "Dimensions" );
        if ( dimensions != null ) {
          for ( int z = 0; z < dimensions.getChildren( "Dimension" ).size(); z++ ) {
            Element dimensionElement = (Element) dimensions.getChildren( "Dimension" ).get( z );
            processDimension( dimensionElement, location );

          }
        }
      }
    }

  }

  private void processDimension( Element dimension, String location ) throws OlapException {

    String dimName = dimension.getAttributeValue( "name" );
    if ( StringUtils.isNotBlank( dimName ) ) {

      QueryDimension dim = qm.getDimension( dimName );

      if ( dim == null ) {
        throw new OlapException( "Dimension not found:" + dimName );
      }

      String sortOrder = dimension.getAttributeValue( "sortOrder" );
      if ( StringUtils.isNotBlank( sortOrder ) ) {
        dim.sort( SortOrder.valueOf( sortOrder ) );
      }

      String hierarchizeMode = dimension.getAttributeValue( "hierarchizeMode" );
      if ( StringUtils.isNotBlank( hierarchizeMode ) ) {
        dim.setHierarchizeMode( HierarchizeMode.valueOf( hierarchizeMode ) );
      }

      String hierarchyConsistent = dimension.getAttributeValue( "hierarchyConsistent" );
      if ( StringUtils.isNotBlank( hierarchyConsistent ) ) {
        dim.setHierarchyConsistent( Boolean.parseBoolean( hierarchyConsistent ) );
      }

      qm.getAxes().get( Axis.Standard.valueOf( location ) ).getDimensions().add( dim );

      Element inclusions = dimension.getChild( "Inclusions" );
      if ( inclusions != null ) {
        for ( int z = 0; z < inclusions.getChildren( SELECTION ).size(); z++ ) {
          Element selectionElement = (Element) inclusions.getChildren( SELECTION ).get( z );
          String name = selectionElement.getAttributeValue( "node" );
          String operator = selectionElement.getAttributeValue( "operator" );
          String type = selectionElement.getAttributeValue( "type" );
          Selection sel = null;
          if ( "level".equals( type ) ) {
            for ( Hierarchy hierarchy : dim.getDimension().getHierarchies() ) {
              for ( Level level : hierarchy.getLevels() ) {
                if ( level.getUniqueName().equals( name ) ) {
                  sel = dim.include( level );
                }
              }
            }
          } else if ( "member".equals( type ) ) {
            sel = dim.include( Selection.Operator.valueOf( operator ),
              IdentifierNode.parseIdentifier( name ).getSegmentList() );
          }

          Element contextElement = selectionElement.getChild( "Context" );
          if ( sel != null && contextElement != null ) {
            for ( int h = 0; h < contextElement.getChildren( SELECTION ).size(); h++ ) {
              Element context = (Element) contextElement.getChildren( SELECTION ).get( h );
              String contextname = context.getAttributeValue( "node" );
              String contextoperator = context.getAttributeValue( "operator" );
              String contextDimension = context.getAttributeValue( "dimension" );
              QueryDimension contextDim = qm.getDimension( contextDimension );
              if ( contextDim != null ) {
                Selection contextSelection = contextDim.createSelection( Selection.Operator.valueOf( contextoperator ),
                  IdentifierNode.parseIdentifier( contextname ).getSegmentList() );
                if ( contextSelection != null ) {
                  sel.addContext( contextSelection );
                } else {
                  throw new OlapException(
                    "Cannot create selection for node: " + contextname + " operator:" + contextoperator
                      + " on dimension: " + dim.getName()
                  );
                }
              } else {
                throw new OlapException( "Context dimension is null" );
              }
            }

          }

        }
      }

      Element exclusions = dimension.getChild( "Exclusions" );
      if ( inclusions != null ) {
        for ( int z = 0; z < exclusions.getChildren( SELECTION ).size(); z++ ) {
          Element selectionElement = (Element) exclusions.getChildren( SELECTION ).get( z );
          String name = selectionElement.getAttributeValue( "node" );
          String operator = selectionElement.getAttributeValue( "operator" );
          dim
            .exclude( Selection.Operator.valueOf( operator ), IdentifierNode.parseIdentifier( name ).getSegmentList() );
          // ADD CONTEXT ?
        }
      }

    } else {
      throw new OlapException( "No Dimension name defined" );
    }

  }

  private Query createEmptyQuery( String queryName, String catalogName, String schemaName, String cubeName )
    throws SQLException {
    if ( !StringUtils.isNotBlank( catalogName ) ) {
      try {
        connection.setCatalog( catalogName );
      } catch ( SQLException e ) {
        throw new OlapException( e.getMessage(), e );
      }
    }

    Cube cube = null;
    if ( connection != null ) {
      for ( Database db : connection.getOlapDatabases() ) {
        Catalog cat = db.getCatalogs().get( catalogName );
        if ( cat != null ) {
          for ( Schema schema : cat.getSchemas() ) {
            if ( schema.getName().equals( schemaName )
              || ( schema.getName().equals( "" ) && schemaName == null ) ) {
              for ( Cube cub : schema.getCubes() ) {
                if ( cub.getName().equals( cubeName ) || cub.getUniqueName().equals( cubeName ) ) {
                  cube = cub;
                }
              }
            }
          }
        }
      }
    }
    if ( cube != null ) {
      try {
          return new Query( queryName, cube );
      } catch ( SQLException e ) {
        throw new OlapException( "Error creating query :" + queryName, e );
      }
    } else {
      throw new OlapException( "No Cube with name: " + cubeName + " found" );
    }

  }

  private Axis.Standard getAxisName(String location) {
    if ( location != null ) {
      return org.olap4j.Axis.Standard.valueOf( location );
    }
    return null;

  }

}


text:
// -----------------------------------------------------------------------
// <copyright file="SupportedTeam.cs" company="Hyperar">
//     Copyright (c) Hyperar. All rights reserved.
// </copyright>
// <author>Matías Ezequiel Sánchez</author>
// -----------------------------------------------------------------------
namespace Hyperar.HattrickUltimate.BusinessObjects.Hattrick.TeamDetails
{
    /// <summary>
    /// SupportedTeam node within TeamDetails XML file.
    /// </summary>
    public class SupportedTeam
    {
        #region Public Properties

        /// <summary>
        /// Gets or sets the Last Match.
        /// </summary>
        public LastMatch LastMatch { get; set; }

        /// <summary>
        /// Gets or sets the League Id.
        /// </summary>
        public long LeagueId { get; set; }

        /// <summary>
        /// Gets or sets the LeagueLevelUnit Id.
        /// </summary>
        public long LeagueLevelUnitId { get; set; }

        /// <summary>
        /// Gets or sets the LeagueLevelUnit Name.
        /// </summary>
        public string LeagueLevelUnitName { get; set; }

        /// <summary>
        /// Gets or sets the League Name.
        /// </summary>
        public string LeagueName { get; set; }

        /// <summary>
        /// Gets or sets the login name.
        /// </summary>
        public string LoginName { get; set; }

        /// <summary>
        /// Gets or sets the Next Match.
        /// </summary>
        public NextMatch NextMatch { get; set; }

        /// <summary>
        /// Gets or sets the Press Announcement.
        /// </summary>
        public PressAnnouncement PressAnnouncement { get; set; }

        /// <summary>
        /// Gets or sets the Team Id.
        /// </summary>
        public long TeamId { get; set; }

        /// <summary>
        /// Gets or sets the Team Name.
        /// </summary>
        public string TeamName { get; set; }

        /// <summary>
        /// Gets or sets the User Id.
        /// </summary>
        public long UserId { get; set; }

        #endregion Public Properties
    }
}


text:
title: Tareas
inshort: Tareas de Outlook
translator: Microsoft Cognitive Services
---

Tareas es las tareas de Outlook que aparece en Office 365.

Recursos
---------

-

Aplicaciones similares
--------------------

-Wunderlist

-Microsoft tareas

-Google tasks

-Tareas Apple

-Planificador Microsoft

Metadatos de
--------

-No se admite compartir externo

-Disponible la aplicación para el móvil


text:
TOOLSDIR="/home/black/caffe/fast-rcnn-action/"
DATADIR="data/Actions/PascalVoc2012/"
CMDDIR="tools"
CMDDIR=$TOOLSDIR$CMDDIR

PROTODIR="models/Actions/CaffeNet/pascalvoc.freeze.convs/"
PROTODIR=$TOOLSDIR$PROTODIR
solvername="pascal_action_solver.prototxt"
solverpath=$PROTODIR$solvername

MODELDIR="action_output/PascalVoc2012/rcnn_PascalVoc2012_train/caffenet.pascalvoc.freeze.convs/"
weightsname="caffenet_pascal_action_iter_32000.caffemodel"
weightspath=$MODELDIR$weightsname

# dataset to train on, the format of `imdb_name` is `rcnn_<datatype>_<split>,
# where datatype is the name of action dataset, like:
# PascalVoc2012, Willowactions, Stanford, MPII
# where split indicates the train/val/trainval/test.
# rcnn_PascalVoc2012_train
imdbname="rcnn_PascalVoc2012_train"
exper_name="caffenet.pascalvoc.freeze.convs/"
re_iter="32000"

# Log
log_path="output/action.logs/"
log_path=$TOOLSDIR$log_path
mkdir -p $log_path
cur_file_prefix="pascal_action_retrain_"
cur_log_filename=$(date -d "today" +"%Y.%m.%d.%H.%M.%S")
log_filename=$log_path$imdbname/$exper_name
mkdir -p $log_filename
log_filename=$log_filename$cur_file_prefix$cur_log_filename.log

# execute
cd
cd $TOOLSDIR
python $CMDDIR/train_action_net.py \
		--gpu 0 \
		--solver $solverpath \
		--weights $weightspath \
		--imdb $imdbname \
		--exper_name $exper_name \
		--re_iter $re_iter \
		2>&1 | tee -a $log_filename


text:
module Main where
import Control.Exception (SomeException(..))

import Test.Tasty.Bench (bench, bgroup, defaultMain, nfIO, whnfIO)
import qualified Control.Concurrent.Async as A
import qualified Control.Concurrent.Async.Lifted as L
import qualified Control.Concurrent.Async.Lifted.Safe as LS

main :: IO ()
main = defaultMain
  [ bgroup "async-wait"
      [ bench "async" $ whnfIO asyncWait_async
      , bench "lifted-async" $ whnfIO asyncWait_liftedAsync
      , bench "lifted-async-safe" $ whnfIO asyncWait_liftedAsyncSafe
      ]
  -- , bgroup "async-cancel-waitCatch"
  --     [ bench "async" $ whnfIO asyncCancelWaitCatch_async
  --     , bench "lifted-async" $ whnfIO asyncCancelWaitCatch_liftedAsync
  --     , bench "lifted-async-safe" $ whnfIO asyncCancelWaitCatch_liftedAsyncSafe
  --     ]
  , bgroup "waitAny"
      [ bench "async" $ whnfIO waitAny_async
      , bench "lifted-async" $ whnfIO waitAny_liftedAsync
      , bench "lifted-async-safe" $ whnfIO waitAny_liftedAsyncSafe
      ]
  , bgroup "race"
      [ bench "async" $ nfIO race_async
      , bench "lifted-async" $ nfIO race_liftedAsync
      , bench "lifted-async-safe" $ nfIO race_liftedAsyncSafe
      , bench "async (inlined)" $ nfIO race_async_inlined
      , bench "lifted-async (inlined)" $ nfIO race_liftedAsync_inlined
      ]
  , bgroup "concurrently"
      [ bench "async" $ nfIO concurrently_async
      , bench "lifted-async" $ nfIO concurrently_liftedAsync
      , bench "lifted-async-safe" $ nfIO concurrently_liftedAsyncSafe
      , bench "async (inlined)" $ nfIO concurrently_async_inlined
      , bench "lifted-async (inlined)" $ nfIO concurrently_liftedAsync_inlined
      ]
  , bgroup "mapConcurrently"
      [ bench "async" $ nfIO mapConcurrently_async
      , bench "lifted-async" $ nfIO mapConcurrently_liftedAsync
      , bench "lifted-async-safe" $ nfIO mapConcurrently_liftedAsyncSafe
      ]
  ]

asyncWait_async :: IO Int
asyncWait_async = do
  a <- A.async (return 1)
  A.wait a

asyncWait_liftedAsync :: IO Int
asyncWait_liftedAsync = do
  a <- L.async (return 1)
  L.wait a

asyncWait_liftedAsyncSafe :: IO Int
asyncWait_liftedAsyncSafe = do
  a <- LS.async (return 1)
  LS.wait a

asyncCancelWaitCatch_async :: IO (Either SomeException Int)
asyncCancelWaitCatch_async = do
  a <- A.async (return 1)
  A.cancel a
  A.waitCatch a

asyncCancelWaitCatch_liftedAsync :: IO (Either SomeException Int)
asyncCancelWaitCatch_liftedAsync = do
  a <- L.async (return 1)
  L.cancel a
  L.waitCatch a

asyncCancelWaitCatch_liftedAsyncSafe :: IO (Either SomeException Int)
asyncCancelWaitCatch_liftedAsyncSafe = do
  a <- LS.async (return 1)
  LS.cancel a
  LS.waitCatch a

waitAny_async :: IO Int
waitAny_async = do
  as <- mapM (A.async . return) [1..10]
  (_, n) <- A.waitAny as
  return n

waitAny_liftedAsync :: IO Int
waitAny_liftedAsync = do
  as <- mapM (L.async . return) [1..10]
  (_, n) <- L.waitAny as
  return n

waitAny_liftedAsyncSafe :: IO Int
waitAny_liftedAsyncSafe = do
  as <- mapM (LS.async . return) [1..10]
  (_, n) <- LS.waitAny as
  return n

race_async :: IO (Either Int Int)
race_async =
  A.race (return 1) (return 2)

race_liftedAsync :: IO (Either Int Int)
race_liftedAsync =
  L.race (return 1) (return 2)

race_liftedAsyncSafe :: IO (Either Int Int)
race_liftedAsyncSafe =
  LS.race (return 1) (return 2)

race_async_inlined :: IO (Either Int Int)
race_async_inlined =
  A.withAsync (return 1) $ \a ->
    A.withAsync (return 2) $ \b ->
      A.waitEither a b

race_liftedAsync_inlined :: IO (Either Int Int)
race_liftedAsync_inlined =
  L.withAsync (return 1) $ \a ->
    L.withAsync (return 2) $ \b ->
      L.waitEither a b

concurrently_async :: IO (Int, Int)
concurrently_async =
  A.concurrently (return 1) (return 2)

concurrently_liftedAsync :: IO (Int, Int)
concurrently_liftedAsync =
  L.concurrently (return 1) (return 2)

concurrently_liftedAsyncSafe :: IO (Int, Int)
concurrently_liftedAsyncSafe =
  LS.concurrently (return 1) (return 2)

concurrently_async_inlined :: IO (Int, Int)
concurrently_async_inlined =
  A.withAsync (return 1) $ \a ->
    A.withAsync (return 2) $ \b ->
      A.waitBoth a b

concurrently_liftedAsync_inlined :: IO (Int, Int)
concurrently_liftedAsync_inlined =
  L.withAsync (return 1) $ \a ->
    L.withAsync (return 2) $ \b ->
      L.waitBoth a b

mapConcurrently_async :: IO [Int]
mapConcurrently_async =
  A.mapConcurrently return [1..10]

mapConcurrently_liftedAsync :: IO [Int]
mapConcurrently_liftedAsync =
  L.mapConcurrently return [1..10]

mapConcurrently_liftedAsyncSafe :: IO [Int]
mapConcurrently_liftedAsyncSafe =
  LS.mapConcurrently return [1..10]


text:
__attribute__((visibility("hidden")))
@interface UIStatusDimmingWindow : UIWindow {
}
// inherited: -(BOOL)_ignoresHitTest;
@end

#endif


text:
Sequel::JDBC.load_driver('org.apache.derby.jdbc.EmbeddedDriver', :Derby)
Sequel.require 'adapters/jdbc/transactions'

module Sequel
  module JDBC
    Sequel.synchronize do
      DATABASE_SETUP[:derby] = proc do |db|
        db.extend(Sequel::JDBC::Derby::DatabaseMethods)
        db.dataset_class = Sequel::JDBC::Derby::Dataset
        org.apache.derby.jdbc.EmbeddedDriver
      end
    end

    # Database and Dataset support for Derby databases accessed via JDBC.
    module Derby
      # Instance methods for Derby Database objects accessed via JDBC.
      module DatabaseMethods
        extend Sequel::Database::ResetIdentifierMangling
        PRIMARY_KEY_INDEX_RE = /\Asql\d+\z/i.freeze

        include ::Sequel::JDBC::Transactions

        # Derby doesn't support casting integer to varchar, only integer to char,
        # and char(254) appears to have the widest support (with char(255) failing).
        # This does add a bunch of extra spaces at the end, but those will be trimmed
        # elsewhere.
        def cast_type_literal(type)
          (type == String) ? 'CHAR(254)' : super
        end

        # Derby uses the :derby database type.
        def database_type
          :derby
        end

        # Derby uses an IDENTITY sequence for autoincrementing columns.
        def serial_primary_key_options
          {:primary_key => true, :type => :integer, :identity=>true, :start_with=>1}
        end

        # The SVN version of the database.
        def svn_version
          @svn_version ||= begin
            v = synchronize{|c| c.get_meta_data.get_database_product_version}
            v =~ /\((\d+)\)\z/
            $1.to_i
          end
        end

        # Derby supports transaction DDL statements.
        def supports_transactional_ddl?
          true
        end

        private

        # Derby optimizes away Sequel's default check of SELECT NULL FROM table,
        # so use a SELECT * FROM table there.
        def _table_exists?(ds)
          ds.first
        end

        # Derby-specific syntax for renaming columns and changing a columns type/nullity.
        def alter_table_sql(table, op)
          case op[:op]
          when :rename_column
            "RENAME COLUMN #{quote_schema_table(table)}.#{quote_identifier(op[:name])} TO #{quote_identifier(op[:new_name])}"
          when :set_column_type
            # Derby is very limited in changing a columns type, so adding a new column and then dropping the existing column is
            # the best approach, as mentioned in the Derby documentation.
            temp_name = :x_sequel_temp_column_x
            [alter_table_sql(table, op.merge(:op=>:add_column, :name=>temp_name)),
             from(table).update_sql(temp_name=>::Sequel::SQL::Cast.new(op[:name], op[:type])),
             alter_table_sql(table, op.merge(:op=>:drop_column)),
             alter_table_sql(table, op.merge(:op=>:rename_column, :name=>temp_name, :new_name=>op[:name]))]
          when :set_column_null
            "ALTER TABLE #{quote_schema_table(table)} ALTER COLUMN #{quote_identifier(op[:name])} #{op[:null] ? 'NULL' : 'NOT NULL'}"
          else
            super
          end
        end

        # Derby doesn't allow specifying NULL for columns, only NOT NULL.
        def column_definition_null_sql(sql, column)
          sql << " NOT NULL" if column.fetch(:null, column[:allow_null]) == false
        end

        # Add NOT LOGGED for temporary tables to improve performance.
        def create_table_sql(name, generator, options)
          s = super
          s << ' NOT LOGGED' if options[:temp]
          s
        end

        # Insert data from the current table into the new table after
        # creating the table, since it is not possible to do it in one step.
        def create_table_as(name, sql, options)
          super
          from(name).insert(sql.is_a?(Dataset) ? sql : dataset.with_sql(sql))
        end

        # Derby currently only requires WITH NO DATA, with a separate insert
        # to import data.
        def create_table_as_sql(name, sql, options)
          "#{create_table_prefix_sql(name, options)} AS #{sql} WITH NO DATA"
        end

        # Temporary table creation on Derby uses DECLARE instead of CREATE.
        def create_table_prefix_sql(name, options)
          if options[:temp]
            "DECLARE GLOBAL TEMPORARY TABLE #{quote_identifier(name)}"
          else
            super
          end
        end

        DATABASE_ERROR_REGEXPS = {
          /The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index/ => UniqueConstraintViolation,
          /violation of foreign key constraint/ => ForeignKeyConstraintViolation,
          /The check constraint .+ was violated/ => CheckConstraintViolation,
          /cannot accept a NULL value/ => NotNullConstraintViolation,
          /A lock could not be obtained due to a deadlock/ => SerializationFailure,
        }.freeze
        def database_error_regexps
          DATABASE_ERROR_REGEXPS
        end

        # Use IDENTITY_VAL_LOCAL() to get the last inserted id.
        def last_insert_id(conn, opts=OPTS)
          statement(conn) do |stmt|
            sql = 'SELECT IDENTITY_VAL_LOCAL() FROM sysibm.sysdummy1'
            rs = log_yield(sql){stmt.executeQuery(sql)}
            rs.next
            rs.getLong(1)
          end
        end

        # Handle nil values by using setNull with the correct parameter type.
        def set_ps_arg_nil(cps, i)
          cps.setNull(i, cps.getParameterMetaData.getParameterType(i))
        end

        # Derby uses RENAME TABLE syntax to rename tables.
        def rename_table_sql(name, new_name)
          "RENAME TABLE #{quote_schema_table(name)} TO #{quote_schema_table(new_name)}"
        end

        # Primary key indexes appear to be named sqlNNNN on Derby
        def primary_key_index_re
          PRIMARY_KEY_INDEX_RE
        end

        # If an :identity option is present in the column, add the necessary IDENTITY SQL.
        def type_literal(column)
          if column[:identity]
            sql = "#{super} GENERATED BY DEFAULT AS IDENTITY"
            if sw = column[:start_with]
              sql << " (START WITH #{sw.to_i}"
              sql << " INCREMENT BY #{column[:increment_by].to_i}" if column[:increment_by]
              sql << ")"
            end
            sql
          else
            super
          end
        end

        # Derby uses clob for text types.
        def uses_clob_for_text?
          true
        end

        # The SQL query to issue to check if a connection is valid.
        def valid_connection_sql
          @valid_connection_sql ||= select(1).sql
        end
      end

      # Dataset class for Derby datasets accessed via JDBC.
      class Dataset < JDBC::Dataset
        PAREN_CLOSE = Dataset::PAREN_CLOSE
        PAREN_OPEN = Dataset::PAREN_OPEN
        OFFSET = Dataset::OFFSET
        CAST_STRING_OPEN = "RTRIM(".freeze
        BLOB_OPEN = "CAST(X'".freeze
        BLOB_CLOSE = "' AS BLOB)".freeze
        HSTAR = "H*".freeze
        TIME_FORMAT = "'%H:%M:%S'".freeze
        DEFAULT_FROM = " FROM sysibm.sysdummy1".freeze
        ROWS = " ROWS".freeze
        FETCH_FIRST = " FETCH FIRST ".freeze
        ROWS_ONLY = " ROWS ONLY".freeze
        BOOL_TRUE_OLD = '(1 = 1)'.freeze
        BOOL_FALSE_OLD = '(1 = 0)'.freeze
        BOOL_TRUE = 'TRUE'.freeze
        BOOL_FALSE = 'FALSE'.freeze
        EMULATED_FUNCTION_MAP = {:char_length=>'length'.freeze}

        # Derby doesn't support an expression between CASE and WHEN,
        # so remove
        # conditions.
        def case_expression_sql_append(sql, ce)
          super(sql, ce.with_merged_expression)
        end

        # If the type is String, trim the extra spaces since CHAR is used instead
        # of varchar.  This can cause problems if you are casting a char/varchar to
        # a string and the ending whitespace is important.
        def cast_sql_append(sql, expr, type)
          if type == String
            sql << CAST_STRING_OPEN
            super
            sql << PAREN_CLOSE
          else
            super
          end
        end

        def complex_expression_sql_append(sql, op, args)
          case op
          when :%, :'B~'
            complex_expression_emulate_append(sql, op, args)
          when :&, :|, :^, :<<, :>>
            raise Error, "Derby doesn't support the #{op} operator"
          when :extract
            sql << args.at(0).to_s << PAREN_OPEN
            literal_append(sql, args.at(1))
            sql << PAREN_CLOSE
          else
            super
          end
        end

        # Derby supports GROUP BY ROLLUP (but not CUBE)
        def supports_group_rollup?
          true
        end

        # Derby does not support IS TRUE.
        def supports_is_true?
          false
        end

        # Derby does not support IN/NOT IN with multiple columns
        def supports_multiple_column_in?
          false
        end

        private

        def empty_from_sql
          DEFAULT_FROM
        end

        # Derby needs a hex string casted to BLOB for blobs.
        def literal_blob_append(sql, v)
          sql << BLOB_OPEN << v.unpack(HSTAR).first << BLOB_CLOSE
        end

        # Derby needs the standard workaround to insert all default values into
        # a table with more than one column.
        def insert_supports_empty_values?
          false
        end

        # Derby uses an expression yielding false for false values.
        # Newer versions can use the FALSE literal, but the latest gem version cannot.
        def literal_false
          if db.svn_version >= 1040133
            BOOL_FALSE
          else
            BOOL_FALSE_OLD
          end
        end

        # Derby handles fractional seconds in timestamps, but not in times
        def literal_sqltime(v)
          v.strftime(TIME_FORMAT)
        end

        # Derby uses an expression yielding true for true values.
        # Newer versions can use the TRUE literal, but the latest gem version cannot.
        def literal_true
          if db.svn_version >= 1040133
            BOOL_TRUE
          else
            BOOL_TRUE_OLD
          end
        end

        # Derby supports multiple rows in INSERT.
        def multi_insert_sql_strategy
          :values
        end

        # Offset comes before limit in Derby
        def select_limit_sql(sql)
          if o = @opts[:offset]
            sql << OFFSET
            literal_append(sql, o)
            sql << ROWS
          end
          if l = @opts[:limit]
            sql << FETCH_FIRST
            literal_append(sql, l)
            sql << ROWS_ONLY
          end
        end
      end
    end
  end
end


text:
package io.jsonwebtoken.gson.io;

import com.google.gson.Gson;
import io.jsonwebtoken.io.DeserializationException;
import io.jsonwebtoken.io.Deserializer;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.lang.Strings;

import java.io.IOException;

public class GsonDeserializer<T> implements Deserializer<T> {

    private final Class<T> returnType;
    private final Gson gson;

    @SuppressWarnings("unused") //used via reflection by RuntimeClasspathDeserializerLocator
    public GsonDeserializer() {
        this(GsonSerializer.DEFAULT_GSON);
    }

    @SuppressWarnings({"unchecked", "WeakerAccess", "unused"}) // for end-users providing a custom gson
    public GsonDeserializer(Gson gson) {
        this(gson, (Class<T>) Object.class);
    }

    private GsonDeserializer(Gson gson, Class<T> returnType) {
        Assert.notNull(gson, "gson cannot be null.");
        Assert.notNull(returnType, "Return type cannot be null.");
        this.gson = gson;
        this.returnType = returnType;
    }

    @Override
    public T deserialize(byte[] bytes) throws DeserializationException {
        try {
            return readValue(bytes);
        } catch (IOException e) {
            String msg = "Unable to deserialize bytes into a " + returnType.getName() + " instance: " + e.getMessage();
            throw new DeserializationException(msg, e);
        }
    }

    protected T readValue(byte[] bytes) throws IOException {
        return gson.fromJson(new String(bytes, Strings.UTF_8), returnType);
    }
}


text:
import { provide } from 'angular2/core';
import { FIREBASE_BOOKS_URL } from '../../config';
import { AuthService } from '../auth/auth-service';
import { BookService } from './book-service';
import { BookStore } from './book-store';

export const BOOK_PROVIDERS: any[] = [
  provide(BookService, {
    deps: [AuthService],
    useFactory: (auth: AuthService): BookService => {
      return new BookService(new Firebase(`${FIREBASE_BOOKS_URL}/${auth.id}`));
    }
  }),

  provide(BookStore, {
    deps: [AuthService],
    useFactory: (auth: AuthService): BookStore => {
      return new BookStore(new Firebase(`${FIREBASE_BOOKS_URL}/${auth.id}`));
    }
  })
];


text:
package sample.client;

import com.github.timeu.gwtlibs.gwasviewer.client.Track;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;

/**
 * Created by uemit.seren on 11/30/15.
 */

@JsType(isNative = true,namespace = JsPackage.GLOBAL,name="Object")
public interface Tracks {
    @JsProperty
    Track[] getTracks();
}


text:
using System;
using System.Web.Mvc;
using RezRouting.Demos.MvcWalkthrough3.Controllers.Common;
using RezRouting.Demos.MvcWalkthrough3.Utility;

namespace RezRouting.Demos.MvcWalkthrough3.Controllers.Manufacturers.Manufacturer
{
    public class EditManufacturerController : ItemTaskController<EditManufacturerRequest,DataAccess.Manufacturer>
    {
        protected override void PrepareRequest(EditManufacturerRequest request, DataAccess.Manufacturer entity)
        {
            request.Id = entity.Id;
            request.Name = entity.Name;
        }

        protected override ActionResult ExecuteTask(EditManufacturerRequest request, DataAccess.Manufacturer manufacturer)
        {
            manufacturer.Name = request.Name;
            manufacturer.ModifiedOn = DateTime.Now;

            TempData["alert-success"] = "Manufacturer Updated";
            return Redirect(Url.ResourceUrl((ManufacturerDetailsController c) => c.Show(manufacturer.Id)));
        }
    }
}


text:
package com.rs.tools;

import java.io.File;
import java.io.IOException;

import com.rs.game.player.Player;
import com.rs.utils.SerializableFilesManager;

public class IPChecker {

	public static void main(String[] args) throws ClassNotFoundException, IOException {
		File[] chars = new File("data/characters").listFiles();
		//String ip = args[0];
		for (File acc : chars) {
			try {
				Player player = (Player) SerializableFilesManager
						.loadSerializedFile(acc);
				if(player == null || player.getMuted() > 0)
					continue;
				player.setMuted(0);
				SerializableFilesManager.storeSerializableClass(player, acc);
			} catch (Throwable e) {
				System.out.println("failed: " + acc.getName()+", "+e);
			}
		}
	}

}


text:
This inspection reports any JUnit assertTrue calls
which can be replaced by equivalent assertEquals calls. assertEquals
calls will normally give better error messages in case of test failure than assertTrue can.

Powered by InspectionGadgets


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

namespace PeeHaa\AsyncTwitter\Examples\Status;

use PeeHaa\AsyncTwitter\Api\Request\Status\UnRetweet;

require_once __DIR__ . '/../../vendor/autoload.php';

$apiClient = require __DIR__ . '/../create-client.php';

$request = (new UnRetweet(789019501211840512))
    ->trimUser()
;

\Amp\wait($apiClient->request($request));


text:
// ZAP: 2012/01/12 Reflected the rename of the class ExtensionPopupMenu to
// ExtensionPopupMenuItem.
// ZAP: 2012/04/25 Added @Override annotation to all appropriate methods.
// ZAP: 2012/07/29 Issue 43: Cleaned up access to ExtensionHistory UI
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
// ZAP: 2014/03/23 Changed to a JMenuItem.
// ZAP: 2016/07/25 Remove String constructor (unused/unnecessary)
// ZAP: 2018/08/15 Added null check

package org.parosproxy.paros.extension.history;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.network.HttpMessage;

public class PopupMenuExportResponse extends JMenuItem {

	private static final long serialVersionUID = 1L;
	private static final String NEWLINE = System.lineSeparator();

	// ZAP: Added logger
    private static Logger log = Logger.getLogger(PopupMenuExportResponse.class);

    private ExtensionHistory extension = null;

    public PopupMenuExportResponse() {
        super(Constant.messages.getString("history.export.response.popup"));	// ZAP: i18n

        this.addActionListener(new java.awt.event.ActionListener() {

        	@Override
        	public void actionPerformed(java.awt.event.ActionEvent e) {

        		List<HistoryReference> hrefs = extension.getSelectedHistoryReferences();
        	    if (hrefs.size() == 0) {
                    extension.getView().showWarningDialog(Constant.messages.getString("history.export.response.select.warning"));        	        	// ZAP: i18n
                    return;
        	    }

        	    File file = getOutputFile();
        	    if (file == null) {
        	        return;
        	    }

        	    boolean isAppend = true;
        	    if (file.exists()) {
                    int rc = extension.getView().showYesNoCancelDialog(Constant.messages.getString("file.overwrite.warning"));
                    if (rc == JOptionPane.CANCEL_OPTION) {
                        return;
                    } else if (rc == JOptionPane.YES_OPTION) {
                        isAppend = false;
                    }
        	    }

                try (BufferedOutputStream bos =
                        new BufferedOutputStream(
                                new FileOutputStream(file, isAppend));) {

                    for (HistoryReference href : hrefs) {
                        HttpMessage msg = null;
                        msg = href.getHttpMessage();
                        exportHistory(msg, bos);
                    }

                } catch (Exception e1) {
                    extension.getView().showWarningDialog(Constant.messages.getString("file.save.error") + file.getAbsolutePath() + ".");
                	// ZAP: Log exceptions
                	log.warn(e1.getMessage(), e1);
                }
        	}
        });

	}

    void setExtension(ExtensionHistory extension) {
        this.extension = extension;
    }

    private void exportHistory(HttpMessage msg, BufferedOutputStream bos) {

        try {
            if (!msg.getResponseHeader().isEmpty()) {
                String boundary = NEWLINE + "==== " + msg.getHistoryRef().getHistoryId() + " ==========" + NEWLINE;
                bos.write(boundary.getBytes());

                bos.write(msg.getResponseBody().getBytes());
            }

        } catch (Exception e) {
        	// ZAP: Log exceptions
        	log.warn(e.getMessage(), e);
        }

    }

    private File getOutputFile() {

        String filename = "untitled.txt";

        JFileChooser chooser = new JFileChooser(extension.getModel().getOptionsParam().getUserDirectory());
        if (filename.length() > 0) {
            chooser.setSelectedFile(new File(filename));
        }

		File file = null;
	    int rc = chooser.showSaveDialog(extension.getView().getMainFrame());
	    if(rc == JFileChooser.APPROVE_OPTION) {
    		file = chooser.getSelectedFile();
    		if (file == null) {
    			return file;
    		}

            extension.getModel().getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());

    		return file;

	    }
	    return file;
    }

}


text:
function SpriteCore(constructor) {
	if(constructor && constructor.spriteScale) this.spriteScale=constructor.spriteScale; else this.spriteScale=1;
	//loop or bounce
	if(constructor && constructor.loopType) this.loopType=constructor.loopType; else this.loopType='loop';
	//number of times to loop. use -1 for ininate; if using bounce dould loops if limiting
	if(constructor && constructor.loops) this.loops=constructor.loops; else this.loops=-1;
	if(constructor && constructor.reverseLoop) this.reverseLoop=constructor.reverseLoop; else this.reverseLoop=false;
	this.spriteWidth=constructor.spriteWidth*this.spriteScale;
	this.spriteHeight=constructor.spriteHeight*this.spriteScale;
	this.spritesheetWidth=constructor.spritesheetWidth*this.spriteScale;
	this.spritesheetHeight=constructor.spritesheetHeight*this.spriteScale;
	this.spritesheetImage=constructor.spritesheetImage;

	this.rows=(this.spritesheetHeight/this.spriteHeight).toFixed();
	this.columns=(this.spritesheetWidth/this.spriteWidth).toFixed();
	//this.totalFrames = this.rows * this.columns;
	this.sheet = Ti.UI.createImageView(
	{
		image:this.spritesheetImage,
		width:this.spritesheetWidth,
		height:this.spritesheetHeight,
	});
	this.spriteView = Ti.UI.createView({
		width:this.spriteWidth,
		height:this.spriteHeight,
	});
	OS_IOS && (this.spriteView.clipMode = Ti.UI.iOS.CLIP_MODE_ENABLED);
	this.spriteView.add(this.sheet);

	this.spriteAnimationPosition=0;
	this.spriteCurrentFrame=0;
	this.startAnimationFrame;
	this.endAnimationFrame;
	this.animationArray;
	this.animationCustomArray;
	this.spriteTimer;
	this.animateFrames=0;
	this.animationDuration=0;

	return this;
};
SpriteCore.prototype.createSprite = function(constructor) {
	if(constructor && constructor.spriteStartCustomFrame)
	{
		this.setCustomFrame(constructor.spriteStartCustomFrame);
	}
	else
	{
		if(constructor && constructor.spriteStart)
			this.spriteCurrentFrame=constructor.spriteStartFrame;
		else
			this.spriteCurrentFrame=0;

		this.setFrame();
	}
	return this.spriteView;
};

SpriteCore.prototype.start = function(args) {
	var self = this;
	if ('undefined' !== typeof args.start)
	{
		this.startAnimationFrame=args.start;
		this.endAnimationFrame=args.end;
		this.animateFrames = args.end-args.start;
		if(this.reverseLoop)
			this.setFrame(args.end);
		else
			this.setFrame(args.start);
	}
	else if(args.animationCustomArray)
	{
		this.animateFrames = args.animationCustomArray.length-1;
		this.animationCustomArray=args.animationCustomArray;
		if(this.reverseLoop)
			this.setCustomFrame(this.animateFrames);
		else
			this.setCustomFrame(this.animationCustomArray[0]);
	}
	else
	{
		this.animateFrames = args.animationArray.length-1;
		this.animationArray=args.animationArray;
		if(this.reverseLoop)
			this.setFrame(this.animateFrames);
		else
			this.setFrame(this.animationArray[0]);
	}
	this.animationDuration=args.time;
    this.spriteTimer = setInterval(function(){self.check_time(self);}, (this.animationDuration/this.animateFrames).toFixed());
    this.spriteView.fireEvent('animationStarted');
	return this;
};

SpriteCore.prototype.check_time =function(thisRef)
{
	self = thisRef;

	if(self.spriteAnimationPosition++ == self.animateFrames)
	{
		if(self.loops!==-1 && --self.loops === 0)
		{
			self.stop();
			this.spriteView.fireEvent('animationComplete');
			return self;
		}
		if(self.loopType=='bounce') self.reverseLoop=!self.reverseLoop;

		self.spriteAnimationPosition=0;

		if(self.animationCustomArray)
			self.setCustomFrame(self.animationCustomArray[self.reverseLoop?self.animateFrames:0]);
		else if ('undefined' !== typeof self.startAnimationFrame)
			self.setFrame(self.reverseLoop?self.endAnimationFrame:self.startAnimationFrame);
		else
			self.setFrame(self.animationArray[self.reverseLoop?self.animateFrames:0]);
	}
	else{
		var nextFrame;
		if(self.startAnimationFrame)
			nextFrame=self.reverseLoop?self.endAnimationFrame-self.spriteAnimationPosition:self.startAnimationFrame+self.spriteAnimationPosition;
		else if(self.reverseLoop)
			nextFrame=self.animateFrames-self.spriteAnimationPosition;
		else
			nextFrame=self.spriteAnimationPosition;

		if(self.animationCustomArray)
			self.setCustomFrame(self.animationCustomArray[nextFrame]);
		else if ('undefined' !== typeof self.startAnimationFrame)
			self.setFrame(nextFrame);
		else
			self.setFrame(self.animationArray[nextFrame]);
	}
	return self;
};

SpriteCore.prototype.setFrame =function(frame)
{
	if ('undefined' !== typeof frame) this.spriteCurrentFrame=frame;
	this.sheet.left = -1*parseInt(this.spriteCurrentFrame%this.columns)*this.spriteWidth;
	this.sheet.top = -1*parseInt(this.spriteCurrentFrame/this.columns)*this.spriteHeight;
	//Ti.API.info(frame+' - x:'+this.sheet.left+' y:'+this.sheet.top);
	return this;
};

SpriteCore.prototype.setCustomFrame =function(frameParam)
{
	this.sheet.left = -1*parseInt(frameParam.x*this.spriteScale);
	this.sheet.top = -1*parseInt(frameParam.y*this.spriteScale);
	if(frameParam.w)this.spriteView.width = parseInt(frameParam.w*this.spriteScale);
	if(frameParam.h)this.spriteView.height = parseInt(frameParam.h*this.spriteScale);
	return this;
};

SpriteCore.prototype.stop = function() {
	clearInterval(this.spriteTimer);
	this.spriteView.fireEvent('animationStopped');
	return this;
};

SpriteCore.prototype.resume = function() {
	var self = this;
	this.spriteTimer = setInterval(function(){self.check_time(self);}, (this.animationDuration/this.animateFrames).toFixed());
	this.spriteView.fireEvent('animationResumed');
	return this;
};

module.exports = SpriteCore;


text:
package de.tuberlin.cit.sdn.opendaylight.hydrogen.model.statistic;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class FlowStatistic {
    public FlowStatisticFlow flow;
    public int tableId;

    // time the flow has been installed in the switch
    public int durationSeconds;
    public int durationNanoseconds;

    public int packetCount;
    public int byteCount;

    @JsonIgnore
    public double getBytesPerSecond() {
        return byteCount / durationSeconds;
    }

    @JsonIgnore
    public double getPacketsPerSecond() {
        return packetCount / durationSeconds;
    }
}


text:
<?php

namespace App\Entity\Statistics;

use Doctrine\ORM\Mapping as ORM;

/**
 * Class AttributeValue
 *
 * @ORM\Entity
 * @ORM\Table(name="statistics__attribute_value")
 */
class AttributeValue
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @var Attribute
     *
     * @ORM\ManyToOne(targetEntity="App\Entity\Statistics\Attribute")
     * @ORM\JoinColumn(name="attribute_id", referencedColumnName="id")
     */
    protected $attribute;

    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     */
    protected $value;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     *
     * @return AttributeValue
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return Attribute
     */
    public function getAttribute()
    {
        return $this->attribute;
    }

    /**
     * @param Attribute $attribute
     *
     * @return AttributeValue
     */
    public function setAttribute($attribute)
    {
        $this->attribute = $attribute;

        return $this;
    }

    /**
     * @return int
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @param int $value
     *
     * @return AttributeValue
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;

namespace TCC2.API
{
    public enum AccessLevel
    {
        [EnumFieldAlias("NONE")]
        None,

        [EnumFieldAlias("VIEWER")]
	    Viewer,

        [EnumFieldAlias("DEPOSITOR")]
	    Depositor,

        [EnumFieldAlias("EDITOR")]
        Editor,

        [EnumFieldAlias("OWNER")]
	    Owner
    }

    public enum ACEType
    {
        [EnumFieldAlias("device")]
        Device,

        [EnumFieldAlias("member")]
        Member,

        [EnumFieldAlias("group")]
        Group
    }

    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    public class AccessControlEntry
    {
        public AccessControlEntry(string id, AccessLevel level, ACEType type)
        {
            if (String.IsNullOrEmpty(id))
                throw new ArgumentException("Id value cannot be null or empty", "id");

            if (!Enum.IsDefined(typeof(AccessLevel), level))
                throw new ArgumentException("Undefined access level: " + level);

            if (!Enum.IsDefined(typeof(ACEType), type))
                throw new ArgumentException("Undefined access level: " + level);

            Id = id;
            Level = level;
            EntryType = type;
        }

        protected AccessControlEntry()
        {
        }

        [JsonProperty(PropertyName = "ACLEntry")]
        public string Id { get; protected set; }

        [JsonProperty(PropertyName = "ACLEntryLevel")]
        public AccessLevel Level { get; protected set; }

        [JsonProperty(PropertyName = "ACLEntryType")]
        public ACEType EntryType { get; protected set; }

        public IEnumerable<ApiParameter> ToInputParams()
        {
            return new ApiParameter[]
                {
                    new ApiParameter("aclentry", Id),
                    new ApiParameter("aclentrylevel", Level.ToString().ToLower(CultureInfo.InvariantCulture)),
                    new ApiParameter("aclentrytype", EntryType.ToString().ToLower(CultureInfo.InvariantCulture))
                };
        }
    }
}


text:
package models;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import javax.inject.Named;
import javax.inject.Singleton;
import java.util.List;

/**
 * Created by baishi on 11/24/15.
 */
@Named
@Singleton
public interface CommentRepository extends CrudRepository<Comment, Long> {
    @Query(value = "select * from Comment where (CommentId = ?)", nativeQuery = true)
    List<Comment> findByWorkflowId(Long workflow);
}


text:
<?php

namespace App\Helpers;

use limenet\GitVersion\Directory;
use limenet\GitVersion\Formatters\CustomFormatter;
use Nette;
use Nette\Utils\Arrays;

/**
 * Holder of configuration API item, which should describe this server.
 */
class ApiConfig
{
    use Nette\SmartObject;

    /**
     * Address of API server as visible from outside world.
     * @var string
     */
    protected $address;

    /**
     * Some basic name which should be used for identification of service
     * @var string
     */
    protected $name;

    /**
     * Basic description of this server.
     * @var string
     */
    protected $description;

    /**
     * Version of the project in semantic versioning (major.minor.patch)
     * @var string
     */
    protected $version;

    /**
     * Format in which version will be displayed
     * @var string
     */
    protected $versionFormat;

    /**
     * Constructs configuration object from given array.
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->address = Arrays::get($config, ["address"]);
        $this->name = Arrays::get($config, ["name"]);
        $this->description = Arrays::get($config, ["description"]);
        $this->versionFormat = Arrays::get($config, ["versionFormat"], "{tag}");

        // version is constructed from git version tag
        $this->version = (new Directory(__DIR__))->get(new CustomFormatter($this->versionFormat)) ?: "UNKNOWN";
    }

    public function getAddress()
    {
        return $this->address;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function getVersion()
    {
        return $this->version;
    }
}


text:
layout: post
title: Self-cleaning 'tmp' directory in Windows
date: 2017-01-08 10:00:00
---

I've recently migrated from Ubuntu 14 to Windows 10. One feature that I really
missed on Windows is the `tmp/` directory that automatically cleans itself up
upon reboot. On Ubuntu, I used `tmp/` instead of my Downloads folder and it
worked great. Here's how I've achieved the same behaviour on my Windows system.

### The target, the job
First, created my self-cleaning directory. Set it up under `C:\Users\Ernest\Temp`.

Next, I created a script that would execute the cleaning. Under Ubuntu, the
entire command would be `rm -Rf <directory>`. It turns out that using basic
Windows shell for this task is [not so great][so], so I decided to use PowerShell.
Here's the entire script:

[so]: http://stackoverflow.com/q/1965787/1167094

{% highlight powershell %}
# clear_temp_folder.ps1
Remove-Item -Recurse -Path "C:\Users\Ernest\Temp\*"
{% endhighlight %}

Not bad!

### The execution
I've used the Task Scheduler app bundled with Windows to schedule the script.
To create the task, fire up the Task Scheduler, then go **Action** -> **Create Basic Task...**. I used the following parameters:

 * Trigger: *When I log on*
 * Action: *Start a Program*

When asked for *Program/Script*, enter

    powershell

Under *Add arguments (optional)*, enter

{% highlight powershell %}
-ExecutionPolicy ByPass -File "C:\Path\To\clear_temp_folder.ps1"
{% endhighlight %}

Finally, change the executing user to `SYSTEM`. Find your task in the **Task
Scheduler Library**, right-click and select **Properties...**.

Under Security options, click on **Change User or Group...**. After entering
`SYSTEM` and closing the dialog, your Properties window should look like this:

![Alt text](http://i.imgur.com/oRWXnLo.png "Optional title")

That should be all. You can test the script right from the Task Scheduler (use
the Actions pane on the right). If the script doesn't seem to run on login (but works when executed manually), you can [enable task history](http://stackoverflow.com/q/11013132/1167094) to de-bug.


text:
import { Optional, Type } from '@ephox/katamari';

import Editor from 'tinymce/core/api/Editor';

const isChildOfBody = (editor: Editor, elm: Node): boolean => {
  return editor.dom.isChildOf(elm, editor.getBody());
};

const isTableCellNode = (node: Node | null): boolean => {
  return Type.isNonNullable(node) && /^(TH|TD)$/.test(node.nodeName);
};

const isListNode = (editor: Editor) => (node: Node | null): boolean => {
  return Type.isNonNullable(node) && (/^(OL|UL|DL)$/).test(node.nodeName) && isChildOfBody(editor, node);
};

const getSelectedStyleType = (editor: Editor): Optional<string> => {
  const listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
  const style = editor.dom.getStyle(listElm, 'listStyleType');
  return Optional.from(style);
};

// Lists/core/Util.ts - Duplicated in Lists plugin
const isWithinNonEditable = (editor: Editor, element: Element | null): boolean =>
  element !== null && editor.dom.getContentEditableParent(element) === 'false';

const isWithinNonEditableList = (editor: Editor, element: Element | null): boolean => {
  const parentList = editor.dom.getParent(element, 'ol,ul,dl');
  return isWithinNonEditable(editor, parentList);
};

export {
  isTableCellNode,
  isListNode,
  getSelectedStyleType,
  isWithinNonEditableList
};


text:
<?php

namespace FOS\UserBundle\Controller;

use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseNullableUserEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Form\Factory\FactoryInterface;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Mailer\MailerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Controller managing the resetting of the password.
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Christophe Coevoet <stof@notk.org>
 *
 * @final
 */
class ResettingController extends Controller
{
    private $eventDispatcher;
    private $formFactory;
    private $userManager;
    private $tokenGenerator;
    private $mailer;

    /**
     * @var int
     */
    private $retryTtl;

    /**
     * @param int $retryTtl
     */
    public function __construct(EventDispatcherInterface $eventDispatcher, FactoryInterface $formFactory, UserManagerInterface $userManager, TokenGeneratorInterface $tokenGenerator, MailerInterface $mailer, $retryTtl)
    {
        $this->eventDispatcher = $eventDispatcher;
        $this->formFactory = $formFactory;
        $this->userManager = $userManager;
        $this->tokenGenerator = $tokenGenerator;
        $this->mailer = $mailer;
        $this->retryTtl = $retryTtl;
    }

    /**
     * Request reset user password: show form.
     */
    public function requestAction()
    {
        return $this->render('@FOSUser/Resetting/request.html.twig');
    }

    /**
     * Request reset user password: submit form and send email.
     *
     * @return Response
     */
    public function sendEmailAction(Request $request)
    {
        $username = $request->request->get('username');

        $user = $this->userManager->findUserByUsernameOrEmail($username);

        $event = new GetResponseNullableUserEvent($user, $request);
        $this->eventDispatcher->dispatch(FOSUserEvents::RESETTING_SEND_EMAIL_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        if (null !== $user && !$user->isPasswordRequestNonExpired($this->retryTtl)) {
            $event = new GetResponseUserEvent($user, $request);
            $this->eventDispatcher->dispatch(FOSUserEvents::RESETTING_RESET_REQUEST, $event);

            if (null !== $event->getResponse()) {
                return $event->getResponse();
            }

            if (null === $user->getConfirmationToken()) {
                $user->setConfirmationToken($this->tokenGenerator->generateToken());
            }

            $event = new GetResponseUserEvent($user, $request);
            $this->eventDispatcher->dispatch(FOSUserEvents::RESETTING_SEND_EMAIL_CONFIRM, $event);

            if (null !== $event->getResponse()) {
                return $event->getResponse();
            }

            $this->mailer->sendResettingEmailMessage($user);
            $user->setPasswordRequestedAt(new \DateTime());
            $this->userManager->updateUser($user);

            $event = new GetResponseUserEvent($user, $request);
            $this->eventDispatcher->dispatch(FOSUserEvents::RESETTING_SEND_EMAIL_COMPLETED, $event);

            if (null !== $event->getResponse()) {
                return $event->getResponse();
            }
        }

        return new RedirectResponse($this->generateUrl('fos_user_resetting_check_email', ['username' => $username]));
    }

    /**
     * Tell the user to check his email provider.
     *
     * @return Response
     */
    public function checkEmailAction(Request $request)
    {
        $username = $request->query->get('username');

        if (empty($username)) {
            // the user does not come from the sendEmail action
            return new RedirectResponse($this->generateUrl('fos_user_resetting_request'));
        }

        return $this->render('@FOSUser/Resetting/check_email.html.twig', [
            'tokenLifetime' => ceil($this->retryTtl / 3600),
        ]);
    }

    /**
     * Reset user password.
     *
     * @param string $token
     *
     * @return Response
     */
    public function resetAction(Request $request, $token)
    {
        $user = $this->userManager->findUserByConfirmationToken($token);

        if (null === $user) {
            return new RedirectResponse($this->container->get('router')->generate('fos_user_security_login'));
        }

        $event = new GetResponseUserEvent($user, $request);
        $this->eventDispatcher->dispatch(FOSUserEvents::RESETTING_RESET_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $this->formFactory->createForm();
        $form->setData($user);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $event = new FormEvent($form, $request);
            $this->eventDispatcher->dispatch(FOSUserEvents::RESETTING_RESET_SUCCESS, $event);

            $this->userManager->updateUser($user);

            if (null === $response = $event->getResponse()) {
                $url = $this->generateUrl('fos_user_profile_show');
                $response = new RedirectResponse($url);
            }

            $this->eventDispatcher->dispatch(
                FOSUserEvents::RESETTING_RESET_COMPLETED,
                new FilterUserResponseEvent($user, $request, $response)
            );

            return $response;
        }

        return $this->render('@FOSUser/Resetting/reset.html.twig', [
            'token' => $token,
            'form' => $form->createView(),
        ]);
    }
}


text:
package org.cs3.pdt.analysis.model;

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

public class AnalysisCategory implements IAnalysisCategory {

	private String name;
	private String description;
	private IFactbase factbase;
	private ArrayList<IAnalysis> analyses = new ArrayList<>();

	public AnalysisCategory(String name, String description, IFactbase factbase) {
		this.name = name;
		this.description = description;
		this.factbase = factbase;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public String getDescription() {
		return description;
	}

	@Override
	public IFactbase getFactbase() {
		return factbase;
	}

	@Override
	public int hashCode() {
		return name.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof AnalysisCategory) {
			return name.equals(((AnalysisCategory) obj).name);
		}
		return false;
	}

	@Override
	public int compareTo(IAnalysisCategory o) {
		return getName().compareTo(o.getName());
	}

	public void addAnalysis(IAnalysis analysis) {
		if (!analyses.contains(analysis))  // gk: added check to
			analyses.add(analysis);        // avoid duplicate entries
	}

	@Override
	public List<IAnalysis> getAnalyses() {
		return new ArrayList<>(analyses);
	}

}


text:
namespace daw {
	namespace rfb {

		namespace impl {
			class RFBServerImpl;
		} // namespace impl

		namespace BitDepth {
			enum values : uint8_t { eight = 8, sixteen = 16, thirtytwo = 32 };
		} // namespace BitDepth

		union ButtonMask {
			uint8_t value;
			struct {
				bool button_1 : 1;
				bool button_2 : 1;
				bool button_3 : 1;
				bool button_4 : 1;
				bool button_5 : 1;
				bool button_6 : 1;
				bool button_7 : 1;
				bool button_8 : 1;
			} button;
			constexpr explicit ButtonMask( uint8_t v ) noexcept : value{v} {}
		}; // union ButtonMask

		struct Colour {
			uint8_t red;
			uint8_t green;
			uint8_t blue;
			uint8_t padding;
		};

		using Box = std::vector<daw::range::Range<uint8_t *>>;
		using BoxReadOnly = std::vector<daw::range::Range<uint8_t const *>>;

		class RFBServer {
			std::shared_ptr<impl::RFBServerImpl> m_impl;

		  public:
			RFBServer( ) = delete;
			~RFBServer( );
			RFBServer( RFBServer const & ) = default;
			RFBServer &operator=( RFBServer const & ) = default;
			RFBServer( RFBServer && ) noexcept = default;
			RFBServer &operator=( RFBServer && ) noexcept = default;

			RFBServer( uint16_t width, uint16_t height, BitDepth::values depth,
			           daw::nodepp::base::EventEmitter emitter = daw::nodepp::base::create_event_emitter( ) );

			uint16_t width( ) const noexcept;
			uint16_t height( ) const noexcept;
			uint16_t max_x( ) const noexcept;
			uint16_t max_y( ) const noexcept;

			void listen( uint16_t port, daw::nodepp::lib::net::ip_version ip_ver );
			void close( );

			void on_key_event( std::function<void( bool key_down, uint32_t key )> callback );
			void on_pointer_event(
			    std::function<void( ButtonMask buttons, uint16_t x_position, uint16_t y_position )> callback );
			void on_client_clipboard_text( std::function<void( daw::string_view text )> callback );

			void send_clipboard_text( daw::string_view text );
			void send_bell( );
			//////////////////////////////////////////////////////////////////////////
			/// Summary: get a bounded area that will later be updated to the client
			Box get_area( uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2 );
			BoxReadOnly get_readonly_area( uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2 ) const;

			//////////////////////////////////////////////////////////////////////////
			/// Summary: send all updated areas to client
			void update( );
		}; // class RFBServer
	}      // namespace rfb
} // namespace daw


text:
namespace seasocks {

class ZlibContext {
public:
    ZlibContext(const ZlibContext&) = delete;
    ZlibContext& operator=(const ZlibContext&) = delete;

    ZlibContext();
    ~ZlibContext();
    void initialise(int deflateBits = 15, int inflateBits = 15, int memLevel = 6);

    void deflate(const uint8_t* input, size_t inputLen, std::vector<uint8_t>& output);

    // WARNING: inflate() alters input
    bool inflate(std::vector<uint8_t>& input, std::vector<uint8_t>& output, int& zlibError);

private:
    struct Impl;
    std::unique_ptr<Impl> _impl;
};

} // namespace seasocks


text:
#
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef YAS_PREPROCESSOR_FACILITIES_OVERLOAD_HPP
# define YAS_PREPROCESSOR_FACILITIES_OVERLOAD_HPP
#
# include <yas/detail/preprocessor/config.hpp>
# include <yas/detail/preprocessor/cat.hpp>
# include <yas/detail/preprocessor/vsize.hpp>
#
# /* BOOST_PP_OVERLOAD */
#
# if YAS_PP_VARIADICS
#    define YAS_PP_OVERLOAD(prefix, ...) YAS_PP_CAT(prefix, YAS_PP_VARIADIC_SIZE(__VA_ARGS__))
# endif
#
# endif


text:
using AutoMapper;
using Newtonsoft.Json;
using sapHowmuch.Api.Business.Events;
using sapHowmuch.Api.Infrastructure.Models;

namespace sapHowmuch.Api.Business.EventHandlers.Profiles
{
	public class JournalVoucherCreatedEventToEventStreamMapperProfile : Profile
	{
		public JournalVoucherCreatedEventToEventStreamMapperProfile()
		{
			CreateMap<JournalVoucherCreatedEvent, EventStream>()
				.ForMember(dest => dest.StreamId, opt => opt.MapFrom(src => src.EventStream))
				.ForMember(dest => dest.EventName, opt => opt.MapFrom(src => src.Name))
				.ForMember(dest => dest.EventType, opt => opt.MapFrom(src => src.GetType().FullName))
				.ForMember(dest => dest.EventBody, opt => opt.MapFrom(src => JsonConvert.SerializeObject(src)))
				.ForMember(dest => dest.DateProjected, opt => opt.MapFrom(src => src.Projector.DateProjected))
				.ForMember(dest => dest.ProjectedBy, opt => opt.MapFrom(src => src.Projector.ProjectorId));
		}
	}
}


text:
const Command = require('../structures/Command');
const axios = require('axios');
const { RichEmbed } = require('discord.js');
const { inspect } = require('util');

class CounterCommand extends Command {
	constructor() {
		super({
			name: 'counter',
			description: 'Display various information regarding the counter of <https://megumin.love>',
			aliases: ['c'],
			args: [
				{
					type: 'string',
					name: 'primarySelector',
					defaultVal: 'general'
				},
				{
					type: 'string',
					name: 'secondarySelector',
					defaultVal: 'general'
				}
			]
		});
	}

	async run(message, args) {
		const { logger, config } = message.client;
		const cb = '```', icb = '``';
		const formatNumber = num => num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1.');
		const newDate = new Date();
		const fl = input => input < 9 ? `0${input}` : `${input}`;
		const time = `${fl(newDate.getHours())}:${fl(newDate.getMinutes())}`;
		const date = `${fl(newDate.getDate())}/${fl(newDate.getMonth() + 1)}/${fl(newDate.getFullYear())}`;
		if (args.primarySelector === 'history') {
			const history = require('../data/counterHistory.json');

			if (args.secondarySelector === 'general') {
				const historyHeader = '**__Here is an overview of the counter\'s saved progress history__**:\n';
				const historyBody = `${cb}${history.join('\n')}${cb}`;
				return message.channel.send(`${historyHeader}${historyBody}`, { split: { prepend: cb, append: cb } });
			}

			if (args.secondarySelector === 'append' && config.owners.includes(message.author.id)) {
				return axios.get('https://megumin.love/api/counter').then(counter => {
					const newCounter = `${formatNumber(counter.data.counter)} ${time} ${date}`;
					history.push(newCounter);
					logger.writeJSON(history, './data/counterHistory.json')
						.then(data => message.reply(`new entry successfully added: ${icb}${newCounter}${icb}`))
						.catch(err => message.reply(`an error occurred writing to the file: ${cb}${err}${cb}`));
				}).catch(err => {
					const errorDetails = `${err.host ? err.host : ''} ${err.message ? err.message : ''}`.trim();
					message.reply(`an error occurred getting the counter: ${icb}${err.code}: ${errorDetails}${icb}`);
					logger.error(inspect(err));
				});
			}

			if (args.secondarySelector === 'revert' && config.owners.includes(message.author.id)) {
				history.pop();
				logger.writeJSON(history, './data/counterHistory.json')
					.then(data => message.reply('latest history entry successfully removed.'))
					.catch(err => {
						message.reply(`an error occurred writing to the file: ${cb}${err}${cb}`);
						logger.error(inspect(err));
					});
			}
		}

		if (args.primarySelector === 'statistics') {
			if (args.secondarySelector === 'general') {
				axios.get('https://megumin.love/api/statistics/summary').then(statistics => {
					const embed = new RichEmbed();

					embed.setAuthor('megumin.love Counter Statistics', 'https://megumin.love/images/favicons/favicon-32x32.png')
						.setURL('https://megumin.love/')
						.setColor((Math.random() * 10e4).toFixed(5))
						.addField('All-time', formatNumber(statistics.data.alltime), true)
						.addField('Today', formatNumber(statistics.data.daily), true)
						.addField('This week', formatNumber(statistics.data.weekly), true)
						.addField('This month', formatNumber(statistics.data.monthly), true)
						.addField('This year', formatNumber(statistics.data.yearly), true)
						.addField('Average/day', formatNumber(statistics.data.average), true);
					return message.channel.send({ embed });
				}).catch(err => {
					const errorDetails = `${err.host ? err.host : ''} ${err.message ? err.message : ''}`.trim();
					message.reply(`an error occurred getting the statistics: ${cb}${err.code}: ${errorDetails}${cb}`);
					logger.error(inspect(err));
				});
			}
		}

		if (args.primarySelector === 'rankings') {
			if (args.secondarySelector === 'general') {
				axios.get('https://megumin.love/api/sounds').then(sounds => {
					const parsedRanks = sounds.data.sort((a, b) => b.count - a.count).slice(0, 12);
					const embed = new RichEmbed();
					embed.setAuthor('megumin.love Soundboard Rankings', 'https://megumin.love/images/favicons/favicon-32x32.png')
						.setURL('https://megumin.love/')
						.setColor((Math.random() * 10e4).toFixed(5));

					for (const rank of parsedRanks) {
						embed.addField(`#${parsedRanks.indexOf(rank) + 1}: ${rank.displayname}`, `${formatNumber(rank.count)} clicks`, true);
					}

					return message.channel.send({ embed });
				}).catch(err => {
					const errorDetails = `${err.host ? err.host : ''} ${err.message ? err.message : ''}`.trim();
					message.reply(`an error occurred getting the rankings: ${cb}${err.code}: ${errorDetails}${cb}`);
					logger.error(inspect(err));
				});
			}
		}

		if (args.primarySelector === 'general') {
			axios.get('https://megumin.love/api/counter').then(counter => {
				const formattedCounter = `**${formatNumber(counter.data.counter)}**`.trim();
				return message.channel.send(`Current https://megumin.love count is: ${formattedCounter}`);
			}).catch(err => {
				const errorDetails = `${err.host ? err.host : ''} ${err.message ? err.message : ''}`.trim();
				message.reply(`an error occurred getting the counter: ${icb}${err.code}: ${errorDetails}${icb}`);
				logger.error(inspect(err));
			});
		}
	}
}

module.exports = CounterCommand;


text:
import sys
from cx_Freeze import setup, Executable

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

options = {
    'build_exe': {
        'includes': 'atexit'
    }
}

executables = [
    Executable('weathertrek.py', base=base)
]

setup(name='Weather Trek',
      version='0.2',
      description='Weather for traveling',
      options=options,
      executables=executables
      )


text:
external help file: Microsoft.Azure.Commands.ResourceManager.Automation.dll-Help.xml
Module Name: AzureRM.Automation
ms.assetid: 38BB4F4E-B72B-460E-8DF2-2A7A9CACDB41
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.automation/get-azurermautomationjoboutputrecord
schema: 2.0.0
---

# Get-AzureRmAutomationJobOutputRecord

## SYNOPSIS
Gets the full output of an Automation job output record.

## SYNTAX

```
Get-AzureRmAutomationJobOutputRecord [-JobId] <Guid> [-Id] <String> [-ResourceGroupName] <String>
 [-AutomationAccountName] <String> [-DefaultProfile <IAzureContextContainer>] [<CommonParameters>]
```

## DESCRIPTION
The **Get-AzureRmAutomationJobOutputRecord** cmdlet gets the full output of an Automation job output record.
Although the **Get-AzureRmAutomationJobOutput** cmdlet lists one or more job output records, it returns only a summary, as a string, of the value of any output record.
It does not return the full value of an output record's outputted value in its original type.
In addition, the summary has a maximum length, which the full value that this cmdlet outputs may exceed.
Unlike **Get-AzureRmAutomationJobOutput**, this cmdlet returns the full value in its originally outputted type, for any output record's outputted value.

## EXAMPLES

### Example 1: Get the full output of an Automation job
```
PS C:\>Get-AzureRmAutomationJobOutput -AutomationAccountName "Contoso17" -Id 2989b069-24fe-40b9-b3bd-cb7e5eac4b64 -ResourceGroupName "ResourceGroup01" -Stream "Any" | Get-AzureRmAutomationJobOutputRecord
```

This command gets the full output of the job that has the specified job ID.

## PARAMETERS

### -AutomationAccountName
Specifies the name of an Automation account for which this cmdlet gets a job output record.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with azure

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Id
Specifies the ID of a job output record for this cmdlet to retrieve.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases: StreamRecordId

Required: True
Position: 3
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -JobId
Specifies the ID of a job for which this cmdlet gets an output record.

```yaml
Type: System.Guid
Parameter Sets: (All)
Aliases:

Required: True
Position: 2
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ResourceGroupName
Specifies the name of a resource group for which this cmdlet gets a job output record.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.Guid

### System.String

## OUTPUTS

### Microsoft.Azure.Commands.Automation.Model.JobStreamRecord

## NOTES

## RELATED LINKS

[Get-AzureRmAutomationJobOutput](./Get-AzureRMAutomationJobOutput.md)