text:
require 'test_helper'

class ChecklistTestsHelperTest < ActiveSupport::TestCase
  include ChecklistTestsHelper

  # This ensures that the filtering on lookup_codevalues properly limits results
  # to a specific bundle when specified
  def test_lookup_codevalues_multiple_bundles
    @bundle1 = FactoryBot.create(:static_bundle)
    @bundle2 = FactoryBot.create(:bundle)

    assert_empty lookup_codevalues(@bundle1.value_sets.first.oid, @bundle2)
  end

  def test_checklist_test_criteria_attribute
    c1 = {}

    c1['dataElementAttributes'] = [{ 'attribute_name' => 'Test', 'attribute_valueset' => 'vs' }]
    assert_equal 'Test', checklist_test_criteria_attribute(c1, 0)
    assert_equal 'Test:vs', checklist_test_criteria_attribute(c1, 0, include_vs: true)
    assert_equal '', checklist_test_criteria_attribute({}, 0)
    assert_equal '', checklist_test_criteria_attribute(c1, 1)
  end

  def test_available_attributes
    c1 = {}
    c1['dataElementAttributes'] = [{ 'attribute_name' => 'Test' }, { 'attribute_name' => 'id' }]
    assert_equal ['Test'], available_attributes(c1)
    c1['dataElementAttributes'][0]['attribute_valueset'] = 'vs'
    assert_equal ['Test:vs'], available_attributes(c1)
  end
end


text:
/**
 *
 */
/**
 * @author lujijiang
 *
 */
package com.saasxx.framework.dao.orm.hibernate.dialect;

redpajama_set_name: RedPajamaGithub


text:
using namespace process;

using std::map;
using std::string;
using std::vector;

using mesos::slave::ContainerState;

namespace mesos {
namespace internal {
namespace slave {

Try<Launcher*> SubprocessLauncher::create(const Flags& flags)
{
  return new SubprocessLauncher();
}

Future<hashset<ContainerID>> SubprocessLauncher::recover(
    const vector<ContainerState>& states)
{
  foreach (const ContainerState& state, states) {
    const ContainerID& containerId = state.container_id();
    pid_t pid = static_cast<pid_t>(state.pid());

    if (pids.contains_value(pid)) {
      // This should (almost) never occur. There is the possibility
      // that a new executor is launched with the same pid as one that
      // just exited (highly unlikely) and the slave dies after the
      // new executor is launched but before it hears about the
      // termination of the earlier executor (also unlikely).
      // Regardless, the launcher can't do anything sensible so this
      // is considered an error.
      return Failure("Detected duplicate pid " + stringify(pid) +
                     " for container " + stringify(containerId));
    }

    pids.put(containerId, pid);
  }

  return hashset<ContainerID>();
}

Try<pid_t> SubprocessLauncher::fork(
    const ContainerID& containerId,
    const string& path,
    const vector<string>& argv,
    const mesos::slave::ContainerIO& containerIO,
    const flags::FlagsBase* flags,
    const Option<map<string, string>>& environment,
    const Option<int>& enterNamespaces,
    const Option<int>& cloneNamespaces,
    const vector<int_fd>& whitelistFds)
{
  if (enterNamespaces.isSome() && enterNamespaces.get() != 0) {
    return Error("Subprocess launcher does not support entering namespaces");
  }

  if (cloneNamespaces.isSome() && cloneNamespaces.get() != 0) {
    return Error("Subprocess launcher does not support cloning namespaces");
  }

  if (pids.contains(containerId)) {
    return Error("Process has already been forked for container " +
                 stringify(containerId));
  }

  vector<process::Subprocess::ParentHook> parentHooks;

#ifdef __linux__
  // If we are on systemd, then extend the life of the child. Any
  // grandchildren's lives will also be extended.
  if (systemd::enabled()) {
    parentHooks.emplace_back(Subprocess::ParentHook(
        &systemd::mesos::extendLifetime));
  }
#elif defined(__WINDOWS__)
  // If we are on Windows, then ensure the child is placed inside a
  // new job object.
  parentHooks.emplace_back(Subprocess::ParentHook::CREATE_JOB());
#endif // __linux__

  vector<Subprocess::ChildHook> childHooks;

#ifndef __WINDOWS__
  childHooks.push_back(Subprocess::ChildHook::SETSID());
#endif // __WINDOWS__

  Try<Subprocess> child = subprocess(
      path,
      argv,
      containerIO.in,
      containerIO.out,
      containerIO.err,
      flags,
      environment,
      None(),
      parentHooks,
      childHooks,
      whitelistFds);

  if (child.isError()) {
    return Error("Failed to fork a child process: " + child.error());
  }

  LOG(INFO) << "Forked child with pid '" << child->pid()
            << "' for container '" << containerId << "'";

  // Store the pid (session id and process group id).
  pids.put(containerId, child->pid());

  return child->pid();
}

// Forward declaration.
Future<Nothing> _destroy(const Future<Option<int>>& future);

Future<Nothing> SubprocessLauncher::destroy(const ContainerID& containerId)
{
  LOG(INFO) << "Asked to destroy container " << containerId;

  if (!pids.contains(containerId)) {
    LOG(WARNING) << "Ignored destroy for unknown container " << containerId;
    return Nothing();
  }

  pid_t pid = pids.get(containerId).get();

  // Kill all processes in the session and process group.
  os::killtree(pid, SIGKILL, true, true);

  pids.erase(containerId);

  // The child process may not have been waited on yet so we'll delay
  // completing destroy until we're sure it has been reaped.
  return process::reap(pid)
    .then(lambda::bind(&_destroy, lambda::_1));
}

Future<Nothing> _destroy(const Future<Option<int>>& future)
{
  if (future.isReady()) {
    return Nothing();
  } else {
    return Failure("Failed to kill all processes: " +
                   (future.isFailed() ? future.failure() : "unknown error"));
  }
}

Future<ContainerStatus> SubprocessLauncher::status(
    const ContainerID& containerId)
{
  if (!pids.contains(containerId)) {
    return Failure("Container does not exist!");
  }

  ContainerStatus status;
  status.set_executor_pid(pids[containerId]);

  return status;
}

} // namespace slave {
} // namespace internal {
} // namespace mesos {


text:
<!doctype html>

<title>Trivial mandatory constraint in getUserMedia</title>
<link rel="author" title="Dominique Hazael-Massieux" href="mailto:dom@w3.org"/>
<link rel="help" href="http://dev.w3.org/2011/webrtc/editor/getusermedia.html#widl-NavigatorUserMedia-getUserMedia-void-MediaStreamConstraints-constraints-NavigatorUserMediaSuccessCallback-successCallback-NavigatorUserMediaErrorCallback-errorCallback">
<link rel="help" href="http://dev.w3.org/2011/webrtc/editor/getusermedia.html#idl-def-NavigatorUserMediaError">

When prompted, accept to share your video stream.

Description

This test checks that setting an impossible mandatory
constraint (width >=1G) in getUserMedia works


text:
/**
 * Render the body of a popout
 */

import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';

var PopoutBody = React.createClass({
	displayName: 'PopoutBody',
	propTypes: {
		children: React.PropTypes.node.isRequired,
		className: React.PropTypes.string,
		scrollable: React.PropTypes.bool,
	},
	render () {
		const className = classnames('Popout__body', {
			'Popout__scrollable-area': this.props.scrollable,
		}, this.props.className);
		const props = blacklist(this.props, 'className', 'scrollable');

		return (
			<div className={className} {...props} />
		);
	},
});

module.exports = PopoutBody;


text:
// See the COPYRIGHT file for copyright and license information
package org.znerd.logdoc;

import org.znerd.util.Preconditions;
import org.znerd.util.log.LogLevel;

/**
 * Abstract base class for LogBridge implementations. Implements the level property by storing it internally.
 */
public abstract class AbstractLogBridge implements LogBridge {

    private LogLevel level = LogLevel.DEBUG;

    @Override
    public void setLevel(LogLevel level) {
        Preconditions.checkArgument(level == null, "level == null");
        this.level = level;
    }

    @Override
    public LogLevel getLevel() {
        return level;
    }
}


text:
lich - Lua IRC Connector and Helper is an IRC bot framework written in Lua

## Overview

LICH is a Lua based IRC bot that can handle plugins written in LUA. It
aims to ship a few standard plugins, as an example on how to roll your
own.

## Configuration

The configuration file format is YAML and looks like this:

```yaml
servers:
  freenode:
    nick: lich
    url: irc.freenode.net
    plugins:
      - name: lua.package.path.to.plugin
        config:
          entry1: first config option
          entry2: second config option
      - name: another.lua.plugin
        config:
          entry1: first config option
    channels:
      - name: "##mychannel"
```

## Requirements

* Lua 5.3
* My own fork of [LuaIRC](https://github.com/n0la/LuaIRC)
* [lyaml](https://github.com/gvvaughan/lyaml)
* [cliargs](https://github.com/amireh/lua_cliargs)

## Running

Create a new configuration file and start it like so:

```shell
lua53 lua-lich -c myconfigfile.yaml
```

## Plugins

### Writing new ones

Your plugin file needs to provide a table that is capable of spawning
a new plugin when calling ```new```. The new function will receive the
config sub tree, as table, as its first parameter. This table should,
for the sake of simplicity, inherit from the ```plugin``` object
provided by lich:

```lua
local plugin = require('lich.plugin')
local myplugin = plugin:new()

function myplugin:new(config)
    local neu = plugin:new(config)

    setmetatable(neu, self)
    self.__index = self

    return neu
end

return myplugin
```

And here is the interface:

```lua
-- Must return the fully qualified package name of the plugin
function myplugin:name()
end

-- Is called when connection to a server has been established
--   server  .. Reference to the LuaIRC server table
function myplugin:onconnect(server)
end

-- Is called when a message has been received
--   server  .. Reference to the LuaIRC server table
--   user    .. Reference to the LuaIRC user table
--   channel .. Channel name
--   msg     .. Message as string
function myplugin:onmessage(server, user, channel, msg)
end

-- Is called when the message parses as command (starts with a #).
-- This method is called after onmessage().
--   server  .. Reference to the LuaIRC server table
--   user    .. Reference to the LuaIRC user table
--   channel .. Channel name
--   cmd     .. Reference to the LICH command object
function myplugin:oncommand(server, user, channel, cmd)
end
```

### freenode_registrar

The plugin ```freenode_registrar``` allows you to register the bot
with the nickserv as provided by freenode:

```
plugins:
  - name: lich.plugin.freenode_registrar
    password: supersecret
```


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>License — Flask-NewProject 0.2.1 documentation</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="prev" title="Tutorial" href="tutorial.html" />

  <link rel="stylesheet" href="_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

License¶

The MIT License (MIT)

Copyright (c) 2016 Raymond

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Related Topics

Documentation overview

Previous: Tutorial

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2017, Raymond Williams.

      |
      Powered by Sphinx 1.5.1
      & Alabaster 0.7.9

      |
      Page source


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>Paused Property</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            IrrKlang.NET

ISound.Paused Property

 returns if the sound is paused

        [Visual Basic]

Public Property Paused As Boolean

        [C#]

public bool Paused {get; set;}

See Also

        ISound Class | IrrKlang Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="Paused property">
        </param>
        <param name="Keyword" value="Paused property, ISound class">
        </param>
        <param name="Keyword" value="ISound.Paused property">
        </param>
      </object>

          The irrKlang Sound Engine Documentation © 2003-2010 by Nikolaus Gebhardt.


text:
using System;
using Microsoft.AspNet.SignalR.Messaging;
using Moq;
using Xunit;

namespace Microsoft.AspNet.SignalR.Tests.Server
{
    public class TopicFacts
    {
        [Fact]
        public void TopicStateCreated()
        {
            var topic = new Topic(100, TimeSpan.Zero);
            Assert.Equal(TopicState.NoSubscriptions, topic.State);
        }

        [Fact]
        public void TopicStateHasSubscriptions()
        {
            var topic = new Topic(100, TimeSpan.Zero);

            topic.AddSubscription(new Mock<ISubscription>().Object);

            Assert.Equal(TopicState.HasSubscriptions, topic.State);
        }

        [Fact]
        public void TopicStateHasSubscriptionsIfMoreThanOne()
        {
            var topic = new Topic(100, TimeSpan.Zero);
            var sub1 = new Mock<ISubscription>();
            sub1.Setup(m => m.Identity).Returns("1");

            topic.AddSubscription(new Mock<ISubscription>().Object);
            topic.AddSubscription(sub1.Object);
            topic.RemoveSubscription(sub1.Object);

            Assert.Equal(TopicState.HasSubscriptions, topic.State);
        }

        [Fact]
        public void TopicStateNoSubscriptions()
        {
            var topic = new Topic(100, TimeSpan.Zero);
            var mock = new Mock<ISubscription>();
            mock.Setup(m => m.Identity).Returns("1");

            topic.AddSubscription(mock.Object);
            topic.RemoveSubscription(mock.Object);

            Assert.Equal(TopicState.NoSubscriptions, topic.State);
        }
    }
}


text:
import re

from requests import Session
from xml.etree import ElementTree as ET

class SfdcSession(Session):
    _DEFAULT_API_VERSION = "37.0"
    _LOGIN_URL = "https://{instance}.salesforce.com"
    _SOAP_API_BASE_URI = "/services/Soap/c/{version}"
    _XML_NAMESPACES = {
        'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
        'mt': 'http://soap.sforce.com/2006/04/metadata',
        'd': 'urn:enterprise.soap.sforce.com'
    }

    _LOGIN_TMPL = \
        """<env:Envelope xmlns:xsd='http://www.w3.org/2001/XMLSchema'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
    <env:Body>
        <sf:login xmlns:sf='urn:enterprise.soap.sforce.com'>
            <sf:username>{username}</sf:username>
            <sf:password>{password}</sf:password>
        </sf:login>
    </env:Body>
</env:Envelope>"""

    def __init__(
            self, username=None, password=None, token=None,
            is_sandbox=False, api_version=_DEFAULT_API_VERSION,
            **kwargs):
        super(SfdcSession, self).__init__()
        self._username = username
        self._password = password
        self._token = token
        self._is_sandbox = is_sandbox
        self._api_version = api_version
        self._session_id = kwargs.get("session_id", None)
        self._instance = kwargs.get("instance", None)

    def login(self):
        url = self.construct_url(self.get_soap_api_uri())
        headers = {'Content-Type': 'text/xml', 'SOAPAction': 'login'}
        password = self._password
        if self._token:
            password += self._token
        data = SfdcSession._LOGIN_TMPL.format(**{'username': self._username, 'password': password})
        r = self.post(url, headers=headers, data=data)
        root = ET.fromstring(r.text)
        if root.find('soapenv:Body/soapenv:Fault', SfdcSession._XML_NAMESPACES):
            raise Exception("Could not log in. Code: %s Message: %s" % (
                root.find('soapenv:Body/soapenv:Fault/faultcode', SfdcSession._XML_NAMESPACES).text,
                root.find('soapenv:Body/soapenv:Fault/faultstring', SfdcSession._XML_NAMESPACES).text))
        self._session_id = root.find('soapenv:Body/d:loginResponse/d:result/d:sessionId', SfdcSession._XML_NAMESPACES).text
        server_url = root.find('soapenv:Body/d:loginResponse/d:result/d:serverUrl', SfdcSession._XML_NAMESPACES).text
        self._instance = re.search("""https://(.*).salesforce.com/.*""", server_url).group(1)

    def get_server_url(self):
        if not self._instance:
            return SfdcSession._LOGIN_URL.format(**{'instance': 'test' if self._is_sandbox else 'login'})
        return SfdcSession._LOGIN_URL.format(**{'instance': self._instance})

    def get_soap_api_uri(self):
        return SfdcSession._SOAP_API_BASE_URI.format(**{'version': self._api_version})

    def construct_url(self, uri):
        return "%s%s" % (self.get_server_url(), uri)

    def get_api_version(self):
        return self._api_version

    def get_session_id(self):
        return self._session_id

    def is_connected(self):
        return True if self._instance else False


text:
<?php

namespace Todstoychev\TableSorter;

/**
 * Simple table sorter.
 *
 * @author Todor Todorov <todstoychev@gmail.com>
 * @package Todstoychev\TableSorter
 */
class TableSorter
{
    /**
     * Table column sorter
     *
     * @param string $action "Controller@action"
     * @param string $columnName Column name to show in the table
     * @param string $param Parameter to order(database table column name)
     * @param string $order Order direction
     * @param integer $limit Items per page
     *
     * @return string
     */
    public static function sort($action, $columnName, $param, $order = 'asc', $limit = 10)
    {
        return view(
            'todstoychev.table-sorter.sort',
            [
                'action' => $action,
                'columnName' => $columnName,
                'param' => $param,
                'order' => static::defineOrder($order),
                'limit' => $limit,
            ]
        );
    }

    /**
     * Table column sorter
     *
     * @param string $action "Controller@action"
     * @param string $columnName Column name
     * @param string $search Search keyword
     * @param string $param Parameter to order(databese table column name)
     * @param string $order Order direction
     *
     * @return string
     */
    public static function sortSearch($action, $columnName, $search = null, $param = null, $order = 'asc')
    {
        return view(
            'todstoychev.table-sorter.sort_search',
            [
                'action' => $action,
                'columnName' => $columnName,
                'search' => $search,
                'param' => $param,
                'order' => static::defineOrder($order)
            ]
        );
    }

    /**
     * Define order direction string
     *
     * @param string $order
     *
     * @return string
     */
    protected static function defineOrder($order)
    {
        If ($order == 'asc') {
            return 'desc';
        }

        return 'asc';
    }
}


text:
/***************************************************************************
 * This file (claypellet_extra.h) is included as-is in claypellet.h when it
 * gets generated.
 ***************************************************************************/

void call_main(AppContextRef app_ctx);
void deinit_claypellet(void);
int init_claypellet(char *path);

struct ClayResourceHandle {
    uint32_t file_id;
};

struct ClayFontHandle {
    bool custom;
    uint32_t file_id;
};

struct ClayGraphicsContext {
    uint32_t gctx_id;
};


text:
import java.io.*;
import java.util.*;

import com.pdfjet.*;

/**
 *  Example_18.java
 *
 */
class Example_18 {

    public Example_18() throws Exception {

        PDF pdf = new PDF(
                new BufferedOutputStream(
                        new FileOutputStream("Example_18.pdf")));

        Page page = new Page(pdf, Letter.PORTRAIT);

        page.setPenWidth(5.0f);
        page.setBrushColor(0x353638);

        float x1 = 300f;
        float y1 = 300f;
        float r1 = 50f;
        float r2 = 50f;

        List<Point> path = new ArrayList<Point>();

        List<Point> segment1 = Path.getCurvePoints(x1, y1, r1, r2, Segment.CLOCKWISE_00_03);
        List<Point> segment2 = Path.getCurvePoints(x1, y1, r1, r2, Segment.CLOCKWISE_03_06);
        List<Point> segment3 = Path.getCurvePoints(x1, y1, r1, r2, Segment.CLOCKWISE_06_09);

        path.addAll(segment1);

        segment2.remove(0);
        path.addAll(segment2);

        segment3.remove(0);
        path.addAll(segment3);

        // page.drawPath(path, Operation.FILL);
        page.drawPath(path, Operation.STROKE);

        List<Point> segment4 = Path.getCurvePoints(x1, y1, r1, r2, Segment.CLOCKWISE_09_12);
        page.setPenWidth(15f);
        page.setPenColor(Color.red);
        page.drawPath(segment4, Operation.STROKE);

        pdf.close();
    }

    public static void main(String[] args) {
        try {
            new Example_18();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

}   // End of Example_18.java


text:
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from libunity.djinni

#pragma once

#include <cstdint>
#include <string>
#include <utility>

struct WitnessFundingResultRecord final {
    /** "success" on success, otherwise an error message */
    std::string status;
    /** txid of the funding transaction, empty on failure */
    std::string txid;
    /** fee charged by the transaction, 0 on failure */
    int64_t fee;

    WitnessFundingResultRecord(std::string status_,
                               std::string txid_,
                               int64_t fee_)
    : status(std::move(status_))
    , txid(std::move(txid_))
    , fee(std::move(fee_))
    {}
};


text:
<!doctype html>

    <title>Code coverage report for app/util/validator.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      All files / app/util validator.js

        59.09%
        Statements
        13/22

        0%
        Branches
        0/10

        18.18%
        Functions
        2/11

        100%
        Lines
        11/11

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

16x
2x
2x
2x
2x
2x
2x
2x
2x
2x
2x

/*
 *  Enter JavaScript-style regular expression to display
 *  https://regexper.com/
 *  Write and test regular expression
 *  http://www.regexr.com/
 */

// var is ={
//   types : ["Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument"]
// };
// for(var i = 0, c; c = is.types[i ++ ]; ){
//   is[c] = (function(type){
//     return function(obj){
//       return Object.prototype.toString.call(obj) == "[object " + type + "]";
//     }
//     )(c);
// }

const isUndefined = (value) => typeof value === 'undefined'
const isNumber = (value) => Object.prototype.toString.call(value) === '[object Number]'
const isString = (value) => Object.prototype.toString.call(value) === '[object String]'
const isStringEmpty = (value) => Object.prototype.toString.call(value) === '[object String]' && value === ''
const isStringNotEmpty = (value) => Object.prototype.toString.call(value) === '[object String]' && value !== ''
const isFunction = (value) => Object.prototype.toString.call(value) === '[object Function]'
const isArray = (value) => Object.prototype.toString.call(value) === '[object Array]'
const isArrayEmpty = (value) => Array.isArray(value) && value.length === 0
const isArrayNotEmpty = (value) => Array.isArray(value) && value.length > 0
const isObject = (value) => Object.prototype.toString.call(value) === '[object Object]'
const isObjectEmpty = (value) => Object.prototype.isPrototypeOf(value) && Object.keys(value).length === 0

export {
  isUndefined,
  isNumber,
  isFunction,
  isArray, isArrayEmpty,
  isString, isStringEmpty, isStringNotEmpty,
  isObject, isObjectEmpty, isArrayNotEmpty
}

  Code coverage
  generated by istanbul at Mon Sep 18 2017 17:44:25 GMT+0800 (CST)


text:
.. _dojox/timing:

============
dojox.timing
============

:Authors: Tom Trenka, Wolfram Kriesing, Jonathan Bond-Caron, Pete Higgins

DojoX Timing is a project that deals with any kind of advanced use of timing
constructs.

dojox.timing.Timer
==================

The central object of ``dojox.timing`` is ``dojox.timing.Timer``
(included by default), is a simple object that fires a callback
on each tick of the timer, as well as when starting or stopping it.
The interval of each tick is settable, but the default is 1
second--useful for driving something such as a clock.

.. js ::

  dojo.require('dojox.timing');
  t = new dojox.timing.Timer(1000);
  t.onTick = function(){
   console.info("One second elapsed");
  }
  t.onStart = function(){
   console.info("Starting timer");
  }
  t.start();

Other elements
==============

dojox.timing.Streamer is an object designed to facilitate streaming/buffer-type
scenarios; it takes an input and an output function, will execute the output
function onTick, and run the input function when the internal buffer gets
beneath a certain threshold of items.  This can be useful for something timed--
such as updating a data plot at every N interval, and getting new data from
a source when there's less than X data points in the internal buffer (think
real-time data updating).

dojox.timing.Sequencer is an object, similar to Streamer, that will allow you
to set up a set of functions to be executed in a specific order, at specific
intervals.

The DojoX Timing ThreadPool is a port from the original implementation in the
f(m) library.  It allows a user to feed a set of callback functions (wrapped
in a Thread constructor) to a pool for background processing.


text:
package org.apache.airavata.workflow.tracking.samples.simple_listener;

import org.apache.airavata.workflow.tracking.client.NotificationType;
import org.apache.xmlbeans.XmlObject;

public class CallbackHandler implements org.apache.airavata.workflow.tracking.client.Callback {

    /*
     * This methods will be callbacked when the particular subcription receives a notification (non-Javadoc)
     *
     * @see org.apache.airavata.workflow.tracking.client.Callback#deliverMessage(java.lang.String,
     * org.apache.airavata.workflow.tracking.client.NotificationType, org.apache.xmlbeans.XmlObject)
     */
    public void deliverMessage(String topic, NotificationType notificationType, XmlObject messageObj) {
        System.out.println("Received a notification of type[" + notificationType + "] for the topic[" + topic);
        System.out.println("The notification message is:");
        System.out.println(messageObj.toString());
    }

}


text:
static const QString SSDP_DESCRIPTION =	"<?xml version=\"1.0\"?>"
										"<root xmlns=\"urn:schemas-upnp-org:device-1-0\">"
											"<specVersion>"
												"<major>1</major>"
												"<minor>0</minor>"
											"</specVersion>"
											"<URLBase>%1</URLBase>"
											"<device>"
												"<deviceType>urn:schemas-upnp-org:device:Basic:1</deviceType>"
												"<friendlyName>%2</friendlyName>"
												"<manufacturer>Hyperion Open Source Ambient Lighting</manufacturer>"
												"<manufacturerURL>https://www.hyperion-project.org</manufacturerURL>"
												"<modelDescription>Hyperion Open Source Ambient Light</modelDescription>"
												"<modelName>Hyperion</modelName>"
												"<modelNumber>%3</modelNumber>"
												"<modelURL>https://www.hyperion-project.org</modelURL>"
												"<serialNumber>%4</serialNumber>"
												"<UDN>uuid:%4</UDN>"
												"<ports>"
													"<jsonServer>%5</jsonServer>"
													"<sslServer>%6</sslServer>"
													"<protoBuffer>%7</protoBuffer>"
													"<flatBuffer>%8</flatBuffer>"
												"</ports>"
												"<presentationURL>index.html</presentationURL>"
												"<iconList>"
													"<icon>"
														"<mimetype>image/png</mimetype>"
														"<height>100</height>"
														"<width>100</width>"
														"<depth>32</depth>"
														"<url>img/hyperion/ssdp_icon.png</url>"
													"</icon>"
												"</iconList>"
											"</device>"
										"</root>";


text:
+++
Title = "Michal El Fartas"
#Twitter = ""
image = "michal-el-fartas.png"
type = "speaker"
linktitle = "michal-el-fartas"
+++

#### Speaker

DevOps Engineer at Egnyte. Working with Kubernetes for last 3 years. Fan of cloud native solutions and tight cooperation with developers.
Privately I enjoy scuba diving, motorcycles and craft beer.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_view_login_activity"
    style="@style/MatchParent"
    android:orientation="vertical"
    android:layout_marginLeft="@dimen/padding_start"
    >

    <TextView
        style="@style/MatchWidth"
        android:paddingTop="@dimen/padding_actionbar"
        android:text="@string/text_welcoming_message"
        />

    <EditText
        android:id="@+id/user_name"
        style="@style/MatchWidth"
        android:paddingTop="@dimen/padding_top"
        android:hint="@string/hint_user_name"
        android:textSize="16sp"
        android:singleLine="true"
        />

    <EditText
        android:id="@+id/chat_room_name"
        style="@style/MatchWidth"
        android:paddingTop="@dimen/padding_top"
        android:hint="@string/hint_chat_room_name"
        android:textSize="16sp"
        android:singleLine="true"
        />

</LinearLayout>


text:
@import MethodPoolA;

@interface D
- (void)method5:(D*)obj;
@end

// expected-note@Inputs/MethodPoolA.h:7{{using}}
// expected-note@Inputs/MethodPoolB.h:12{{also found}}

void testMethod1(id object) {
  [object method1];
}

void testMethod2(id object) {
  [object method2:1];
}

void testMethod4(id object) {
  [object method4]; // expected-warning{{instance method '-method4' not found (return type defaults to 'id')}}
}

void testMethod5(id object, D* d) {
  [object method5:d];
}

@import MethodPoolB;

void testMethod1Again(id object) {
  [object method1];
}

void testMethod2Again(id object) {
  [object method2:1]; // expected-warning{{multiple methods named 'method2:' found}}
}

void testMethod3(id object) {
  [object method3]; // expected-warning{{instance method '-method3' not found (return type defaults to 'id')}}
}

@import MethodPoolB.Sub;

void testMethod3Again(id object) {
  char *str = [object method3]; // okay: only found in MethodPoolB.Sub
}

void testMethod6(id object) {
  [object method6];
}

@import MethodPoolA.Sub;

void testMethod3AgainAgain(id object) {
  [object method3]; // expected-warning{{multiple methods named 'method3' found}}
  // expected-note@Inputs/MethodPoolBSub.h:2{{using}}
  // expected-note@Inputs/MethodPoolASub.h:2{{also found}}
}

void testMethod4Again(id object) {
  [object method4];
}

void testMethod5Again(id object, D* d) {
  [object method5:d];
}


text:
"use strict";

module.exports = require('./msteams');


text:
"""
Start a Suplemon instance in the current window
"""

import sys

try:
    import argparse
except:
    # Python < 2.7
    argparse = False

from .main import App, __version__

def main():
    """Handle CLI invocation"""
    # Parse our CLI arguments
    config_file = None
    if argparse:
        parser = argparse.ArgumentParser(description="Console text editor with multi cursor support")
        parser.add_argument("filenames", metavar="filename", type=str, nargs="*", help="Files to load into Suplemon")
        parser.add_argument("--version", action="version", version=__version__)
        parser.add_argument("--config", type=str, help="Configuration file path.")
        args = parser.parse_args()
        filenames = args.filenames
        config_file = args.config
    else:
        # Python < 2.7 fallback
        filenames = sys.argv[1:]

    # Generate and start our application
    app = App(filenames=filenames, config_file=config_file)
    if app.init():
        app.run()

    # Output log info
    if app.debug:
        for logger_handler in app.logger.handlers:
            logger_handler.close()

if __name__ == "__main__":
    main()


text:
param (
    [string]$filename = $(throw "-filename is required."),
    [string]$outputFolder = $(throw "-outputFolder is required."),
    [string]$sevenZip = ""
)
if("" -ne $sevenZip){
    $cmd = '& ' + $sevenZip + 'x ' + $filename + ' ' + $outputFolder + ' -aoa'
    Invoke-Expression $cmd
}else{
    $shell_app=new-object -com shell.application
    $zip_file = $shell_app.namespace((Get-Location).Path + "\$filename")
    $destination = $shell_app.namespace((Get-Location).Path + "\$outputFolder")
    $destination.Copyhere($zip_file.items());
}


text:
package main

import (
  "github.com/gin-gonic/gin"
)
func createotpHandler(c *gin.Context)  {
  var request struct {
    FirstName string `json:"firstname"`
    EmailID string `json:"email_id"`
    Mobileno    string `json:"mobileno"`
    RequestType string `json:"request_type"`
  }
  if c.Bind(&request) == nil {
    if request.RequestType == "n" {
      if exists := checkExists(request.Mobileno); !exists {
        otp := generate_otp(request.Mobileno)
        if req := createOTP(request.Mobileno, otp); req {
          go sendOtpThroughMail(request.EmailID, otp)
          // go sendOtpThroughSms(request.FirstName, request.Mobileno, otp)
          go expireOTPchannel(request.Mobileno)
        }
        c.JSON(200, gin.H{
          "status" : "success",
          "is_exists" : exists,
          "valid_request" : true,
        })
      }else{
        c.JSON(200, gin.H{
          "status" : "success",
          "is_exists" : true,
          "valid_request" : true,
        })
      }
    }else{
      c.JSON(200, gin.H{
        "status" : "failed",
        "is_exists" : false,
        "valid_request" : false,
      })
    }
  }
}


text:
using SimpleNets

#Simulate a data set

#Apply single layer perceptron learning to the dataset
p = SimpleNets.SingleLayerPerceptron.Perceptron(3)

steps = 50
batch_size = 10

all_x = Array(Array{Float64}, steps*batch_size)
all_x[ 1:steps*batch_size ]  = [rand(3) for k in 1:(steps*batch_size)]

all_y = Array(Float64, steps*batch_size)
counter=1
for example in all_x
  all_y[counter] = convert(Float64, (3*example[1]+example[2] - example[3] -2 ) > 1 )
  counter += 1
end

all_goodness = Array(Float64, steps)
step=1
while step < steps

  #Train the model
  counter = (step-1)*batch_size + 1
  for example in all_x[((step-1)*batch_size+1):(step*batch_size)]
    SimpleNets.SingleLayerPerceptron.train!(p, example, all_y[counter] )
    counter += 1
  end

  #Validate the score, print a goodness metric
  scores = Array(Float64, steps*batch_size)
  counter = 1
  for example in all_x
    scores[counter] = SimpleNets.SingleLayerPerceptron.score(p, example)
    counter += 1
  end

  #hopefully the goodness gets better as you train.
  goodness = SimpleNets.AssociationMeasures.kendallstau(all_y, scores)
  all_goodness[steps] = goodness
  println(string("step: " , step, " goodness: ", goodness))

  step += 1

end


text:
export * from './side-panel.component';
export * from './side-panel-close.directive';
export * from './side-panel.module';


text:
from __future__ import unicode_literals

import django.contrib.postgres.fields.jsonb
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('funding_stripe', '0005_auto_20201118_0954'),
    ]

    operations = [
        migrations.AlterField(
            model_name='stripepayoutaccount',
            name='eventually_due',
            field=django.contrib.postgres.fields.jsonb.JSONField(default=[], null=True),
        ),
    ]


text:
package be.joengenduvel.java.verifiers;

import java.lang.reflect.Field;

public class WrongToStringImplementationException extends RuntimeException {

    private static final String OBJECT_NULL_MESSAGE = "Cannot verify '%s' because the object provided was null.";
    private static final String FIELD_NOT_ACCESSABLE = "Could not verify field '%s' in class '%s' because %s";
    private static final String VALUE_NOT_FOUND = "Could not find the value '%s' of '%s' in '%s' for class '%s'";
    private static final String FIELD_NOT_FOUND = "Could not find field '%s' in '%s' for class '%s'";
    private static final String CLASS_NAME_NOT_FOUND = "Could not find the class name '%s' in %s for class %s";

    private WrongToStringImplementationException(String message, Throwable cause) {
        super(message, cause);
    }

    public WrongToStringImplementationException(String message) {
        this(message, null);
    }

    public static WrongToStringImplementationException forObjectNull(Class<?> classToVerify) {
        return new WrongToStringImplementationException(String.format(OBJECT_NULL_MESSAGE, classToVerify));
    }

    public static WrongToStringImplementationException forIllegalAccess(Field field, Class<?> classToVerify, IllegalAccessException cause) {
        return new WrongToStringImplementationException(String.format(FIELD_NOT_ACCESSABLE, field.getName(), classToVerify, cause.getMessage()), cause);
    }

    public static WrongToStringImplementationException forValueNotFound(Field field, String fieldValue, Class<?> classToVerify, String toString) {
        return new WrongToStringImplementationException(String.format(VALUE_NOT_FOUND, fieldValue, field.getName(), toString, classToVerify));
    }

    public static WrongToStringImplementationException forFieldNameNotFound(Field field, Class<?> classToVerify, String toString) {
        return new WrongToStringImplementationException(String.format(FIELD_NOT_FOUND, field.getName(), toString, classToVerify));
    }

    public static WrongToStringImplementationException forClassNameNotFound(String toString, String classToVerifyName, Class<?> classToVerify) {
        return new WrongToStringImplementationException(String.format(CLASS_NAME_NOT_FOUND, classToVerifyName, toString, classToVerify));
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.compute.model;

/**
 * A policy that specifies how requests intended for the route's backends are shadowed to a separate
 * mirrored backend service. The load balancer doesn't wait for responses from the shadow service.
 * Before sending traffic to the shadow service, the host or authority header is suffixed with
 * -shadow.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class RequestMirrorPolicy extends com.google.api.client.json.GenericJson {

  /**
   * The full or partial URL to the BackendService resource being mirrored to. The backend service
   * configured for a mirroring policy must reference backends that are of the same type as the
   * original backend service matched in the URL map. Serverless NEG backends are not currently
   * supported as a mirrored backend service.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String backendService;

  /**
   * The full or partial URL to the BackendService resource being mirrored to. The backend service
   * configured for a mirroring policy must reference backends that are of the same type as the
   * original backend service matched in the URL map. Serverless NEG backends are not currently
   * supported as a mirrored backend service.
   * @return value or {@code null} for none
   */
  public java.lang.String getBackendService() {
    return backendService;
  }

  /**
   * The full or partial URL to the BackendService resource being mirrored to. The backend service
   * configured for a mirroring policy must reference backends that are of the same type as the
   * original backend service matched in the URL map. Serverless NEG backends are not currently
   * supported as a mirrored backend service.
   * @param backendService backendService or {@code null} for none
   */
  public RequestMirrorPolicy setBackendService(java.lang.String backendService) {
    this.backendService = backendService;
    return this;
  }

  @Override
  public RequestMirrorPolicy set(String fieldName, Object value) {
    return (RequestMirrorPolicy) super.set(fieldName, value);
  }

  @Override
  public RequestMirrorPolicy clone() {
    return (RequestMirrorPolicy) super.clone();
  }

}


text:
package br.ufrn.Myeclone.apifb;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author augusto
 */
public class TokenException extends Exception{
    public String getMessage(){
        return "Permissão Negada";
    }
}


text:
from __future__ import unicode_literals

import json
from itertools import groupby, islice
from operator import itemgetter

import re
import time

from six import iteritems, text_type
from six.moves import map

from docker.errors import NotFound

from ..utils import format_image_tag

KWARG_MAP = {
    'timeout': 'time',
    'extra_hosts': 'add-host',
    'nocache': 'no-cache',
    'volumes': 'volume',
    'options': 'opt',
    'ipv4_address': 'ip',
    'ipv6_address': 'ip6',
    'links': 'link',
    'aliases': 'alias',
    'mem_limit': 'memory',
    'mem_reservation': 'memory-reservation',
    'memswap_limit': 'memory-swap',
}
NONE_TAG = '<none>'
_arg_format = '--{0}={1}'.format
_mapping_format = '--{0}={1}:{2}'.format
_get_image_id = itemgetter(2)

def _quoted_arg_format(key, value):
    return '--{0}="{1}"'.format(key, text_type(value).replace('"', '\\"'))

_CONTAINER_FIELDS = ['ID', 'Image', 'CreatedAt', 'Status', 'Names', 'Command', 'Ports']
CONTAINER_FORMAT_ARG = _quoted_arg_format('format', '||'.join('{{{{.{0}}}}}'.format(f) for f in _CONTAINER_FIELDS))
JSON_FORMAT_ARG = _quoted_arg_format('format', '{{json .}}')

def _summarize_tags(image_id, image_lines):
    first_line = next(image_lines)
    image_tags = [format_image_tag(first_line)] if first_line[0] != NONE_TAG else []
    image_tags.extend(format_image_tag(image) for image in image_lines if image[0] != NONE_TAG)
    return {
        'Id': image_id,
        'RepoTags': image_tags or NONE_TAG,
        'ParentId': '',
        'Created': 0,
        'VirtualSize': 0,
        'Size': 0,
    }

CREATED_AT_PATTERN = re.compile(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) [+-]\d{4} \w+')
PRIVATE_PORT_PATTERN = re.compile(r'(?P<PrivatePort>\d+(-\d+)?)\/(?P<Type>\w+)')
PUBLIC_PORT_PATTERN = re.compile(r'(?P<IP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(?P<PublicPort>\d+(-\d+)?)->'
                                 r'(?P<PrivatePort>\d+(-\d+)?)\/(?P<Type>\w+)')

def _port_info(ports):
    for port in ports.split(', '):
        public_match = PUBLIC_PORT_PATTERN.match(port)
        if public_match:
            yield public_match.groupdict()
        else:
            private_match = PRIVATE_PORT_PATTERN.match(port)
            if private_match:
                yield private_match.groupdict()

def _container_info(line):
    items = line.split('||')
    return {
        'Id': items[0],
        'Image': items[1],
        'Created': time.mktime(tuple(map(int, CREATED_AT_PATTERN.match(items[2]).groups())) + (0, 0, 0)),
        'Status': items[3],
        'Names': ['/{0}'.format(name) for name in items[4].split(',')],
        'Command': items[5].strip('"'),
        'Ports': list(_port_info(items[6])),
    }

def _network_info(line):
    items = line.split()
    return {
        'Id': items[0],
        'Name': items[1],
        'Driver': items[2],
        'Scope': items[3],
    }

def _volume_info(line):
    items = line.split()
    return {
        'Driver': items[0],
        'Name': items[1],
    }

def _first_key_value(d, *keys):
    for k in keys:
        v = d.get(k)
        if v:
            return k, v
    return None, None

def _transform_kwargs(ka):
    for key, value in iteritems(ka):
        cmd_arg = KWARG_MAP.get(key, key.replace('_', '-'))
        if isinstance(value, list):
            for vi in value:
                yield _quoted_arg_format(cmd_arg, vi)
        elif isinstance(value, dict):
            for ki, vi in iteritems(value):
                yield _mapping_format(cmd_arg, ki, vi)
        elif value is None:
            pass
        elif isinstance(value, bool):
            yield _arg_format(cmd_arg, 'true' if value else 'false')
        else:
            yield _quoted_arg_format(cmd_arg, value)

def _transform_create_kwargs(ka):
    network = ka.pop('network_mode', None)
    network_disabled = ka.pop('network_disabled', False)
    network_config = ka.pop('networking_config', None)
    environment = ka.pop('environment', None)
    binds = ka.pop('binds', None)
    volumes = ka.pop('volumes', None) if binds else None
    expose = ka.pop('ports', None)
    port_bindings = ka.pop('port_bindings', None)
    links = ka.pop('links', None)
    restart_policy = ka.pop('restart_policy', None)
    healthcheck = ka.pop('healthcheck', None)

    for arg in _transform_kwargs(ka):
        yield arg

    if environment:
        if isinstance(environment, list):
            for vi in environment:
                yield _quoted_arg_format('env', vi)
        elif isinstance(environment, dict):
            for ki, vi in iteritems(environment):
                yield _quoted_arg_format('env', '{0}={1}'.format(ki, vi))

    if network_disabled:
        yield _arg_format('net', 'none')
    elif network:
        yield _arg_format('net', network)
    elif network_config:
        ep_config = network_config['EndpointsConfig']
        network_name = tuple(ep_config.keys())[0]
        nc = ep_config[network_name]
        yield _arg_format('net', network_name)
        for a in nc.get('Aliases') or ():
            yield _arg_format('network-alias', a)
        for nc_link in nc.get('Links') or ():
            yield _arg_format('link', nc_link)
        ipam = nc.get('IPAMConfig')
        if ipam:
            ip4 = ipam.get('IPv4Address')
            if ip4:
                yield _arg_format('ip', ip4)
            ip6 = ipam.get('IPv6Address')
            if ip6:
                yield _arg_format('ip6', ip6)
            for ll_ip in ipam.get('LinkLocalIPs') or ():
                yield _arg_format('link-local-ip', ll_ip)

    if volumes:
        bind_keys = {}
        for b in binds:
            b_key = b.split(':')[1]
            bind_keys[b_key] = b
        for v in volumes:
            v_bind = bind_keys.get(v)
            if v_bind:
                yield _quoted_arg_format('volume', v_bind)
            else:
                yield _quoted_arg_format('volume', v)

    if expose:
        for e in expose:
            if isinstance(e, tuple):
                port, proto = e
                yield _arg_format('expose', '{0}/{1}'.format(port, proto))
            else:
                port, proto = e, None
                yield _arg_format('expose', e)
            if not port_bindings:
                continue
            if proto:
                pkey = '{0}/{1}'.format(port, proto)
                pbind = port_bindings.get(pkey)
            else:
                pkey, pbind = _first_key_value(port_bindings, port, text_type(port), '{0}/tcp'.format(port))
            if pbind:
                for pbi in pbind:
                    if isinstance(pbi, tuple):
                        b_ip, b_port = pbi
                        yield _arg_format('publish', '{0}:{1}:{2}'.format(b_ip, b_port, pkey))
                    else:
                        yield _arg_format('publish', '{0}:{1}'.format(pbi, pkey))

    if links:
        for link in links:
            yield _mapping_format('link', *link)

    if restart_policy:
        policy_name = restart_policy.get('Name')
        if policy_name:
            max_retries = restart_policy.get('MaximumRetryCount')
            if max_retries is not None:
                yield _mapping_format('restart-policy', policy_name, max_retries)
            else:
                yield _arg_format('restart-policy', policy_name)

    if healthcheck:
        cmd = healthcheck.get('test')
        if cmd and isinstance(cmd, list) and cmd[0] in ('CMD', 'CMD-SHELL') and len(cmd) > 1:
            yield _quoted_arg_format('healthcheck-cmd', ' '.join(cmd[1:]))
            for hc_key in ('interval', 'timeout', 'retries', 'start_period'):
                hc_val = healthcheck.get(hc_key)
                if hc_val:
                    yield _arg_format('healthcheck-{0}'.format(hc_key.replace('_', '-')), hc_val)

def parse_containers_output(out):
    """
    Parses the output of the Docker CLI 'docker ps --format="{{ID}}||{{Image}}||..."' and returns it in the format
    similar to the Docker API.

    :param out: CLI output.
    :type out: unicode | str
    :return: Parsed result.
    :rtype: list[dict]
    """
    return [
        _container_info(line) for line in out.splitlines() or ()
    ]

def parse_networks_output(out):
    """
    Parses the output of the Docker CLI 'docker network ls' and returns it in the format similar to the Docker API.

    :param out: CLI output.
    :type out: unicode | str
    :return: Parsed result.
    :rtype: list[dict]
    """
    if not out:
        return []
    line_iter = islice(out.splitlines(), 1, None)  # Skip header
    return list(map(_network_info, line_iter))

def parse_volumes_output(out):
    """
    Parses the output of the Docker CLI 'docker volume ls' and returns it in the format similar to the Docker API.

    :param out: CLI output.
    :type out: unicode | str
    :return: Parsed result.
    :rtype: list[dict]
    """
    if not out:
        return []
    line_iter = islice(out.splitlines(), 1, None)  # Skip header
    return list(map(_volume_info, line_iter))

def parse_inspect_output(out, item_type):
    """
    Parses the output of the Docker CLI 'docker inspect <container>' or 'docker network inspect <network>'. Essentially
    just returns the parsed JSON string, like the Docker API does.

    :param out: CLI output.
    :type out: unicode | str
    :param item_type: Type of the item that has been inspected (e.g. 'container').
    :type item_type: unicode | str
    :return: Parsed result.
    :rtype: dict
    """
    parsed = json.loads(out, encoding='utf-8')
    if parsed:
        return parsed[0]
    raise NotFound("{0} not found.".format(item_type.title()), None)

def parse_images_output(out):
    """
    Parses the output of the Docker CLI 'docker images'. Note this is currently incomplete and only returns the ids and
    tags of images, as the Docker CLI heavily modifies the output for human readability. The parent image id is also
    not available on the CLI, so a full API compatibility is not possible.

    :param out: CLI output.
    :type out: unicode | str
    :return: Parsed result.
    :rtype: list[dict]
    """
    line_iter = islice(out.splitlines(), 1, None)  # Skip header
    split_lines = (line.split() for line in line_iter)
    return [
        _summarize_tags(image_id, image_lines)
        for image_id, image_lines in groupby(sorted(split_lines, key=_get_image_id), key=_get_image_id)
    ]

def parse_version_output(out):
    """
    Parses the output of 'docker version --format="{{json .}}"'. Essentially just returns the parsed JSON string,
    like the Docker API does. Fields are slightly different however.

    :param out: CLI output.
    :type out: unicode | str
    :return: Parsed result.
    :rtype: dict
    """
    parsed = json.loads(out, encoding='utf-8')
    if parsed:
        return parsed.get('Client', {})
    return {}

def parse_info_output(out):
    """
    Parses the output of 'docker info --format="{{json .}}"'. Essentially just returns the parsed JSON string,
    like the Docker API does. Fields are slightly different however.

    :param out: CLI output.
    :type out: unicode | str
    :return: Parsed result.
    :rtype: dict
    """
    return json.loads(out, encoding='utf-8')

def parse_top_output(out):
    """
    Parses the output of the Docker CLI 'docker top <container>'. Note that if 'ps' output columns are modified and
    'args' (for the command) is anywhere but in the last column, this will not parse correctly. However, the Docker API
    produces wrong output in this case as well.
    Returns a dictionary with entries 'Titles' and 'Processes' just like the Docker API would.

    :param out: CLI output.
    :type out: unicode | str
    :return: Parsed result.
    :rtype: dict
    """
    lines = out.splitlines()
    line_iter = iter(lines)
    header_line = next(line_iter)
    titles = header_line.split()
    max_split = len(titles) - 1
    return {
        'Titles': titles,
        'Processes': [line.split(None, max_split) for line in line_iter],
    }

def _extend_or_append(cmd_args, exec_cmd):
    if exec_cmd:
        if isinstance(exec_cmd, list):
            cmd_args.extend(exec_cmd)
        else:
            cmd_args.append(exec_cmd)

class DockerCommandLineOutput(object):
    cmd_map = {
        'create_container': 'create',
        'containers': 'ps',
        'exec_create': 'exec',
        'exec_start': None,
        'inspect_container': 'inspect',
        'remove_container': 'rm',
        'remove_image': 'rmi',
        'create_network': 'network create',
        'networks': 'network ls',
        'inspect_network': 'network inspect',
        'remove_network': 'network rm',
        'create_volume': 'volume create',
        'volumes': 'volume ls',
        'inspect_volume': 'volume inspect',
        'remove_volume': 'volume rm',
        'connect_container_to_network': 'network connect',
        'disconnect_container_from_network': 'network disconnect',
    }

    def __init__(self, cmd_prefix=None, default_bin='docker', cmd_args=None):
        super(DockerCommandLineOutput, self).__init__()
        if cmd_prefix:
            cmd = '{0} {1}'.format(cmd_prefix, default_bin)
        else:
            cmd = default_bin
        if cmd_args:
            self._cmd = '{0} {1}'.format(cmd, ' '.join(cmd_args))
        else:
            self._cmd = cmd

    def get_cmd(self, c_cmd, *args, **kwargs):
        cli_cmd = self.cmd_map.get(c_cmd, c_cmd)
        if not cli_cmd:
            return None
        cmd_prefix = None
        cmd_args = [cli_cmd]
        if cli_cmd == 'create':
            p_args = [kwargs.pop('image')]
            _extend_or_append(p_args, kwargs.pop('command', None))
            cmd_args.extend(_transform_create_kwargs(kwargs))
        elif cli_cmd == 'exec':
            p_args = [kwargs.pop('container')]
            _extend_or_append(p_args, kwargs.pop('cmd'))
            cmd_args.append('--detach')
            cmd_args.extend(_transform_kwargs(kwargs))
        elif cli_cmd in ('network create', 'volume create', 'volume rm'):
            p_args = [kwargs.pop('name')]
            cmd_args.extend(_transform_kwargs(kwargs))
        elif cli_cmd.startswith('network') and (cli_cmd.endswith('connect') or cli_cmd.endswith('rm')):
            p_args = [kwargs.pop('net_id')]
            if cli_cmd.endswith('connect'):
                p_args.append(kwargs.pop('container'))
            cmd_args.extend(_transform_kwargs(kwargs))
        else:
            if cli_cmd in ('images', 'ps', 'network ls'):
                cmd_args.append('--no-trunc')
                if cli_cmd == 'ps':
                    cmd_args.append(CONTAINER_FORMAT_ARG)
                p_args = None
            elif cli_cmd in ('version', 'info'):
                cmd_args.append(JSON_FORMAT_ARG)
                p_args = None
            else:
                if cli_cmd == 'wait':
                    timeout = kwargs.pop('timeout', None)
                    if timeout:
                        cmd_prefix = 'timeout -s INT {0} '.format(timeout)
                container_arg = kwargs.pop('container', None)
                if container_arg:
                    p_args = [container_arg]
                else:
                    p_args = None
            cmd_args.extend(_transform_kwargs(kwargs))
        if p_args:
            cmd_args.extend(p_args)
        cmd_args.extend(args)
        return '{0}{1} {2}'.format(cmd_prefix or '', self._cmd, ' '.join(cmd_args))


text:
export const getOauthEndPoint = () => {
  return window.location.href.indexOf('localhost') === -1 ? 'https://fluxo-api.herokuapp.com/oauth/login' : 'http://localhost:3100/oauth/login'
}

export const getApiEndPoint = (isDemo) => {
  const apiEndPoint = window.location.href.indexOf('localhost') === -1 ? 'https://fluxo-api.herokuapp.com' : 'http://localhost:3100'
  return isDemo ? `${apiEndPoint}/fake` : `${apiEndPoint}/api`
}

export const getRedirectUrl = (signInUrl) => {
  return `${signInUrl}/?action=${window.location.href}`
}


text:
"use strict";
importPackage(java.io);
importPackage(java.lang);
//
// the pupose of the stdio class is to provide console I/O support
// in the rhino JavaScript environment using native JavaScript types.
// rhino I/O support is provided via Java library calls, which
// return Java types and not JavaScript types.
//
var stdio = (

function stdioImplementation()
{
    var stdin = new BufferedReader(new InputStreamReader(System['in']));

    var stdio = {};

    stdio.readLine = function()
    {
        return new String( stdin.readLine() );
    };
    stdio.readChar = function()
    {
        return String.fromCharCode( stdin.read() );
    };
    // readToken() will read the input stream one character at a time.
    // it will ignore whitespace, then read non-whitespace characters
    // until a whitespace is read. the function returns the sequence
    // of non-whitespace characters read from stdin.
    stdio.readToken = function()
    {
        var token = '';
        var intValue = stdin.read(); // read a single character
        while( intValue <= 32 )
            intValue = stdin.read();
        while( intValue > 32 )
        {
            token += String.fromCharCode( intValue );
            intValue = stdin.read();
        }
        return token;
    };
    stdio.print = function( s )
    {
        System.out.print( s );
    };
    stdio.printLine = function( s )
    {
        System.out.printLine( s );
    };
    return stdio;
}

) ();

var statementRules =
[
    {
        regex: /^([A-Z0-9]+) NOT ON FLOOR ([1-5])$/,
        matchCount: 3,
        createRule: function( matches, nameSet )
        {
            var name = matches[1];
            var floor = matches[2];
            nameSet[ name ] = true;
            return function( floorList, nameHash )
            {
                return( floorList[ floor ] !== name );
            };
        }
    },
    {
        regex: /^([A-Z0-9]+) NOT ON FLOORS ([1-5]) OR ([1-5])$/,
        matchCount: 4,
        createRule: function( matches, nameSet )
        {
            var name = matches[1];
            var floorX = matches[2];
            var floorY = matches[3];
            nameSet[ name ] = true;
            return function( floorList, nameHash )
            {
                return( floorList[ floorX ] !== name && floorList[ floorY ] !== name );
            };
        }
    },
    {
        regex: /^([A-Z0-9]+) ON HIGHER FLOOR THAN ([A-Z0-9]+)$/,
        matchCount: 3,
        createRule: function( matches, nameSet )
        {
            var nameA = matches[1];
            var nameB = matches[2];
            nameSet[ nameA ] = true;
            nameSet[ nameB ] = true;
            return function( floorList, nameHash )
            {
                return( nameHash[ nameA ] > nameHash[ nameB ] );
            };
        }
    },
    {
        regex: /^([A-Z0-9]+) ON ADJACENT FLOOR TO ([A-Z0-9]+)$/,
        matchCount: 3,
        createRule: function( matches, nameSet )
        {
            var nameA = matches[1];
            var nameB = matches[2];
            nameSet[ nameA ] = true;
            nameSet[ nameB ] = true;
            return function( floorList, nameHash )
            {
                var difference = nameHash[ nameA ] - nameHash[ nameB ];
                return( difference * difference === 1 );
            };
        }
    },
    {
        regex: /^([A-Z0-9]+) NOT ON ADJACENT FLOOR TO ([A-Z0-9]+)$/,
        matchCount: 3,
        createRule: function( matches, nameSet )
        {
            var nameA = matches[1];
            var nameB = matches[2];
            nameSet[ nameA ] = true;
            nameSet[ nameB ] = true;
            return function( floorList, nameHash )
            {
                var difference = nameHash[ nameA ] - nameHash[ nameB ];
                return( difference * difference > 1 );
            };
        }
    }
];
function RuleFactory( promptText, nameSet )
{
    var statement = '';
    var rule = null;
    while( rule === null )
    {
        statement = stdio.readLine();
        for( var i=0; i<statementRules.length && rule === null; i++ )
        {
            var matches = statement.match( statementRules[i].regex );
            if( matches && matches.length === statementRules[i].matchCount )
                rule = statementRules[i].createRule( matches, nameSet );
        }
    }
    return rule;
};
function RuleSet()
{
    this._rule_text = "NO RULES";
    this._rule_list = [ ];
    this._name_set = {};
};
RuleSet.prototype.getNameSet = function()
{
    return this._name_set;
};
RuleSet.prototype.read = function()
{
    for( var i=0; i<6; i++ )
        this._rule_list.push( RuleFactory( "rule " + (i+1), this._name_set ) );
};
RuleSet.prototype.validate = function( floorList, nameHash )
{
    for( var i=0; i<6; i++ )
    {
        var rule = this._rule_list[i];
        if( !rule( floorList, nameHash ) )
            return false;
    }
    return true;
};
function FloorSolution( rules )
{
    this._ruleSet = rules;
    this._result = '';
    this._permutations = [ ];
    this._solve();
};
FloorSolution.prototype._solve = function()
{
    var numSolutions = 0;
    // convert the nameSet (associative array) to a normal array
    nameSet = this._ruleSet.getNameSet();
    var nameList = [ ];
    for( var name in nameSet )
        nameList.push( name );
    permutation = [ ];
    this._permutations = this._makePermutations( nameList );
    for( var i=0; i<this._permutations.length; i++ )
    {
        permutation = this._permutations[i];
        permutation.unshift( "ZERO" ); // there is no floor zero
        var hash = {};
        for( var j=0; j<permutation.length; j++ )
        {
            hash[ permutation[j] ] = j;
        }
        if( this._ruleSet.validate( permutation, hash ) )
        {
            this._solution = permutation;
            ++numSolutions;
        }
    }
    print( "" + numSolutions + " solutions" );
};
FloorSolution.prototype._makePermutations = function( nameList )
{
    var permutations = [ ];
    if( nameList.length === 1 )
    {
        permutations = [ nameList ];
    }
    else
    {
        for( var i=0; i<nameList.length; i++ )
        {
            var name = nameList[i];
            var subList = [ ];
            for( var j=0; j<nameList.length; j++ )
            {
                if( i !== j )
                    subList.push( nameList[j] );
            }
            var subPermutations = this._makePermutations( subList );
            for( var j=0; j<subPermutations.length; j++ )
            {
                subPermutations[j].push( name );
                permutations.push( subPermutations[j] );
            }
        }
    }
    return permutations;
};
FloorSolution.prototype.printPermutations = function()
{
    for( var i=0; i<this._permutations.length; i++ )
    {
        var text = '';
        var permutation = this._permutations[i];
        for( var j=0; j<permutation.length; j++ )
        {
            text += permutation[j] + " ";
        }
        print( text );
    }
};
FloorSolution.prototype.print = function()
{
    for( var i=this._solution.length-1; i>0; i-- )
        print( "" + i + " " + this._solution[i] );
};
function main()
{
    var rules = new RuleSet();
    rules.read();
    var solution = new FloorSolution( rules );
    solution.print();
};
main();


text:
using UnityEditor;

public class Foo : UnityEditor.AssetModificationProcessor
{
    public int On{caret}StatusUpdated(int value)
    {
        return 42;
    }
}


text:
FROM node:5

# bundle app's source code inside the Docker image
COPY . /src

# for using bower install
RUN echo '{ "allow_root": true }' > /src/.bowerrc
# move into the src directory where all the source code files live. install all npm dependencies
RUN cd /src; npm install;

#map port 8080 to the docker daemon.
#REMEMBER TO CHANGE THIS IF THE PORT IS CHANGED IN server.js
EXPOSE 8080

# define the command line code that will start up the server. src는 root directory로 보면 된다
CMD ["node", "/src/server.js"]


text:
@interface NSStringRestKitSpec : RKSpec

@end

@implementation NSStringRestKitSpec

- (void)testShouldAppendQueryParameters {
    NSString *resourcePath = @"/controller/objects/";
    NSDictionary *queryParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                 @"ascend", @"sortOrder",
                                 @"name", @"groupBy",nil];
    NSString *resultingPath = [resourcePath stringByAppendingQueryParameters:queryParams];
    assertThat(resultingPath, isNot(equalTo(nil)));
    NSString *expectedPath1 = @"/controller/objects/?sortOrder=ascend&groupBy=name";
    NSString *expectedPath2 = @"/controller/objects/?groupBy=name&sortOrder=ascend";
    BOOL isValidPath = ( [resultingPath isEqualToString:expectedPath1] ||
                         [resultingPath isEqualToString:expectedPath2] );
    assertThatBool(isValidPath, is(equalToBool(YES)));
}

- (void)testShouldInterpolateObjects {
    RKObjectMapperSpecModel *person = [[[RKObjectMapperSpecModel alloc] init] autorelease];
    person.name = @"CuddleGuts";
    person.age  = [NSNumber numberWithInt:6];
    NSString *interpolatedPath = [@"/people/:name/:age" interpolateWithObject:person];
    assertThat(interpolatedPath, isNot(equalTo(nil)));
    NSString *expectedPath = @"/people/CuddleGuts/6";
    assertThat(interpolatedPath, is(equalTo(expectedPath)));
}

- (void)testShouldInterpolateObjectsWithDeprecatedParentheses {
    RKObjectMapperSpecModel *person = [[[RKObjectMapperSpecModel alloc] init] autorelease];
    person.name = @"CuddleGuts";
    person.age  = [NSNumber numberWithInt:6];
    NSString *interpolatedPath = [@"/people/(name)/(age)" interpolateWithObject:person];
    assertThat(interpolatedPath, isNot(equalTo(nil)));
    NSString *expectedPath = @"/people/CuddleGuts/6";
    assertThat(interpolatedPath, is(equalTo(expectedPath)));
}

- (void)testShouldParseQueryParameters {
    NSString *resourcePath = @"/views/thing/?keyA=valA&keyB=valB";
    NSDictionary *queryParams = [resourcePath queryParametersUsingEncoding:NSASCIIStringEncoding];
    assertThat(queryParams, isNot(empty()));
    assertThat(queryParams, hasCountOf(2));
    assertThat(queryParams, hasEntries(@"keyA", @"valA", @"keyB", @"valB", nil));
}

- (void)testShouldReturnTheMIMETypeForAPath {
    NSString *MIMEType = [@"/path/to/file.xml" MIMETypeForPathExtension];
    assertThat(MIMEType, is(equalTo(@"application/xml")));
}

- (void)itShouldKnowIfTheReceiverContainsAnIPAddress {
    assertThatBool([@"127.0.0.1" isIPAddress], equalToBool(YES));
    assertThatBool([@"173.45.234.197" isIPAddress], equalToBool(YES));
    assertThatBool([@"google.com" isIPAddress], equalToBool(NO));
    assertThatBool([@"just some random text" isIPAddress], equalToBool(NO));
}

@end


text:
import test from 'tape';
import customSelect from './../';

var actual;
var expected;

test('Check the library instances using an HTMLElement', assert => {
  var select = document.createElement('select');
  select.setAttribute('id', 'mySelect');
  document.body.appendChild(select);
  actual = customSelect(document.getElementById('mySelect'));
  assert.deepEqual(actual.length, 1,
    'should return 1');
  assert.end();
});

test('Check the library instances using an HTMLCollection', assert => {
  document.body.innerHTML = '';
  const select1 = document.createElement('select');
  const select2 = document.createElement('select');
  document.body.appendChild(select1);
  document.body.appendChild(select2);
  actual = customSelect(document.getElementsByTagName('select'));
  assert.deepEqual(actual.length, 2,
    'should return 2');
  assert.end();
});

test('Check the library instances using a NodeList', assert => {
  document.body.innerHTML = '';
  const select1 = document.createElement('select');
  const select2 = document.createElement('select');
  document.body.appendChild(select1);
  document.body.appendChild(select2);
  actual = customSelect(document.querySelectorAll('select'));
  assert.deepEqual(actual.length, 2,
    'should return 2');
  assert.end();
});

test('Check the library instances using a selector', assert => {
  document.body.innerHTML = '';
  const select = document.createElement('select');
  document.body.appendChild(select);
  actual = customSelect('select');
  assert.deepEqual(actual.length, 1,
    'should return 1');
  assert.end();
});

test('Check the library instances using a not select selector', assert => {
  document.body.innerHTML = '';
  actual = customSelect('body');
  assert.deepEqual(actual.length, 0,
    'should return 0');
  assert.end();
});

test('Check the library instances using an array of selects', assert => {
  document.body.innerHTML = '';
  const select1 = document.createElement('select');
  const select2 = document.createElement('select');
  document.body.appendChild(select1);
  document.body.appendChild(select2);
  actual = customSelect([select1, select2]);
  assert.deepEqual(actual.length, 2,
    'should return 2');
  assert.end();
});

test('Check the library instances using a mixed array', assert => {
  document.body.innerHTML = '';
  const select = document.createElement('select');
  document.body.appendChild(select);
  actual = customSelect([1, select]);
  assert.deepEqual(actual.length, 1,
    'should return 1');
  assert.end();
});

test('Check the library instances with 10000 selects', assert => {
  document.body.innerHTML = '';
  for (let i = 0; i < 10000; ++i) {
    document.body.appendChild(document.createElement('select'));
  }
  actual = customSelect('select');
  assert.deepEqual(actual.length, 10000,
    'should return 10000');
  assert.end();
});

test('Checks correlations between the HTMLElements and the public exposed elements', assert => {
  document.body.innerHTML = '';
  const select = document.createElement('select');
  document.body.appendChild(select);
  const myNewCustomSelect = customSelect([select])[0];

  assert.test('... the opener', t => {
    actual = myNewCustomSelect.opener;
    expected = document.body.children[0].children[0];
    t.deepEqual(actual, expected,
      'the two elements should be the same');
    t.end();
  });

  assert.test('... the select', t => {
    actual = myNewCustomSelect.select;
    expected = document.getElementsByTagName('select')[0];
    t.deepEqual(actual, expected,
      'the two elements should be the same');
    t.end();
  });

  assert.test('... the panel', t => {
    actual = document.getElementsByClassName('custom-select-container')[0].customSelect.panel;
    expected = document.body.children[0].querySelector('.custom-select-panel');
    t.deepEqual(actual, expected,
      'the two elements should be the same');
    t.end();
  });

  assert.end();
});


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Redirecting…</title>
  <link rel="canonical" href="/carta-para-uma-velha-amiga/">

  <meta http-equiv="refresh" content="0; url=/carta-para-uma-velha-amiga/">
  <meta name="robots" content="noindex">

Redirecting…

  Click here if you are not redirected.


text:
<?php

namespace Symfony\Component\Ldap\Exception;

/**
 * LdapException is throw if php ldap module is not loaded.
 *
 * @author Charles Sarrazin <charles@sarraz.in>
 */
class DriverNotFoundException extends \RuntimeException implements ExceptionInterface
{
}


text:
<manifest
    package="android.zetterstrom.com.forecast"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true"
        >

    </application>

</manifest>


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Page Not Found :(</title>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Not Found :(</title>
    <meta name="404 Page" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="shortcut icon" href="img/favicon.ico" type="img/x-icon">
    <link rel="icon" href="img/favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="css/main.css">

Not found :(

Sorry, but the page you were trying to view does not exist.

It looks like this was the result of either:

a mistyped address

an out-of-date link

Oh well. In the meantime, check out the rest of the site!


text:
'''
    api tests
'''

import pytaf_utils
from apilib import ApiLib
import json
from bs4 import BeautifulSoup

def test_api(args={}):
    ''' generic test showing params and settings extraction from args '''
    settings = args['settingss']
    params = args['params']
    try:
        apilib = ApiLib()
        print(settings, params)
        apilib.some_function()
        return (True, '')
    except:
        return (False, pytaf_utils.formatExceptionInfo())

def test_html_get(args={}):
    ''' example using BeautifulSoup to parse html '''
    params = args['params']
    settings = args['settings']
    url = params.get('url',"www.google.com")
    try:
        errors = []
        headers = {}
        locator = "/index.html"
        lib = ApiLib()
        response = lib.do_get(url, locator, settings, headers, False)
        data = response['data']
        soup = BeautifulSoup(data)
        divs = soup.findAll('div')
        for div in divs:
            try:
                print("div style = %s" % div['style'])
            except:
                pass
        return pytaf_utils.verify(len(errors) == 0,
                                'there were errors: %s' % errors)
    except:
        return (False, pytaf_utils.formatExceptionInfo())

def test_simple_get(args={}):
    '''
        example of json parsing from http get
        http://httpbin.org/

        It echoes the data used in your request for any of these types:

        http://httpbin.org/ip Returns Origin IP.
        http://httpbin.org/user-agent Returns user-agent.
        http://httpbin.org/headers Returns header dict.
        http://httpbin.org/get Returns GET data.
        http://httpbin.org/post Returns POST data.
        http://httpbin.org/put Returns PUT data.
        http://httpbin.org/delete Returns DELETE data
        http://httpbin.org/gzip Returns gzip-encoded data.
        http://httpbin.org/status/:code Returns given HTTP Status code.
        http://httpbin.org/redirect/:n 302 Redirects n times.
        http://httpbin.org/cookies Returns cookie data.
        http://httpbin.org/cookies/set/:name/:value Sets a simple cookie.
        http://httpbin.org/basic-auth/:user/:passwd Challenges HTTPBasic Auth.
        http://httpbin.org/hidden-basic-auth/:user/:passwd 404'd BasicAuth.
        http://httpbin.org/stream/:n Streams n–100 lines.
        http://httpbin.org/delay/:n Delays responding for n–10 seconds.
'''
    params = args['params']
    settings = args['settings']
    url = params.get('url',"httpbin.org")
    try:
        errors = []
        headers = {}
        locator = "/get"
        lib = ApiLib()
        response = lib.do_get(url, locator, settings, headers, False)
        data = json.loads(response['data'])
        print(data)
        origin = data.get('origin', None)
        if origin == None:
            errors.append("did not get expected 'origin' field")
        else:
            print("origin = %s" % origin)

        return pytaf_utils.verify(len(errors) == 0,
                                  'there were errors: %s' % errors)
    except:
        return (False, pytaf_utils.formatExceptionInfo())

def test_simple_post(args={}):
    ''' example of json parsing from http post '''
    params = args['params']
    settings = args['settings']
    url = params.get('url',"httpbin.org")
    try:
        errors = []
        headers = {}
        request = ''
        locator = "/post"
        lib = ApiLib()
        response = lib.do_post(url, locator, request,
                               settings, headers, False)
        data = json.loads(response['data'])
        print(data)
        origin = data.get('origin', None)
        if origin == None:
            errors.append("did not get expected 'origin' field")
        else:
            print("origin = %s" % origin)

        return pytaf_utils.verify(len(errors) == 0,
                                  'there were errors: %s' % errors)
    except:
        return (False, pytaf_utils.formatExceptionInfo())