text:
package com.github.tminglei.swagger.route;

import com.github.tminglei.swagger.fake.ConstDataProvider;
import io.swagger.models.HttpMethod;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 *
 * @author Luis Antunes
 */
public class TestTreeRouter extends RouterContractTest<TreeRouterImpl> {

    @Override
    protected TreeRouterImpl newRouter() {
        return new TreeRouterImpl();
    }

    @Override
    protected Route newRoute(String path) {
        return new RouteImpl(HttpMethod.GET, path, true, new ConstDataProvider(""));
    }

    ///---

    @Test
    // produces the correct tree when given the root route
    public void treeTest1() {
        Route r = newRoute("/");

        router.add(r);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertEquals(r, root.getRoute(HttpMethod.GET));
        assertEquals(0, root.getChildren().size());

        assertEquals(r, route("/"));
        assertNull(route("/*"));
        assertNull(route("/blah"));
    }

    @Test
    // produces the correct tree when given a single route with a single static path element
    public void treeTest2() {
        Route r = newRoute("/hello");

        router.add(r);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^hello$", child.toString());
        assertEquals(r, child.getRoute(HttpMethod.GET));

        assertNull(route("/"));
        assertEquals(r, route("/hello"));
        assertNull(route("/hello/"));
        assertNull(route("/blah"));
    }

    @Test
    // produces the correct tree when given the same route twice
    public void treeTest3() {
        Route r1 = newRoute("/hello");
        Route r2 = newRoute("/hello");

        router.add(r1);
        router.add(r2);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^hello$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));

        assertNull(route("/"));
        assertEquals(r1, route("/hello"));
        assertNull(route("/hello/"));
        assertNull(route("/blah"));
    }

    @Test
    // produces the correct tree when given a single route with a single static path element ending with a path separator
    public void treeTest4() {
        Route r = newRoute("/hello/");

        router.add(r);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^hello$", child.toString());
        assertNull(child.getRoute(HttpMethod.GET));
        assertEquals(1, child.getChildren().size());

        child = child.getChildren().get(0);
        assertEquals("^/$", child.toString());
        assertEquals(r, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertNull(route("/"));
        assertEquals(r, route("/hello/"));
        assertNull(route("/hello"));
        assertNull(route("/blah"));
    }

    @Test
    // produces the correct tree when given a single route with a single static path element with a regex symbol
    public void treeTest5() {
        Route r = newRoute("/hello$.html");

        router.add(r);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^hello\\$\\.html$", child.toString());
        assertEquals(r, child.getRoute(HttpMethod.GET));

        assertNull(route("/"));
        assertEquals(r, route("/hello$.html"));
        assertNull(route("/hello/"));
        assertNull(route("/blah"));
    }

    @Test
    // produces the correct tree when given the root route and a route with a single static path element
    public void treeTest6() {
        Route r1 = newRoute("/");
        Route r2 = newRoute("/hello");

        router.add(r1);
        router.add(r2);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertEquals(r1, root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^hello$", child.toString());
        assertEquals(r2, child.getRoute(HttpMethod.GET));

        assertEquals(r1, route("/"));
        assertEquals(r2, route("/hello"));
        assertNull(route("/hello/"));
        assertNull(route("/blah"));
    }

    @Test
    // produces the correct tree when given multiple routes with static path elements
    public void treeTest7() {
        Route r1 = newRoute("/");
        Route r2 = newRoute("/hello");
        Route r3 = newRoute("/hello/world");
        Route r4 = newRoute("/protected");

        router.add(r1);
        router.add(r2);
        router.add(r3);
        router.add(r4);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertEquals(r1, root.getRoute(HttpMethod.GET));
        assertEquals(2, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^hello$", child.toString());
        assertEquals(r2, child.getRoute(HttpMethod.GET));
        assertEquals(1, child.getChildren().size());

        child = child.getChildren().get(0);
        assertEquals("^world$", child.toString());
        assertEquals(r3, child.getRoute(HttpMethod.GET));

        child = root.getChildren().get(1);
        assertEquals("^protected$", child.toString());
        assertEquals(r4, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertEquals(r1, route("/"));
        assertEquals(r2, route("/hello"));
        assertNull(route("/hello/"));
        assertEquals(r3, route("/hello/world"));
        assertEquals(r4, route("/protected"));
        assertNull(route("/blah"));
        assertNull(route("/protected/"));
        assertNull(route("/hello/world/"));
    }

    @Test
    // produces the correct tree when given a sigle route with a single named path element
    public void treeTest8() {
        Route r1 = newRoute("/:name");

        router.add(r1);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^([^/]+)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertNull(route("/"));
        assertEquals(r1, route("/john"));
        assertNull(route("/john/doe"));
        assertNull(route("/john/"));
    }

    @Test
    // produces the correct tree when given a single route with multiple named path elements
    public void treeTest9() {
        Route r1 = newRoute("/:name/:id");

        router.add(r1);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^([^/]+)$", child.toString());
        assertNull(child.getRoute(HttpMethod.GET));
        assertEquals(1, child.getChildren().size());

        child = child.getChildren().get(0);
        assertEquals("^([^/]+)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertNull(route("/"));
        assertNull(route("/john"));
        assertEquals(r1, route("/john/doe"));
        assertNull(route("/john/"));
        assertNull(route("/john/doe/"));
    }

    @Test
    // produces the correct tree when given a single route with a single named parameter with custom regex
    public void treeTest10() {
        Route r1 = newRoute("/:id<[0-9]+>");

        router.add(r1);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^([0-9]+)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertNull(route("/"));
        assertEquals(r1, route("/123"));
        assertNull(route("/123/456"));
        assertNull(route("/123/"));
    }

    @Test
    // produces the correct tree when given multiples routes with multiple elements with a named parameter with custom regex
    public void treeTest11() {
        Route r1 = newRoute("/cntrl/actn/:id<[0-9]+>");
        Route r2 = newRoute("/cntrl/actn/:id<[a-z]+>");

        router.add(r1);
        router.add(r2);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode firstChild = root.getChildren().get(0);
        assertEquals("^cntrl$", firstChild.toString());
        assertNull(firstChild.getRoute(HttpMethod.GET));
        assertEquals(1, firstChild.getChildren().size());

        TreeNode secondChild = firstChild.getChildren().get(0);
        assertEquals("^actn$", secondChild.toString());
        assertNull(secondChild.getRoute(HttpMethod.GET));
        assertEquals(2, secondChild.getChildren().size());

        TreeNode child = secondChild.getChildren().get(0);
        assertEquals("^([0-9]+)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        child = secondChild.getChildren().get(1);
        assertEquals("^([a-z]+)$", child.toString());
        assertEquals(r2, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertEquals(r1, route("/cntrl/actn/123"));
        assertNull(route("/cntrl/actn/123/"));
        assertEquals(r2, route("/cntrl/actn/bob"));
        assertNull(route("/cntrl/actn/bob/"));
    }

    @Test
    // produces the correct tree when given a single route with a splat that matches all paths
    public void treeTest12() {
        Route r1 = newRoute("/*");

        router.add(r1);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^(.*)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertEquals(r1, route("/"));
        assertEquals(r1, route("/123"));
        assertEquals(r1, route("/123/456"));
        assertEquals(r1, route("/123/"));
    }

    @Test
    // produces the correct tree when given a single route with a splat that matches all paths, and the root route
    public void treeTest13() {
        Route r0 = newRoute("/");
        Route r1 = newRoute("/*");

        router.add(r0);
        router.add(r1);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertEquals(r0, root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^(.*)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertEquals(r0, route("/"));
        assertEquals(r1, route("/123"));
        assertEquals(r1, route("/123/456"));
        assertEquals(r1, route("/123/"));
    }

    @Test
    // produces the correct tree when given a single route with a splat with a preceding static element
    public void treeTest14() {
        Route r1 = newRoute("/protected/*");

        router.add(r1);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^protected$", child.toString());
        assertNull(child.getRoute(HttpMethod.GET));
        assertEquals(1, child.getChildren().size());

        child = child.getChildren().get(0);
        assertEquals("^(.*)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertNull(route("/protected"));
        assertEquals(r1, route("/protected/content"));
        assertEquals(r1, route("/protected/"));
    }

    @Test
    // produces the correct tree when given multiple routes, one with a splat with a preceding static element
    public void treeTest15() {
        Route r1 = newRoute("/protected/*");
        Route r2 = newRoute("/protected/:id<[0-9]+>");
        Route r3 = newRoute("/:name<[a-z]+>");

        router.add(r1);
        router.add(r2);
        router.add(r3);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(2, root.getChildren().size());

        TreeNode firstChild = root.getChildren().get(0);
        assertEquals("^protected$", firstChild.toString());
        assertNull(firstChild.getRoute(HttpMethod.GET));
        assertEquals(2, firstChild.getChildren().size());

        TreeNode child = firstChild.getChildren().get(0);
        assertEquals("^(.*)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        child = firstChild.getChildren().get(1);
        assertEquals("^([0-9]+)$", child.toString());
        assertEquals(r2, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        TreeNode secondChild = root.getChildren().get(1);
        assertEquals("^([a-z]+)$", secondChild.toString());
        assertEquals(r3, secondChild.getRoute(HttpMethod.GET));
        assertEquals(0, secondChild.getChildren().size());

        assertEquals(r1, route("/protected/content"));
        assertEquals(r1, route("/protected/123"));
        assertEquals(r3, route("/john"));
        assertEquals(r1, route("/protected/"));
    }

    @Test
    // produces the correct tree when given a single route with multiple splat elements
    public void treeTest16() {
        Route r1 = newRoute("/say/*/to/*");

        router.add(r1);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertNull(root.getRoute(HttpMethod.GET));
        assertEquals(1, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^say$", child.toString());
        assertNull(child.getRoute(HttpMethod.GET));
        assertEquals(1, child.getChildren().size());

        child = child.getChildren().get(0);
        assertEquals("^(.*)$", child.toString());
        assertNull(child.getRoute(HttpMethod.GET));
        assertEquals(1, child.getChildren().size());

        child = child.getChildren().get(0);
        assertEquals("^to$", child.toString());
        assertNull(child.getRoute(HttpMethod.GET));
        assertEquals(1, child.getChildren().size());

        child = child.getChildren().get(0);
        assertEquals("^(.*)$", child.toString());
        assertEquals(r1, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        assertNull(route("/hello"));
        assertEquals(r1, route("/say/hello/to/world"));
        assertEquals(r1, route("/say/bye/to/Tim"));
        assertNull(route("/say/bye/bye/to/Tim"));
        assertEquals(r1, route("/say/bye/to/John/Doe"));
        assertNull(route("/say/hello/to"));
        assertEquals(r1, route("/say/hello/to/"));
    }

    @Test
    // matches a similar route containing a splat before the route containing the static element
    public void treeTest17() {
        Route r1  = newRoute("/abc/*/def");
        Route r2  = newRoute("/abc/123/def");

        router.add(r2);
        router.add(r1);

        assertEquals(r1, route("/abc/123/def"));
    }

    @Test
    // matches a similar route containing a static element before the route containing the named parameter
    public void treeTest18() {
        Route r1  = newRoute("/abc/123/def");
        Route r2  = newRoute("/abc/:name/def");

        router.add(r2);
        router.add(r1);

        assertEquals(r1, route("/abc/123/def"));
    }

    @Test
    // matches a similar route containing a splat before the route containing the named parameter
    public void treeTest19() {
        Route r1  = newRoute("/abc/*/def");
        Route r2  = newRoute("/abc/:name/def");

        router.add(r2);
        router.add(r1);

        assertEquals(r1, route("/abc/123/def"));
    }

    @Test
    // produces a tree with multiple routes with children sorted properly
    public void treeTest20() {
        Route r1  = newRoute("/");
        Route r2  = newRoute("/*");
        Route r3  = newRoute("/1");
        Route r4  = newRoute("/x");
        Route r5  = newRoute("/y");
        Route r6  = newRoute("/:id");

        router.add(r6);
        router.add(r5);
        router.add(r3);
        router.add(r4);
        router.add(r1);
        router.add(r2);

        TreeNode root = router.getRoot();
        assertEquals("^/$", root.toString());
        assertEquals(r1, root.getRoute(HttpMethod.GET));
        assertEquals(5, root.getChildren().size());

        TreeNode child = root.getChildren().get(0);
        assertEquals("^(.*)$", child.toString());
        assertEquals(r2, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        child = root.getChildren().get(1);
        assertEquals("^1$", child.toString());
        assertEquals(r3, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        child = root.getChildren().get(2);
        assertEquals("^x$", child.toString());
        assertEquals(r4, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        child = root.getChildren().get(3);
        assertEquals("^y$", child.toString());
        assertEquals(r5, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());

        child = root.getChildren().get(4);
        assertEquals("^([^/]+)$", child.toString());
        assertEquals(r6, child.getRoute(HttpMethod.GET));
        assertEquals(0, child.getChildren().size());
    }
}


text:
#ifndef JERRYSCRIPT_COMPILER_H
#define JERRYSCRIPT_COMPILER_H

#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */

/** \addtogroup jerry-compiler Jerry compiler compatibility components
 * @{
 */

#ifdef __GNUC__

/*
 * Compiler-specific macros relevant for GCC.
 */
#define JERRY_ATTR_ALIGNED(ALIGNMENT) __attribute__((aligned(ALIGNMENT)))
#define JERRY_ATTR_ALWAYS_INLINE __attribute__((always_inline))
#define JERRY_ATTR_CONST __attribute__((const))
#define JERRY_ATTR_DEPRECATED __attribute__((deprecated))
#define JERRY_ATTR_FORMAT(...) __attribute__((format(__VA_ARGS__)))
#define JERRY_ATTR_HOT __attribute__((hot))
#define JERRY_ATTR_NOINLINE __attribute__((noinline))
#define JERRY_ATTR_NORETURN __attribute__((noreturn))
#define JERRY_ATTR_PURE __attribute__((pure))
#define JERRY_ATTR_SECTION(SECTION) __attribute__((section(SECTION)))
#define JERRY_ATTR_WARN_UNUSED_RESULT __attribute__((warn_unused_result))

#define JERRY_LIKELY(x) __builtin_expect(!!(x), 1)
#define JERRY_UNLIKELY(x) __builtin_expect(!!(x), 0)

#endif /* __GNUC__ */

#ifdef _MSC_VER

/*
 * Compiler-specific macros relevant for Microsoft Visual C/C++ Compiler.
 */
#define JERRY_ATTR_DEPRECATED __declspec(deprecated)
#define JERRY_ATTR_NOINLINE __declspec(noinline)
#define JERRY_ATTR_NORETURN __declspec(noreturn)

/*
 * Microsoft Visual C/C++ Compiler doesn't support for VLA, using _alloca
 * instead.
 */
void * __cdecl _alloca (size_t _Size);
#define JERRY_VLA(type, name, size) type *name = (type *) (_alloca (sizeof (type) * size))

#endif /* _MSC_VER */

/*
 * Default empty definitions for all compiler-specific macros. Define any of
 * these in a guarded block above (e.g., as for GCC) to fine tune compilation
 * for your own compiler. */

/**
 * Function attribute to align function to given number of bytes.
 */
#ifndef JERRY_ATTR_ALIGNED
#define JERRY_ATTR_ALIGNED(ALIGNMENT)
#endif /* !JERRY_ATTR_ALIGNED */

/**
 * Function attribute to inline function to all call sites.
 */
#ifndef JERRY_ATTR_ALWAYS_INLINE
#define JERRY_ATTR_ALWAYS_INLINE
#endif /* !JERRY_ATTR_ALWAYS_INLINE */

/**
 * Function attribute to declare that function has no effect except the return
 * value and it only depends on parameters.
 */
#ifndef JERRY_ATTR_CONST
#define JERRY_ATTR_CONST
#endif /* !JERRY_ATTR_CONST */

/**
 * Function attribute to trigger warning if deprecated function is called.
 */
#ifndef JERRY_ATTR_DEPRECATED
#define JERRY_ATTR_DEPRECATED
#endif /* !JERRY_ATTR_DEPRECATED */

/**
 * Function attribute to declare that function is variadic and takes a format
 * string and some arguments as parameters.
 */
#ifndef JERRY_ATTR_FORMAT
#define JERRY_ATTR_FORMAT(...)
#endif /* !JERRY_ATTR_FORMAT */

/**
 * Function attribute to predict that function is a hot spot, and therefore
 * should be optimized aggressively.
 */
#ifndef JERRY_ATTR_HOT
#define JERRY_ATTR_HOT
#endif /* !JERRY_ATTR_HOT */

/**
 * Function attribute not to inline function ever.
 */
#ifndef JERRY_ATTR_NOINLINE
#define JERRY_ATTR_NOINLINE
#endif /* !JERRY_ATTR_NOINLINE */

/**
 * Function attribute to declare that function never returns.
 */
#ifndef JERRY_ATTR_NORETURN
#define JERRY_ATTR_NORETURN
#endif /* !JERRY_ATTR_NORETURN */

/**
 * Function attribute to declare that function has no effect except the return
 * value and it only depends on parameters and global variables.
 */
#ifndef JERRY_ATTR_PURE
#define JERRY_ATTR_PURE
#endif /* !JERRY_ATTR_PURE */

/**
 * Function attribute to place function in given section.
 */
#ifndef JERRY_ATTR_SECTION
#define JERRY_ATTR_SECTION(SECTION)
#endif /* !JERRY_ATTR_SECTION */

/**
 * Function attribute to trigger warning if function's caller doesn't use (e.g.,
 * check) the return value.
 */
#ifndef JERRY_ATTR_WARN_UNUSED_RESULT
#define JERRY_ATTR_WARN_UNUSED_RESULT
#endif /* !JERRY_ATTR_WARN_UNUSED_RESULT */

/**
 * Helper to predict that a condition is likely.
 */
#ifndef JERRY_LIKELY
#define JERRY_LIKELY(x) (x)
#endif /* !JERRY_LIKELY */

/**
 * Helper to predict that a condition is unlikely.
 */
#ifndef JERRY_UNLIKELY
#define JERRY_UNLIKELY(x) (x)
#endif /* !JERRY_UNLIKELY */

/**
 * Helper to declare (or mimic) a C99 variable-length array.
 */
#ifndef JERRY_VLA
#define JERRY_VLA(type, name, size) type name[size]
#endif /* !JERRY_VLA */

/**
 * @}
 */

#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* !JERRYSCRIPT_COMPILER_H */

redpajama_set_name: RedPajamaGithub


text:
define([
  'errors',
  'fxpay',
  'helper',
  'receipts',
  'settings',
], function(errorsModule, fxpay, helper, receipts, settingsModule) {

  describe('fxpay', function() {

    beforeEach(function() {
      helper.setUp();
    });

    afterEach(function() {
      helper.tearDown();
    });

    it('should expose fxpay.errors', function() {
      assert.equal(fxpay.errors.FxPayError, errorsModule.FxPayError);
    });

    it('should expose fxpay.settings', function() {
      assert.equal(fxpay.settings.fakeProducts, settingsModule.fakeProducts);
    });

    it('should expose fxpay.receipts', function() {
      assert.equal(fxpay.receipts.validateInAppProductReceipt,
                   receipts.validateInAppProductReceipt);
    });

  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<endpoint xmlns="http://ws.apache.org/ns/synapse" name="resut_display_ep">
    <address uri="http://10.100.0.117:7001/as/services/ResultDisplayService"/>
</endpoint>


text:
import webpack from "webpack";
import { resolve, join } from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";
import FaviconsWebpackPlugin from "favicons-webpack-plugin";
import OfflinePlugin from "offline-plugin";

/// Constants ///
const PORT = 6464;
const HOST = "localhost";
const build_directory = "build";
const source_directory = "source";
const env = process.env.NODE_ENV;
const isProduction = env == "production";
const sourceMapType = isProduction ? "" : "eval-source-map";

// This plugin allows for base-page template
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
  template: `${resolve(__dirname, source_directory)}/index.ejs`,
  env: env,
  filename: "index.html",
  inject: true,
  port: PORT
});

const FaviconsWebpackPluginConfig = new FaviconsWebpackPlugin({
  // Your source logo
  logo: "./images/logo.png",
  // The prefix for all image files (might be a folder or a name)
  prefix: "./images/",
  // Emit all stats of the generated icons
  emitStats: true,
  // The name of the json containing all favicon information
  statsFilename: "iconstats.json",
  // Generate a cache file with control hashes and
  // don"t rebuild the favicons until those hashes change
  persistentCache: true,
  // Inject the html into the html-webpack-plugin
  inject: true,
  // favicon background color (see https://github.com/haydenbleasel/favicons#usage)
  background: "#FFFFFF",
  // favicon app title (see https://github.com/haydenbleasel/favicons#usage)
  title: "Mackie Drew",
  theme_color: "#FFC107",

  // which icons should be generated (see https://github.com/haydenbleasel/favicons#usage)
  icons: {
    android: true,
    appleIcon: true,
    appleStartup: true,
    coast: true,
    favicons: true,
    firefox: true,
    opengraph: true,
    twitter: true,
    yandex: true,
    windows: true
  }
});

const developmentPlugins = [
  FaviconsWebpackPluginConfig,
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NamedModulesPlugin(),
  HtmlWebpackPluginConfig,
  new OfflinePlugin()
];

const productionPlugins = [
  new webpack.DefinePlugin({
    "process.env": {
      NODE_ENV: JSON.stringify("production")
    }
  }),
  FaviconsWebpackPluginConfig,
  HtmlWebpackPluginConfig,
  new webpack.LoaderOptionsPlugin({
    minimize: true,
    debug: false
  }),
  new webpack.optimize.UglifyJsPlugin({
    beautify: false,
    mangle: {
      screw_ie8: true,
      keep_fnames: true
    },
    compress: {
      screw_ie8: true
    },
    comments: false,
    exclude: [/\.worker\.js$/, /\.map\.js$/]
  }),
  new OfflinePlugin()
];

const developmentEntry = [
  "react-hot-loader/patch",
  `webpack-dev-server/client?http://${HOST}:${PORT}`,
  "webpack/hot/only-dev-server",
  "./index.js"
];

const entry = isProduction ? "./index.js" : developmentEntry;

const configuration = {
  context: join(__dirname, source_directory),

  devtool: sourceMapType,

  devServer: {
    hot: true,
    inline: true,
    host: HOST,
    port: PORT,
    contentBase: "/build",
    publicPath: "/"
  },

  entry: entry,

  output: {
    path: resolve(__dirname, `${build_directory}`),
    filename: "bundle.js",
    sourceMapFilename: "bundle.js.map"
  },

  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: ["babel-loader"],
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: ["json-loader"]
      },
      {
        test: /\.css$/,
        loader: ["style-loader", "css-loader?modules", "postcss-loader"]
      },
      {
        test: /\.styl$/,
        loader: ["style-loader", "css-loader", "stylus-loader"]
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        exclude: /node_modules/,
        loader: [
          "file-loader?name=images/[hash].[ext]",
          {
            loader: "img-loader",
            options: {
              enabled: isProduction,
              gifsicle: {
                interlaced: false
              },
              mozjpeg: {
                progressive: true,
                arithmetic: false
              },
              optipng: isProduction,
              pngquant: {
                floyd: 0.5,
                speed: 2
              }
            }
          }
        ]
      },
      {
        test: /\.ico$/,
        exclude: /node_modules/,
        loader: "file-loader?name=favicon.ico"
      },
      {
        test: /CNAME$/,
        exclude: /node_modules/,
        loader: "file-loader?name=CNAME"
      },
      {
        test: /\.worker\.js$/,
        exclude: /node_modules/,
        loader: ["worker-loader", "babel-loader"]
      }
    ]
  },

  plugins: isProduction ? productionPlugins : developmentPlugins
};

export default configuration;


text:
<?php
/**
 * Created by PhpStorm.
 * User: stefan
 * Date: 23.07.15
 * Time: 11:01
 */

namespace TQ\ExtDirect\Tests\Metadata;

use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase;
use TQ\ExtDirect\Metadata\Driver\AnnotationDriver;

/**
 * Class MethodMetadataTest
 *
 * @package TQ\ExtDirect\Tests\Metadata
 */
class MethodMetadataTest extends TestCase
{
    public function testSerialize()
    {
        $driver          = new AnnotationDriver(new AnnotationReader());
        $reflectionClass = new \ReflectionClass('TQ\ExtDirect\Tests\Metadata\Services\Service1');
        $origMetadata    = $driver->loadMetadataForClass($reflectionClass);

        $serialized = serialize($origMetadata);
        /** @var \TQ\ExtDirect\Metadata\ActionMetadata $restoredMetadata */
        $restoredMetadata = unserialize($serialized);

        /** @var \TQ\ExtDirect\Metadata\MethodMetadata $origMethodMetadata */
        /** @var \TQ\ExtDirect\Metadata\MethodMetadata $restoredMethodMetadata */
        $origMethodMetadata     = $origMetadata->methodMetadata['methodA'];
        $restoredMethodMetadata = $restoredMetadata->methodMetadata['methodA'];

        $this->assertEquals($origMethodMetadata->isMethod, $restoredMethodMetadata->isMethod);
        $this->assertEquals($origMethodMetadata->isFormHandler, $restoredMethodMetadata->isFormHandler);
        $this->assertEquals($origMethodMetadata->hasNamedParams, $restoredMethodMetadata->hasNamedParams);
        $this->assertEquals($origMethodMetadata->isStrict, $restoredMethodMetadata->isStrict);
        $this->assertEquals($origMethodMetadata->batched, $restoredMethodMetadata->batched);

        $this->assertEquals(count($origMethodMetadata->parameters), count($restoredMethodMetadata->parameters));
        $this->assertEquals(count($origMethodMetadata->parameterMetadata),
            count($restoredMethodMetadata->parameterMetadata));

        $this->assertEquals($origMethodMetadata->authorizationExpression, $restoredMethodMetadata->authorizationExpression);
        $this->assertEquals($origMethodMetadata->result, $restoredMethodMetadata->result);
    }
}


text:
package ar.glyphsets.implicitgeometry;

/**Wrappers for mathematical functions.
 *
 * Many of these are pulled from java.lang.Math others are simple arithmetic operators.
 */
public class MathValuers {
	/**Perform log based on the double-value of the input.
	 * By default, the add1 flag is set to true.
	 *
	 * If basis is set to 0, will just echo input values (convenient with interactive tools).
	 */
	public static final class Log<A extends Number> implements Valuer<A,Double> {
		final double base;
		final boolean add1;

		public Log(Integer base) {this((double) base.intValue(), true);}
		public Log(Integer base, boolean add1) {this((double) base.intValue(), add1);}

		public Log(Double base) {this(base, true);}
		public Log(Double base, boolean add1) {
			this.base = base;
			this.add1=add1;
		}

		public Double apply(A from) {
			double val = from.doubleValue();
			if (base == 0) {return val;}
			else if (add1 && base == Math.E) {return Math.log1p(val);}
			else if (add1) {return Math.log1p(val)/Math.log(base);}
			else if (base == Math.E) {return Math.log(val);}
			else if (base == 10) {return Math.log10(val);}
			else {return Math.log(val)/Math.log(base);}
		}
	}

	public static final class ToDouble implements Valuer<Number, Double> {
		public Double apply(Number d) {return d.doubleValue();}
	}

	public static final class ToFloat implements Valuer<Number, Float> {
		public Float apply(Number d) {return d.floatValue();}
	}

	public static final class ToLong implements Valuer<Number, Long> {
		public Long apply(Number d) {return d.longValue();}
	}

	public static final class ToInteger implements Valuer<Number, Integer> {
		public Integer apply(Number d) {return d.intValue();}
	}

	public static final class ToShort implements Valuer<Double, Short> {
		public Short apply(Double d) {return d.shortValue();}
	}

	public static final class GT<N extends Number> implements Valuer<N, Boolean> {
		final double ref;
		public GT(Double ref) {this.ref = ref;}
		public Boolean apply(N from) {return from.doubleValue() > ref;}
	}

	public static final class GTE<N extends Number> implements Valuer<N, Boolean> {
		final double ref;
		public GTE(Double ref) {this.ref = ref;}
		public Boolean apply(N from) {return from.doubleValue() >= ref;}
	}

	public static final class LT<N extends Number> implements Valuer<N, Boolean> {
		final double ref;
		public LT(Double ref) {this.ref = ref;}
		public Boolean apply(N from) {return from.doubleValue() < ref;}
	}

	public static final class LTE<N extends Number> implements Valuer<N, Boolean> {
		final double ref;
		public LTE(Double ref) {this.ref = ref;}
		public Boolean apply(N from) {return from.doubleValue() <= ref;}
	}

	public static final class EQ<N extends Number> implements Valuer<N, Boolean> {
		final double ref;
		public EQ(Double ref) {this.ref = ref;}
		public Boolean apply(N from) {return ref == from.doubleValue();}
	}
}


text:
=head1 NAME

Mail::SpamAssassin::Plugin::ASN - SpamAssassin plugin to look up the Autonomous System Number (ASN) of the connecting IP address.

=head1 SYNOPSIS

 loadplugin Mail::SpamAssassin::Plugin::ASN

 asn_lookup asn.routeviews.org _ASN_ _ASNCIDR_

 add_header all ASN _ASN_ _ASNCIDR_

=head1 DESCRIPTION

This plugin uses DNS lookups to the services of
C<http://www.routeviews.org/> to do the actual work. Please make sure
that your use of the plugin does not overload their infrastructure -
this generally means that B<you should not use this plugin in a
high-volume environment> or that you should use a local mirror of the
zone (see C<ftp://ftp.routeviews.org/dnszones/>).

=head1 TEMPLATE TAGS

This plugin allows you to create template tags containing the connecting
IP's AS number and route info for that AS number.

The default config will add a header that looks like this:

 X-Spam-ASN: AS24940 213.239.192.0/18

where "AS24940" is the ASN and "213.239.192.0/18" is the route
announced by that ASN where the connecting IP address came from. If
the AS announces multiple networks (more/less specific), they will
all be added to the C<_ASNCIDR_> tag, separated by spaces, eg:

 X-Spam-ASN: AS1680 89.138.0.0/15 89.139.0.0/16

=head1 CONFIGURATION

The standard ruleset contains a configuration that will add a header
containing ASN data to scanned messages.  The bayes tokenizer will use the
added header for bayes calculations, and thus affect which BAYES_* rule will
trigger for a particular message.

B<Note> that in most cases you should not score on the ASN data directly.
Bayes learning will probably trigger on the _ASNCIDR_ tag, but probably not
very well on the _ASN_ tag alone.

=head1 SEE ALSO

http://www.routeviews.org/ - all data regarding routing, ASNs etc

http://issues.apache.org/SpamAssassin/show_bug.cgi?id=4770 -
SpamAssassin Issue #4770 concerning this plugin

=head1 STATUS

Experimental - Dec. 18, 2006

No in-depth analysis of the usefulness of bayes tokenization of ASN data has
been performed.

=cut

package Mail::SpamAssassin::Plugin::ASN;

use strict;
use Mail::SpamAssassin;
use Mail::SpamAssassin::Plugin;
use Mail::SpamAssassin::Logger;
use Mail::SpamAssassin::Dns;

our @ISA = qw(Mail::SpamAssassin::Plugin);

sub new {
  my ($class, $mailsa) = @_;
  $class = ref($class) || $class;
  my $self = $class->SUPER::new($mailsa);
  bless ($self, $class);

  $self->set_config($mailsa->{conf});

  return $self;
}

###########################################################################

sub set_config {
  my ($self, $conf) = @_;
  my @cmds = ();

=head1 ADMINISTRATOR SETTINGS

=over 4

=item asn_lookup asn-zone.example.com [ _ASNTAG_ _ASNCIDRTAG_ ]

Use this to lookup the ASN info for first external IP address in the specified
zone and add the AS number to the first specified tag and routing info to the
second specified tag.

If no tags are specified the AS number will be added to the _ASN_ tag and the
routing info will be added to the _ASNCIDR_ tag.  You must specify either none
or both of the tags.  Tags must start and end with an underscore.

If two or more I<asn_lookup>s use the same set of template tags, the results of
their lookups will be appended to each other in the template tag values in no
particular order.  Duplicate results will be omitted when combining results.
In a similar fashion, you can also use the same template tag for both the AS
number tag and the routing info tag.

Examples:

  asn_lookup asn.routeviews.org

  asn_lookup asn.routeviews.org _ASN_ _ASNCIDR_
  asn_lookup myview.example.com _MYASN_ _MYASNCIDR_

  asn_lookup asn.routeviews.org _COMBINEDASN_ _COMBINEDASNCIDR_
  asn_lookup myview.example.com _COMBINEDASN_ _COMBINEDASNCIDR_

  asn_lookup in1tag.example.net _ASNDATA_ _ASNDATA_

=cut

  push (@cmds, {
    setting => 'asn_lookup',
    is_admin => 1,
    code => sub {
      my ($self, $key, $value, $line) = @_;
      unless (defined $value && $value !~ /^$/) {
        return $Mail::SpamAssassin::Conf::MISSING_REQUIRED_VALUE;
      }
      unless ($value =~ /^(\S+?)\.?(?:\s+_(\S+)_\s+_(\S+)_)?$/) {
        return $Mail::SpamAssassin::Conf::INVALID_VALUE;
      }
      my $zone = $1.'.';
      my $asn_tag = (defined $2 ? $2 : 'ASN');
      my $route_tag = (defined $3 ? $3 : 'ASNCIDR');

      push @{$self->{main}->{conf}->{asnlookups}}, { zone=>$zone, asn_tag=>$asn_tag, route_tag=>$route_tag };
    }
  });

  $conf->{parser}->register_commands(\@cmds);
}

# ---------------------------------------------------------------------------

sub parsed_metadata {
  my ($self, $opts) = @_;

  my $scanner = $opts->{permsgstatus};
  my $conf = $self->{main}->{conf};

  unless ($conf->{asnlookups}) {
    dbg("asn: no asn_lookup configured, skipping ASN lookups");
    return; # no asn_lookups mean no tags need to be initialized
  }

  # get reversed IP-quad of last external relay to lookup
  # don't return until we've initialized the template tags
  my $reversed_ip_quad;
  my $relay = $scanner->{relays_external}->[0];
  if (!$scanner->is_dns_available()) {
    dbg("asn: DNS is not available, skipping ASN checks");
  } elsif ($relay->{ip_private}) {
    dbg("asn: first external relay is a private IP, skipping ASN check");
  } else {
    if (defined $relay->{ip} && $relay->{ip} =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) {
      $reversed_ip_quad = "$4.$3.$2.$1";
      dbg("asn: using first external relay IP for lookups: $relay->{ip}");
    } else {
      dbg("asn: could not parse IP from first external relay, skipping ASN check");
    }
  }

  # random note: we use arrays and array indices rather than hashes and hash
  # keys in case someone wants the same zone added to multiple sets of tags
  my $index = 0;
  foreach my $entry (@{$conf->{asnlookups}}) {
    # initialize the tag data so that if no result is returned from the DNS
    # query we won't end up with a missing tag
    unless (defined $scanner->{tag_data}->{$entry->{asn_tag}}) {
      $scanner->{tag_data}->{$entry->{asn_tag}} = '';
    }
    unless (defined $scanner->{tag_data}->{$entry->{route_tag}}) {
      $scanner->{tag_data}->{$entry->{route_tag}} = '';
    }
    next unless $reversed_ip_quad;

    # do the DNS query, have the callback process the result rather than poll for them later
    my $zone_index = $index;
    my $zone = $reversed_ip_quad . '.' . $entry->{zone};
    my $key = "asnlookup-${zone_index}-$entry->{zone}";
    my $id = $scanner->{main}->{resolver}->bgsend($zone, 'TXT', undef, sub {
      my ($pkt, $id, $timestamp) = @_;
      $scanner->{async}->set_response_packet($id, $pkt, $key, $timestamp);
      $self->process_dns_result($scanner, $pkt, $zone_index);
    });
    my $ent = {
      key=>$key, id=>$id, type=>'TXT',
      zone => $zone,  # serves to fetch other per-zone settings
    };
    $scanner->{async}->start_lookup($ent);
    dbg("asn: launched DNS TXT query for $reversed_ip_quad.$entry->{zone} in background");

    $index++;
  }
}

sub process_dns_result {
  my ($self, $scanner, $response, $zone_index) = @_;

  my $conf = $self->{main}->{conf};

  my $zone = $conf->{asnlookups}[$zone_index]->{zone};
  my $asn_tag = $conf->{asnlookups}[$zone_index]->{asn_tag};
  my $route_tag = $conf->{asnlookups}[$zone_index]->{route_tag};

  my @answer = !defined $response ? () : $response->answer;

  foreach my $rr (@answer) {
    dbg("asn: $zone: lookup result packet: '".$rr->string."'");
    if ($rr->type eq 'TXT') {
      my @items = split(/ /, $rr->txtdata);
      unless ($#items == 2) {
        dbg("asn: TXT query response format unknown, ignoring zone: $zone response: '".$rr->txtdata."'");
        next;
      }
      unless ($scanner->{tag_data}->{$asn_tag} =~ /\bAS$items[0]\b/) {
        if ($scanner->{tag_data}->{$asn_tag}) {
          $scanner->{tag_data}->{$asn_tag} .= " AS$items[0]";
        } else {
          $scanner->{tag_data}->{$asn_tag} = "AS$items[0]";
        }
      }
      unless ($scanner->{tag_data}->{$route_tag} =~ m{\b$items[1]/$items[2]\b}) {
        if ($scanner->{tag_data}->{$route_tag}) {
          $scanner->{tag_data}->{$route_tag} .= " $items[1]/$items[2]";
        } else {
          $scanner->{tag_data}->{$route_tag} = "$items[1]/$items[2]";
        }
      }
    }
  }

  return;
}

1;


text:
{% extends "site_base.html"%}
{% load i18n %}
{% load bootstrap %}

{% block extra_body %}
 {{ form.media }}
{% endblock %}

{% block body %}

Reserva

    <form action="" method="post">{% csrf_token %}
      {{ form|bootstrap }}

      <button type="submit">Guardar</button>

    </form>
{% endblock %}


text:
require 'spec_helper'

describe Serveit::InferExtension do

  def app
    @app ||= Rack::Builder.new do
      use Serveit::InferExtension
      use Serveit::Static, root: TEST_APP_ROOT
      run Serveit::NotFound
    end
  end

  context 'GET /contact.html' do
    it "renders /contact.html as a 200" do
      response = get '/contact.html'
      expect( response.status  ).to eq 200
      expect( response.body    ).to eq "
Contact us at:
\n"
      expect( response.headers['Content-Type']   ).to eq 'text/html'
      expect( response.headers['Content-Length'] ).to eq '24'
      expect( response.headers['Last-Modified']  ).to_not be_nil
    end
  end

  context 'GET /contact' do
    it "renders /contact.html as a 200" do
      response = get '/contact'
      expect( response.status  ).to eq 200
      expect( response.body    ).to eq "
Contact us at:
\n"
      expect( response.headers['Content-Type']   ).to eq 'text/html'
      expect( response.headers['Content-Length'] ).to eq '24'
      expect( response.headers['Last-Modified']  ).to_not be_nil
    end
  end

  context 'GET /contact/' do
    it "renders /contact/index.html as a 200" do
      response = get '/contact/'
      expect( response.status  ).to eq 200
      expect( response.body    ).to eq "
Contact Page:
\n"
      expect( response.headers['Content-Type']   ).to eq 'text/html'
      expect( response.headers['Content-Length'] ).to eq '22'
      expect( response.headers['Last-Modified']  ).to_not be_nil
    end
  end

  context 'GET /contact/index' do
    it "renders /contact/index.html as a 200" do
      response = get '/contact/index'
      expect( response.status  ).to eq 200
      expect( response.body    ).to eq "
Contact Page:
\n"
      expect( response.headers['Content-Type']   ).to eq 'text/html'
      expect( response.headers['Content-Length'] ).to eq '22'
      expect( response.headers['Last-Modified']  ).to_not be_nil
    end
  end

  context 'GET /contact/index.html' do
    it "renders /contact/index.html as a 200" do
      response = get '/contact/index.html'
      expect( response.status  ).to eq 200
      expect( response.body    ).to eq "
Contact Page:
\n"
      expect( response.headers['Content-Type']   ).to eq 'text/html'
      expect( response.headers['Content-Length'] ).to eq '22'
      expect( response.headers['Last-Modified']  ).to_not be_nil
    end
  end

  context 'GET /contact/address' do
    it "renders /contact/address.html as a 200" do
      response = get '/contact/address'
      expect( response.status  ).to eq 200
      expect( response.body    ).to eq "
Our Address
\n"
      expect( response.headers['Content-Type']   ).to eq 'text/html'
      expect( response.headers['Content-Length'] ).to eq '21'
      expect( response.headers['Last-Modified']  ).to_not be_nil
    end
  end

  context 'GET /contact/address.html' do
    it "renders /contact/address.html as a 200" do
      response = get '/contact/address.html'
      expect( response.status  ).to eq 200
      expect( response.body    ).to eq "
Our Address
\n"
      expect( response.headers['Content-Type']   ).to eq 'text/html'
      expect( response.headers['Content-Length'] ).to eq '21'
      expect( response.headers['Last-Modified']  ).to_not be_nil
    end
  end

end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace BeaconLib
{
    /// <summary>
    /// Instances of this class can be autodiscovered on the local network through UDP broadcasts
    /// </summary>
    /// <remarks>
    /// The advertisement consists of the beacon's application type and a short beacon-specific string.
    /// </remarks>
    public class Beacon : IDisposable
    {
        internal const int DiscoveryPort = 35891;
        private readonly UdpClient udp;

        public Beacon(string beaconType, ushort advertisedPort)
        {
            BeaconType     = beaconType;
            AdvertisedPort = advertisedPort;
            BeaconData     = "";

            udp = new UdpClient();
            udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udp.Client.Bind(new IPEndPoint(IPAddress.Any, DiscoveryPort));

            try
            {
                udp.AllowNatTraversal(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error switching on NAT traversal: " + ex.Message);
            }
        }

        public void Start()
        {
            Stopped = false;
            udp.BeginReceive(ProbeReceived, null);
        }

        public void Stop()
        {
            Stopped = true;
        }

        private void ProbeReceived(IAsyncResult ar)
        {
            var remote = new IPEndPoint(IPAddress.Any, 0);
            var bytes  = udp.EndReceive(ar, ref remote);

            // Compare beacon type to probe type
            var typeBytes = Encode(BeaconType);
            if (HasPrefix(bytes, typeBytes))
            {
                // If true, respond again with our type, port and payload
                var responseData = Encode(BeaconType)
                    .Concat(BitConverter.GetBytes((ushort)IPAddress.HostToNetworkOrder((short)AdvertisedPort)))
                    .Concat(Encode(BeaconData)).ToArray();
                udp.Send(responseData, responseData.Length, remote);
            }

            if (!Stopped) udp.BeginReceive(ProbeReceived, null);
        }

        internal static bool HasPrefix<T>(IEnumerable<T> haystack, IEnumerable<T> prefix)
        {
            return haystack.Count() >= prefix.Count() &&
                haystack.Zip(prefix, (a, b) => a.Equals(b)).All(_ => _);
        }

        /// <summary>
        /// Convert a string to network bytes
        /// </summary>
        internal static IEnumerable<byte> Encode(string data)
        {
            var bytes = Encoding.UTF8.GetBytes(data);
            var len = IPAddress.HostToNetworkOrder((short)bytes.Length);

            return BitConverter.GetBytes(len).Concat(bytes);
        }

        /// <summary>
        /// Convert network bytes to a string
        /// </summary>
        internal static string Decode(IEnumerable<byte> data)
        {
            var listData = data as IList<byte> ?? data.ToList();

            var len = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(listData.Take(2).ToArray(), 0));
            if (listData.Count() < 2 + len) throw new ArgumentException("Too few bytes in packet");

            return Encoding.UTF8.GetString(listData.Skip(2).Take(len).ToArray());
        }

        /// <summary>
        /// Return the machine's hostname (usually nice to mention in the beacon text)
        /// </summary>
        public static string HostName
        {
            get { return Dns.GetHostName(); }
        }

        public string BeaconType { get; private set; }
        public ushort AdvertisedPort { get; private set; }
        public bool Stopped { get; private set; }

        public string BeaconData { get; set; }

        public void Dispose()
        {
            Stop();
        }
    }
}


text:
package validator

import "os"

// DirExists is a dir and exists
func DirExists(path string) (bool, error) {
	fi, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}

	switch mode := fi.Mode(); {
	case mode.IsDir():
		return true, nil
	case mode.IsRegular():
		return false, nil
	}

	return false, err
}


text:
<?php

namespace Limelight\Classes;

use Limelight\Helpers\Contracts\Arrayable;
use Limelight\Helpers\Contracts\Convertable;
use Limelight\Helpers\Contracts\Jsonable;
use Limelight\Helpers\PluginHelper;

class LimelightResults extends Collection implements Arrayable, Convertable, Jsonable
{
    use PluginHelper;

    /**
     * The original input.
     *
     * @var string
     */
    protected $text;

    /**
     * Array of words returned from parser.
     *
     * @var array
     */
    protected $words;

    /**
     * Results from plugins.
     *
     * @var array
     */
    protected $pluginData = [];

    /**
     * Construct.
     *
     * @param string $text
     * @param array $words
     * @param array/null $pluginData
     */
    public function __construct($text, array $words, $pluginData)
    {
        $this->text = $text;
        $this->words = $words;
        $this->pluginData = $pluginData;
    }

    /**
     * Print JSON.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->toJson();
    }

    /**
     * Get values as string.
     *
     * @param string $value
     * @param string $glue
     * @return string
     */
    public function string($value, $glue = null)
    {
        $value = $this->makeSingular($value);

        $collection = $this->map(function ($item, $key) use ($value, $glue) {
            return $this->buildString($item, $value, $glue);
        });

        return $this->cutFirst($collection, $glue);
    }

    /**
     * Get the original, user input text.
     *
     * @return string
     */
    public function original()
    {
        return $this->text;
    }

    /**
     * Get all words.
     *
     * @return static
     */
    public function words()
    {
        return $this->pluck('word');
    }

    /**
     * Get all lemmas.
     *
     * @return static
     */
    public function lemmas()
    {
        return $this->pluck('lemma');
    }

    /**
     * Get all readings.
     *
     * @return static
     */
    public function readings()
    {
        return $this->pluck('reading');
    }

    /**
     * Get all pronunciations.
     *
     * @return static
     */
    public function pronunciations()
    {
        return $this->pluck('pronunciation');
    }

    /**
     * Get all partsOfSpeech.
     *
     * @return static
     */
    public function partsOfSpeech()
    {
        return $this->pluck('partOfSpeech');
    }

    /**
     * Get romaji if data exists.
     *
     * @throws PluginNotFoundException
     *
     * @return static
     */
    public function romaji()
    {
        return $this->getPluginData('romaji');
    }

    /**
     * Get furigana if data exists.
     *
     * @throws PluginNotFoundException
     *
     * @return static
     */
    public function furigana()
    {
        return $this->getPluginData('furigana');
    }

    /**
     * Convert items to hiragana.
     *
     * @return static
     */
    public function toHiragana()
    {
        return $this->convert('hiragana');
    }

    /**
     * Convert items to katakana.
     *
     * @return static
     */
    public function toKatakana()
    {
        return $this->convert('katakana');
    }

    /**
     * Get plugin data from object.
     *
     * @param string $name
     * @return mixed|bool
     */
    public function plugin($name)
    {
        return $this->getPluginData($name, 'self');
    }

    /**
     * Build string for word.
     *
     * @param LimelightWord $item
     * @param string $value
     * @param string|null $glue
     * @return string
     */
    private function buildString($item, $value, $glue)
    {
        if ($this->shouldNotGlue($item, $value, $glue)) {
            return $item->$value;
        }

        return $glue . $item->$value;
    }

    /**
     * Return true if should not prefix with glue.
     *
     * @param LimelightWord $item
     * @param string        $value
     * @param string        $glue
     * @return bool
     */
    private function shouldNotGlue($item, $value, $glue)
    {
        return $value !== 'partOfSpeech' &&
            $item->partOfSpeech === 'symbol' &&
            preg_match('/\\s/', $glue);
    }

    /**
     * Cut first chars if its is glue.
     *
     * @param Collection $collection
     * @param string $glue
     * @return string
     */
    private function cutFirst(Collection $collection, $glue)
    {
        $string = implode('', $collection->all());

        if ($glue) {
            return implode($glue, array_filter(explode($glue, $string)));
        }

        return $string;
    }

    /**
     * Make value singular.
     *
     * @param string $value
     * @return string
     */
    private function makeSingular($value)
    {
        if (substr($value, -1) === 's') {
            return substr($value, 0, -1);
        }

        return $value;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.edgent.analytics.math3.stat.Statistic2 (Apache Edgent (incubating) v1.2.0 API)</title>
<meta name="date" content="2017-12-18">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.edgent.analytics.math3.stat.Statistic2

Packages that use Statistic2

Package
Description

org.apache.edgent.analytics.math3.stat

Statistical algorithms using Apache Commons Math.

Uses of Statistic2 in org.apache.edgent.analytics.math3.stat

Methods in org.apache.edgent.analytics.math3.stat that return Statistic2

Modifier and Type
Method and Description

static Statistic2
Statistic2.valueOf(String name)

Returns the enum constant of this type with the specified name.

static Statistic2[]
Statistic2.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Constructors in org.apache.edgent.analytics.math3.stat with parameters of type Statistic2

Constructor and Description

StorelessStatistic(Statistic2 stat,
                  org.apache.commons.math3.stat.descriptive.StorelessUnivariateStatistic statImpl)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016–2017 The Apache Software Foundation. All rights reserved.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `src/request.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>request.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

use std::io::Read;
use std::mem;
use std::str;
use std::convert::From;
use std::default::Default;
use std::net::TcpStream;
use std::fmt;
use http_muncher::{Parser, ParserHandler};

#[derive(Debug)]
pub struct Request {
    version: (u16, u16),
    pub method: String,
    pub path: String,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
    error: Option<String>,
    is_parsed: bool,
    last_header_field: Option<String>,
    last_header_value: Option<String>,
}

impl Request {
    pub fn is_ok(&self) -> bool {
        self.error.is_none()
    }

    pub fn is_err(&self) -> bool {
        self.error.is_some()
    }

    pub fn error(&self) -> Option<&String> {
        self.error.as_ref()
    }

    pub fn find_header(&self, searched_field: &str) -> Option<&String> {
        self.headers.iter().find(|&&(ref field, _)| field == searched_field).and_then(|&(_, ref value)| Some(value))
    }

    fn is_parsed(&self) -> bool {
        self.is_parsed
    }

    fn record_last_header(&mut self) {
        if self.last_header_field.is_some() && self.last_header_value.is_some() {
            let last_header_field = mem::replace(&mut self.last_header_field, None).unwrap();
            let last_header_value = mem::replace(&mut self.last_header_value, None).unwrap();
            self.headers.push((last_header_field.to_lowercase(), last_header_value));
        }
    }
}

impl Default for Request {
    fn default() -> Self {
        Request {
            version: (1, 1),
            method: String::new(),
            path: String::new(),
            headers: Vec::new(),
            body: Vec::new(),
            error: None,
            is_parsed: false,
            last_header_field: None,
            last_header_value: None,
        }
    }
}

impl<'a> From<&'a mut TcpStream> for Request {
    fn from(mut stream: &mut TcpStream) -> Self {
        let mut request = Request::default();
        let mut parser = Parser::request();
        let mut first_read = true;

        loop {
            if request.is_parsed() { break; }

            let mut buffer = [0; 1024];
            let read_length = stream.read(&mut buffer).unwrap_or(0);

            if read_length == 0 {
                if first_read { request.error = Some("Nothing to read.".to_string()); }
                break;
            }

            first_read = false;

            let parse_length = parser.parse(&mut request, (&buffer).chunks(read_length).nth(0).unwrap());
            if parse_length == 0 || parser.has_error() { break; }
        }

        if parser.has_error() {
            request.error = Some(parser.error().to_string());
        } else {
            request.version = parser.http_version();
            request.method = parser.http_method().to_string();
        }

        request
    }
}

impl ParserHandler for Request {
    fn on_message_begin(&mut self, parser: &mut Parser) -> bool {
        !parser.has_error()
    }

    fn on_url(&mut self, parser: &mut Parser, value: &[u8]) -> bool {
        self.path.push_str(str::from_utf8(value).unwrap());

        !parser.has_error()
    }

    fn on_header_field(&mut self, parser: &mut Parser, value: &[u8]) -> bool {
        self.record_last_header();

        if self.last_header_field.is_none() {
            self.last_header_field = Some(String::new());
        }

        (*self.last_header_field.as_mut().unwrap()).push_str(str::from_utf8(value).unwrap());

        !parser.has_error()
    }

    fn on_header_value(&mut self, parser: &mut Parser, value: &[u8]) -> bool {
        if self.last_header_value.is_none() {
            self.last_header_value = Some(String::new());
        }

        (*self.last_header_value.as_mut().unwrap()).push_str(str::from_utf8(value).unwrap());

        !parser.has_error()
    }

    fn on_headers_complete(&mut self, parser: &mut Parser) -> bool {
        self.record_last_header();

        !parser.has_error()
    }

    fn on_body(&mut self, parser: &mut Parser, value: &[u8]) -> bool {
        self.body.extend(value);

        !parser.has_error()
    }

    fn on_message_complete(&mut self, parser: &mut Parser) -> bool {
        self.is_parsed = true;

        !parser.has_error()
    }
}

impl fmt::Display for Request {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut formatted = String::new();

        formatted.push_str("\r\n");
        formatted.push_str(&self.method);
        formatted.push_str(" ");
        formatted.push_str(&self.path);
        formatted.push_str("\r\n");

        for &(ref key, ref value) in &self.headers {
            formatted.push_str(key);
            formatted.push_str(": ");
            formatted.push_str(value);
            formatted.push_str("\r\n");
        }

        if self.body.len() > 0 {
            formatted.push_str(&String::from_utf8_lossy(&self.body));
            formatted.push_str("\r\n");
        }

        write!(f, "{}", formatted)
    }
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
"""Tests the email scanner summary notifier."""

import json
import unittest.mock as mock
import unittest

from google.cloud.forseti.notifier.notifiers import slack_webhook
from tests.unittest_utils import ForsetiTestCase

class SlackWebhooknotifierTest(ForsetiTestCase):
    """Tests for the slack_webhook_notifier."""

    def test_can_compose_slack_message(self):
        """Test that the slack message is built correctly."""
        violation_data = """
            {
                "role": "READER",
                "email": "",
                "bucket": "test-bucket-world-readable-123",
                "domain": "",
                "entity": "allUsers"
            }
        """

        violation = {'violation_data': json.loads(violation_data),
                     'resource_id': '123',
                     'rule_name': 'Public buckets (allUsers)',
                     'rule_index': 0,
                     'violation_type': 'BUCKET_VIOLATION',
                     'id': 1, 'resource_type': 'bucket'}

        with mock.patch.object(slack_webhook.SlackWebhook, '__init__', lambda x: None):
            slack_notifier = slack_webhook.SlackWebhook()
            slack_notifier.resource = 'buckets_acl_violations'
            actual_output = slack_notifier._compose(violation=violation)

            expected_output = "*type*:\t`buckets_acl_violations`\n*details*:\n\t*bucket*:\t\t`test-bucket-world-readable-123`\n\t*domain*:\t\t`n/a`\n\t*email*:\t\t`n/a`\n\t*entity*:\t\t`allUsers`\n\t*role*:\t\t`READER`"

            self.assertEqual(expected_output.strip(), actual_output.strip())

    def test_dump_slack_output_for_string_returns_string(self):
        violation_data = 'Test violation data string'
        with mock.patch.object(
                slack_webhook.SlackWebhook,
                '__init__',
                lambda x: None):
            slack_notifier = slack_webhook.SlackWebhook()
            actual_output = slack_notifier._dump_slack_output(violation_data)

            expected_output = '\t' + '`' + str(violation_data) + '`\n'

            self.assertEqual(expected_output.strip(), actual_output.strip())

    def test_no_url_no_run_notifier(self):
        """Test that no url for Slack notifier will skip running."""
        with mock.patch.object(slack_webhook.SlackWebhook, '__init__', lambda x: None):
            slack_notifier = slack_webhook.SlackWebhook()
            slack_notifier.notification_config = {}
            slack_notifier._compose = mock.MagicMock()
            slack_notifier.run()

            slack_notifier._compose.assert_not_called()

if __name__ == '__main__':
    unittest.main()


text:
package com.huchiwei.zhihudailynews.common.support.recyclerview;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.huchiwei.zhihudailynews.R;

/**
 * RecyclerView二次封装,统一增加下拉刷新、加载更多事件
 *
 * @author huchiwei
 * @version 1.0.0
 */
public class SimpleRecyclerView extends FrameLayout {

    protected SwipeRefreshLayout mSwipeRefresh;
    protected RecyclerView mRecyclerView;
    protected RecyclerView.LayoutManager mLayoutManager;

    private int mLastVisibleItem;

    public SimpleRecyclerView(Context context) {
        super(context, null);
    }

    public SimpleRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);

        View rootView = LayoutInflater.from(getContext()).inflate(R.layout.widget_recyclerview, this);

        mSwipeRefresh = (SwipeRefreshLayout) rootView.findViewById(R.id.widget_base_swipe_refresh);
        mSwipeRefresh.setColorSchemeResources(R.color.swipe_refresh_red, R.color.swipe_refresh_blue, R.color.swipe_refresh_green);

        mLayoutManager = new LinearLayoutManager(context);

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.widget_base_recycler_view);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);
    }

    /**
     * 设计布局管理器
     * @param layoutManager
     */
    public void setLayoutManager(RecyclerView.LayoutManager layoutManager){
        this.mLayoutManager = layoutManager;
        this.mRecyclerView.setLayoutManager(layoutManager);
    }

    /**
     * 设置Adapter
     * @param adapter
     */
    public void setAdapter(RecyclerView.Adapter adapter){
        this.mRecyclerView.setAdapter(adapter);
    }

    /**
     * 设置点击事件
     * @param itemClickListener
     */
    public void addOnItemTouchListener(RecyclerItemClickListener itemClickListener){
        this.mRecyclerView.addOnItemTouchListener(itemClickListener);
    }

    /**
     * 设置下拉刷新
     * @param onRefreshListener
     */
    public void addOnRefreshListener(SwipeRefreshLayout.OnRefreshListener onRefreshListener){
        this.mSwipeRefresh.setOnRefreshListener(onRefreshListener);
    }

    public void setRefreshing(boolean refreshing){
        this.mSwipeRefresh.setRefreshing(refreshing);
    }

    /**
     * 添加滚动到底加载更多事件监听
     *
     * @param onLoadMoreListener
     */
    public void addOnLoadMoreListener(final OnLoadMoreListener onLoadMoreListener) {
        this.addScrollListener(onLoadMoreListener, null);
    }

    /**
     * 添加滚动事件以及到底加载更多事件监听
     * @param onLoadMoreListener
     * @param onScrollListener
     */
    public void addScrollListener(final OnLoadMoreListener onLoadMoreListener, final OnScrollListener onScrollListener){
        this.mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLastVisibleItem + 1 == mRecyclerView.getAdapter().getItemCount()) {
                    if (onLoadMoreListener != null) {
                        onLoadMoreListener.onLoadMore();
                    }
                    if (mSwipeRefresh.isRefreshing())
                        mSwipeRefresh.setRefreshing(false);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if(mLayoutManager instanceof LinearLayoutManager)
                    mLastVisibleItem = ((LinearLayoutManager)mLayoutManager).findLastVisibleItemPosition();

                if(null != onScrollListener)
                    onScrollListener.onScrolled();
            }
        });
    }

    public RecyclerView getRecyclerView(){
        return this.mRecyclerView;
    }

    public SwipeRefreshLayout getSwipeRefresh() {
        return mSwipeRefresh;
    }

    public RecyclerView.LayoutManager getLayoutManager() {
        return mLayoutManager;
    }

    // =====================================================================
    // OnLoadMoreListener ==================================================
    public interface OnLoadMoreListener{
        void onLoadMore();
    }

    public interface OnScrollListener{
        void onScrolled();
    }
}


text:
<!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><?php echo $title; ?> : <?php echo $settings['site_name']; ?></title>
<link href="css/960.css" rel="stylesheet" type="text/css" media="all" />
<link href="css/master.css" rel="stylesheet" type="text/css" media="all" />

<link rel="stylesheet" href="jquery-treeview/jquery.treeview.css" type="text/css" />

<meta http-equiv='expires' content='-1' />
<meta http-equiv= 'pragma' content='no-cache' />
<meta name='robots' content='all' />

<?php echo $settings['site_name']; ?>

				<form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="68kb.com/user_guide/" />Search User Guide  <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" /> <input type="submit" class="submit" name="sa" value="Go" /></form>

					<a href="<?php echo site_url(); ?>">68KB Home  ›
					User Guide Home  ›  <?php echo $title; ?>

<?php echo $title; ?>

				<?php echo $description; ?>

				 Collapse All
				 Expand All
				Toggle All

			<?php echo $navigation; ?>

Powered by 68 Knowledge Base  ·  Top of Page


text:
namespace GPS {

    /// Die Klasse Waypoint verwaltet Wegpunkte.
    class Waypoint : public GeoCoord {
    protected:
        /// Zeitstempel (wann der Wegpunkt aufgezeichnet wurde).
        Timestamp _Timestamp;

        /// Horizontal Dilusion of Precision
        DoubleValue _HDOP;

        /// Vertical Dilusion of Precision
        DoubleValue _VDOP;

        /// Position Dilusion of Precision
        DoubleValue _PDOP;

        /// Global Dilusion of Precision
        DoubleValue _GDOP;

        /// Magnetic variation (in degrees) at the point
        DoubleValue _MagneticVariation;

        /// Name des Wegpunkts. Sollte möglichst kurz sein.
        std::string _Name;

        /// (Optionaler) Kommentar zum Wegpunkt. Darf beliebig lange sein.
        std::string _Comment;

        /// (Optionale) Beschreibung des Wegpunkts. Darf etwas länger sein als der Name.
        std::string _Description;

        /// (Optionaler) Link zu einer Webseite, die mehr Informationen über den Wegpunkt enthält.
        std::string _Link;

        /// (Optionale) Informationen zur Herkunft des Wegpunkts, zum Beispiel "Garmin GPSmap 60 CSx"
        std::string _Src;

        /// Fix: "none", "2d", "3d", "dgps" oder "pps".
        std::string _Fix;

        /// Typ.
        std::string _Type;

        DoubleValue _AgeOfDGPSData;

        IntValue _DGPSStationId;

        /// Anzahl der Satelliten, die zum Fix beigetragen haben.
        UnsignedIntValue _SatCount;

        /// Höhe (in Metern) des Geoids (Normal Null) über dem WGS84-Ellipsoid (aus NMEA-GGA-Satz).
        DoubleValue _GeoidHeight;

        /// Geschwindigkeit in km/h.
        double _Speed;

        /// Geschwindigkeit in min/km.
        double _Pace;

        /// Kurs in °.
        DoubleValue _Course;

    public:
        /// Konstruktor.
        Waypoint(void);

        /// Konstruktor.
        /// @param lon Längengrad
        /// @param lat Breitengrad
        Waypoint(double lon, double lat);

        /// Konstruktor.
        /// @param lon Längengrad
        /// @param lat Breitengrad
        /// @param ele Höhe üNN in Metern
        /// @param timestamp Zeitstempel
        Waypoint(double lon, double lat, DoubleValue ele, Timestamp timestamp);

        /// Einen Wegpunkt durch Interpolation zweier anderer erzeugen.
        /// @param wpt1 Wegpunkt 1
        /// @param wpt2 Wegpunkt 2
        /// @return Interpolierter Wegpunkt
        static Waypoint interpolated(const Waypoint& wpt1, const Waypoint& wpt2);

        /// Zeitstempel zurückgeben.
        /// @return Zeitstempel
        /// @see _Timestamp
        inline const Timestamp& timestamp(void) const { return _Timestamp; }

        /// Horizontal Dilusion of Precision (2D) zurückliefern.
        /// @return HDOP
        /// @see _HDOP
        inline const DoubleValue& HDOP(void) const { return _HDOP; }

        /// Vertical Dilusion of Precision (1D) zurückliefern.
        /// @return VDOP
        /// @see _VDOP
        inline const DoubleValue& VDOP(void) const { return _VDOP; }

        /// Position Dilusion of Precision (3D) zurückliefern.
        /// @return PDOP
        /// @see _PDOP
        inline const DoubleValue& PDOP(void) const { return _PDOP; }

        /// Global Dilusion of Precision (4D) zurückliefern.
        /// @return GDOP
        /// @see _GDOP
        inline const DoubleValue& GDOP(void) const { return _GDOP; }

        /// Magnetische Abweichung zurückliefern.
        /// @return Magnetische Abweichung in Grad (0.0 < x < 360.0)
        /// @see _MagneticVariation
        inline const DoubleValue& MagneticVariation(void) const { return _MagneticVariation; }

        /// Den Namen des Wegpunkts zurückliefern.
        /// @return Name des Wegpunkts
        /// @see _Name
        inline std::string name(void) const { return _Name; }

        /// Die Beschreibung des Wegpunkts zurückliefern.
        /// @return Kurzbeschreibung des Wegpunkts
        /// @see _Description
        inline std::string description(void) const { return _Description; }

        /// Den Kommentar zum Wegpunkt zurückliefern.
        /// @return Kommentar zum Wegpunkt
        /// @see _Comment
        inline std::string comment(void) const { return _Comment; }

        /// Link auf weiterführende Informationen über den Wegpunkt zurückliefern.
        /// @return Link
        /// @see _Link
        inline std::string link(void) const { return _Link; }

        /// Informationen über die Herkunft des Wegpunkts zurückliefern.
        /// @return Text mit Informationen über die Herkunft des Wegpunkts
        /// @see _Src
        inline std::string source(void) const { return _Src; }

        /// Höhe des Geoids über dem WGS84-Ellipsoid zurückliefern.
        /// @return Geoid-Höhe in Metern
        /// @see _GeoidHeight
        inline const DoubleValue& GeoidHeight(void) const { return _GeoidHeight; }

        /// Type of GPX fix.
        /// @return Type of GPX fix
        inline const std::string& Fix(void) const { return _Fix; }

        /// Type (classification) of the waypoint.
        /// @return Type (classification) of the waypoint
        inline const std::string& Type(void) const { return _Type; }

        /// Number of satellites used to calculate the GPX fix.
        /// @return Number of satellites used to calculate the GPX fix
        inline const UnsignedIntValue& SatCount(void) const { return _SatCount; }

        /// Number of seconds since last DGPS update.
        /// @return Number of seconds since last DGPS update
        inline const DoubleValue& AgeOfDGPSData(void) const { return _AgeOfDGPSData; }

        /// ID of DGPS station used in differential correction.
        /// @return ID of DGPS station used in differential correction
        inline const IntValue& DGPSStationId(void) const { return _DGPSStationId; }

        /// Geschwindigkeit in km/h zurückgeben.
        /// @see _Speed
        /// @return Geschwindigkeit (km/h)
        inline double speed(void) const { return _Speed; }

        /// Geschwindigkeit in min/km zurückgeben.
        /// @see _Pace
        inline double pace(void) const { return _Pace; }

        /// Kurs (°) zurückgeben.
        /// @see _Course
        inline const DoubleValue& course(void) const { return _Course; }

        /// Geschwindigkeit in min/km als String im Format mm:ss zurückgeben.
        /// @see _Pace
        /// @return Geschwindigkeit (min/km) im Format mm:ss
        std::string paceString(void) const;

        /// Horizontal Dilusion of Precision setzen.
        /// @see _HDOP
        inline void setHDOP(double HDOP) { _HDOP = HDOP; }

        /// Vertical Dilusion of Precision setzen.
        /// @see _VDOP
        inline void setVDOP(double VDOP) { _VDOP = VDOP; }

        /// Set position dilusion of precision setzen.
        /// @see _PDOP
        inline void setPDOP(double PDOP) { _PDOP = PDOP; }

        /// Set global dilusion of precision setzen.
        /// @see _GDOP
        inline void setGDOP(double GDOP) { _GDOP = GDOP; }

        /// Namen des Wegpunkts setzen.
        /// @see _Name
        inline void setName(std::string name) { _Name = name; }

        /// Beschreibung des Wegpunkts setzen.
        /// @see _Description
        inline void setDescription(std::string description) { _Description = description; }

        /// Kommentar zum Wegpunkt setzen.
        /// @see _Comment
        inline void setComment(std::string comment) { _Comment = comment; }

        /// Informationen über die Herkunft des Wegpunkts setzen.
        /// @see _Src
        inline void setSource(std::string src) { _Src = src; }

        /// Link auf weiterführende Informationen über den Wegpunkt setzen.
        /// @see _Link
        inline void setLink(std::string link) { _Link = link; }

        /// Höhe des Geoids über dem WGS84-Ellipsoid setzen.
        /// @see _GeoidHeight
        inline void setGeoidHeight(double GeoidHeight) { _GeoidHeight = GeoidHeight; }

        /// Magnetische Abweichung in Grad (0.0 < x < 360.0) setzen.
        /// @see _MagneticVariation
        inline void setMagneticVariation(double MagVar) { _MagneticVariation = MagVar; }

        /// Set type of GPX fix.
        inline void setFix(std::string Fix) { _Fix = Fix; }

        /// Set type (classification) of the waypoint.
        inline void setType(std::string Type) { _Type = Type; }

        /// Set number of satellites used to calculate the GPX fix.
        inline void setSatCount(unsigned int SatCount) { _SatCount = SatCount; }

        /// Set number of seconds since last DGPS update.
        inline void setAgeOfDGPSData(double AgeOfDGPSData) { _AgeOfDGPSData = AgeOfDGPSData; }

        /// Set ID of DGPS station used in differential correction.
        inline void setDGPSStationId(int DGPSStationId) { _DGPSStationId = DGPSStationId; }

        /// Zeitstempel setzen.
        /// @see _Timestamp
        inline void setTimestamp(const Timestamp& timestamp) { _Timestamp = timestamp; }

        /// Setzen der Geschwindigkeit (km/h).
        /// @see _Speed
        inline void setSpeed(double speed) { _Speed = speed; }

        /// Setzen der Geschwindigkeit (min/km).
        /// @see _Pace
        inline void setPace(double pace) { _Pace = pace; }

        /// Setzen des Kurses (°).
        /// @see _Course
        inline void setCourse(double course) { _Course = course; }

    };

};
#endif // __WAYPOINT_H_


text:
<?php

namespace PeskyCMF\Scaffold\Form;

use PeskyCMF\Scaffold\ScaffoldException;
use PeskyCMF\Scaffold\ValueRenderer;

class InputRenderer extends ValueRenderer {
    /** @var array */
    protected $attributes = [];
    /** @var array */
    protected $attributesForCreate = [];
    /** @var array */
    protected $attributesForEdit = [];
    /** @var array|\Closure */
    protected $options = [];
    /** @var array|\Closure */
    protected $optionsForCreate = [];
    /** @var array|\Closure */
    protected $optionsForEdit = [];
    /** @var bool */
    protected $isRequired = false;
    /** @var bool */
    protected $isRequiredForCreate = null;
    /** @var bool */
    protected $isRequiredForEdit = null;
    /** @var string */
    protected $prefix = '';
    /** @var string */
    protected $suffix = '';

    /**
     * @param null $view
     * @param array $attributes
     * @return InputRenderer
     */
    static public function create($view = null, array $attributes = []) {
        return new InputRenderer($view, $attributes);
    }

    /**
     * InputRenderer constructor.
     * @param string $view
     * @param array $attributes
     */
    public function __construct($view = null, array $attributes = []) {
        parent::__construct($view);
        $this->attributes = $attributes;
    }

    /**
     * @return array
     */
    public function getAttributes() {
        $ret = $this->attributes;
        if ($this->isRequired()) {
            $ret['required'] = true;
        }
        if (empty($ret['type']) || !in_array($ret['type'], ['checkbox', 'radio'], true)) {
            unset($ret['value']);
        }
        return $ret;
    }

    /**
     * @param array $attributes
     * @return $this
     * @throws \PeskyCMF\Scaffold\ScaffoldException
     */
    public function setAttributes($attributes) {
        if (array_key_exists('options', $attributes)) {
            $this->setOptions($attributes['options']);
            unset($attributes['options']);
        }
        $this->attributes = $attributes;
        return $this;
    }

    /**
     * @param string $name
     * @param string|bool $value
     * @param bool $owerwrite
     *  - true: overwrites existing attribute value
     *  - false: do nothing if attribute value already set
     * @return $this
     */
    public function addAttribute($name, $value, $owerwrite = true) {
        if ($owerwrite || !array_key_exists($name, $this->attributes)) {
            $this->attributes[$name] = $value;
        }
        return $this;
    }

    /**
     * @param string $name
     * @param string|null|bool $default
     * @return mixed
     */
    public function getAttribute($name, $default = null) {
        return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default;
    }

    /**
     * @param array $excludeAttributes
     * @return array
     */
    public function getAttributesForCreate(array $excludeAttributes = []) {
        $ret = array_merge($this->attributes, $this->attributesForCreate);
        if ($this->isRequiredForCreate()) {
            $ret['required'] = true;
        }
        if (empty($ret['type']) || !in_array($ret['type'], ['checkbox', 'radio'], true)) {
            unset($ret['value']);
        }
        foreach ($excludeAttributes as $attr) {
            unset($ret[$attr]);
        }
        return $ret;
    }

    /**
     * @param array $attributesForCreate
     * @return $this
     */
    public function setAttributesForCreate($attributesForCreate) {
        $this->attributesForCreate = $attributesForCreate;
        return $this;
    }

    /**
     * @param array $excludeAttributes
     * @return array
     */
    public function getAttributesForEdit(array $excludeAttributes = []) {
        $ret = array_merge($this->attributes, $this->attributesForEdit);
        if ($this->isRequiredForEdit()) {
            $ret['required'] = true;
        }
        if (empty($ret['type']) || !in_array($ret['type'], ['checkbox', 'radio'], true)) {
            unset($ret['value']);
        }
        foreach ($excludeAttributes as $attr) {
            unset($ret[$attr]);
        }
        return $ret;
    }

    /**
     * @param array $attributesForEdit
     * @return $this
     */
    public function setAttributesForEdit($attributesForEdit) {
        $this->attributesForEdit = $attributesForEdit;
        return $this;
    }

    /**
     * @return array
     * @throws \InvalidArgumentException
     */
    public function getOptions() {
        return $this->collectOptions($this->options);
    }

    /**
     * @param array|\Closure $options
     * @return mixed
     * @throws \InvalidArgumentException
     */
    private function collectOptions($options) {
        if (!is_string($options) && $options instanceof \Closure) {
            $options = $options();
            if (!is_array($options)) {
                throw new \InvalidArgumentException('$options closure must return an array');
            }
        }
        return $options;
    }

    /**
     * @param array|\Closure $options
     * @return $this
     * @throws ScaffoldException
     */
    public function setOptions($options) {
        if (!is_array($options) && !($options instanceof \Closure)) {
            throw new ScaffoldException('Invalid $options passed to InputRenderer');
        }
        $this->options = $options;
        return $this;
    }

    /**
     * @return bool
     */
    public function areOptionsDifferent() {
        return (
            !empty($this->optionsForCreate)
            || !empty($this->optionsForEdit)
        );
    }

    /**
     * @return array
     * @throws \InvalidArgumentException
     */
    public function getOptionsForCreate() {
        if (empty($this->optionsForCreate)) {
            return $this->getOptions();
        } else {
            return $this->collectOptions($this->optionsForCreate);
        }
    }

    /**
     * @param array|\Closure $options
     * @return $this
     * @throws ScaffoldException
     * @internal param array $optionsForCreate
     */
    public function setOptionsForCreate($options) {
        if (!is_array($options) && !($options instanceof \Closure)) {
            throw new ScaffoldException('Invalid $options passed to InputRenderer');
        }
        $this->optionsForCreate = $options;
        return $this;
    }

    /**
     * @return array
     * @throws \InvalidArgumentException
     */
    public function getOptionsForEdit() {
        if (empty($this->optionsForEdit)) {
            return $this->getOptions();
        } else {
            return $this->collectOptions($this->optionsForEdit);
        }
    }

    /**
     * @param array|\Closure $options
     * @return $this
     * @throws ScaffoldException
     * @internal param array $optionsForEdit
     */
    public function setOptionsForEdit($options) {
        if (!is_array($options) && !($options instanceof \Closure)) {
            throw new ScaffoldException('Invalid $options passed to InputRenderer');
        }
        $this->optionsForEdit = $options;
        return $this;
    }

    /**
     * @return boolean
     */
    public function isRequired() {
        return $this->isRequired;
    }

    /**
     * @return $this
     */
    public function required() {
        $this->setIsRequired(true);
        return $this;
    }

    /**
     * @return $this
     */
    public function notRequired() {
        $this->setIsRequired(false);
        return $this;
    }

    /**
     * @return boolean
     */
    public function isRequiredForCreate() {
        return $this->isRequiredForCreate === null ? $this->isRequired : $this->isRequiredForCreate;
    }

    /**
     * @return $this
     */
    public function requiredForCreate() {
        $this->setIsRequiredForCreate(true);
        return $this;
    }

    /**
     * @return $this
     */
    public function notRequiredForCreate() {
        $this->setIsRequiredForCreate(false);
        return $this;
    }

    /**
     * @return boolean
     */
    public function isRequiredForEdit() {
        return $this->isRequiredForEdit === null ? $this->isRequired : $this->isRequiredForEdit;
    }

    /**
     * @return $this
     */
    public function requiredForEdit() {
        $this->setIsRequiredForEdit(true);
        return $this;
    }

    /**
     * @return $this
     */
    public function notRequiredForEdit() {
        $this->setIsRequiredForEdit(false);
        return $this;
    }

    /**
     * @param $bool
     * @return $this
     */
    public function setIsRequired($bool) {
        $this->isRequired = (bool)$bool;
        if ($this->isRequired) {
            $this->isRequiredForCreate = $this->isRequiredForEdit = true;
        } else if ($this->isRequiredForCreate && $this->isRequiredForEdit) {
            $this->isRequiredForCreate = $this->isRequiredForEdit = false;
        }
        return $this;
    }

    /**
     * @param $bool
     * @return $this
     */
    public function setIsRequiredForCreate($bool) {
        $this->isRequiredForCreate = (bool)$bool;
        $this->isRequired = $this->isRequiredForCreate && $this->isRequiredForEdit;
        return $this;
    }

    /**
     * @param $bool
     * @return $this
     */
    public function setIsRequiredForEdit($bool) {
        $this->isRequiredForEdit = (bool)$bool;
        $this->isRequired = $this->isRequiredForCreate && $this->isRequiredForEdit;
        return $this;
    }

    /**
     * Add prefix text to input (text for left side addon in terms of bootstrap css)
     * Note: not all templates support this feature
     * @param string $string
     * @return $this
     */
    public function setPrefixText($string) {
        $this->prefix = trim((string)$string);
        return $this;
    }

    /**
     * @return bool
     */
    public function hasPrefixText() {
        return !empty($this->prefix);
    }

    /**
     * @return string
     */
    public function getPrefixText() {
        return $this->prefix;
    }

    /**
     * Add suffix text to input (text for right side addon in terms of bootstrap css)
     * Note: not all templates support this feature
     * @param string $string
     * @return $this
     */
    public function setSuffixText($string) {
        $this->suffix = trim((string)$string);
        return $this;
    }

    /**
     * @return bool
     */
    public function hasSuffixText() {
        return !empty($this->suffix);
    }

    /**
     * @return string
     */
    public function getSuffixText() {
        return $this->suffix;
    }

}


text:
import inspect
import os

import pytest

@pytest.fixture(scope="session")
def find_data_file():
    """
    This fixture provides a function that finds a test data file based on the
    filename. It will look in the data subfolder of the calling function's
    directory

    .. code-block:: python
        :caption: example usage

        test_file_path = find_data_file('my_data.json')
    """

    def _helper(filename):
        frame = inspect.stack()[1]
        module = inspect.getmodule(frame[0])
        return os.path.join(
            os.path.dirname(os.path.realpath(module.__file__)),
            "data",
            filename,
        )

    return _helper


text:
require 'test_helper'

class PagesControllerTest < ActionController::TestCase
  def setup
    @controller = HighVoltage::PagesController.new
  end

  test 'should get how_to' do
    get :show, params: { id: 'how_to' }
    assert_response :success
    assert response.body.include? '
How to
'
  end
end


text:
Passes arguments directly to the linker command line without translation.

```lua
linkoptions { "options" }
```

## Parameters ##

`options` is a list of linker flags and options, specific to a particular linker.

### Applies To ###

Project configurations.

### Availability ###

Premake 4.0 or later.

### Examples ###

Use `pkg-config` style configuration when building on Linux with GCC. Build options are always linker specific and should be targeted to a particular toolset.

```lua
filter { "system:linux", "action:gmake" }
  linkoptions { "`wx-config --libs`" }
```


text:
API Documentation
------------------------
This is the API documentation of **RemindMeLater** App.
The API provides endpoints for creatting a reminder and accessing the reminder for updatation and deletion. It can be accessed via a simple API call.

The API defines the following endpoint:

> * https://remind-me-later.herokuapp.com/apis/reminders

API request
-----------

>   curl -H "Content-Type: application/json" -X POST http://remind-me-later.herokuapp.com/apis/reminders -d '{"message":"The message","date":"2016-08-06","time":"17:40:10","phone_number":"+919876543210","email":"example@example.com"}'

The JSON object returned looks like:

    {
        "id": 4,
        "message": "The message",
        "phone_number": "+919876543210",
        "email": "example@example.com",
        "date": "2016-08-06",
        "time": "17:40:10",
        "completed": false
    }

In case of a successful task execution by celery, the `completed` field gets changed to `true`.

    {
        "id": 4,
        "message": "The message",
        "phone_number": "+919876543210",
        "email": "example@example.com",
        "date": "2016-08-06",
        "time": "17:40:10",
        "completed": true
    }


text:
class String
  # Same as +indent+, except it indents the receiver in-place.
  #
  # Returns the indented string, or +nil+ if there was nothing to indent.
  def indent!(amount, indent_string = nil, indent_empty_lines = false)
    indent_string = indent_string || self[/^[ \t]/] || " "
    re = indent_empty_lines ? /^/ : /^(?!$)/
    gsub!(re, indent_string * amount)
  end

  # Indents the lines in the receiver:
  #
  #   <<EOS.indent(2)
  #   def some_method
  #     some_code
  #   end
  #   EOS
  #   # =>
  #     def some_method
  #       some_code
  #     end
  #
  # The second argument, +indent_string+, specifies which indent string to
  # use. The default is +nil+, which tells the method to make a guess by
  # peeking at the first indented line, and fallback to a space if there is
  # none.
  #
  #   "  foo".indent(2)        # => "    foo"
  #   "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
  #   "foo".indent(2, "\t")    # => "\t\tfoo"
  #
  # While +indent_string+ is typically one space or tab, it may be any string.
  #
  # The third argument, +indent_empty_lines+, is a flag that says whether
  # empty lines should be indented. Default is false.
  #
  #   "foo\n\nbar".indent(2)            # => "  foo\n\n  bar"
  #   "foo\n\nbar".indent(2, nil, true) # => "  foo\n  \n  bar"
  #
  def indent(amount, indent_string = nil, indent_empty_lines = false)
    dup.tap { |_| _.indent!(amount, indent_string, indent_empty_lines) }
  end
end


text:
#include "core/svg/SVGUnknownElement.h"

namespace blink {

inline SVGUnknownElement::SVGUnknownElement(const QualifiedName& tagName,
                                            Document& document)
    : SVGElement(tagName, document) {}

DEFINE_ELEMENT_FACTORY_WITH_TAGNAME(SVGUnknownElement)

}  // namespace blink