text:
<?php defined('COREPATH') or exit('No direct script access allowed'); ?>

INFO - 2015-11-02 22:13:26 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "home"
INFO - 2015-11-02 22:13:26 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:26 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:26 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "login"
INFO - 2015-11-02 22:13:26 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:26 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:33 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "login"
INFO - 2015-11-02 22:13:33 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:33 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:33 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "home"
INFO - 2015-11-02 22:13:33 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:33 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:45 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "mypage"
INFO - 2015-11-02 22:13:45 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:45 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:46 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "changeregistration"
INFO - 2015-11-02 22:13:46 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:46 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:48 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "changeregistration"
INFO - 2015-11-02 22:13:48 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:48 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:50 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "changeregistration"
INFO - 2015-11-02 22:13:50 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:50 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:52 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "changeregistration"
INFO - 2015-11-02 22:13:52 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:52 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:13:52 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "mypage"
INFO - 2015-11-02 22:13:52 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:13:52 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:14:15 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "changeregistration"
INFO - 2015-11-02 22:14:15 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:14:15 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:14:16 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "login/logout"
INFO - 2015-11-02 22:14:16 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:14:16 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2015-11-02 22:14:16 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "login"
INFO - 2015-11-02 22:14:16 --> Fuel\Core\Request::execute - Called
INFO - 2015-11-02 22:14:16 --> Fuel\Core\Request::execute - Setting main Request


text:
using System;

namespace DigitalLabels.WebApi.Infrastructure
{
    [AttributeUsage(AttributeTargets.Method)]
    public class ApiParameterDocAttribute : Attribute
    {
        public ApiParameterDocAttribute(string param, string doc)
        {
            Parameter = param;
            Documentation = doc;
        }
        public string Parameter { get; set; }
        public string Documentation { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class AddFollowingThisUserOnUserDetails < ActiveRecord::Migration
  def up
    execute %Q{
CREATE OR REPLACE VIEW "1"."user_details" AS
 SELECT u.id,
    u.name,
    u.address_city,
    u.deactivated_at,
    thumbnail_image(u.*) AS profile_img_thumbnail,
    u.facebook_link,
    u.twitter AS twitter_username,
        CASE
            WHEN is_owner_or_admin(u.id) THEN u.email
            ELSE NULL::text
        END AS email,
    COALESCE(ut.total_contributed_projects, (0)::bigint) AS total_contributed_projects,
    COALESCE(ut.total_published_projects, (0)::bigint) AS total_published_projects,
    ( SELECT json_agg(links.*) AS json_agg
           FROM ( SELECT ul.id,
                    ul.link
                   FROM user_links ul
                  WHERE (ul.user_id = u.id)) links) AS links,
    ( SELECT count(*) AS count
           FROM user_follows uf
          WHERE (uf.user_id = u.id)) AS follows_count,
    ( SELECT count(*) AS count
           FROM user_follows uf
          WHERE (uf.follow_id = u.id)) AS followers_count,
        CASE
            WHEN is_owner_or_admin(u.id) THEN json_build_object('street', u.address_street, 'number', u.address_number, 'complement', u.address_complement, 'neighbourhood', u.address_neighbourhood, 'city', u.address_city, 'state', u.address_state, 'zipcode', u.address_zip_code, 'phonenumber', u.phone_number, 'country_id', u.country_id)
            ELSE NULL::json
        END AS address,
        CASE
            WHEN is_owner_or_admin(u.id) THEN u.cpf
            ELSE NULL::text
        END AS owner_document,
    cover_image_url(u.*) AS profile_cover_image,
    u.created_at,
    u.about_html,
    is_owner_or_admin(u.id) AS is_owner_or_admin,
    u.newsletter,
    u.subscribed_to_project_posts,
    u.subscribed_to_new_followers,
    u.subscribed_to_friends_contributions,
    ("current_user"() = 'admin'::name) AS is_admin,
    u.permalink,
    (CASE
        WHEN is_owner_or_admin(u.id) THEN email_active(u.*)
        ELSE NULL::boolean
    END) AS email_active,
    u.public_name,
    (case when current_user = 'anonymous' then false
    else public.user_following_this_user(public.current_user_id(), u.id) end) AS following_this_user
   FROM (users u
     LEFT JOIN "1".user_totals ut ON ((ut.user_id = u.id)));
}
  end

  def down
    execute %Q{
DROP VIEW "1".user_details;
CREATE OR REPLACE VIEW "1"."user_details" AS
 SELECT u.id,
    u.name,
    u.address_city,
    u.deactivated_at,
    thumbnail_image(u.*) AS profile_img_thumbnail,
    u.facebook_link,
    u.twitter AS twitter_username,
        CASE
            WHEN is_owner_or_admin(u.id) THEN u.email
            ELSE NULL::text
        END AS email,
    COALESCE(ut.total_contributed_projects, (0)::bigint) AS total_contributed_projects,
    COALESCE(ut.total_published_projects, (0)::bigint) AS total_published_projects,
    ( SELECT json_agg(links.*) AS json_agg
           FROM ( SELECT ul.id,
                    ul.link
                   FROM user_links ul
                  WHERE (ul.user_id = u.id)) links) AS links,
    ( SELECT count(*) AS count
           FROM user_follows uf
          WHERE (uf.user_id = u.id)) AS follows_count,
    ( SELECT count(*) AS count
           FROM user_follows uf
          WHERE (uf.follow_id = u.id)) AS followers_count,
        CASE
            WHEN is_owner_or_admin(u.id) THEN json_build_object('street', u.address_street, 'number', u.address_number, 'complement', u.address_complement, 'neighbourhood', u.address_neighbourhood, 'city', u.address_city, 'state', u.address_state, 'zipcode', u.address_zip_code, 'phonenumber', u.phone_number, 'country_id', u.country_id)
            ELSE NULL::json
        END AS address,
        CASE
            WHEN is_owner_or_admin(u.id) THEN u.cpf
            ELSE NULL::text
        END AS owner_document,
    cover_image_url(u.*) AS profile_cover_image,
    u.created_at,
    u.about_html,
    is_owner_or_admin(u.id) AS is_owner_or_admin,
    u.newsletter,
    u.subscribed_to_project_posts,
    u.subscribed_to_new_followers,
    u.subscribed_to_friends_contributions,
    ("current_user"() = 'admin'::name) AS is_admin,
    u.permalink,
    (CASE
        WHEN is_owner_or_admin(u.id) THEN email_active(u.*)
        ELSE NULL::boolean
    END) AS email_active,
    u.public_name
   FROM (users u
     LEFT JOIN "1".user_totals ut ON ((ut.user_id = u.id)));
}
  end
end


text:
package com.aesthetikx.hubski.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.*;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
import com.aesthetikx.hubski.R;
import com.aesthetikx.hubski.model.Post;

public class ArticleFragment extends Fragment {

    private Post post;

    public static ArticleFragment newInstance(Post post) {
        ArticleFragment fragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putSerializable("post", post);
        fragment.setArguments(args);
        return fragment;
    }

    public ArticleFragment() { }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        WebView webview = prepareWebView();
        webview.loadUrl(post.getArticleUrl().toString());
        return webview;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.article, menu);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.post = (Post) getArguments().getSerializable("post");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_comments:
                FragmentManager manager = getActivity().getSupportFragmentManager();
                manager.beginTransaction()
                        .replace(R.id.container, CommentsFragment.newInstance(post))
                        //.addToBackStack(null)
                        .commit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private WebView prepareWebView() {
        WebView webview = new WebView(getActivity().getApplicationContext());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setBuiltInZoomControls(true);
        webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                //TODO handle progress
            }
        });
        webview.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(getActivity(), description, Toast.LENGTH_SHORT).show();
            }
        });

        return webview;
    }
}


text:
<?php

/* OCPAppliBundle:cordes:ajouter.html.twig */
class __TwigTemplate_f9ea38211452d6d21c2d3b5cfe9d32f56df9914433c418201fe72376d86adc87 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("OCPAppliBundle::layout.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "OCPAppliBundle::layout.html.twig";
    }

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

    // line 2
    public function block_title($context, array $blocks = array())
    {
        $this->displayParentBlock("title", $context, $blocks);
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "

                            <button type=\"button\"  class=\"btn btn-primary  col-lg-offset-5\" data-toggle=\"modal\" data-target=\"#exampleModal\" data-whatever=\"@mdo\">Ajout  Coordonnees de Destockage</button>
.

        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">×</button>

Ajout Coordonnees de Destockage

            <form method=\"post\" id=\"addcordes\" ";
        // line 20
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
        echo " action=\"\" >
            ";
        // line 21
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'widget');
        echo "

            <input type=\"submit\" class=\"btn btn-primary\" value=\"ajouter\" />

              </form>

            ";
    }

    public function getTemplateName()
    {
        return "OCPAppliBundle:cordes:ajouter.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  92 => 42,  68 => 21,  64 => 20,  46 => 4,  43 => 3,  37 => 2,  11 => 1,);
    }
}


text:
/**
 * Created by yusong on 10/25/16.
 */
let articles = { articles: [
          { id:1, author: 'Scott', text:'A post 1' },
          { id:2, author: 'Scott1', text:'A post 2' },
          { id:3, author: 'Scott2', text:'A post 3' },
          { id:4, author: 'ys004', text:'A post 4' },
          { id:5, author: 'ys005', text:'A post 5' },

     ]}

// receives a JSON article, return the article with an id,
// and add the article to the list returned by GET
const addArticle = (req, res) => {
     console.log('Payload received', req.body)
     const numArticles = articles['articles'].length;
     const article = {}
     let result = {}
     article.id = numArticles + 1
     // console.log(typeof(req.body))
     article.text = req.body.text
     result.articles = [article]
     res.send(result)
     articles['articles'].push(article)

}
// supplies JSON articles, start with 5 hard coded articles
const getArticles = (req, res) => {
    const id = req.params.id
    if (!id) {
        res.send(articles)
    } else {
    	const result = {}
    	result.articles = articles.articles.filter(x => (x.id == id))
        res.send(result)
    }
}

module.exports = (app) => {
	app.post('/article', addArticle)
	app.get('/articles/:id*?', getArticles)
}


text:
namespace Gimela.Toolkit.CommandLines.MoveDate
{
    internal class MoveDateCommandLineOptions
    {
        public MoveDateCommandLineOptions()
        {
        }

        public string RegexPattern { get; set; }
        public string InputDirectory { get; set; }

        public bool IsSetHelp { get; set; }
        public bool IsSetVersion { get; set; }
    }
}


text:
package org.olat.search.service.document.file;

import java.io.IOException;
import java.io.InputStream;

import org.apache.lucene.document.Document;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;
import org.olat.core.util.FileUtils;
import org.olat.core.util.filter.impl.NekoHTMLFilter;
import org.olat.core.util.filter.impl.NekoHTMLFilter.NekoContent;
import org.olat.core.util.vfs.VFSLeaf;
import org.olat.search.service.SearchResourceContext;

/**
 * Lucene document mapper.
 * @author Christian Guretzki
 */
public class HtmlDocument extends FileDocument {
	private static final long serialVersionUID = 4816587780227792396L;
	private static final OLog log = Tracing.createLoggerFor(HtmlDocument.class);

	public static final String FILE_TYPE = "type.file.html";

	public HtmlDocument() {
		//
	}

	public static Document createDocument(SearchResourceContext leafResourceContext, VFSLeaf leaf) throws IOException,DocumentException,DocumentAccessException {
    HtmlDocument htmlDocument = new HtmlDocument();
    htmlDocument.init(leafResourceContext,leaf);
    htmlDocument.setFileType(FILE_TYPE);
    htmlDocument.setCssIcon("b_filetype_html");
		if (log.isDebug() ) log.debug(htmlDocument.toString());
		return htmlDocument.getLuceneDocument();
	}

	protected FileContent readContent(VFSLeaf leaf) {
		InputStream is = leaf.getInputStream();
    // Remove all HTML and   Tags
    NekoContent output = new NekoHTMLFilter().filter(is);
    if (log.isDebug() ) log.debug("HTML content without tags :" + output);
  	FileUtils.closeSafely(is);
		return new FileContent(output.getTitle(), output.getContent());
	}
}


text:
import logging, os, re, argparse, peakparser, discordant

# +1 if a > b
# -1 if a < b
#  0 if a == b
def cmpChrPosList(a,b):

    chrA = a[0].lstrip('chr')
    if chrA < ':' and chrA > '0': chrA = int(chrA)

    chrB = b[0].lstrip('chr')
    if chrB < ':' and chrB > '0': chrB = int(chrB)

    posA = int(a[1])
    posB = int(b[1])

    if (chrA == chrB):
        if (posA == posB): return 0
        if (posA < posB): return -1
        if (posA > posB): return 1

    if (chrA < chrB):
        return -1
    if (chrA > chrB):
        return 1

# sorts files whose first two columns are chromosome and position, respectively.
def sortChrPos(file):
    f = open(file,'r')
    bedlist = []
    for bedline in f:
        bedlist.append(bedline.rstrip().split("\t"))
    return sorted(bedlist, cmp=cmpChrPosList)

# concatenates files, sorts, and outputs to outfile
def mergeChrPosFiles(infile1,infile2,outfile,maxDist,eltLenDict):
    bedlist = []
    for file in (infile1,infile2):
        f = open(file,'r')
        findex = 0
        bedhead = ''
        for bedline in f:
            if findex == 0 and re.search(".bed$", outfile) and re.search("track", bedline): # ignore BED header
                bedhead = bedline
            else:
                bedlist.append(bedline.rstrip().split("\t"))
            findex = findex + 1
        f.close()

    outlist = []

    if re.search(".readpairs.txt$", outfile):
        outlist = discordant.reindexReads(sorted(bedlist, cmp=cmpChrPosList), maxDist, eltLenDict)
    else:
        outlist = sorted(bedlist, cmp=cmpChrPosList)

    f = open(outfile, 'w')
    if re.search("track", bedhead):
        f.write("track\tname=%s\tvisibility=2\titemRgb=On db=hg19\n" % os.path.basename(outfile))
    for outline in outlist: #sorted(bedlist, cmp=cmpChrPosList):
        outstring = "\t".join(outline)
        f.write(outstring + "\n")
    f.close()

def main(args):
    # debugging info
    logfile = args.outDirName + "/" + args.outBaseName + "/logs/%d" % os.getpid() + "." + args.outBaseName + ".mergepairs.log"
    logging.basicConfig(format='%(asctime)s %(message)s',filename=logfile,level=logging.DEBUG)

    logging.info("\ninDir1=%s\ninDir2=%s\noutBaseName=%s\nconfigFileName=%s"
                 % (args.inDir1,args.inDir2,args.outBaseName,args.configFileName))

    # create output directory
    discordant.prepOutDir(args.outBaseName,args.outDirName,args.overwrite)

    # make sure input sources exist
    peakparser.checkOutDir(args.inDir1,args.outDirName)
    peakparser.checkOutDir(args.inDir2,args.outDirName)

    # make sure config files exist
    configPath1 = args.outDirName + "/" + args.inDir1 + "/" + args.configFileName
    configPath2 = args.outDirName + "/" + args.inDir2 + "/" + args.configFileName
    discordant.checkfile(configPath1)
    discordant.checkfile(configPath2)

    # read parameters for both inputs
    configDict1 = peakparser.readConfig(configPath1,args.inDir1,args.outDirName)
    configDict2 = peakparser.readConfig(configPath2,args.inDir2,args.outDirName)

    maxDist = int(configDict1['insertSize']) + 2*int(configDict1['readLength'])
    eltLenDict = discordant.makeEltLenDict(configDict1['eltLenFileName'])

    # merge readfiles
    outReadFileName = args.outDirName + "/" + args.outBaseName + "/" + args.outBaseName + ".readpairs.txt"
    readFileName1 = args.outDirName + "/" + args.inDir1 + "/" + args.inDir1 + ".readpairs.txt"
    readFileName2 = args.outDirName + "/" + args.inDir2 + "/" + args.inDir2 + ".readpairs.txt"
    logging.info("merging readfiles (%s, %s)" % (readFileName1,readFileName2))
#   print "merging readfiles (%s, %s)" % (readFileName1,readFileName2)
    mergeChrPosFiles(readFileName1,readFileName2,outReadFileName,maxDist,eltLenDict)

    # merge bedfiles
    outBedFileName = args.outDirName + "/" + args.outBaseName + "/" + args.outBaseName + ".reads.bed"
    bedFileName1 = args.outDirName + "/" + args.inDir1 + "/" + args.inDir1 + ".reads.bed"
    bedFileName2 = args.outDirName + "/" + args.inDir2 + "/" + args.inDir2 + ".reads.bed"
    logging.info("merging bedfiles (%s,%s)" % (bedFileName1,bedFileName2))
#   print "merging bedfiles (%s,%s)" % (bedFileName1,bedFileName2)
    mergeChrPosFiles(bedFileName1,bedFileName2,outBedFileName,maxDist,eltLenDict)

    # write new config file
    configPath = args.outDirName + "/" + args.outBaseName + "/" + args.configFileName
    configDict = configDict1
    configDict['bamFileName1'] = configDict1['bamFileName']
    configDict['bamFileName2'] = configDict2['bamFileName']
    configDict['merged'] = 'True'
    configDict['outBaseName'] = args.outBaseName
    configDict['outDirName'] = args.outDirName
    configDict['readFileName'] = outReadFileName

    del configDict['bamFileName']

    f = open(configPath, 'w')
    for k,v in configDict.iteritems():
        f.write(k + "=" + v + "\n")
    f.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='merge files in the specified output directories, maintains sorting')
    parser.add_argument('-1', '--1', dest='inDir1', required=True,
                        help='output directory 1 (input 1)')
    parser.add_argument('-2', '--2', dest='inDir2', required=True,
                        help='output directory 2 (input 2)')
    parser.add_argument('-o', '--outbasename', dest='outBaseName', required=True,
                        help='basename for merged output')
    parser.add_argument('-d', '--outdirname', dest='outDirName', default='output',
                        help='output directory')
    parser.add_argument('-c', '--config', dest='configFileName', default='config.txt',
                        help='filname for config file left by discordant.py')
    parser.add_argument('--overwrite', action='store_true')
    args = parser.parse_args()

    main(args)


text:
package io.fabric8.istio.api.networking.v1alpha3;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;

public enum LoadBalancerSettingsSimpleLB {

    ROUND_ROBIN(0),
    LEAST_CONN(1),
    RANDOM(2),
    PASSTHROUGH(3);
    private final Integer value;
    private final static Map<Integer, LoadBalancerSettingsSimpleLB> CONSTANTS = new HashMap<Integer, LoadBalancerSettingsSimpleLB>();
    private final static Map<String, LoadBalancerSettingsSimpleLB> NAME_CONSTANTS = new HashMap<String, LoadBalancerSettingsSimpleLB>();

    static {
        for (LoadBalancerSettingsSimpleLB c: values()) {
            CONSTANTS.put(c.value, c);
        }
        for (LoadBalancerSettingsSimpleLB c: values()) {
            NAME_CONSTANTS.put(c.name().toLowerCase(), c);
        }
    }

    private LoadBalancerSettingsSimpleLB(Integer value) {
        this.value = value;
    }

    @JsonCreator
    public static LoadBalancerSettingsSimpleLB fromValue(Object value) {
        if (value instanceof String) {
            {
                LoadBalancerSettingsSimpleLB constant = NAME_CONSTANTS.get(((String) value).toLowerCase());
                if (constant == null) {
                    throw new IllegalArgumentException((value +""));
                } else {
                    return constant;
                }
            }
        }
        LoadBalancerSettingsSimpleLB constant = CONSTANTS.get(value);
        if (constant == null) {
            throw new IllegalArgumentException((value +""));
        } else {
            return constant;
        }
    }

}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../../libc/constant.QFMT_VFS_V1.html">

Redirecting to ../../../../../libc/constant.QFMT_VFS_V1.html...


text:
package org.apache.openwhisk.core.cli.test

import akka.http.scaladsl.model.StatusCodes.NotFound
import akka.http.scaladsl.model.StatusCodes.OK
import akka.http.scaladsl.model.StatusCodes.BadRequest
import akka.http.scaladsl.model.StatusCodes.Conflict
import java.time.Instant
import java.time.Clock

import scala.language.postfixOps
import scala.concurrent.duration.DurationInt
import scala.util.Random
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import common.TestHelpers
import common.TestUtils
import common.TestUtils._
import common.WhiskProperties
import common.WskProps
import common.WskTestHelpers
import common.WskActorSystem
import common.rest.WskRestOperations
import spray.json.DefaultJsonProtocol._
import spray.json._
import org.apache.openwhisk.core.entity._
import org.apache.openwhisk.core.entity.size.SizeInt
import TestJsonArgs._
import org.apache.openwhisk.http.Messages

/**
 * Tests for basic CLI usage. Some of these tests require a deployed backend.
 */
@RunWith(classOf[JUnitRunner])
class WskRestBasicUsageTests extends TestHelpers with WskTestHelpers with WskActorSystem {

  implicit val wskprops = WskProps()
  val wsk = new WskRestOperations
  val defaultAction: Some[String] = Some(TestUtils.getTestActionFilename("hello.js"))
  val usrAgentHeaderRegEx: String = """\bUser-Agent\b": \[\s+"OpenWhisk\-CLI/1.\d+.*"""

  val requireAPIKeyAnnotation = WhiskProperties.getBooleanProperty("whisk.feature.requireApiKeyAnnotation", true);

  private val retriesOnTestFailures = 5
  private val waitBeforeRetry = 1.second

  val behaviorwskapi = "Wsk API basic usage"
  behavior of s"$behaviorwskapi"

  it should "allow a 3 part Fully Qualified Name (FQN) without a leading '/'" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "allow a 3 part Fully Qualified Name (FQN) without a leading '/'"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val guestNamespace = wsk.namespace.whois()
            val packageName = "packageName3ptFQN"
            val actionName = "actionName3ptFQN"
            val triggerName = "triggerName3ptFQN"
            val ruleName = "ruleName3ptFQN"
            val fullQualifiedName = s"${guestNamespace}/${packageName}/${actionName}"
            // Used for action and rule creation below
            assetHelper.withCleaner(wsk.pkg, packageName) { (pkg, _) =>
              pkg.create(packageName)
            }
            assetHelper.withCleaner(wsk.trigger, triggerName) { (trigger, _) =>
              trigger.create(triggerName)
            }
            // Test action and rule creation where action name is 3 part FQN w/out leading slash
            assetHelper.withCleaner(wsk.action, fullQualifiedName) { (action, _) =>
              action.create(fullQualifiedName, defaultAction)
            }
            assetHelper.withCleaner(wsk.rule, ruleName) { (rule, _) =>
              rule.create(ruleName, trigger = triggerName, action = fullQualifiedName)
            }

            val run = wsk.action.invoke(fullQualifiedName)
            withActivation(wsk.activation, run) { activation =>
              activation.response.status shouldBe "success"
            }
            val action = wsk.action.get(fullQualifiedName)
            action.getField("name") shouldBe actionName
            action.getField("namespace") shouldBe s"${guestNamespace}/${packageName}"
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskapi should $testname not successful, retrying.."))
  }

  val behaviorwskactions = "Wsk actions"
  behavior of s"$behaviorwskactions"

  it should "reject creating entities with invalid names" in withAssetCleaner(wskprops) { (wp, assetHelper) =>
    val testname = "reject creating entities with invalid names"
    org.apache.openwhisk.utils
      .retry(
        {
          assetHelper.deleteAssets()
          val names = Seq(
            ("", NotFound.intValue),
            (" ", BadRequest.intValue),
            ("hi+there", BadRequest.intValue),
            ("$hola", BadRequest.intValue),
            ("dora?", BadRequest.intValue),
            ("|dora|dora?", BadRequest.intValue))

          names foreach {
            case (name, ec) =>
              assetHelper.withCleaner(wsk.action, name, confirmDelete = false) { (action, _) =>
                action.create(name, defaultAction, expectedExitCode = ec)
              }
          }
        },
        retriesOnTestFailures,
        Some(waitBeforeRetry),
        Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "create, and get an action to verify parameter and annotation parsing" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create, and get an action to verify parameter and annotation parsing"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "actionAnnotations"
            val file = Some(TestUtils.getTestActionFilename("hello.js"))
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, file, annotations = getValidJSONTestArgInput, parameters = getValidJSONTestArgInput)
            }

            val action = wsk.action.get(name)
            action.getField("name") shouldBe name

            val receivedParams = wsk.parseJsonString(action.stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(action.stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getValidJSONTestArgOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "create, and get an action to verify file parameter and annotation parsing" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create, and get an action to verify file parameter and annotation parsing"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "actionAnnotAndParamParsing"
            val file = Some(TestUtils.getTestActionFilename("hello.js"))
            val argInput = Some(TestUtils.getTestActionFilename("validInput1.json"))

            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, file, annotationFile = argInput, parameterFile = argInput)
            }

            val action = wsk.action.get(name)
            action.getField("name") shouldBe name

            val receivedParams = wsk.parseJsonString(action.stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(action.stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getJSONFileOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "create an action with the proper parameter and annotation escapes" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create an action with the proper parameter and annotation escapes"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "actionEscapes"
            val file = Some(TestUtils.getTestActionFilename("hello.js"))

            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action
                .create(name, file, parameters = getEscapedJSONTestArgInput, annotations = getEscapedJSONTestArgInput)
            }

            val action = wsk.action.get(name)
            action.getField("name") shouldBe name

            val receivedParams = wsk.parseJsonString(action.stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(action.stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getEscapedJSONTestArgOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action that exits during initialization and get appropriate error" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "invoke an action that exits during initialization and get appropriate error"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "abort init"
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, Some(TestUtils.getTestActionFilename("initexit.js")))
            }

            withActivation(wsk.activation, wsk.action.invoke(name)) { activation =>
              val response = activation.response
              response.result.get.fields("error") shouldBe Messages.abnormalInitialization.toJson
              response.status shouldBe ActivationResponse.messageForCode(ActivationResponse.DeveloperError)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action that hangs during initialization and get appropriate error" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "invoke an action that hangs during initialization and get appropriate error"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "hang init"
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, Some(TestUtils.getTestActionFilename("initforever.js")), timeout = Some(3 seconds))
            }

            withActivation(wsk.activation, wsk.action.invoke(name)) { activation =>
              val response = activation.response
              response.result.get.fields("error") shouldBe Messages.timedoutActivation(3 seconds, true).toJson
              response.status shouldBe ActivationResponse.messageForCode(ActivationResponse.DeveloperError)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action that exits during run and get appropriate error" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "invoke an action that exits during run and get appropriate error"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "abort run"
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, Some(TestUtils.getTestActionFilename("runexit.js")))
            }

            withActivation(wsk.activation, wsk.action.invoke(name)) { activation =>
              val response = activation.response
              response.result.get.fields("error") shouldBe Messages.abnormalRun.toJson
              response.status shouldBe ActivationResponse.messageForCode(ActivationResponse.DeveloperError)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "ensure keys are not omitted from activation record" in withAssetCleaner(wskprops) {
    val testname = "ensure keys are not omitted from activation record"
    val name = "activationRecordTest"

    (wp, assetHelper) =>
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, Some(TestUtils.getTestActionFilename("argCheck.js")))
            }

            val run = wsk.action.invoke(name)
            withActivation(wsk.activation, run) { activation =>
              activation.start should be > Instant.EPOCH
              activation.end should be > Instant.EPOCH
              activation.response.status shouldBe ActivationResponse.messageForCode(ActivationResponse.Success)
              activation.response.success shouldBe true
              activation.response.result shouldBe Some(JsObject.empty)
              activation.logs shouldBe Some(List.empty)
              activation.annotations shouldBe defined
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "write the action-path and the limits to the annotations" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "write the action-path and the limits to the annotations"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "annotations"
            val memoryLimit = 512 MB
            val logLimit = 1 MB
            val timeLimit = 60 seconds

            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(
                name,
                Some(TestUtils.getTestActionFilename("helloAsync.js")),
                memory = Some(memoryLimit),
                timeout = Some(timeLimit),
                logsize = Some(logLimit))
            }

            val run = wsk.action.invoke(name, Map("payload" -> "this is a test".toJson))
            withActivation(wsk.activation, run) {
              activation =>
                activation.response.status shouldBe "success"
                val annotations = activation.annotations.get

                val limitsObj = JsObject(
                  "key" -> JsString("limits"),
                  "value" -> ActionLimits(TimeLimit(timeLimit), MemoryLimit(memoryLimit), LogLimit(logLimit)).toJson)

                val path = annotations.find {
                  _.fields("key").convertTo[String] == "path"
                }.get

                path.fields("value").convertTo[String] should fullyMatch regex (s""".*/$name""")
                annotations should contain(limitsObj)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "create, and invoke an action that utilizes an invalid docker container with appropriate error" in withAssetCleaner(
    wskprops) {
    val testname = "create, and invoke an action that utilizes an invalid docker container with appropriate error"
    val name = "invalidDockerContainer"
    val containerName = s"bogus${Random.alphanumeric.take(16).mkString.toLowerCase}"

    (wp, assetHelper) =>
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            assetHelper.withCleaner(wsk.action, name) {
              // docker name is a randomly generate string
              (action, _) =>
                action.create(name, None, docker = Some(containerName))
            }

            val run = wsk.action.invoke(name)
            withActivation(wsk.activation, run) {
              activation =>
                activation.response.status shouldBe ActivationResponse.messageForCode(ActivationResponse.DeveloperError)
                activation.response.result.get
                  .fields("error") shouldBe s"Failed to pull container image '$containerName'.".toJson
                activation.annotations shouldBe defined
                val limits = activation.annotations.get.filter(_.fields("key").convertTo[String] == "limits")
                withClue(limits) {
                  limits.length should be > 0
                  limits(0).fields("value") should not be JsNull
                }
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action using npm openwhisk" in withAssetCleaner(wskprops) { (wp, assetHelper) =>
    val testname = "invoke an action using npm openwhisk"
    org.apache.openwhisk.utils
      .retry(
        {
          assetHelper.deleteAssets()
          val name = "hello npm openwhisk"
          assetHelper.withCleaner(wsk.action, name, confirmDelete = false) { (action, _) =>
            action.create(
              name,
              Some(TestUtils.getTestActionFilename("helloOpenwhiskPackage.js")),
              annotations = Map(Annotations.ProvideApiKeyAnnotationName -> JsTrue))
          }

          val run = wsk.action.invoke(name, Map("ignore_certs" -> true.toJson, "name" -> name.toJson))
          withActivation(wsk.activation, run) { activation =>
            activation.response.status shouldBe "success"
            activation.response.result shouldBe Some(JsObject("delete" -> true.toJson))
            activation.logs.get.mkString(" ") should include("action list has this many actions")
          }

          wsk.action.delete(name, expectedExitCode = NotFound.intValue)
        },
        retriesOnTestFailures,
        Some(waitBeforeRetry),
        Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action receiving context properties excluding api key" in withAssetCleaner(wskprops) {
    val testname = "invoke an action receiving context properties excluding api key"
    assume(requireAPIKeyAnnotation)
    (wp, assetHelper) =>
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val namespace = wsk.namespace.whois()
            val name = "context"
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, Some(TestUtils.getTestActionFilename("helloContext.js")))
            }

            val start = Instant.now(Clock.systemUTC()).toEpochMilli
            val run = wsk.action.invoke(name)
            withActivation(wsk.activation, run) { activation =>
              activation.response.status shouldBe "success"
              val fields = activation.response.result.get.convertTo[Map[String, String]]
              fields("api_host") shouldBe WhiskProperties.getApiHostForAction
              fields.get("api_key") shouldBe empty
              fields("namespace") shouldBe namespace
              fields("action_name") shouldBe s"/$namespace/$name"
              fields("action_version") should fullyMatch regex ("""\d+.\d+.\d+""")
              fields("activation_id") shouldBe activation.activationId
              fields("deadline").toLong should be >= start
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action receiving context properties including api key" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "invoke an action receiving context properties including api key"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val namespace = wsk.namespace.whois()
            val name = "context"
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(
                name,
                Some(TestUtils.getTestActionFilename("helloContext.js")),
                annotations = Map(Annotations.ProvideApiKeyAnnotationName -> JsTrue))
            }

            val start = Instant.now(Clock.systemUTC()).toEpochMilli
            val run = wsk.action.invoke(name)
            withActivation(wsk.activation, run) { activation =>
              activation.response.status shouldBe "success"
              val fields = activation.response.result.get.convertTo[Map[String, String]]
              fields("api_host") shouldBe WhiskProperties.getApiHostForAction
              fields("api_key") shouldBe wskprops.authKey
              fields("namespace") shouldBe namespace
              fields("action_name") shouldBe s"/$namespace/$name"
              fields("action_version") should fullyMatch regex ("""\d+.\d+.\d+""")
              fields("activation_id") shouldBe activation.activationId
              fields("deadline").toLong should be >= start
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action successfully with options --blocking and --result" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "invoke an action successfully with options --blocking and --result"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "invokeResult"
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, Some(TestUtils.getTestActionFilename("echo.js")))
            }
            val args = Map("hello" -> "Robert".toJson)
            val run = wsk.action.invoke(name, args, blocking = true, result = true)
            //--result takes precedence over --blocking
            run.stdout.parseJson shouldBe args.toJson
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action that returns a result by the deadline" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "invoke an action that returns a result by the deadline"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "deadline"
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, Some(TestUtils.getTestActionFilename("helloDeadline.js")), timeout = Some(3 seconds))
            }

            val run = wsk.action.invoke(name)
            withActivation(wsk.activation, run) { activation =>
              activation.response.status shouldBe "success"
              activation.response.result shouldBe Some(JsObject("timedout" -> true.toJson))
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke an action twice, where the first times out but the second does not and should succeed" in withAssetCleaner(
    wskprops) {
    val testname = "invoke an action twice, where the first times out but the second does not and should succeed"
    // this test issues two activations: the first is forced to time out and not return a result by its deadline (ie it does not resolve
    // its promise). The invoker should reclaim its container so that a second activation of the same action (which must happen within a
    // short period of time (seconds, not minutes) is allocated a fresh container and hence runs as expected (vs. hitting in the container
    // cache and reusing a bad container).
    (wp, assetHelper) =>
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "timeout"
            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, Some(TestUtils.getTestActionFilename("helloDeadline.js")), timeout = Some(3 seconds))
            }

            val start = Instant.now(Clock.systemUTC()).toEpochMilli
            val hungRun = wsk.action.invoke(name, Map("forceHang" -> true.toJson))
            withActivation(wsk.activation, hungRun) { activation =>
              // the first action must fail with a timeout error
              activation.response.status shouldBe ActivationResponse.messageForCode(ActivationResponse.DeveloperError)
              activation.response.result shouldBe Some(
                JsObject("error" -> Messages.timedoutActivation(3 seconds, false).toJson))
            }

            // run the action again, this time without forcing it to timeout
            // it should succeed because it ran in a fresh container
            val goodRun = wsk.action.invoke(name, Map("forceHang" -> false.toJson))
            withActivation(wsk.activation, goodRun) { activation =>
              // the first action must fail with a timeout error
              activation.response.status shouldBe "success"
              activation.response.result shouldBe Some(JsObject("timedout" -> true.toJson))
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "ensure --web flags set the proper annotations" in withAssetCleaner(wskprops) { (wp, assetHelper) =>
    val testname = "ensure --web flags set the proper annotations"
    org.apache.openwhisk.utils
      .retry(
        {
          assetHelper.deleteAssets()
          Seq("true", "faLse", "tRue", "nO", "yEs", "no", "raw", "NO", "Raw").foreach {
            flag =>
              val webEnabled = flag.toLowerCase == "true" || flag.toLowerCase == "yes"
              val rawEnabled = flag.toLowerCase == "raw"

              val runtime = "nodejs:default"
              val name = "webaction-" + flag
              assetHelper.withCleaner(wsk.action, name) { (action, _) =>
                action.create(
                  name,
                  Some(TestUtils.getTestActionFilename("echo.js")),
                  web = Some(flag.toLowerCase),
                  kind = Some(runtime))
              }

              val action = wsk.action.get(name)

              // first check if we got 'nodejs:*' in the exec value
              action
                .getFieldJsValue("annotations")
                .convertTo[Seq[JsObject]]
                .find(_.fields("key").convertTo[String] == "exec")
                .map(_.fields("value"))
                .map(exec => { exec.convertTo[String] should startWith("nodejs:") })
                .getOrElse(fail())

              // then we check the remaining annotations
              val baseAnnotations = Parameters("web-export", JsBoolean(webEnabled || rawEnabled)) ++
                Parameters("raw-http", JsBoolean(rawEnabled)) ++
                Parameters("final", JsBoolean(webEnabled || rawEnabled))
              val testAnnotations = if (requireAPIKeyAnnotation) {
                baseAnnotations ++ Parameters(Annotations.ProvideApiKeyAnnotationName, JsFalse)
              } else baseAnnotations

              // we ignore the exec field here, since we already compared it above
              action
                .getFieldJsValue("annotations")
                .convertTo[Set[JsObject]]
                .filter(annotation => annotation.fields("key").convertTo[String] != "exec") shouldBe testAnnotations.toJsArray
                .convertTo[Set[JsObject]]
          }
        },
        retriesOnTestFailures,
        Some(waitBeforeRetry),
        Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "ensure action update creates an action with --web flag" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "ensure action update creates an action with --web flag"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val runtime = "nodejs:default"
            val name = "webaction"
            val file = Some(TestUtils.getTestActionFilename("echo.js"))

            assetHelper.withCleaner(wsk.action, name) { (action, _) =>
              action.create(name, file, web = Some("true"), update = true, kind = Some(runtime))
            }

            val baseAnnotations =
              Parameters("web-export", JsTrue) ++
                Parameters("raw-http", JsFalse) ++
                Parameters("final", JsTrue)

            val testAnnotations = if (requireAPIKeyAnnotation) {
              baseAnnotations ++
                Parameters(Annotations.ProvideApiKeyAnnotationName, JsFalse)
            } else {
              baseAnnotations
            }

            val action = wsk.action.get(name)

            // first check if we got 'nodejs:*' in the exec value
            action
              .getFieldJsValue("annotations")
              .convertTo[Seq[JsObject]]
              .find(_.fields("key").convertTo[String] == "exec")
              .map(_.fields("value"))
              .map(exec => { exec.convertTo[String] should startWith("nodejs:") })
              .getOrElse(fail())

            // then we check the remaining annotations
            // we ignore the exec field here, since we already compared it above
            action
              .getFieldJsValue("annotations")
              .convertTo[Set[JsObject]]
              .filter(annotation => annotation.fields("key").convertTo[String] != "exec") shouldBe testAnnotations.toJsArray
              .convertTo[Set[JsObject]]

          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  it should "invoke action while not encoding &, <, > characters" in withAssetCleaner(wskprops) { (wp, assetHelper) =>
    val testname = "invoke action while not encoding &, <, > characters"
    org.apache.openwhisk.utils
      .retry(
        {
          assetHelper.deleteAssets()
          val name = "nonescape"
          val file = Some(TestUtils.getTestActionFilename("hello.js"))
          val nonescape = "&<>"
          val input = Map("payload" -> nonescape.toJson)
          val output = JsObject("payload" -> JsString(s"hello, $nonescape!"))

          assetHelper.withCleaner(wsk.action, name) { (action, _) =>
            action.create(name, file)
          }

          withActivation(wsk.activation, wsk.action.invoke(name, parameters = input)) { activation =>
            activation.response.success shouldBe true
            activation.response.result shouldBe Some(output)
            activation.logs.toList.flatten.filter(_.contains(nonescape)).length shouldBe 1
          }
        },
        retriesOnTestFailures,
        Some(waitBeforeRetry),
        Some(s"${this.getClass.getName} > $behaviorwskactions should $testname not successful, retrying.."))
  }

  val behaviorwskpkgs = "Wsk packages"
  behavior of s"$behaviorwskpkgs"

  it should "create, and delete a package" in {
    val testname = "create, and delete a package"
    org.apache.openwhisk.utils
      .retry(
        {
          val name = "createDeletePackage"
          wsk.pkg.create(name).statusCode shouldBe OK
          wsk.pkg.delete(name).statusCode shouldBe OK
        },
        retriesOnTestFailures,
        Some(waitBeforeRetry),
        Some(s"${this.getClass.getName} > $behaviorwskpkgs should $testname not successful, retrying.."))
  }

  it should "create, and get a package to verify parameter and annotation parsing" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create, and get a package to verify parameter and annotation parsing"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "packageAnnotAndParamParsing"

            assetHelper.withCleaner(wsk.pkg, name) { (pkg, _) =>
              pkg.create(name, annotations = getValidJSONTestArgInput, parameters = getValidJSONTestArgInput)
            }

            val pack = wsk.pkg.get(name)

            val receivedParams = wsk.parseJsonString(pack.stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(pack.stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getValidJSONTestArgOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskpkgs should $testname not successful, retrying.."))
  }

  it should "create, and get a package to verify file parameter and annotation parsing" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create, and get a package to verify file parameter and annotation parsing"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "packageAnnotAndParamFileParsing"
            val file = Some(TestUtils.getTestActionFilename("hello.js"))
            val argInput = Some(TestUtils.getTestActionFilename("validInput1.json"))

            assetHelper.withCleaner(wsk.pkg, name) { (pkg, _) =>
              pkg.create(name, annotationFile = argInput, parameterFile = argInput)
            }

            val stdout = wsk.pkg.get(name).stdout
            val receivedParams = wsk.parseJsonString(stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getJSONFileOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskpkgs should $testname not successful, retrying.."))
  }

  it should "create a package with the proper parameter and annotation escapes" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create a package with the proper parameter and annotation escapes"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "packageEscapses"

            assetHelper.withCleaner(wsk.pkg, name) { (pkg, _) =>
              pkg.create(name, parameters = getEscapedJSONTestArgInput, annotations = getEscapedJSONTestArgInput)
            }

            val pack = wsk.pkg.get(name)
            val receivedParams = wsk.parseJsonString(pack.stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(pack.stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getEscapedJSONTestArgOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwskpkgs should $testname not successful, retrying.."))
  }

  it should "report conformance error accessing action as package" in withAssetCleaner(wskprops) { (wp, assetHelper) =>
    val testname = "report conformance error accessing action as package"
    org.apache.openwhisk.utils
      .retry(
        {
          assetHelper.deleteAssets()
          val name = "aAsP"
          val file = Some(TestUtils.getTestActionFilename("hello.js"))
          assetHelper.withCleaner(wsk.action, name) { (action, _) =>
            action.create(name, file)
          }

          wsk.pkg.get(name, expectedExitCode = Conflict.intValue).stderr should include(Messages.conformanceMessage)

          wsk.pkg.bind(name, "bogus", expectedExitCode = Conflict.intValue).stderr should include(
            Messages.requestedBindingIsNotValid)

          wsk.pkg.bind("bogus", "alsobogus", expectedExitCode = BadRequest.intValue).stderr should include(
            Messages.bindingDoesNotExist)

        },
        retriesOnTestFailures,
        Some(waitBeforeRetry),
        Some(s"${this.getClass.getName} > $behaviorwskpkgs should $testname not successful, retrying.."))
  }

  val behaviorwsktgs = "Wsk triggers"
  behavior of s"$behaviorwsktgs"

  it should "create, and get a trigger to verify parameter and annotation parsing" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create, and get a trigger to verify parameter and annotation parsing"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "triggerAnnotAndParamParsing"

            assetHelper.withCleaner(wsk.trigger, name) { (trigger, _) =>
              trigger.create(name, annotations = getValidJSONTestArgInput, parameters = getValidJSONTestArgInput)
            }

            val stdout = wsk.trigger.get(name).stdout

            val receivedParams = wsk.parseJsonString(stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getValidJSONTestArgOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwsktgs should $testname not successful, retrying.."))
  }

  it should "create, and get a trigger to verify file parameter and annotation parsing" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create, and get a trigger to verify file parameter and annotation parsing"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "triggerAnnotAndParamFileParsing"
            val file = Some(TestUtils.getTestActionFilename("hello.js"))
            val argInput = Some(TestUtils.getTestActionFilename("validInput1.json"))

            assetHelper.withCleaner(wsk.trigger, name) { (trigger, _) =>
              trigger.create(name, annotationFile = argInput, parameterFile = argInput)
            }

            val stdout = wsk.trigger.get(name).stdout

            val receivedParams = wsk.parseJsonString(stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getJSONFileOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwsktgs should $testname not successful, retrying.."))
  }

  it should "create a trigger with the proper parameter and annotation escapes" in withAssetCleaner(wskprops) {
    (wp, assetHelper) =>
      val testname = "create a trigger with the proper parameter and annotation escapes"
      org.apache.openwhisk.utils
        .retry(
          {
            assetHelper.deleteAssets()
            val name = "triggerEscapes"

            assetHelper.withCleaner(wsk.trigger, name) { (trigger, _) =>
              trigger.create(name, parameters = getEscapedJSONTestArgInput, annotations = getEscapedJSONTestArgInput)
            }

            val stdout = wsk.trigger.get(name).stdout

            val receivedParams = wsk.parseJsonString(stdout).fields("parameters").convertTo[JsArray].elements
            val receivedAnnots = wsk.parseJsonString(stdout).fields("annotations").convertTo[JsArray].elements
            val escapedJSONArr = getEscapedJSONTestArgOutput.convertTo[JsArray].elements

            for (expectedItem <- escapedJSONArr) {
              receivedParams should contain(expectedItem)
              receivedAnnots should contain(expectedItem)
            }
          },
          retriesOnTestFailures,
          Some(waitBeforeRetry),
          Some(s"${this.getClass.getName} > $behaviorwsktgs should $testname not successful, retrying.."))
  }

  it should "not create a trigger when feed fails to initialize" in withAssetCleaner(wskprops) { (wp, assetHelper) =>
    val testname = "not create a trigger when feed fails to initialize"
    org.apache.openwhisk.utils
      .retry(
        {
          assetHelper.deleteAssets()
          assetHelper.withCleaner(wsk.trigger, "badfeed", confirmDelete = false) { (trigger, name) =>
            trigger.create(name, feed = Some(s"bogus"), expectedExitCode = ANY_ERROR_EXIT).exitCode should equal(
              NOT_FOUND)
            trigger.get(name, expectedExitCode = NotFound.intValue)

            trigger.create(name, feed = Some(s"bogus/feed"), expectedExitCode = ANY_ERROR_EXIT).exitCode should equal(
              NOT_FOUND)
            trigger.get(name, expectedExitCode = NotFound.intValue)
          }
        },
        retriesOnTestFailures,
        Some(waitBeforeRetry),
        Some(s"${this.getClass.getName} > $behaviorwsktgs should $testname not successful, retrying.."))
  }

  it should "invoke a feed action with the correct lifecyle event when creating, retrieving and deleting a feed trigger" in withAssetCleaner(
    wskprops) { (wp, assetHelper) =>
    val testname =
      "invoke a feed action with the correct lifecyle event when creating, retrieving and deleting a feed trigger"
    org.apache.openwhisk.utils
      .retry(
        {
          assetHelper.deleteAssets()
          val actionName = "echo"
          val triggerName = "feedTest"

          assetHelper.withCleaner(wsk.action, actionName) { (action, _) =>
            action.create(actionName, Some(TestUtils.getTestActionFilename("echo.js")))
          }

          try {
            wsk.trigger.create(triggerName, feed = Some(actionName)).statusCode shouldBe OK

            wsk.trigger.get(triggerName).statusCode shouldBe OK
          } finally {
            wsk.trigger.delete(triggerName).statusCode shouldBe OK
          }
        },
        retriesOnTestFailures,
        Some(waitBeforeRetry),
        Some(s"${this.getClass.getName} > $behaviorwsktgs should $testname not successful, retrying.."))
  }
}


text:
package mekanism.common.network;

import io.netty.buffer.ByteBuf;

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

import mekanism.api.Coord4D;
import mekanism.api.Range4D;
import mekanism.common.Mekanism;
import mekanism.common.ObfuscatedNames;
import mekanism.common.PacketHandler;
import mekanism.common.frequency.Frequency;
import mekanism.common.frequency.FrequencyManager;
import mekanism.common.item.ItemPortableTeleporter;
import mekanism.common.network.PacketPortableTeleporter.PortableTeleporterMessage;
import mekanism.common.network.PacketPortalFX.PortalFXMessage;
import mekanism.common.tile.TileEntityTeleporter;
import mekanism.common.util.MekanismUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;

public class PacketPortableTeleporter implements IMessageHandler<PortableTeleporterMessage, IMessage>
{
	@Override
	public IMessage onMessage(PortableTeleporterMessage message, MessageContext context)
	{
		EntityPlayer player = PacketHandler.getPlayer(context);
		ItemStack itemstack = player.getCurrentEquippedItem();
		World world = player.worldObj;

		if(itemstack != null && itemstack.getItem() instanceof ItemPortableTeleporter)
		{
			ItemPortableTeleporter item = (ItemPortableTeleporter)itemstack.getItem();

			switch(message.packetType)
			{
				case DATA_REQUEST:
					sendDataResponse(message.frequency, world, player, item, itemstack);
					break;
				case DATA_RESPONSE:
					Mekanism.proxy.handleTeleporterUpdate(message);
					break;
				case SET_FREQ:
					FrequencyManager manager1 = getManager(message.frequency.isPublic() ? null : player.getCommandSenderName(), world);
					Frequency toUse = null;

					for(Frequency freq : manager1.getFrequencies())
					{
						if(freq.name.equals(message.frequency.name))
						{
							toUse = freq;
							break;
						}
					}

					if(toUse == null)
					{
						toUse = new Frequency(message.frequency.name, player.getCommandSenderName()).setPublic(message.frequency.isPublic());
						manager1.addFrequency(toUse);
					}

					sendDataResponse(toUse, world, player, item, itemstack);

					break;
				case DEL_FREQ:
					FrequencyManager manager = getManager(message.frequency.isPublic() ? null : player.getCommandSenderName(), world);
					manager.remove(message.frequency.name, player.getCommandSenderName());

					break;
				case TELEPORT:
					FrequencyManager manager2 = getManager(message.frequency.isPublic() ? null : player.getCommandSenderName(), world);
					Frequency found = null;

					for(Frequency freq : manager2.getFrequencies())
					{
						if(message.frequency.name.equals(freq.name))
						{
							found = freq;
							break;
						}
					}

					if(found == null)
					{
						break;
					}

					Coord4D coords = found.getClosestCoords(new Coord4D(player));

					World teleWorld = FMLCommonHandler.instance().getMinecraftServerInstance().worldServerForDimension(coords.dimensionId);
					TileEntityTeleporter teleporter = (TileEntityTeleporter)coords.getTileEntity(teleWorld);

					if(teleporter != null)
					{
						try {
							teleporter.didTeleport.add(player);
							teleporter.teleDelay = 5;

							item.setEnergy(itemstack, item.getEnergy(itemstack) - item.calculateEnergyCost(player, coords));

							if(player instanceof EntityPlayerMP)
							{
								MekanismUtils.setPrivateValue(((EntityPlayerMP)player).playerNetServerHandler, 0, NetHandlerPlayServer.class, ObfuscatedNames.NetHandlerPlayServer_floatingTickCount);
							}

							player.closeScreen();

							Mekanism.packetHandler.sendToAllAround(new PortalFXMessage(new Coord4D(player)), coords.getTargetPoint(40D));
							TileEntityTeleporter.teleportPlayerTo((EntityPlayerMP)player, coords, teleporter);

							world.playSoundAtEntity(player, "mob.endermen.portal", 1.0F, 1.0F);
							Mekanism.packetHandler.sendToReceivers(new PortalFXMessage(coords), new Range4D(coords));
						} catch(Exception e) {}
					}

					break;
			}
		}

		return null;
	}

	public void sendDataResponse(Frequency given, World world, EntityPlayer player, ItemPortableTeleporter item, ItemStack itemstack)
	{
		List<Frequency> publicFreqs = new ArrayList<Frequency>();

		for(Frequency f : getManager(null, world).getFrequencies())
		{
			publicFreqs.add(f);
		}

		List<Frequency> privateFreqs = new ArrayList<Frequency>();

		for(Frequency f : getManager(player.getCommandSenderName(), world).getFrequencies())
		{
			privateFreqs.add(f);
		}

		byte status = 3;

		if(given != null)
		{
			FrequencyManager manager = given.isPublic() ? getManager(null, world) : getManager(player.getCommandSenderName(), world);
			boolean found = false;

			for(Frequency iterFreq : manager.getFrequencies())
			{
				if(given.equals(iterFreq))
				{
					given = iterFreq;
					found = true;
					break;
				}
			}

			if(!found)
			{
				given = null;
			}
		}

		if(given != null)
		{
			if(given.activeCoords.size() == 0)
			{
				status = 3;
			}
			else {
				Coord4D coords = given.getClosestCoords(new Coord4D(player));
				double energyNeeded = item.calculateEnergyCost(player, coords);

				if(energyNeeded > item.getEnergy(itemstack))
				{
					status = 4;
				}
				else {
					status = 1;
				}
			}
		}

		Mekanism.packetHandler.sendTo(new PortableTeleporterMessage(given, status, publicFreqs, privateFreqs), (EntityPlayerMP)player);
	}

	public FrequencyManager getManager(String owner, World world)
	{
		if(owner == null)
		{
			return Mekanism.publicTeleporters;
		}
		else {
			if(!Mekanism.privateTeleporters.containsKey(owner))
			{
				FrequencyManager manager = new FrequencyManager(Frequency.class, owner);
				Mekanism.privateTeleporters.put(owner, manager);
				manager.createOrLoad(world);
			}

			return Mekanism.privateTeleporters.get(owner);
		}
	}

	public static class PortableTeleporterMessage implements IMessage
	{
		public PortableTeleporterPacketType packetType;
		public Frequency frequency;
		public byte status;

		public List<Frequency> publicCache = new ArrayList<Frequency>();
		public List<Frequency> privateCache = new ArrayList<Frequency>();

		public PortableTeleporterMessage() {}

		public PortableTeleporterMessage(PortableTeleporterPacketType type, Frequency freq)
		{
			packetType = type;

			if(type == PortableTeleporterPacketType.DATA_REQUEST)
			{
				frequency = freq;
			}
			else if(type == PortableTeleporterPacketType.SET_FREQ)
			{
				frequency = freq;
			}
			else if(type == PortableTeleporterPacketType.DEL_FREQ)
			{
				frequency = freq;
			}
			else if(type == PortableTeleporterPacketType.TELEPORT)
			{
				frequency = freq;
			}
		}

		public PortableTeleporterMessage(Frequency freq, byte b, List<Frequency> publicFreqs, List<Frequency> privateFreqs)
		{
			packetType = PortableTeleporterPacketType.DATA_RESPONSE;

			frequency = freq;
			status = b;

			publicCache = publicFreqs;
			privateCache = privateFreqs;
		}

		@Override
		public void toBytes(ByteBuf buffer)
		{
			buffer.writeInt(packetType.ordinal());

			if(packetType == PortableTeleporterPacketType.DATA_REQUEST)
			{
				if(frequency != null)
				{
					buffer.writeBoolean(true);
					PacketHandler.writeString(buffer, frequency.name);
					buffer.writeBoolean(frequency.publicFreq);
				}
				else {
					buffer.writeBoolean(false);
				}
			}
			else if(packetType == PortableTeleporterPacketType.DATA_RESPONSE)
			{
				if(frequency != null)
				{
					buffer.writeBoolean(true);
					PacketHandler.writeString(buffer, frequency.name);
					buffer.writeBoolean(frequency.publicFreq);
				}
				else {
					buffer.writeBoolean(false);
				}

				buffer.writeByte(status);

				ArrayList data = new ArrayList();
				data.add(publicCache.size());

				for(Frequency freq : publicCache)
				{
					freq.write(data);
				}

				data.add(privateCache.size());

				for(Frequency freq : privateCache)
				{
					freq.write(data);
				}

				PacketHandler.encode(data.toArray(), buffer);
			}
			else if(packetType == PortableTeleporterPacketType.SET_FREQ)
			{
				PacketHandler.writeString(buffer, frequency.name);
				buffer.writeBoolean(frequency.publicFreq);
			}
			else if(packetType == PortableTeleporterPacketType.DEL_FREQ)
			{
				PacketHandler.writeString(buffer, frequency.name);
				buffer.writeBoolean(frequency.publicFreq);
			}
			else if(packetType == PortableTeleporterPacketType.TELEPORT)
			{
				PacketHandler.writeString(buffer, frequency.name);
				buffer.writeBoolean(frequency.publicFreq);
			}
		}

		@Override
		public void fromBytes(ByteBuf buffer)
		{
			packetType = PortableTeleporterPacketType.values()[buffer.readInt()];

			if(packetType == PortableTeleporterPacketType.DATA_REQUEST)
			{
				if(buffer.readBoolean())
				{
					frequency = new Frequency(PacketHandler.readString(buffer), null).setPublic(buffer.readBoolean());
				}
			}
			else if(packetType == PortableTeleporterPacketType.DATA_RESPONSE)
			{
				if(buffer.readBoolean())
				{
					frequency = new Frequency(PacketHandler.readString(buffer), null).setPublic(buffer.readBoolean());
				}

				status = buffer.readByte();

				int amount = buffer.readInt();

				for(int i = 0; i < amount; i++)
				{
					publicCache.add(new Frequency(buffer));
				}

				amount = buffer.readInt();

				for(int i = 0; i < amount; i++)
				{
					privateCache.add(new Frequency(buffer));
				}
			}
			else if(packetType == PortableTeleporterPacketType.SET_FREQ)
			{
				frequency = new Frequency(PacketHandler.readString(buffer), null).setPublic(buffer.readBoolean());
			}
			else if(packetType == PortableTeleporterPacketType.DEL_FREQ)
			{
				frequency = new Frequency(PacketHandler.readString(buffer), null).setPublic(buffer.readBoolean());
			}
			else if(packetType == PortableTeleporterPacketType.TELEPORT)
			{
				frequency = new Frequency(PacketHandler.readString(buffer), null).setPublic(buffer.readBoolean());
			}
		}
	}

	public static enum PortableTeleporterPacketType
	{
		DATA_REQUEST,
		DATA_RESPONSE,
		SET_FREQ,
		DEL_FREQ,
		TELEPORT;
	}
}


text:
package org.oscm.ui.menu;

import static org.oscm.ui.authorization.Conditions.ALWAYS;
import static org.oscm.ui.authorization.Conditions.NEVER;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import org.oscm.ui.authorization.UIStatus;

public class MenuGroupBuilderTest implements UIStatus {

    private String currentPage = null;

    private MenuGroupBuilder builder;

    public String getCurrentPageLink() {
        return currentPage;
    }

    public boolean isHidden(String id) {
        return false;
    }

    @Before
    public void setup() {
        Map<String, MenuGroupBuilder> all = new HashMap<String, MenuGroupBuilder>();
        builder = new MenuGroupBuilder("id", "label.key", all, ALWAYS, this);
        assertEquals("id", builder.getId());
        assertEquals("label.key", builder.getLabelKey());
        assertSame(builder, all.get("id"));
    }

    @Test
    public void testExpanded() {
        assertTrue(builder.isExpanded());
        builder.toggleExpanded();
        assertFalse(builder.isExpanded());
        builder.toggleExpanded();
        assertTrue(builder.isExpanded());
    }

    @Test
    public void testAddGroup() {
        builder.addGroup("id", ALWAYS);
        assertEquals(1, builder.getGroups().size());
        final MenuGroup g = builder.getGroups().get(0);
        assertEquals("id", g.getId());
        assertEquals("id", g.getLabelKey());
        assertTrue(g.isVisible());
    }

    @Test
    public void testAddGroupAnd() {
        builder.addGroup("id", ALWAYS, NEVER);
        final MenuGroup g = builder.getGroups().get(0);
        assertFalse(g.isVisible());
    }

    @Test
    public void testItem() {
        builder.addItem("id", "somepage.html", ALWAYS);
        assertEquals(1, builder.getItems().size());
        final MenuItem i = builder.getItems().get(0);
        assertEquals("id", i.getId());
        assertEquals("id.title", i.getLabelKey());
        assertEquals("somepage.html", i.getLink());
        assertTrue(i.isVisible());
    }

    @Test
    public void testItemAnd() {
        builder.addItem("id", "somepage.html", ALWAYS, NEVER);
        final MenuItem i = builder.getItems().get(0);
        assertFalse(i.isVisible());
    }

    @Test
    public void testItemSelection() {
        builder.addItem("id", "somepage.html");
        final MenuItem i = builder.getItems().get(0);
        assertFalse(i.isSelected());
        currentPage = "somepage.html";
        assertTrue(i.isSelected());
        currentPage = "otherpage.html";
        assertFalse(i.isSelected());
    }

}


text:
var assert = require('assert');
var OAuth = require('oauth');
var url = require('url');
var Promise = require('promise');
var debug = require('debug')('oauth-1-client');
var request = require('request');

require('extend-error');
var HttpApiError = Error.extend('HttpApiError');

var Client = function(options) {
    assert(options.key, 'Must provide API key');
    assert(options.secret, 'Must provide API secret');
    assert(options.requestUrl, 'Must provide requestUrl');
    assert(options.accessUrl, 'Must provide accessUrl');
    assert(options.apiHostName, 'Must provide apiHostName');

    this.apiKey = options.key;
    this.apiSecret = options.secret;
    this.apiHostName = options.apiHostName;

    // Note: callbackURL is optional here. Can also be provided via extraParams arg to requestToken
    this.callbackURL = options.callbackURL;

    this.oauthClient = new OAuth.OAuth(
        options.requestUrl,
        options.accessUrl,
        this.apiKey,
        this.apiSecret,
        '1.0',
        this.callbackURL,
        'HMAC-SHA1');
};

function getCredentials(token, secret, required) {
    var credentials;
    if (typeof token === 'object') {
        credentials = token;
    } else {
        credentials = {
            token: token,
            secret: secret
        };
    }
    if (required) {
        assert(credentials.token, 'Must supply authentication token');
        assert(credentials.secret, 'Must supply authentication secret');
    }
    return credentials;
}

Client.prototype.auth = function(token, secret) {
    var credentials = getCredentials(token, secret);
    var self = this;
    return {
        get: function(path, pageOrQuery) {
            return self.get(path, pageOrQuery, credentials);
        },
        put: function(path, content) {
            return self.put(path, content, credentials);
        },
        post: function(path, content) {
            return self.post(path, content, credentials);
        },
        'delete': function(path) {
            return self['delete'](path, credentials);
        }
    };
};

Client.prototype.get = function(path, pageOrQuery, token, secret) {
    var credentials = getCredentials(token, secret);
    return new Promise(function(resolve, reject) {
        var responseHandler = createResponseHandler(resolve, reject);
        var url;
        if (credentials.token && credentials.secret) {
            url = buildUrl(this.apiKey, this.apiSecret, this.apiHostName, path, pageOrQuery);
            debug('GET (auth):', url);
            this.oauthClient.get(url, credentials.token, credentials.secret, responseHandler);
        } else {
            url = buildUrl(this.apiKey, null, this.apiHostName, path, pageOrQuery);
            debug('GET (unauth):', url);
            request({
                uri: url,
                method: 'GET'
            }, function(err, res, body) {
                responseHandler(err, body, res);
            }.bind(this));
        }
    }.bind(this));
};

Client.prototype.put = function(path, content, token, secret) {
    var credentials = getCredentials(token, secret, true);
    var url = buildUrl(this.apiKey, this.apiSecret, this.apiHostName, path);
    return new Promise(function(resolve, reject) {
        var responseHandler = createResponseHandler(resolve, reject);
        debug('PUT:', url);
        this.oauthClient.put(url, credentials.token, credentials.secret, content, responseHandler);
    }.bind(this));
};

Client.prototype.post = function(path, content, token, secret) {
    var credentials = getCredentials(token, secret, true);
    var url = buildUrl(this.apiKey, this.apiSecret, this.apiHostName, path);
    return new Promise(function(resolve, reject) {
        var responseHandler = createResponseHandler(resolve, reject);
        debug('POST:', url);
        this.oauthClient.post(url, credentials.token, credentials.secret, content, responseHandler);
    }.bind(this));
};

Client.prototype['delete'] = function(path, token, secret) {
    var credentials = getCredentials(token, secret, true);
    var url = buildUrl(this.apiKey, this.apiSecret, this.apiHostName, path);
    return new Promise(function(resolve, reject) {
        var responseHandler = createResponseHandler(resolve, reject);
        debug('DELETE:', url);
        this.oauthClient['delete'](url, credentials.token, credentials.secret, responseHandler);
    }.bind(this));
};

Client.prototype.requestToken = function(extraParams) {
    return new Promise(function(resolve, reject) {
        this.oauthClient.getOAuthRequestToken(extraParams || {}, function(err, oauthToken, oauthTokenSecret, parsedQueryString) {
            if (err) {
                return reject(err);
            }
            resolve({
                token: oauthToken,
                tokenSecret: oauthTokenSecret,
                authorizeUrl: parsedQueryString.login_url,
                query: parsedQueryString
            });
        });
    }.bind(this));
};

Client.prototype.accessToken = function(token, secret, verifier) {
    return new Promise(function(resolve, reject) {
        this.oauthClient.getOAuthAccessToken(token, secret, verifier, function (err, oauthAccessToken, oauthAccessTokenSecret, parsedQueryString) {
            if (err) {
                return reject(err);
            }
            resolve({
                token: oauthAccessToken,
                tokenSecret: oauthAccessTokenSecret,
                query: parsedQueryString
            });
        });
    }.bind(this));
};

function createResponseHandler(resolve, reject) {
    return function responseHandler(err, data, res) {
        if (err) {
            // patch the error returned from oauth lib to add headers (can include important info like request IDs)
            if (res && res.headers) {
                err.headers = res.headers;
            }
            return reject(err);
        }
        if (res.statusCode.toString()[0] !== '2') {
            return reject(new HttpApiError({ statusCode: res.statusCode, body: data }));
        }
        if (typeof data === 'string') {
            try {
                var parsedBody = JSON.parse(data || '{}');
                resolve({
                    statusCode: res.statusCode,
                    body: parsedBody,
                    headers: res.headers
                });
            } catch (err) {
                reject('Error parsing JSON response from API. Error:' + err);
            }
        }
    };
}

function buildUrl(apiKey, apiSecret, apiHostName, path, pageOrQuery) {
    if (apiHostName === null) {
        throw new Error('Must provide apiHostName');
    }
    if (path === null) {
        throw new Error('Must provide a path');
    }
    var query = (pageOrQuery && typeof pageOrQuery === 'object')
        ? pageOrQuery
        : {};
    if (apiKey && !apiSecret) {
        query.api_key = apiKey;
    }
    return url.format({
        protocol: "https:",
        hostname: apiHostName,
        pathname: path,
        query: query
    });
}

module.exports = Client;


text:
'use strict';

bookly.config(['$routeProvider', function ($routeProvider) {
    $routeProvider

        .when('/register', {
            templateUrl: '../templates/register.html',
            controller: 'RegistrationController'
        })
        .when('/login', {
            templateUrl: '../templates/login.html',
            controller: 'RegistrationController'
        })
        .when('/books', {
            templateUrl: '../templates/books.html',
            controller: 'BooksController'
        })
        .otherwise({
            redirectTo: '/login'
        });
}]);


text:
package org.apache.solr.analytics.value;

import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import org.apache.solr.analytics.facet.compare.ExpressionComparator;
import org.apache.solr.analytics.util.function.FloatConsumer;
import org.apache.solr.analytics.value.constant.ConstantFloatValue;

/**
 * A single-valued analytics value that can be represented as a float.
 *
 *
The back-end production of the value can change inbetween calls to {@link #getFloat()} and
 * {@link #exists()}, resulting in different values on each call.
 */
public interface FloatValue extends FloatValueStream, AnalyticsValue {
  /**
   * Get the float representation of the current value.
   *
   *
NOTE: The value returned is not valid unless calling {@link #exists()} afterwards returns
   * {@code TRUE}.
   *
   * @return the current value
   */
  float getFloat();

  /**
   * An interface that represents all of the types a {@link FloatValue} should be able to cast to.
   */
  public static interface CastingFloatValue
      extends FloatValue, DoubleValue, StringValue, ComparableValue {}

  /**
   * An abstract base for {@link CastingFloatValue} that automatically casts to all types if {@link
   * #getFloat()} and {@link #exists()} are implemented.
   */
  public abstract static class AbstractFloatValue implements CastingFloatValue {
    @Override
    public double getDouble() {
      return getFloat();
    }

    @Override
    public String getString() {
      float val = getFloat();
      return exists() ? Float.toString(val) : null;
    }

    @Override
    public Object getObject() {
      float val = getFloat();
      return exists() ? val : null;
    }

    @Override
    public void streamFloats(FloatConsumer cons) {
      float val = getFloat();
      if (exists()) {
        cons.accept(val);
      }
    }

    @Override
    public void streamDoubles(DoubleConsumer cons) {
      double val = getDouble();
      if (exists()) {
        cons.accept(val);
      }
    }

    @Override
    public void streamStrings(Consumer<String> cons) {
      String val = getString();
      if (exists()) {
        cons.accept(val);
      }
    }

    @Override
    public void streamObjects(Consumer<Object> cons) {
      Object val = getObject();
      if (exists()) {
        cons.accept(val);
      }
    }

    @Override
    public AnalyticsValue convertToConstant() {
      if (getExpressionType().equals(ExpressionType.CONST)) {
        return new ConstantFloatValue(getFloat());
      }
      return this;
    }

    @Override
    public ExpressionComparator<Float> getObjectComparator(String expression) {
      return new ExpressionComparator<>(expression);
    }
  }
}


text:
<?php
namespace app\models;

class Moves extends \lithium\data\Model {

}
?>


text:
DawPRFinal
==========

Mi práctica final de la asignatura Desarrollo de Aplicaciones Web


text:
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -fwarn-redundant-constraints #-}
module T10770b where

f :: (Show a, Show (Maybe a)) => Maybe a -> String
f x = let k = show x in k

g :: (Show a, Show (Maybe a)) => Maybe a -> String
g x = show x


text:
package cz.zcu.kiv.crce.client.base.metadata;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAttribute;

/**
 *
 * Parent object for all CRCE value objects.
 *
 * Marked as Serializable and contains id and namespace properties.
 *
 * Date: 18.5.15
 *
 * @author Jakub Danek
 */
public class ValueObject implements Serializable {

    /**
	 *
	 */
	private static final long serialVersionUID = -6128720967772972230L;
	private String id;
    private String namespace;

    public ValueObject() {
    }

    public ValueObject(String id) {
        this.id = id;
    }

    public ValueObject(String id, String namespace) {
        this.id = id;
        this.namespace = namespace;
    }

    @XmlAttribute(name = "uuid")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @XmlAttribute(name = "namespace")
    public String getNamespace() {
        return namespace;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }
}


text:
function onPasswordStrenghtCheck(response, headers)
{

}


text:
		   Aceita .

		    Taxa de entrega
 para o bairro  (mais informações)

		    Taxa de entrega
 para todos os bairros de  (mais informações)

		     Selecione um bairro da área de entrega: <select dojoType="dijit.form.FilteringSelect" class="nSelection"
		      autoComplete="false" selectOnClick="true" hasDownArrow="false" invalidMessage="Bairro fora da área do restaurante" promptMessage="Digite o bairro"  style="background-color: white;width: 150px;margin-bottom:0px;margin-top: 0px;" ></select>

		    Prazo de entrega estimado 30 min (mais informações).