text:
package org.apache.flink.table.planner.delegation;

import org.apache.flink.annotation.Internal;
import org.apache.flink.sql.parser.validate.FlinkSqlConformance;
import org.apache.flink.table.api.SqlDialect;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.table.catalog.FunctionCatalog;
import org.apache.flink.table.module.ModuleManager;
import org.apache.flink.table.planner.calcite.CalciteConfig;
import org.apache.flink.table.planner.calcite.CalciteConfig$;
import org.apache.flink.table.planner.calcite.FlinkContext;
import org.apache.flink.table.planner.calcite.FlinkContextImpl;
import org.apache.flink.table.planner.calcite.FlinkConvertletTable;
import org.apache.flink.table.planner.calcite.FlinkPlannerImpl;
import org.apache.flink.table.planner.calcite.FlinkRelBuilder;
import org.apache.flink.table.planner.calcite.FlinkRelFactories;
import org.apache.flink.table.planner.calcite.FlinkRelOptClusterFactory;
import org.apache.flink.table.planner.calcite.FlinkRexBuilder;
import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
import org.apache.flink.table.planner.calcite.FlinkTypeSystem;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverter;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterFactory;
import org.apache.flink.table.planner.calcite.SqlExprToRexConverterImpl;
import org.apache.flink.table.planner.catalog.FunctionCatalogOperatorTable;
import org.apache.flink.table.planner.codegen.ExpressionReducer;
import org.apache.flink.table.planner.functions.sql.FlinkSqlOperatorTable;
import org.apache.flink.table.planner.hint.FlinkHintStrategies;
import org.apache.flink.table.planner.parse.CalciteParser;
import org.apache.flink.table.planner.plan.FlinkCalciteCatalogReader;
import org.apache.flink.table.planner.plan.cost.FlinkCostFactory;
import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
import org.apache.flink.table.planner.utils.TableConfigUtils;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;

import org.apache.calcite.config.Lex;
import org.apache.calcite.jdbc.CalciteSchema;
import org.apache.calcite.plan.Context;
import org.apache.calcite.plan.Contexts;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptPlanner;
import org.apache.calcite.plan.RelTraitDef;
import org.apache.calcite.plan.volcano.VolcanoPlanner;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeSystem;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.dialect.AnsiSqlDialect;
import org.apache.calcite.sql.dialect.HiveSqlDialect;
import org.apache.calcite.sql.parser.SqlParser;
import org.apache.calcite.sql.util.SqlOperatorTables;
import org.apache.calcite.sql.validate.SqlConformance;
import org.apache.calcite.sql2rel.SqlToRelConverter;
import org.apache.calcite.tools.FrameworkConfig;
import org.apache.calcite.tools.Frameworks;

import javax.annotation.Nullable;

import java.util.List;

import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * Utility class to create {@link org.apache.calcite.tools.RelBuilder} or {@link FrameworkConfig}
 * used to create a corresponding {@link org.apache.calcite.tools.Planner}. It tries to separate
 * static elements in a {@link org.apache.flink.table.api.TableEnvironment} like: root schema, cost
 * factory, type system etc. from a dynamic properties like e.g. default path to look for objects in
 * the schema.
 */
@Internal
public class PlannerContext {

    private final RelDataTypeSystem typeSystem = new FlinkTypeSystem();
    private final FlinkTypeFactory typeFactory = new FlinkTypeFactory(typeSystem);
    private final SqlExprToRexConverterFactory rexConverterFactory =
            new DefaultSqlExprToRexConverterFactory();
    private final TableConfig tableConfig;
    private final RelOptCluster cluster;
    private final FlinkContext context;
    private final CalciteSchema rootSchema;
    private final List<RelTraitDef> traitDefs;
    private final FrameworkConfig frameworkConfig;

    public PlannerContext(
            boolean isBatchMode,
            TableConfig tableConfig,
            ModuleManager moduleManager,
            FunctionCatalog functionCatalog,
            CatalogManager catalogManager,
            CalciteSchema rootSchema,
            List<RelTraitDef> traitDefs) {
        this.tableConfig = tableConfig;

        this.context =
                new FlinkContextImpl(
                        isBatchMode,
                        tableConfig,
                        moduleManager,
                        functionCatalog,
                        catalogManager,
                        rexConverterFactory);

        this.rootSchema = rootSchema;
        this.traitDefs = traitDefs;
        // Make a framework config to initialize the RelOptCluster instance,
        // caution that we can only use the attributes that can not be overwritten/configured
        // by user.
        this.frameworkConfig = createFrameworkConfig();

        RelOptPlanner planner =
                new VolcanoPlanner(frameworkConfig.getCostFactory(), frameworkConfig.getContext());
        planner.setExecutor(frameworkConfig.getExecutor());
        for (RelTraitDef traitDef : frameworkConfig.getTraitDefs()) {
            planner.addRelTraitDef(traitDef);
        }
        this.cluster = FlinkRelOptClusterFactory.create(planner, new FlinkRexBuilder(typeFactory));
    }

    public SqlExprToRexConverterFactory getSqlExprToRexConverterFactory() {
        return rexConverterFactory;
    }

    public FrameworkConfig createFrameworkConfig() {
        return Frameworks.newConfigBuilder()
                .defaultSchema(rootSchema.plus())
                .parserConfig(getSqlParserConfig())
                .costFactory(new FlinkCostFactory())
                .typeSystem(typeSystem)
                .convertletTable(FlinkConvertletTable.INSTANCE)
                .sqlToRelConverterConfig(getSqlToRelConverterConfig(getCalciteConfig(tableConfig)))
                .operatorTable(getSqlOperatorTable(getCalciteConfig(tableConfig)))
                // set the executor to evaluate constant expressions
                .executor(new ExpressionReducer(tableConfig, false))
                .context(context)
                .traitDefs(traitDefs)
                .build();
    }

    /** Returns the {@link FlinkTypeFactory} that will be used. */
    public FlinkTypeFactory getTypeFactory() {
        return typeFactory;
    }

    /** Returns the {@link FlinkContext}. */
    public FlinkContext getFlinkContext() {
        return context;
    }

    /**
     * Creates a configured {@link FlinkRelBuilder} for a planning session.
     *
     * @param currentCatalog the current default catalog to look for first during planning.
     * @param currentDatabase the current default database to look for first during planning.
     * @return configured rel builder
     */
    public FlinkRelBuilder createRelBuilder(String currentCatalog, String currentDatabase) {
        FlinkCalciteCatalogReader relOptSchema =
                createCatalogReader(false, currentCatalog, currentDatabase);

        Context chain =
                Contexts.of(
                        context,
                        // Sets up the ViewExpander explicitly for FlinkRelBuilder.
                        createFlinkPlanner(currentCatalog, currentDatabase).createToRelContext());
        return new FlinkRelBuilder(chain, cluster, relOptSchema);
    }

    /**
     * Creates a configured {@link FlinkPlannerImpl} for a planning session.
     *
     * @param currentCatalog the current default catalog to look for first during planning.
     * @param currentDatabase the current default database to look for first during planning.
     * @return configured flink planner
     */
    public FlinkPlannerImpl createFlinkPlanner(String currentCatalog, String currentDatabase) {
        return new FlinkPlannerImpl(
                createFrameworkConfig(),
                isLenient -> createCatalogReader(isLenient, currentCatalog, currentDatabase),
                typeFactory,
                cluster);
    }

    /**
     * Creates a configured instance of {@link CalciteParser}.
     *
     * @return configured calcite parser
     */
    public CalciteParser createCalciteParser() {
        return new CalciteParser(getSqlParserConfig());
    }

    public FlinkCalciteCatalogReader createCatalogReader(
            boolean lenientCaseSensitivity, String currentCatalog, String currentDatabase) {
        SqlParser.Config sqlParserConfig = getSqlParserConfig();
        final boolean caseSensitive;
        if (lenientCaseSensitivity) {
            caseSensitive = false;
        } else {
            caseSensitive = sqlParserConfig.caseSensitive();
        }

        SqlParser.Config newSqlParserConfig =
                SqlParser.configBuilder(sqlParserConfig).setCaseSensitive(caseSensitive).build();

        SchemaPlus rootSchema = getRootSchema(this.rootSchema.plus());
        return new FlinkCalciteCatalogReader(
                CalciteSchema.from(rootSchema),
                asList(asList(currentCatalog, currentDatabase), singletonList(currentCatalog)),
                typeFactory,
                CalciteConfig$.MODULE$.connectionConfig(newSqlParserConfig));
    }

    public RelOptCluster getCluster() {
        return cluster;
    }

    private SchemaPlus getRootSchema(SchemaPlus schema) {
        if (schema.getParentSchema() == null) {
            return schema;
        } else {
            return getRootSchema(schema.getParentSchema());
        }
    }

    private CalciteConfig getCalciteConfig(TableConfig tableConfig) {
        return TableConfigUtils.getCalciteConfig(tableConfig);
    }

    /**
     * Returns the SQL parser config for this environment including a custom Calcite configuration.
     */
    private SqlParser.Config getSqlParserConfig() {
        return JavaScalaConversionUtil.<SqlParser.Config>toJava(
                        getCalciteConfig(tableConfig).getSqlParserConfig())
                .orElseGet(
                        // we use Java lex because back ticks are easier than double quotes in
                        // programming
                        // and cases are preserved
                        () -> {
                            SqlConformance conformance = getSqlConformance();
                            return SqlParser.config()
                                    .withParserFactory(FlinkSqlParserFactories.create(conformance))
                                    .withConformance(conformance)
                                    .withLex(Lex.JAVA)
                                    .withIdentifierMaxLength(256);
                        });
    }

    private FlinkSqlConformance getSqlConformance() {
        SqlDialect sqlDialect = tableConfig.getSqlDialect();
        switch (sqlDialect) {
            case HIVE:
                return FlinkSqlConformance.HIVE;
            case DEFAULT:
                return FlinkSqlConformance.DEFAULT;
            default:
                throw new TableException("Unsupported SQL dialect: " + sqlDialect);
        }
    }

    private org.apache.calcite.sql.SqlDialect getCalciteSqlDialect() {
        SqlDialect sqlDialect = tableConfig.getSqlDialect();
        switch (sqlDialect) {
            case HIVE:
                return HiveSqlDialect.DEFAULT;
            case DEFAULT:
                return AnsiSqlDialect.DEFAULT;
            default:
                throw new TableException("Unsupported SQL dialect: " + sqlDialect);
        }
    }

    /**
     * Returns the {@link SqlToRelConverter} config.
     *
     * <p>`expand` is set as false, and each sub-query becomes a
     * [[org.apache.calcite.rex.RexSubQuery]].
     */
    private SqlToRelConverter.Config getSqlToRelConverterConfig(CalciteConfig calciteConfig) {
        return JavaScalaConversionUtil.<SqlToRelConverter.Config>toJava(
                        calciteConfig.getSqlToRelConverterConfig())
                .orElseGet(
                        () ->
                                SqlToRelConverter.config()
                                        .withTrimUnusedFields(false)
                                        .withHintStrategyTable(
                                                FlinkHintStrategies.createHintStrategyTable())
                                        .withInSubQueryThreshold(Integer.MAX_VALUE)
                                        .withExpand(false)
                                        .withRelBuilderFactory(
                                                FlinkRelFactories.FLINK_REL_BUILDER()));
    }

    /** Returns the operator table for this environment including a custom Calcite configuration. */
    private SqlOperatorTable getSqlOperatorTable(CalciteConfig calciteConfig) {
        return JavaScalaConversionUtil.<SqlOperatorTable>toJava(calciteConfig.getSqlOperatorTable())
                .map(
                        operatorTable -> {
                            if (calciteConfig.replacesSqlOperatorTable()) {
                                return operatorTable;
                            } else {
                                return SqlOperatorTables.chain(
                                        getBuiltinSqlOperatorTable(), operatorTable);
                            }
                        })
                .orElseGet(this::getBuiltinSqlOperatorTable);
    }

    /** Returns builtin the operator table and external the operator for this environment. */
    private SqlOperatorTable getBuiltinSqlOperatorTable() {
        return SqlOperatorTables.chain(
                new FunctionCatalogOperatorTable(
                        context.getFunctionCatalog(),
                        context.getCatalogManager().getDataTypeFactory(),
                        typeFactory),
                FlinkSqlOperatorTable.instance());
    }

    // --------------------------------------------------------------------------------------------
    // DefaultSqlExprToRexConverterFactory
    // --------------------------------------------------------------------------------------------

    private class DefaultSqlExprToRexConverterFactory implements SqlExprToRexConverterFactory {

        @Override
        public SqlExprToRexConverter create(
                RelDataType inputRowType, @Nullable RelDataType outputType) {
            return new SqlExprToRexConverterImpl(
                    checkNotNull(frameworkConfig),
                    checkNotNull(typeFactory),
                    checkNotNull(cluster),
                    checkNotNull(getCalciteSqlDialect()),
                    inputRowType,
                    outputType);
        }

        @Override
        public SqlExprToRexConverter create(
                RowType inputRowType, @Nullable LogicalType outputType) {
            final RelDataType convertedInputRowType = typeFactory.buildRelNodeRowType(inputRowType);

            final RelDataType convertedOutputType;
            if (outputType != null) {
                convertedOutputType = typeFactory.createFieldTypeFromLogicalType(outputType);
            } else {
                convertedOutputType = null;
            }

            return create(convertedInputRowType, convertedOutputType);
        }
    }
}


text:
require 'spec_helper'

module VCR
  module HttpStubbingAdapters
    describe MultiObjectProxy do
      let(:mock1) { mock }
      let(:mock2) { mock }
      subject { described_class.new(mock1, mock2) }

      it 'raises an error when it is created with no objects' do
        expect { described_class.new }.to raise_error(ArgumentError)
      end

      it 'raises an error when one of the objects is nil' do
        expect { described_class.new(Object.new, nil) }.to raise_error(ArgumentError)
      end

      it 'is a basic object with very few of its own methods' do
        inst_methods = described_class.instance_methods.map { |m| m.to_sym }
        inst_methods.should_not include(:send, :object_id, :__id__)
      end

      describe '#proxied_objects' do
        it 'returns the proxied objects' do
          subject.proxied_objects.should == [mock1, mock2]
        end
      end

      describe '#respond_to?' do
        it 'responds to any method that any of the objects responds to' do
          mock1.stub(:respond_to?).with(:foo).and_return(true)
          mock1.stub(:respond_to?).with(:bar).and_return(false)
          mock2.stub(:respond_to?).with(:bar).and_return(true)
          mock2.stub(:respond_to?).with(:foo).and_return(false)

          subject.respond_to?(:foo).should be_true
          subject.respond_to?(:bar).should be_true
        end

        it 'does not respond to a method that none of the objects respond to' do
          subject.respond_to?(:bazz).should be_false
        end
      end

      describe 'calling a method' do
        it 'raises a no method error when none of the objects responds to the method' do
          expect { subject.some_undefined_method }.to raise_error(NoMethodError)
        end

        it 'properly proxies messages to a single object when only one object responds to the message' do
          mock1.should_not respond_to(:request_stubbed?)
          mock2.should_receive(:request_stubbed?).and_return(true)

          subject.request_stubbed?.should == true
        end

        it 'proxies messages to each object' do
          mock1.should_receive(:stub_requests).with(:arg1, :arg2)
          mock2.should_receive(:stub_requests).with(:arg1, :arg2)

          subject.stub_requests(:arg1, :arg2)
        end

        [:http_connections_allowed?, :request_uri].each do |method|
          context "for ##{method}" do
            it 'raises an error if the the objects return different values' do
              mock1.should_receive(method).and_return(:return_value_1)
              mock2.should_receive(method).and_return(:return_value_2)

              expect { subject.__send__(method) }.to raise_error(/proxied objects returned different values/)
            end

            it 'returns the value returned by both objects when they return the same value' do
              mock1.should_receive(method).and_return(:return_value_1)
              mock2.should_receive(method).and_return(:return_value_1)

              subject.__send__(method).should == :return_value_1
            end
          end
        end

        context 'for a non-predicate method' do
          it 'does not raise an error when the objects have different return values' do
            mock1.should_receive(:stub_requests).and_return(:val1)
            mock2.should_receive(:stub_requests).and_return(:val2)

            subject.stub_requests
          end

          it 'returns nil regardless of the return values of the objects' do
            mock1.should_receive(:stub_requests).and_return(:val1)
            mock2.should_receive(:stub_requests).and_return(:val1)

            subject.stub_requests.should be_nil
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
cli-path-resolve
================

resolve/normalize a filepath using the cwd as the basepath if relative

## installation

```
$ npm install cli-path-resolve
```

## usage

If an argument is passed to your cli script that points to the file system, it can be absolute or relative.

If it's relative - this module will use the current working directory (process.cwd) as the basedir.

globalscript.js

```js
var args = require('minimist').parse(process.argv, {
	alias:{
    f:'filepath'
  }
})
var resolve = require('cli-path-resolve')
var filepath = resolve(args.filepath)

// filepath is now normalized and absolute
console.log(filepath)
```

If we have installed globalscript.js globally - we can run it from anywhere.

```
$ cd /home/myfolder
$ globalscript.js --filepath imgs/balloons.jpg
/home/myfolder/imgs/balloons.jpg
```

## api

### `var resolved = resolve(path)`

Will return path if it is absolute or will resolve it against process.cwd if its relative.

### license

MIT


text:
__author__ = 'Filippo'

import csv

artistsPerYear = {}

for i in range(1940,2011):
    with open("../data/genresByYear/"+str(i)+'Genres.csv', 'rb') as csvfile:
        year=[]
        spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
        spamreader.next()
        for row in spamreader:
            if row[0] != "Artist":
                year.append({"name":row[0].decode('latin-1').encode("utf-8"),"value":row[1]})
        artistsPerYear[i]=year

decadeForTop = {}
topTen = []
for i in [1940,1950,1960,1970,1980,1990,2000]:
    with open("../data/GenresByDecade/"+str(i)+'sGenres.csv', 'rb') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
        spamreader.next()
        j = 0
        for row in spamreader:
            j+=1
            if j<11:
                topTen.append(row[0])
                decadeForTop[row[0]]=i

print topTen
print len(topTen)

res=[]
perArtist = {}

for i in artistsPerYear.keys():
    yearArray = artistsPerYear[i]
    for art in yearArray:
        if art["name"] in topTen:
            if not(art["name"] in perArtist.keys()):
                perArtist[art["name"]]=[]
            res.append({"name":art["name"],"value":art["value"],"date":i,"decade":decadeForTop[art["name"]]})

for i in range(1940,2011):
    for j in topTen:
        alreadyThere = False
        for k in res:
            if (k["date"]==i and k["name"]==j):
                alreadyThere = True
                break
        if (not alreadyThere):
            res.append({"name":j,"value":"0","date":i,"decade":decadeForTop[j]})

def comparer(x,y):
    return (topTen.index(x["name"]) - topTen.index(y["name"]))*100 - (y["date"]-x["date"])

orderedRes = sorted(res,cmp = comparer)

import json
with open("../data/genresStaticData.js", 'w') as csvfile:
    json.dump(orderedRes,csvfile)


text:
package iso20022

type ExternalTypeOfParty1Code string


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>BRRelutionIBeaconMessageActionMapper Class Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				BlueRange SDK

				M-Way Solutions GmbH

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Instance Methods">

		<option value="//api/name/getBeaconActionInformationForMessage:">- getBeaconActionInformationForMessage:</option>

		<option value="//api/name/initWithRelution:">- initWithRelution:</option>

		<option value="//api/name/isAvailable">- isAvailable</option>

	</optgroup>

</select>

BRRelutionIBeaconMessageActionMapper Class Reference

	Inherits from
	NSObject

	Conforms to
	BRIBeaconMessageActionMapper

	Declared in
	BRRelutionIBeaconMessageActionMapper.h
BRRelutionIBeaconMessageActionMapper.m

– initWithRelution:

- (id)initWithRelution:(BRRelution *)relution

– getBeaconActionInformationForMessage:

- (BRRelutionActionInformation *)getBeaconActionInformationForMessage:(BRIBeaconMessage *)message

– isAvailable

- (BOOL)isAvailable

Copyright © 2017 M-Way Solutions GmbH. All rights reserved. Updated: 2017-09-15

Generated by appledoc 2.2.1 (build 1334).


text:
package androidx.media.filterpacks.transform;

import androidx.media.filterfw.*;

// TODO: In the future this could be done with a meta-filter that simply "hard-codes" the crop
// parameters.
public class ResizeFilter extends CropFilter {

    public ResizeFilter(MffContext context, String name) {
        super(context, name);
    }

    @Override
    public Signature getSignature() {
        FrameType imageIn = FrameType.image2D(FrameType.ELEMENT_RGBA8888, FrameType.READ_GPU);
        FrameType imageOut = FrameType.image2D(FrameType.ELEMENT_RGBA8888, FrameType.WRITE_GPU);
        return new Signature()
            .addInputPort("image", Signature.PORT_REQUIRED, imageIn)
            .addInputPort("outputWidth", Signature.PORT_OPTIONAL, FrameType.single(int.class))
            .addInputPort("outputHeight", Signature.PORT_OPTIONAL, FrameType.single(int.class))
            .addInputPort("useMipmaps", Signature.PORT_OPTIONAL, FrameType.single(boolean.class))
            .addOutputPort("image", Signature.PORT_REQUIRED, imageOut)
            .disallowOtherPorts();
    }
}


text:
#include <gtest/gtest.h>
#include "m3bp/logger.hpp"

int main(int argc, char **argv){
	::testing::InitGoogleTest(&argc, argv);
	m3bp::Logger::add_destination_stream(std::clog, m3bp::LogLevel::WARNING);
	return RUN_ALL_TESTS();
}


text:
/* matrix.h -- define types for matrices using Iliffe vectors
 *
 *************************************************************
 * HISTORY
 *
 * 02-Apr-95  Reg Willson (rgwillson@mmm.com) at 3M St. Paul, MN
 *      Rewrite memory allocation to avoid memory alignment problems
 *      on some machines.
 */

typedef struct {
    int       lb1,
              ub1,
              lb2,
              ub2;
    char     *mat_sto;
    double  **el;
} dmat;

void      print_mat ();
dmat      newdmat ();
int       matmul ();
int       matcopy ();
int       transpose ();
double    matinvert ();
int       solve_system ();

#define freemat(m) free((m).mat_sto) ; free((m).el)


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>dbstl_exit</title>
    <link rel="stylesheet" href="apiReference.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
    <link rel="start" href="index.html" title="Berkeley DB C++ Standard Template Library API Reference" />
    <link rel="up" href="dbstl_global_functions.html" title="Chapter 1.  Dbstl Global Public Functions" />
    <link rel="prev" href="stldbstl_global_functionsdbstl_startup.html" title="dbstl_startup" />
    <link rel="next" href="stldbstl_global_functionsdbstl_thread_exit.html" title="dbstl_thread_exit" />

Library Version 11.2.5.3

          dbstl_exit

          Prev
          Chapter 1.
 Dbstl Global Public Functions
           Next

dbstl_exit

Function Details

 void dbstl_exit()

This function releases memory allocated by dbstl on the heap, and closes all Berkeley DB handles in the right order.

 You can call dbstl_exit()
 before the process exits to release any memory allocated by dbstl that has to persist during the entire process lifetime.

Class

  dbstl_global_functions

          Prev

            Up

           Next

          dbstl_startup

            Home

dbstl_thread_exit


text:
Ti.include('tiutils.js');
Ti.include('main.js');

var app = {
    init: function () {
        this.showMainWindow();
        return this;
    },
    showMainWindow: function () {
        if (!this.mainWinMgr) {
            this.mainWinMgr = new MainWinMgr().init();
        }
    }
};

app.init();

// // this sets the background color of the master UIView (when there are no windows/tab groups on it)
// Titanium.UI.setBackgroundColor('#000');

// // create tab group
// var tabGroup = Titanium.UI.createTabGroup();

// //
// // create base UI tab and root window
// //
// var win1 = Titanium.UI.createWindow({
//     title:'Tab 1',
//     backgroundColor:'#fff'
// });
// var tab1 = Titanium.UI.createTab({
//     icon:'KS_nav_views.png',
//     title:'Tab 1',
//     window:win1
// });

// var label1 = Titanium.UI.createLabel({
// 	color:'#999',
// 	text:'I am Window 1',
// 	font:{fontSize:20,fontFamily:'Helvetica Neue'},
// 	textAlign:'center',
// 	width:'auto'
// });

// win1.add(label1);

// //
// // create controls tab and root window
// //
// var win2 = Titanium.UI.createWindow({
//     title:'Tab 2',
//     backgroundColor:'#fff'
// });
// var tab2 = Titanium.UI.createTab({
//     icon:'KS_nav_ui.png',
//     title:'Tab 2',
//     window:win2
// });

// var label2 = Titanium.UI.createLabel({
// 	color:'#999',
// 	text:'I am Window 2',
// 	font:{fontSize:20,fontFamily:'Helvetica Neue'},
// 	textAlign:'center',
// 	width:'auto'
// });

// win2.add(label2);

// //
// //  add tabs
// //
// tabGroup.addTab(tab1);
// tabGroup.addTab(tab2);

// // open tab group
// tabGroup.open();


text:
/*
 * @(#)message_deliverystatus.java	1.3 06/02/27
 *
 * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
 */

package com.sun.mail.dsn;

import java.io.*;
import java.util.Properties;
import java.awt.datatransfer.DataFlavor;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * @version	1.3, 06/02/27
 */
public class message_deliverystatus implements DataContentHandler {

    ActivationDataFlavor ourDataFlavor = new ActivationDataFlavor(
	DeliveryStatus.class,
	"message/delivery-status",
	"Delivery Status");

    /**
     * return the DataFlavors for this DataContentHandler
     * @return The DataFlavors.
     */
    public DataFlavor[] getTransferDataFlavors() {
	return new DataFlavor[] { ourDataFlavor };
    }

    /**
     * return the Transfer Data of type DataFlavor from InputStream
     * @param df The DataFlavor.
     * @param ins The InputStream corresponding to the data.
     * @return a Message object
     */
    public Object getTransferData(DataFlavor df, DataSource ds)
				throws IOException {
	// make sure we can handle this DataFlavor
	if (ourDataFlavor.equals(df))
	    return getContent(ds);
	else
	    return null;
    }

    /**
     * Return the content.
     */
    public Object getContent(DataSource ds) throws IOException {
	// create a new DeliveryStatus
	try {
	    /*
	    Session session;
	    if (ds instanceof MessageAware) {
		javax.mail.MessageContext mc =
			((MessageAware)ds).getMessageContext();
		session = mc.getSession();
	    } else {
		// Hopefully a rare case.  Also hopefully the application
		// has created a default Session that can just be returned
		// here.  If not, the one we create here is better than
		// nothing, but overall not a really good answer.
		session = Session.getDefaultInstance(new Properties(), null);
	    }
	    return new DeliveryStatus(session, ds.getInputStream());
	    */
	    return new DeliveryStatus(ds.getInputStream());
	} catch (MessagingException me) {
	    throw new IOException("Exception creating DeliveryStatus in " +
		    "message/devliery-status DataContentHandler: " +
		    me.toString());
	}
    }

    /**
     */
    public void writeTo(Object obj, String mimeType, OutputStream os)
			throws IOException {
	// if the object is a DeliveryStatus, we know how to write that out
	if (obj instanceof DeliveryStatus) {
	    DeliveryStatus ds = (DeliveryStatus)obj;
	    try {
		ds.writeTo(os);
	    } catch (MessagingException me) {
		throw new IOException(me.toString());
	    }

	} else {
	    throw new IOException("unsupported object");
	}
    }
}


text:
<?php

namespace FelixOnline\Admin\Actions;

class user_from_email extends BaseAction {
	public function __construct($permissions) {
		parent::__construct($permissions);
	}

	public function run($records, $pullThrough = false) {
		if(count($records) != 1) {
			throw new \Exception('Expecting one record');
		}

		$this->validateAccess();

		$records = $this->getRecords($records);
		$record = $records[0];
		$failed = false;

		// Check LDAP
		if(LOCAL) {
			if($record->getEmail() == 'valid@example.com') {
				// Testing
				$username = 'test'.rand(0,9999);
			} else {
				$failed = true;
			}
		} else {
			if(preg_match('/[^a-zA-Z0-9-@]/', $record->getEmail()) === 1) {
				$record->purge('Could not generate from email: '.$record->getEmail());

				throw new \Exception('Invalid email address.');
			}

			$ldap = ldap_connect("addressbook.ic.ac.uk");
			$bind = ldap_bind($ldap);
			$query = ldap_search($ds, "ou=People,ou=shibboleth,dc=ic,dc=ac,dc=uk", "mail=".$record->getEmail(), array("uid"));
			$data = ldap_get_entries($ldap, $query);
			if($data["count"] > 0) {
				$username = $data[0]['mail'][0];
			} else {
				$failed = true;
			}
		}

		if($failed) {
			$record->purge('Could not generate from email: '.$record->getEmail());

			throw new \Exception('No user found for this email address so no user could be created.');
		} else {
			$record->setUser($username)
				   ->setName($username)
				   ->setInfo(json_encode(array()))
				   ->setVisits(0)
				   ->setIp(0)
				   ->setShowEmail(TRUE)
				   ->setShowLdap(TRUE)
				   ->save();

			// Fetch other LDAP information
			try {
				$ldapUpdate = new user_ldap($this->rawPage);
				$ldapUpdate->run(array($record->getUser()));
			} catch(\Exception $e) { }
		}

		return 'Created and did directory fetch for '.$record->getUser();
	}
}


text:
//---------------------------------------------------------------------
// <copyright file="OperationResponse.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.OData.Client
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    /// Operation response base class
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1010", Justification = "required for this feature")]
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710", Justification = "required for this feature")]
    public abstract class OperationResponse
    {
        /// Http headers of the response.
        private readonly HeaderCollection headers;

        /// Http status code of the response.
        private int statusCode;

        /// exception to throw during get results
        private Exception innerException;

        ///
        /// constructor
        ///
        /// <param name="headers">HTTP headers</param>
        internal OperationResponse(HeaderCollection headers)
        {
            Debug.Assert(null != headers, "null headers");
            this.headers = headers;
        }

        /// When overridden in a derived class, contains the HTTP response headers associated with a single operation.
        /// <returns><see cref="T:System.Collections.IDictionary" /> object that contains name value pairs of headers and values.</returns>
        public IDictionary<string, string> Headers
        {
            get { return this.headers.UnderlyingDictionary; }
        }

        /// When overridden in a derived class, gets or sets the HTTP response code associated with a single operation.
        /// <returns>Integer value that contains response code.</returns>
        public int StatusCode
        {
            get { return this.statusCode; }
            internal set { this.statusCode = value; }
        }

        /// Gets error thrown by the operation.
        /// <returns>An <see cref="T:System.Exception" /> object that contains the error.</returns>
        public Exception Error
        {
            get
            {
                return this.innerException;
            }

            set
            {
                this.innerException = value;
            }
        }

        /// Http headers of the response.
        internal HeaderCollection HeaderCollection
        {
            get { return this.headers; }
        }
    }
}


text:
"""
Compute semantic similarities between GO terms. Borrowed from book chapter from
Alex Warwick Vesztrocy and Christophe Dessimoz (thanks). For details, please
check out:
notebooks/semantic_similarity.ipynb
"""

from __future__ import print_function

import sys
from collections import Counter
from collections import defaultdict
from goatools.godag.consts import NAMESPACE2GO
from goatools.godag.consts import NAMESPACE2NS
from goatools.godag.go_tasks import get_go2ancestors
from goatools.gosubdag.gosubdag import GoSubDag
from goatools.godag.relationship_combos import RelationshipCombos
from goatools.anno.update_association import clean_anno
from goatools.utils import get_b2aset

class TermCounts:
    '''
        TermCounts counts the term counts for each
    '''
    # pylint: disable=too-many-instance-attributes
    def __init__(self, go2obj, annots, relationships=None, **kws):
        '''
            Initialise the counts and
        '''
        _prt = kws.get('prt')
        # Backup
        self.go2obj = go2obj  # Full GODag
        self.annots, go_alts = clean_anno(annots, go2obj, _prt)[:2]
        # Genes annotated to all associated GO, including inherited up ancestors'
        _relationship_set = RelationshipCombos(go2obj).get_set(relationships)
        self.go2genes = self._init_go2genes(_relationship_set, go2obj)
        self.gene2gos = get_b2aset(self.go2genes)
        # Annotation main GO IDs (prefer main id to alt_id)
        self.goids = set(self.go2genes.keys())
        self.gocnts = Counter({go:len(geneset) for go, geneset in self.go2genes.items()})
        # Get total count for each branch: BP MF CC
        self.aspect_counts = {
            'biological_process': self.gocnts.get(NAMESPACE2GO['biological_process'], 0),
            'molecular_function': self.gocnts.get(NAMESPACE2GO['molecular_function'], 0),
            'cellular_component': self.gocnts.get(NAMESPACE2GO['cellular_component'], 0)}
        self._init_add_goid_alt(go_alts)
        self.gosubdag = GoSubDag(
            set(self.gocnts.keys()),
            go2obj,
            tcntobj=self,
            relationships=_relationship_set,
            prt=None)
        if _prt:
            self.prt_objdesc(_prt)

    def get_annotations_reversed(self):
        """Return go2geneset for all GO IDs explicitly annotated to a gene"""
        return set.union(*get_b2aset(self.annots))

    def _init_go2genes(self, relationship_set, godag):
        '''
            Fills in the genes annotated to each GO, including ancestors

            Due to the ontology structure, gene products annotated to
            a GO Terma are also annotated to all ancestors.
        '''
        go2geneset = defaultdict(set)
        go2up = get_go2ancestors(set(godag.values()), relationship_set)
        # Fill go-geneset dict with GO IDs in annotations and their corresponding counts
        for geneid, goids_anno in self.annots.items():
            # Make a union of all the terms for a gene, if term parents are
            # propagated but they won't get double-counted for the gene
            allterms = set()
            for goid_main in goids_anno:
                allterms.add(goid_main)
                if goid_main in go2up:
                    allterms.update(go2up[goid_main])
            # Add 1 for each GO annotated to this gene product
            for ancestor in allterms:
                go2geneset[ancestor].add(geneid)
        return dict(go2geneset)

    def _init_add_goid_alt(self, not_main):
        '''
            Add alternate GO IDs to term counts. Report GO IDs not found in GO DAG.
        '''
        if not not_main:
            return
        for go_id in not_main:
            if go_id in self.go2obj:
                goid_main = self.go2obj[go_id].item_id
                self.gocnts[go_id] = self.gocnts[goid_main]
                self.go2genes[go_id] = self.go2genes[goid_main]

    def get_count(self, go_id):
        '''
            Returns the count of that GO term observed in the annotations.
        '''
        return self.gocnts[go_id]

    def get_total_count(self, aspect):
        '''
            Gets the total count that's been precomputed.
        '''
        return self.aspect_counts[aspect]

    def get_term_freq(self, go_id):
        '''
            Returns the frequency at which a particular GO term has
            been observed in the annotations.
        '''
        num_ns = float(self.get_total_count(self.go2obj[go_id].namespace))
        return float(self.get_count(go_id))/num_ns if num_ns != 0 else 0

    def get_gosubdag_all(self, prt=sys.stdout):
        '''
            Get GO DAG subset include descendants which are not included in the annotations
        '''
        goids = set()
        for gos in self.gosubdag.rcntobj.go2descendants.values():
            goids.update(gos)
        return GoSubDag(goids, self.go2obj, self.gosubdag.relationships, tcntobj=self, prt=prt)

    def prt_objdesc(self, prt=sys.stdout):
        """Print TermCount object description"""
        ns_tot = sorted(self.aspect_counts.items())
        cnts = ['{NS}({N:,})'.format(NS=NAMESPACE2NS.get(ns, ns), N=n) for ns, n in ns_tot if n != 0]
        go_msg = "TermCounts {CNT}".format(CNT=' '.join(cnts))
        prt.write('{GO_MSG} {N:,} genes\n'.format(GO_MSG=go_msg, N=len(self.gene2gos)))
        self.gosubdag.prt_objdesc(prt, go_msg)

def get_info_content(go_id, termcounts):
    '''
        Retrieve the information content of a GO term.
    '''
    ntd = termcounts.gosubdag.go2nt.get(go_id)
    return ntd.tinfo if ntd else 0.0

def resnik_sim(go_id1, go_id2, godag, termcounts):
    '''
        Computes Resnik's similarity measure.
    '''
    goterm1 = godag[go_id1]
    goterm2 = godag[go_id2]
    if goterm1.namespace == goterm2.namespace:
        msca_goid = deepest_common_ancestor([go_id1, go_id2], godag)
        return get_info_content(msca_goid, termcounts)
    return None

def lin_sim(goid1, goid2, godag, termcnts, dfltval=None):
    '''
        Computes Lin's similarity measure.
    '''
    sim_r = resnik_sim(goid1, goid2, godag, termcnts)
    return lin_sim_calc(goid1, goid2, sim_r, termcnts, dfltval)

def lin_sim_calc(goid1, goid2, sim_r, termcnts, dfltval=None):
    '''
        Computes Lin's similarity measure using pre-calculated Resnik's similarities.
    '''
    # If goid1 and goid2 are in the same namespace
    if sim_r is not None:
        tinfo1 = get_info_content(goid1, termcnts)
        tinfo2 = get_info_content(goid2, termcnts)
        info = tinfo1 + tinfo2
        # Both GO IDs must be annotated
        if tinfo1 != 0.0 and tinfo2 != 0.0 and info != 0:
            return (2*sim_r)/info
        if termcnts.go2obj[goid1].item_id == termcnts.go2obj[goid2].item_id:
            return 1.0
        # The GOs are separated by the root term, so are not similar
        if sim_r == 0.0:
            return 0.0
    return dfltval

def common_parent_go_ids(goids, godag):
    '''
        This function finds the common ancestors in the GO
        tree of the list of goids in the input.
    '''
    # Find main GO ID candidates from first main or alt GO ID
    rec = godag[goids[0]]
    candidates = rec.get_all_parents()
    candidates.update({rec.item_id})

    # Find intersection with second to nth GO ID
    for goid in goids[1:]:
        rec = godag[goid]
        parents = rec.get_all_parents()
        parents.update({rec.item_id})

        # Find the intersection with the candidates, and update.
        candidates.intersection_update(parents)
    return candidates

def deepest_common_ancestor(goterms, godag):
    '''
        This function gets the nearest common ancestor
        using the above function.
        Only returns single most specific - assumes unique exists.
    '''
    # Take the element at maximum depth.
    return max(common_parent_go_ids(goterms, godag), key=lambda t: godag[t].depth)

def min_branch_length(go_id1, go_id2, godag, branch_dist):
    '''
        Finds the minimum branch length between two terms in the GO DAG.
    '''
    # First get the deepest common ancestor
    goterm1 = godag[go_id1]
    goterm2 = godag[go_id2]
    if goterm1.namespace == goterm2.namespace:
        dca = deepest_common_ancestor([go_id1, go_id2], godag)

        # Then get the distance from the DCA to each term
        dca_depth = godag[dca].depth
        depth1 = goterm1.depth - dca_depth
        depth2 = goterm2.depth - dca_depth

        # Return the total distance - i.e., to the deepest common ancestor and back.
        return depth1 + depth2

    if branch_dist is not None:
        return goterm1.depth + goterm2.depth + branch_dist
    return None

def semantic_distance(go_id1, go_id2, godag, branch_dist=None):
    '''
        Finds the semantic distance (minimum number of connecting branches)
        between two GO terms.
    '''
    return min_branch_length(go_id1, go_id2, godag, branch_dist)

def semantic_similarity(go_id1, go_id2, godag, branch_dist=None):
    '''
        Finds the semantic similarity (inverse of the semantic distance)
        between two GO terms.
    '''
    dist = semantic_distance(go_id1, go_id2, godag, branch_dist)
    if dist is not None:
        return 1.0 / float(dist) if dist != 0 else 1.0
    return None

# 1. Schlicker, Andreas et al.
# "A new measure for functional similarity of gene products based on Gene Ontology"
# BMC Bioinformatics (2006)
#
# 2. Yang, Haixuan et al.
# Improving GO semantic similarity measures by exploring the ontology
#   beneath the terms and modelling uncertainty
# Bioinformatics (2012)


text:
<!DOCTYPE html>

  <meta property="og:site_name" content="OnStage">

<title>OnStage</title>

<meta property="og:title" content="OnStage">
<meta name="description" content="">
<meta name="keywords" content="">
<meta property="og:description" content="">

<META HTTP-EQUIV='Content-Security-Policy'>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">

<meta property="og:locale" content="pt_PT">
<meta property="og:type" content="website">

<meta property="og:url" content="http://localhost:4000">
<meta property="og:image" content="/OnStage/assets/background/party2.jpg">

<link type="text/css" rel="stylesheet" href="/OnStage/assets/main.css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

      </button>

            Plataforma

            Aluguer de Musicos

            OnStage

Equipa

Contactos

Galeria

			Encontra nos

Contactos


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

namespace Ploeh.Samples.AssortedCodeSnippets.AbstractFactory.Route
{
    public interface IRouteAlgorithmFactory
    {
        IRouteAlgorithm CreateAlgorithm(RouteType routeType);
    }
}


text:
package org.omg.PortableInterceptor;

/**
* org/omg/PortableInterceptor/SUCCESSFUL.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u112/7884/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl
* Thursday, September 22, 2016 9:33:09 PM PDT
*/

public interface SUCCESSFUL
{

  /**
   * Indicates a successful Reply Status. One possible value for
   * RequestInfo.reply_status.
   * @see RequestInfo#reply_status
   * @see SYSTEM_EXCEPTION
   * @see USER_EXCEPTION
   * @see LOCATION_FORWARD
   * @see TRANSPORT_RETRY
   */
  public static final short value = (short)(0);
}


text: export const _momentAdapter = 0;


text:
#include <rviz/frame_manager.h>
#include <rviz/properties/bool_property.h>
#include <rviz/properties/ros_topic_property.h>
#include <rviz/selection/selection_manager.h>
#include <rviz/validate_floats.h>
#include <rviz/validate_quaternions.h>
#include <rviz/display_context.h>

#include <rviz/default_plugin/interactive_marker_display.h>

namespace rviz
{
//////////////
bool validateFloats(const visualization_msgs::InteractiveMarker& msg)
{
  bool valid = true;
  valid = valid && validateFloats(msg.pose);
  valid = valid && validateFloats(msg.scale);
  for (unsigned c = 0; c < msg.controls.size(); c++)
  {
    valid = valid && validateFloats(msg.controls[c].orientation);
    for (unsigned m = 0; m < msg.controls[c].markers.size(); m++)
    {
      valid = valid && validateFloats(msg.controls[c].markers[m].pose);
      valid = valid && validateFloats(msg.controls[c].markers[m].scale);
      valid = valid && validateFloats(msg.controls[c].markers[m].color);
      valid = valid && validateFloats(msg.controls[c].markers[m].points);
    }
  }
  return valid;
}

bool validateQuaternions(const visualization_msgs::InteractiveMarker& marker)
{
  if (!validateQuaternions(marker.pose.orientation))
    return false;
  for (size_t c = 0; c < marker.controls.size(); ++c)
  {
    if (!validateQuaternions(marker.controls[c].orientation))
      return false;
    for (size_t m = 0; m < marker.controls[c].markers.size(); ++m)
    {
      if (!validateQuaternions(marker.controls[c].markers[m].pose.orientation))
        return false;
    }
  }
  return true;
}
/////////////

InteractiveMarkerDisplay::InteractiveMarkerDisplay() : Display()
{
  marker_update_topic_property_ = new RosTopicProperty(
      "Update Topic", "", ros::message_traits::datatype<visualization_msgs::InteractiveMarkerUpdate>(),
      "visualization_msgs::InteractiveMarkerUpdate topic to subscribe to.", this, SLOT(updateTopic()));

  show_descriptions_property_ =
      new BoolProperty("Show Descriptions", true,
                       "Whether or not to show the descriptions of each Interactive Marker.", this,
                       SLOT(updateShowDescriptions()));

  show_axes_property_ =
      new BoolProperty("Show Axes", false, "Whether or not to show the axes of each Interactive Marker.",
                       this, SLOT(updateShowAxes()));

  show_visual_aids_property_ = new BoolProperty(
      "Show Visual Aids", false,
      "Whether or not to show visual helpers while moving/rotating Interactive Markers.", this,
      SLOT(updateShowVisualAids()));
  enable_transparency_property_ = new BoolProperty(
      "Enable Transparency", true,
      "Whether or not to allow transparency for auto-completed markers (e.g. rings and arrows).", this,
      SLOT(updateEnableTransparency()));
}

void InteractiveMarkerDisplay::onInitialize()
{
  auto tf = context_->getFrameManager()->getTF2BufferPtr();
  im_client_.reset(new interactive_markers::InteractiveMarkerClient(*tf, fixed_frame_.toStdString()));

  im_client_->setInitCb(boost::bind(&InteractiveMarkerDisplay::initCb, this, boost::placeholders::_1));
  im_client_->setUpdateCb(
      boost::bind(&InteractiveMarkerDisplay::updateCb, this, boost::placeholders::_1));
  im_client_->setResetCb(boost::bind(&InteractiveMarkerDisplay::resetCb, this, boost::placeholders::_1));
  im_client_->setStatusCb(boost::bind(&InteractiveMarkerDisplay::statusCb, this, boost::placeholders::_1,
                                      boost::placeholders::_2, boost::placeholders::_3));

  client_id_ = ros::this_node::getName() + "/" + getNameStd();

  onEnable();
}

void InteractiveMarkerDisplay::setTopic(const QString& topic, const QString& /*datatype*/)
{
  marker_update_topic_property_->setString(topic);
}

void InteractiveMarkerDisplay::onEnable()
{
  subscribe();
}

void InteractiveMarkerDisplay::onDisable()
{
  unsubscribe();
}

void InteractiveMarkerDisplay::updateTopic()
{
  unsubscribe();

  std::string update_topic = marker_update_topic_property_->getTopicStd();

  size_t idx = update_topic.find("/update");
  if (idx != std::string::npos)
  {
    topic_ns_ = update_topic.substr(0, idx);
    subscribe();
  }
  else
  {
    setStatusStd(StatusProperty::Error, "Topic", "Invalid topic name: " + update_topic);
  }
}

void InteractiveMarkerDisplay::subscribe()
{
  if (isEnabled())
  {
    im_client_->subscribe(topic_ns_);

    std::string feedback_topic = topic_ns_ + "/feedback";
    feedback_pub_ =
        update_nh_.advertise<visualization_msgs::InteractiveMarkerFeedback>(feedback_topic, 100, false);
  }
}

void InteractiveMarkerDisplay::publishFeedback(visualization_msgs::InteractiveMarkerFeedback& feedback)
{
  feedback.client_id = client_id_;
  feedback_pub_.publish(feedback);
}

void InteractiveMarkerDisplay::onStatusUpdate(StatusProperty::Level level,
                                              const std::string& name,
                                              const std::string& text)
{
  setStatusStd(level, name, text);
}

void InteractiveMarkerDisplay::unsubscribe()
{
  if (im_client_)
  {
    im_client_->shutdown();
  }
  feedback_pub_.shutdown();
  Display::reset();
}

void InteractiveMarkerDisplay::update(float wall_dt, float /*ros_dt*/)
{
  im_client_->update();

  M_StringToStringToIMPtr::iterator server_it;
  for (server_it = interactive_markers_.begin(); server_it != interactive_markers_.end(); server_it++)
  {
    M_StringToIMPtr::iterator im_it;
    for (im_it = server_it->second.begin(); im_it != server_it->second.end(); im_it++)
    {
      im_it->second->update(wall_dt);
    }
  }
}

InteractiveMarkerDisplay::M_StringToIMPtr&
InteractiveMarkerDisplay::getImMap(const std::string& server_id)
{
  M_StringToStringToIMPtr::iterator im_map_it = interactive_markers_.find(server_id);

  if (im_map_it == interactive_markers_.end())
  {
    im_map_it = interactive_markers_.insert(std::make_pair(server_id, M_StringToIMPtr())).first;
  }

  return im_map_it->second;
}

void InteractiveMarkerDisplay::updateMarkers(
    const std::string& server_id,
    const std::vector<visualization_msgs::InteractiveMarker>& markers)
{
  M_StringToIMPtr& im_map = getImMap(server_id);

  for (size_t i = 0; i < markers.size(); i++)
  {
    const visualization_msgs::InteractiveMarker& marker = markers[i];

    if (!validateFloats(marker))
    {
      setStatusStd(StatusProperty::Error, marker.name, "Marker contains invalid floats!");
      // setStatusStd( StatusProperty::Error, "General", "Marker " + marker.name + " contains invalid
      // floats!" );
      continue;
    }

    if (!validateQuaternions(marker))
    {
      ROS_WARN_ONCE_NAMED("quaternions",
                          "Interactive marker '%s' contains unnormalized quaternions. "
                          "This warning will only be output once but may be true for others; "
                          "enable DEBUG messages for ros.rviz.quaternions to see more details.",
                          marker.name.c_str());
      ROS_DEBUG_NAMED("quaternions", "Interactive marker '%s' contains unnormalized quaternions.",
                      marker.name.c_str());
    }
    ROS_DEBUG("Processing interactive marker '%s'. %d", marker.name.c_str(), (int)marker.controls.size());

    std::map<std::string, IMPtr>::iterator int_marker_entry = im_map.find(marker.name);

    if (int_marker_entry == im_map.end())
    {
      int_marker_entry =
          im_map
              .insert(std::make_pair(marker.name, IMPtr(new InteractiveMarker(getSceneNode(), context_))))
              .first;
      connect(int_marker_entry->second.get(),
              SIGNAL(userFeedback(visualization_msgs::InteractiveMarkerFeedback&)), this,
              SLOT(publishFeedback(visualization_msgs::InteractiveMarkerFeedback&)));
      connect(int_marker_entry->second.get(),
              SIGNAL(statusUpdate(StatusProperty::Level, const std::string&, const std::string&)), this,
              SLOT(onStatusUpdate(StatusProperty::Level, const std::string&, const std::string&)));
    }

    if (int_marker_entry->second->processMessage(marker))
    {
      int_marker_entry->second->setShowAxes(show_axes_property_->getBool());
      int_marker_entry->second->setShowVisualAids(show_visual_aids_property_->getBool());
      int_marker_entry->second->setShowDescription(show_descriptions_property_->getBool());
    }
    else
    {
      unsubscribe();
      return;
    }
  }
}

void InteractiveMarkerDisplay::eraseMarkers(const std::string& server_id,
                                            const std::vector<std::string>& erases)
{
  M_StringToIMPtr& im_map = getImMap(server_id);

  for (size_t i = 0; i < erases.size(); i++)
  {
    im_map.erase(erases[i]);
    deleteStatusStd(erases[i]);
  }
}

void InteractiveMarkerDisplay::updatePoses(
    const std::string& server_id,
    const std::vector<visualization_msgs::InteractiveMarkerPose>& marker_poses)
{
  M_StringToIMPtr& im_map = getImMap(server_id);

  for (size_t i = 0; i < marker_poses.size(); i++)
  {
    const visualization_msgs::InteractiveMarkerPose& marker_pose = marker_poses[i];

    if (!validateFloats(marker_pose.pose))
    {
      setStatusStd(StatusProperty::Error, marker_pose.name, "Pose message contains invalid floats!");
      return;
    }

    if (!validateQuaternions(marker_pose.pose))
    {
      setStatusStd(StatusProperty::Error, marker_pose.name,
                   "Pose message contains invalid quaternions (length not equal to 1)!");
      return;
    }

    std::map<std::string, IMPtr>::iterator int_marker_entry = im_map.find(marker_pose.name);

    if (int_marker_entry != im_map.end())
    {
      int_marker_entry->second->processMessage(marker_pose);
    }
    else
    {
      setStatusStd(StatusProperty::Error, marker_pose.name,
                   "Pose received for non-existing marker '" + marker_pose.name);
      unsubscribe();
      return;
    }
  }
}

void InteractiveMarkerDisplay::initCb(const visualization_msgs::InteractiveMarkerInitConstPtr& msg)
{
  resetCb(msg->server_id);
  updateMarkers(msg->server_id, msg->markers);
}

void InteractiveMarkerDisplay::updateCb(const visualization_msgs::InteractiveMarkerUpdateConstPtr& msg)
{
  updateMarkers(msg->server_id, msg->markers);
  updatePoses(msg->server_id, msg->poses);
  eraseMarkers(msg->server_id, msg->erases);
}

void InteractiveMarkerDisplay::resetCb(const std::string& server_id)
{
  interactive_markers_.erase(server_id);
  deleteStatusStd(server_id);
}

void InteractiveMarkerDisplay::statusCb(interactive_markers::InteractiveMarkerClient::StatusT status,
                                        const std::string& server_id,
                                        const std::string& msg)
{
  setStatusStd(static_cast<StatusProperty::Level>(status), server_id, msg);
}

void InteractiveMarkerDisplay::fixedFrameChanged()
{
  if (im_client_)
    im_client_->setTargetFrame(fixed_frame_.toStdString());
  reset();
}

void InteractiveMarkerDisplay::reset()
{
  Display::reset();
  unsubscribe();
  subscribe();
}

void InteractiveMarkerDisplay::updateShowDescriptions()
{
  bool show = show_descriptions_property_->getBool();

  M_StringToStringToIMPtr::iterator server_it;
  for (server_it = interactive_markers_.begin(); server_it != interactive_markers_.end(); server_it++)
  {
    M_StringToIMPtr::iterator im_it;
    for (im_it = server_it->second.begin(); im_it != server_it->second.end(); im_it++)
    {
      im_it->second->setShowDescription(show);
    }
  }
}

void InteractiveMarkerDisplay::updateShowAxes()
{
  bool show = show_axes_property_->getBool();

  M_StringToStringToIMPtr::iterator server_it;
  for (server_it = interactive_markers_.begin(); server_it != interactive_markers_.end(); server_it++)
  {
    M_StringToIMPtr::iterator im_it;
    for (im_it = server_it->second.begin(); im_it != server_it->second.end(); im_it++)
    {
      im_it->second->setShowAxes(show);
    }
  }
}

void InteractiveMarkerDisplay::updateShowVisualAids()
{
  bool show = show_visual_aids_property_->getBool();

  M_StringToStringToIMPtr::iterator server_it;
  for (server_it = interactive_markers_.begin(); server_it != interactive_markers_.end(); server_it++)
  {
    M_StringToIMPtr::iterator im_it;
    for (im_it = server_it->second.begin(); im_it != server_it->second.end(); im_it++)
    {
      im_it->second->setShowVisualAids(show);
    }
  }
}

void InteractiveMarkerDisplay::updateEnableTransparency()
{
  // This is not very efficient... but it should do the trick.
  unsubscribe();
  im_client_->setEnableAutocompleteTransparency(enable_transparency_property_->getBool());
  subscribe();
}

} // namespace rviz

#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(rviz::InteractiveMarkerDisplay, rviz::Display)


text:
package com.wandoulabs.nedis.protocol;

import io.netty.util.concurrent.Future;

import java.util.List;

/**
 * @author Apache9
 * @see http://redis.io/commands#transactions
 */
public interface TransactionsCommands {

    public static final String QUEUED = "QUEUED";

    Future<Void> discard();

    Future<List<Object>> exec();

    Future<Void> multi();

    Future<Void> unwatch();

    Future<Void> watch(byte[]... keys);
}


text:
layout: "alicloud"
page_title: "Alicloud: alicloud_mns_topic_subscriptions"
sidebar_current: "docs-alicloud-datasource-mns-topic-subscriptions"
description: |-
    Provides a list of mns topic subscriptions available to the user.
---

# alicloud\_mns\_topic_subscriptions

This data source provides a list of MNS topic subscriptions in an Alibaba Cloud account according to the specified parameters.

## Example Usage

```
data "alicloud_mns_topic_subscriptions" "subscriptions" {
  topic_name="topic_name"
  name_prefix = "tf-"
}

output "first_topic_subscription_id" {
  value = "${data.alicloud_mns_topic_subscriptions.subscriptions.subscriptions.0.id}"
}
```

## Argument Reference

The following arguments are supported:

* `topic_name` - (Required) Two topics on a single account in the same region cannot have the same name. A topic name must start with an English letter or a digit, and can contain English letters, digits, and hyphens, with the length not exceeding 256 characters.
* `name_prefix` - (Optional) A string to filter resulting subscriptions of the topic by their name prefixs.
* `output_file` - (Optional) File name where to save data source results (after running `terraform plan`).

## Attributes Reference

The following attributes are exported in addition to the arguments listed above:

* `subscriptions` - A list of users. Each element contains the following attributes:
   * `id` - The ID of the topic subscription. Format to <topic_name>:<name>.
   * `name` - The name of the subscription.
   * `topic_name`- The topic which The subscription belongs to was named with the name.
   * `notify_strategy` - The NotifyStrategy attribute of Subscription. This attribute specifies the retry strategy when message sending fails.
   * `notify_content_format` - The NotifyContentFormat attribute of Subscription. This attribute specifies the content format of the messages pushed to users.
   * `endpoint` - Describe the terminal address of the message received in this subscription.
   * `filter_tag`- A string to filter resulting messages of the topic by their message tag.


text:
'use strict';

var moment = require('moment');

var utils = {

  /**
   * Log a message to the confole formatted with the current timestamp.
   * Usefull for debug purposes.
   * @param  string msg The message to log
   * @return void
   */
  log: function(msg){
    console.log(moment().format('YYYY-MM-DD HH:mm:ss') + " - " + msg);
  }

};

module.exports = utils;


text:
To create a new project open your terminal of choice (PowerShell, cmd, bash, zsh).

First create a new folder and change to this folder. Now execute the following command.

```sh
yo simplestyle
```

This will launch the wizard that creates the base structure and setup of your project.

![First SimpleStyle Project](./assets/01-first-project-wizard.png)

The current SimpleStyle supports the following options:

* **SASS**
If unselected only plain CSS can be used
* **TypeScript**
TypeScript compiler won't be installed to generator
* **jQuery**
In addition to TypeScript jQuery can be added by default to the generator.

After the selection the required files gets copied to the project folder and the  NodeJS packages gets installed.
In case [Yarn](https://yarnpkg.com/en/) is installed all packages will be installed through this package manager, otherwise [NPM](https://www.npmjs.com) is used.

![After installation](./assets/02-yarn-installed-package.png)

## Documentation
* [[Create first SimpleStyle project]]
* [[Working with patterns]]
* [[Create advanced patterns]]
* [[Important Folders]]
* [[Data Binding with SimpleStyle]]


text:
package com.amazonaws.services.dynamodbv2.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ScalarAttributeType {

    S("S"),
    N("N"),
    B("B");

    private String value;

    private ScalarAttributeType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ScalarAttributeType corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ScalarAttributeType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ScalarAttributeType enumEntry : ScalarAttributeType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text: Useful stuff for linux why not (\/) (;,,;) (\/)


text:
import React, { Component } from 'react';
import { Row, Col, Button } from 'react-bootstrap';
import { Table, Tr, Td } from 'reactable';
import { css } from 'aphrodite';
import { _ } from 'underscore';

import FilePath from './FilePath';
import NewDirectoryModal from './NewDirectoryModal';
import NewFileModal from './NewFileModal';
import EditFileModal from './EditFileModal';
import FileLink from './FileLink';
import DirectoryLink from './DirectoryLink';
import ActionButtons from './ActionButtons';
import { currentDirectoryListing } from '../../../api/fs_files/methods';
import UtilityStyles from '../../styles/utility';

class Files extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentDirectory: '',
      fsFiles: [],
      showNewDirectoryModal: false,
      showFileMetadataModal: false,
      showNewFileModal: false,
      selectedFsFile: null,
    };
    this.setCurrentDirectory = this.setCurrentDirectory.bind(this);
    this.showDirectory = this.showDirectory.bind(this);
    this.openNewDirectoryModal = this.openNewDirectoryModal.bind(this);
    this.openNewFileModal = this.openNewFileModal.bind(this);
    this.openFileMetadataModal = this.openFileMetadataModal.bind(this);
    this.closeNewDirectoryModal = this.closeNewDirectoryModal.bind(this);
    this.closeNewFileModal = this.closeNewFileModal.bind(this);
    this.closeFileMetadataModal = this.closeFileMetadataModal.bind(this);
  }

  componentDidMount() {
    this.showDirectory();
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.currentDirectory !== this.state.currentDirectory) {
      this.showDirectory();
    }
  }

  setCurrentDirectory(event) {
    event.preventDefault();
    const pathMatches = event.target.closest('a').href.match(/^(.*)\/files(.*)$/);
    if (pathMatches.length === 3) {
      this.setState({ currentDirectory: decodeURIComponent(pathMatches[2]) });
    } else {
      this.setState({ currentDirectory: '' });
    }
  }

  showDirectory() {
    currentDirectoryListing.call({
      currentDirectory: decodeURIComponent(this.state.currentDirectory),
    }, (error, fsFiles) => {
      if (fsFiles) {
        this.setState({ fsFiles });
      }
    });
  }

  openNewDirectoryModal() {
    this.setState({ showNewDirectoryModal: true });
  }

  openNewFileModal() {
    this.setState({ showNewFileModal: true });
  }

  openFileMetadataModal(event, selectedFsFile) {
    event.preventDefault();
    this.props.selectedUid.set(selectedFsFile.uid);
    this.setState({
      showFileMetadataModal: true,
      selectedFsFile,
    });
  }

  closeNewDirectoryModal(event, refresh) {
    if (refresh) {
      this.showDirectory();
    }
    this.setState({ showNewDirectoryModal: false });
  }

  closeNewFileModal(event, refresh) {
    if (refresh) {
      this.showDirectory();
    }
    this.setState({ showNewFileModal: false });
  }

  closeFileMetadataModal() {
    this.props.selectedUid.set(null);
    this.setState({
      showFileMetadataModal: false,
      selectedFsFile: null,
    });
  }

  renderRows() {
    const rows = [];
    const currentDirectory = this.state.currentDirectory;
    this.state.fsFiles.forEach((fsFile) => {
      let link;
      if (fsFile.type === 'directory') {
        link = (
          <DirectoryLink
            key={fsFile.name}
            fsFile={fsFile}
            currentDirectory={currentDirectory}
            setCurrentDirectory={this.setCurrentDirectory}
          />
        );
      } else {
        link = (
          <FileLink
            key={fsFile.name}
            fsFile={fsFile}
            openFileMetadataModal={this.openFileMetadataModal}
          />
        );
      }
      rows.push(

            {link}

            <ActionButtons
              fsFile={fsFile}
              refreshDirectory={this.showDirectory}
            />

,
      );
    });

    let content;
    if (_.isEmpty(rows)) {
      content =
No files found.
;
    } else {
      content = (

          {rows}

      );
    }

    return content;
  }

  render() {
    return (

        <Row className="header">
          <Col md={8}>

              Directory: <FilePath
                path={this.state.currentDirectory}
                setCurrentDirectory={this.setCurrentDirectory}
              />

          </Col>
          <Col md={4} className="text-right">
            <Button
              bsStyle="info"
              className={`btn-fill ${css(UtilityStyles.marginRight10)}`}
              onClick={this.openNewDirectoryModal}
            >
               New Directory
            </Button>
            <Button
              bsStyle="info"
              className="btn-fill"
              onClick={this.openNewFileModal}
            >
               New File
            </Button>
          </Col>
        </Row>
        <Row className={css(UtilityStyles.marginTop20)}>
          <Col md={12}>
            {this.renderRows()}
          </Col>
        </Row>

        <NewDirectoryModal
          showModal={this.state.showNewDirectoryModal}
          closeModal={this.closeNewDirectoryModal}
          currentPath={this.state.currentDirectory}
        />
        <NewFileModal
          showModal={this.state.showNewFileModal}
          closeModal={this.closeNewFileModal}
          currentPath={this.state.currentDirectory}
        />
        <EditFileModal
          showModal={this.state.showFileMetadataModal}
          closeModal={this.closeFileMetadataModal}
          metadataSchema={this.props.metadataSchema}
          file={this.props.file}
          fsFile={this.state.selectedFsFile}
          currentDirectory={this.state.currentDirectory}
        />

    );
  }
}

Files.propTypes = {
  metadataSchema: React.PropTypes.object.isRequired,
  file: React.PropTypes.object.isRequired,
  selectedUid: React.PropTypes.object.isRequired,
};

export default Files;


text:
package org.joda.time.format;

import java.text.DateFormat;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;

/**
 * This class is a Junit unit test for DateTimeFormat styles.
 *
 * @author Stephen Colebourne
 */
public class TestDateTimeFormatStyle extends TestCase {

    private static final Locale UK = Locale.UK;
    private static final Locale US = Locale.US;
    private static final Locale FRANCE = Locale.FRANCE;
    private static final DateTimeZone UTC = DateTimeZone.UTC;
    private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris");
    private static final DateTimeZone LONDON = DateTimeZone.forID("Europe/London");
    private static final DateTimeZone TOKYO = DateTimeZone.forID("Asia/Tokyo");
    private static final DateTimeZone NEWYORK = DateTimeZone.forID("America/New_York");

    long y2002days = 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
                     366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 +
                     365 + 365 + 366 + 365 + 365 + 365 + 366 + 365 + 365 + 365 +
                     366 + 365;
    // 2002-06-09
    private long TEST_TIME_NOW =
            (y2002days + 31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;

    private DateTimeZone originalDateTimeZone = null;
    private TimeZone originalTimeZone = null;
    private Locale originalLocale = null;

    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }

    public static TestSuite suite() {
        return new TestSuite(TestDateTimeFormatStyle.class);
    }

    public TestDateTimeFormatStyle(String name) {
        super(name);
    }

    protected void setUp() throws Exception {
        DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
        originalDateTimeZone = DateTimeZone.getDefault();
        originalTimeZone = TimeZone.getDefault();
        originalLocale = Locale.getDefault();
        DateTimeZone.setDefault(LONDON);
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
        Locale.setDefault(UK);
    }

    protected void tearDown() throws Exception {
        DateTimeUtils.setCurrentMillisSystem();
        DateTimeZone.setDefault(originalDateTimeZone);
        TimeZone.setDefault(originalTimeZone);
        Locale.setDefault(originalLocale);
        originalDateTimeZone = null;
        originalTimeZone = null;
        originalLocale = null;
    }

    //-----------------------------------------------------------------------
    public void testForStyle_stringLengths() {
        try {
            DateTimeFormat.forStyle(null);
            fail();
        } catch (IllegalArgumentException ex) {}
        try {
            DateTimeFormat.forStyle("");
            fail();
        } catch (IllegalArgumentException ex) {}
        try {
            DateTimeFormat.forStyle("S");
            fail();
        } catch (IllegalArgumentException ex) {}
        try {
            DateTimeFormat.forStyle("SSS");
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    public void testForStyle_invalidStrings() {
        try {
            DateTimeFormat.forStyle("AA");
            fail();
        } catch (IllegalArgumentException ex) {}
        try {
            DateTimeFormat.forStyle("--");
            fail();
        } catch (IllegalArgumentException ex) {}
        try {
            DateTimeFormat.forStyle("ss");
            fail();
        } catch (IllegalArgumentException ex) {}
    }

    //-----------------------------------------------------------------------
    public void testForStyle_shortDate() throws Exception {
        DateTimeFormatter f = DateTimeFormat.shortDate();
        DateTimeFormatter g = DateTimeFormat.forStyle("S-");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateInstance(DateFormat.SHORT, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateInstance(DateFormat.SHORT, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateInstance(DateFormat.SHORT, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));

        DateTime date = new DateTime(
                DateFormat.getDateInstance(DateFormat.SHORT, FRANCE).parse(expect));
        assertEquals(date, f.withLocale(FRANCE).parseDateTime(expect));
    }

    public void testForStyle_shortTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.shortTime();
        DateTimeFormatter g = DateTimeFormat.forStyle("-S");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getTimeInstance(DateFormat.SHORT, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getTimeInstance(DateFormat.SHORT, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getTimeInstance(DateFormat.SHORT, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));

        if (TimeZone.getDefault() instanceof SimpleTimeZone) {
            // skip test, as it needs historical time zone info
        } else {
            DateTime date = new DateTime(
                DateFormat.getTimeInstance(DateFormat.SHORT, FRANCE).parse(expect));
            assertEquals(date, f.withLocale(FRANCE).parseDateTime(expect));
        }
    }

    public void testForStyle_shortDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.shortDateTime();
        DateTimeFormatter g = DateTimeFormat.forStyle("SS");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));

        DateTime date = new DateTime(
            DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, FRANCE).parse(expect));
        assertEquals(date, f.withLocale(FRANCE).parseDateTime(expect));
    }

    //-----------------------------------------------------------------------
    public void testForStyle_mediumDate() throws Exception {
        DateTimeFormatter f = DateTimeFormat.mediumDate();
        DateTimeFormatter g = DateTimeFormat.forStyle("M-");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateInstance(DateFormat.MEDIUM, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateInstance(DateFormat.MEDIUM, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateInstance(DateFormat.MEDIUM, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_mediumTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.mediumTime();
        DateTimeFormatter g = DateTimeFormat.forStyle("-M");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getTimeInstance(DateFormat.MEDIUM, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getTimeInstance(DateFormat.MEDIUM, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getTimeInstance(DateFormat.MEDIUM, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_mediumDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.mediumDateTime();
        DateTimeFormatter g = DateTimeFormat.forStyle("MM");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    //-----------------------------------------------------------------------
    public void testForStyle_longDate() throws Exception {
        DateTimeFormatter f = DateTimeFormat.longDate();
        DateTimeFormatter g = DateTimeFormat.forStyle("L-");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateInstance(DateFormat.LONG, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateInstance(DateFormat.LONG, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateInstance(DateFormat.LONG, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_longTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.longTime();
        DateTimeFormatter g = DateTimeFormat.forStyle("-L");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getTimeInstance(DateFormat.LONG, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getTimeInstance(DateFormat.LONG, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getTimeInstance(DateFormat.LONG, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_longDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.longDateTime();
        DateTimeFormatter g = DateTimeFormat.forStyle("LL");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    //-----------------------------------------------------------------------
    public void testForStyle_fullDate() throws Exception {
        DateTimeFormatter f = DateTimeFormat.fullDate();
        DateTimeFormatter g = DateTimeFormat.forStyle("F-");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateInstance(DateFormat.FULL, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateInstance(DateFormat.FULL, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateInstance(DateFormat.FULL, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_fullTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.fullTime();
        DateTimeFormatter g = DateTimeFormat.forStyle("-F");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getTimeInstance(DateFormat.FULL, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getTimeInstance(DateFormat.FULL, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getTimeInstance(DateFormat.FULL, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_fullDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.fullDateTime();
        DateTimeFormatter g = DateTimeFormat.forStyle("FF");
        assertSame(g, f);
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    //-----------------------------------------------------------------------
    public void testForStyle_shortMediumDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.forStyle("SM");
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_shortLongDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.forStyle("SL");
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_shortFullDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.forStyle("SF");
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    //-----------------------------------------------------------------------
    public void testForStyle_mediumShortDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.forStyle("MS");
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_mediumLongDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.forStyle("ML");
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

    public void testForStyle_mediumFullDateTime() throws Exception {
        DateTimeFormatter f = DateTimeFormat.forStyle("MF");
        DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 0);
        String expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL, UK).format(dt.toDate());
        assertEquals(expect, f.print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL, US).format(dt.toDate());
        assertEquals(expect, f.withLocale(US).print(dt));
        expect = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL, FRANCE).format(dt.toDate());
        assertEquals(expect, f.withLocale(FRANCE).print(dt));
    }

}


text:
package org.drools.planner.core.heuristic.selector.value.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An iterator for planning values.
 * @see Iterator
 */
public interface ValueIterator extends Iterator<Object> {

    /**
     * Follows the specification of {@link Iterator#hasNext()}.
     *
     * @param entity never null
     * @return true if there are more planning values
     */
    boolean hasNext(Object entity);

    /**
     * Follows the specification of {@link Iterator#next()}.
     *
     * @param entity never null
     * @return the next planning value
     * @exception NoSuchElementException if there are no more planning values
     */
    Object next(Object entity);

}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>NMZL - Matches</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="apple-touch-icon" sizes="57x57" href="/icon/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/icon/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/icon/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/icon/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/icon/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/icon/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/icon/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/icon/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/icon/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/icon/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/icon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="/icon/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/icon/favicon-16x16.png">
    <link rel="manifest" href="/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/icon/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

    <link rel="stylesheet prefetch"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/matches.css">

            MATCHES

This page is still under development.


text:
var cordova_util = require('./util'),
    HooksRunner  = require('../hooks/HooksRunner'),
    Q            = require('q'),
    platform_lib = require('../platforms/platforms'),
    _ = require('underscore');

// Returns a promise.
module.exports = function emulate(options) {
    return Q().then(function() {
        var projectRoot = cordova_util.cdProjectRoot();
        options = cordova_util.preProcessOptions(options);
        options.options.device = false;
        options.options.emulator = true;

        var optsClone = _.clone(options.options);
        // This is needed as .build modifies opts
        optsClone.nobuild = true;

        var hooksRunner = new HooksRunner(projectRoot);
        return hooksRunner.fire('before_emulate', options)
        .then(function() {
            if (!options.options.noprepare) {
                // Run a prepare first!
                return require('./cordova').prepare(options);
            }
        }).then(function() {
            // Deploy in parallel (output gets intermixed though...)
            return Q.all(options.platforms.map(function(platform) {

                var buildPromise = options.options.nobuild ? Q() :
                    platform_lib.getPlatformApi(platform).build(options.options);

                return buildPromise
                .then(function() {
                    return hooksRunner.fire('before_deploy', options);
                })
                .then(function() {
                    return platform_lib.getPlatformApi(platform).run(optsClone);
                });
            }));
        }).then(function() {
            return hooksRunner.fire('after_emulate', options);
        });
    });
};


text:
from bokeh.io import output_file, show
from bokeh.layouts import column
from bokeh.models.widgets import Button, RadioButtonGroup, Select, Slider

output_file("layout_widgets.html")

# create some widgets
slider = Slider(start=0, end=10, value=1, step=.1, title="Slider")
button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)
select = Select(title="Option:", value="foo", options=["foo", "bar", "baz", "quux"])
button_1 = Button(label="Button 1")
button_2 = Button(label="Button 2")

show(column(button_1, slider, button_group, select, button_2, width=300))


text:
'use strict';

// Modules

var Q = require('q');

/**
 * Run a Promise-returning function while a condition is met.
 * By https://stackoverflow.com/users/100172/stuart-k, from http://stackoverflow.com/a/17238793
 * @param {Function} condition  A Boolean-returning function. If the condition is true, the while loop runs.
 * @param {Function} body       A Promise-returning function.
 * @param {Promise} A promise that is fulfilled when the loop is completed.
 */

function promiseWhile(condition, body) {
    var done = Q.defer();

    function loop() {
        if (!condition()) return done.resolve();
        Q.when(body(), loop, done.reject);
    }

    Q.nextTick(loop);

    return done.promise;
}

exports.promiseWhile = promiseWhile;


text:
require 'spec_helper'

class Context
  include CanTango::Api::Attributes
end

describe CanTango::Api::Attributes do
  subject { Context.new }

  [:read, :edit].each do |action|
    describe ":#{action} attribute" do
      specify do
        subject.send(:"#{action}_attribute", :post).should == :"#{action}_attr_post"
      end
    end

    describe ":#{action} attributes" do
      specify do
        subject.send(:"#{action}_attributes", :post, :project).should include(:"#{action}_attr_post")
      end
    end
  end
end