text:
package org.cloudfoundry.abacus.demo.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Arrays;
import java.util.StringJoiner;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Usage {

  @JsonProperty("start")
  private long start;

  @JsonProperty("end")
  private long end;

  @JsonProperty("organization_id")
  private String organizationID = "us-south:a3d7fe4d-3cb1-4cc3-a831-ffe98e20cf27";

  @JsonProperty("space_id")
  private String spaceID = "aaeae239-f3f8-483c-9dd0-de5d41c38b6a";

  @JsonProperty("consumer_id")
  private String consumerID = "app:bbeae239-f3f8-483c-9dd0-de6781c38bab";

  @JsonProperty("resource_id")
  private String resourceID = "object-storage";

  @JsonProperty("plan_id")
  private String planID = "basic";

  @JsonProperty("resource_instance_id")
  private String resourceInstanceID = "0b39fa70-a65f-4183-bae8-385633ca5c87";

  @JsonProperty("measured_usage")
  private Measure[] measures;

  public Usage(long timestamp, Measure[] measures) {
    this.start = timestamp;
    this.end = timestamp;
    this.measures = measures;
  }

  public long getStart() {
    return start;
  }

  public void setStart(long start) {
    this.start = start;
  }

  public long getEnd() {
    return end;
  }

  public void setEnd(long end) {
    this.end = end;
  }

  public String getOrganizationID() {
    return organizationID;
  }

  public void setOrganizationID(String organizationID) {
    this.organizationID = organizationID;
  }

  public String getSpaceID() {
    return spaceID;
  }

  public void setSpaceID(String spaceID) {
    this.spaceID = spaceID;
  }

  public String getConsumerID() {
    return consumerID;
  }

  public void setConsumerID(String consumerID) {
    this.consumerID = consumerID;
  }

  public String getResourceID() {
    return resourceID;
  }

  public void setResourceID(String resourceID) {
    this.resourceID = resourceID;
  }

  public String getPlanID() {
    return planID;
  }

  public void setPlanID(String planID) {
    this.planID = planID;
  }

  public String getResourceInstanceID() {
    return resourceInstanceID;
  }

  public void setResourceInstanceID(String resourceInstanceID) {
    this.resourceInstanceID = resourceInstanceID;
  }

  public Measure[] getMeasures() {
    return measures;
  }

  public void setMeasures(Measure[] measures) {
    this.measures = measures;
  }

  @Override
  public String toString() {
    return new StringJoiner(", ", Usage.class.getSimpleName() + "[", "]")
        .add("start=" + start)
        .add("end=" + end)
        .add("organizationID='" + organizationID + "'")
        .add("spaceID='" + spaceID + "'")
        .add("consumerID='" + consumerID + "'")
        .add("resourceID='" + resourceID + "'")
        .add("planID='" + planID + "'")
        .add("resourceInstanceID='" + resourceInstanceID + "'")
        .add("measures=" + Arrays.toString(measures))
        .toString();
  }
}


text:
<?php
/**
 * Smarty Internal Plugin Templateparser Parsetrees
 * These are classes to build parsetrees in the template parser
 *
 * @package    Smarty
 * @subpackage Compiler
 * @author     Thue Kristensen
 * @author     Uwe Tews
 */

/**
 * Raw chars as part of a double quoted string.
 *
 * @package    Smarty
 * @subpackage Compiler
 * @ignore
 */
class Smarty_Internal_ParseTree_DqContent extends Smarty_Internal_ParseTree
{
    /**
     * Create parse tree buffer with string content
     *
     * @param object $parser parser object
     * @param string $data   string section
     */
    public function __construct($parser, $data)
    {
        $this->parser = $parser;
        $this->data = $data;
    }

    /**
     * Return content as double quoted string
     *
     * @return string doubled quoted string
     */
    public function to_smarty_php()
    {
        return '"' . $this->data . '"';
    }
}

redpajama_set_name: RedPajamaGithub


text:
package iso20022

// Account to or from which a cash entry is made.
type CashAccount21 struct {

	// Party that manages the account on behalf of the account owner, that is manages the registration and booking of entries on the account, calculates balances on the account and provides information about the account.
	Servicer *BICIdentifier `xml:"Svcr,omitempty"`

	// Unique and unambiguous identification for the account between the account owner and the account servicer.
	Identification *AccountIdentification5Choice `xml:"Id"`
}

func (c *CashAccount21) SetServicer(value string) {
	c.Servicer = (*BICIdentifier)(&value)
}

func (c *CashAccount21) AddIdentification() *AccountIdentification5Choice {
	c.Identification = new(AccountIdentification5Choice)
	return c.Identification
}


text:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class _0140WordBreakII {
  public List<String> wordBreak(String s, List<String> wordDict) {
    Set<String> wordSet = new HashSet<>(wordDict);
    Map<String, List<String>> map = new HashMap<>();
    return subWordBreak(s, 0, s.length(), wordSet, map);
  }

  private List<String> subWordBreak(String s, int start, int end, Set<String> wordSet, Map<String, List<String>> map) {
    String key = start + " " + end;
    if (map.containsKey(key)) {
      return map.get(key);
    }
    List<String> breaks = new ArrayList<>();
    for (int i = start; i < end; i++) {
      String prefix = s.substring(start, i + 1);
      if (wordSet.contains(prefix)) {
        if (i == s.length() - 1) {
          breaks.add(prefix);
        } else {
          List<String> suffixes = subWordBreak(s, i + 1, end, wordSet, map);
          if (suffixes.isEmpty()) {
            continue;
          } else {
            for (String suffix : suffixes) {
              breaks.add(prefix + " " + suffix);
            }
          }
        }
      }
    }
    map.put(key, breaks);
    return breaks;
  }
}


text:
<?php
/**
 *
 * This file is part of the Aura project for PHP.
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Framework\View\Helper;

use Aura\View\Helper\AbstractHelper;
use Aura\Router\Map as RouterMap;

/**
 *
 * Generates route links.
 *
 * @package Aura.Framework
 *
 */
class Route extends AbstractHelper
{
    /**
     *
     * A router map object.
     *
     * @var RouterMap
     *
     */
    protected $router;

    /**
     *
     * Constructor.
     *
     * @param RouterMap $router The router map.
     *
     */
    public function __construct(RouterMap $router)
    {
        $this->router = $router;
    }

    /**
     *
     * Returns a route by name; optional interpolates data into it.
     *
     * @param string $name The route name to look up.
     *
     * @param array $data The data to interpolate into the URI; data keys
     * map to param tokens in the path.
     *
     * @return string|false A URI path string if the route name is found, or
     * boolean false if not.
     *
     */
    public function __invoke($name, array $data = [])
    {
        return $this->router->generate($name, $data);
    }
}


text:
/* */
'use strict';
var babelHelpers = require('./util/babelHelpers');
var style = require('./style/index'),
    events = require('./events/index'),
    query = require('./query/index'),
    activeElement = require('./activeElement'),
    ownerDocument = require('./ownerDocument'),
    ownerWindow = require('./ownerWindow');
module.exports = babelHelpers._extends({}, style, events, query, {
  activeElement: activeElement,
  ownerDocument: ownerDocument,
  ownerWindow: ownerWindow,
  requestAnimationFrame: require('./util/requestAnimationFrame')
});


text:
package org.apache.beehive.netui.compiler.model.validation;

public interface ValidatorConstants
{
    String RULENAME_INT_RANGE = "netui_longRange";
    String RULENAME_FLOAT_RANGE = "floatRange";
    String RULENAME_REQUIRED = "required";
    String RULENAME_EMAIL = "email";
    String RULENAME_CREDIT_CARD = "creditCard";
    String RULENAME_MINLENGTH = "minlength";
    String RULENAME_MAXLENGTH = "maxlength";
    String RULENAME_MASK = "mask";
    String RULENAME_BYTE = "byte";
    String RULENAME_SHORT = "short";
    String RULENAME_INTEGER = "integer";
    String RULENAME_LONG = "long";
    String RULENAME_FLOAT = "float";
    String RULENAME_DOUBLE = "double";
    String RULENAME_DATE = "date";
    String RULENAME_VALID_WHEN = "netui_validwhen";
    String RULENAME_URL = "url";

    String VARNAME_MIN = "min";
    String VARNAME_MAX = "max";
    String VARNAME_MINLENGTH = "minlength";
    String VARNAME_MAXLENGTH = "maxlength";
    String VARNAME_MASK = "mask";
    String VARNAME_DATE_PATTERN = "datePattern";
    String VARNAME_DATE_PATTERN_STRICT = "datePatternStrict";
    String VARNAME_VALID_WHEN = RULENAME_VALID_WHEN;
    String VARNAME_ALLOW_ALL_SCHEMES = "allowallschemes";
    String VARNAME_ALLOW_TWO_SLASHES = "allow2slashes";
    String VARNAME_DISALLOW_FRAGMENTS = "nofragments";
    String VARNAME_SCHEMES = "schemes";

    String EXPRESSION_KEY_PREFIX = "NETUI-EXPRESSION:";
}


text:
package com.github.nicolediana;

import com.github.nicolediana.exception.FieldValidationException;
import com.github.nicolediana.model.Film;
import com.github.nicolediana.model.Attore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by pcnicole on 04/11/2014.
 */

public class IngaggioResource extends Controller {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Attore attore = Attore.validate(Attore.class, request.getParameter("idattore"));
            if(attore == null)
                throw new FieldValidationException();

            Film film = Film.validate(Film.class, request.getParameter("idfilm"));
            if(film == null)
                throw new FieldValidationException();

            attore.getFilms().add(film);
            attore.update();

            PrintWriter writer = response.getWriter();
            writer.println(attore.toJson());
        } catch(FieldValidationException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AspNetMvcBlog.Application
{
    public class BaseController : Controller
    {
        const string MSG_SUCCESS = "MSG_SUCCESS";
        const string MSG_ERROR = "MSG_ERROR";

        protected void Success(string message)
        {
            TempData[MSG_SUCCESS] = message;
        }

        protected void Error(string message)
        {
            TempData[MSG_ERROR] = message;
        }

        protected override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            ViewBag.SUCCESS = TempData[MSG_SUCCESS];
            ViewBag.ERROR = TempData[MSG_ERROR];

            base.OnResultExecuting(filterContext);
        }
    }
}


text:
set -x

# is /dev/sdb formatted to ext4?
if lsblk -f /dev/sdb | grep -q 'ext4' ; then
  echo "/dev/sdb already formatted"
else
  sudo mkfs.ext4 -m 0 -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/sdb
fi

# is disk mounted?
findmnt /datadisk1
if [ $? -ne 0 ]; then
  sudo mkdir -p /datadisk1
  sudo mount -o discard,defaults /dev/sdb /datadisk1
  sudo chmod a+rw /datadisk1
fi

# is disk entry in fstab?
UUID=$(sudo blkid -s UUID -o value /dev/sdb)
if cat /etc/fstab | grep -q '/datadisk1' ; then
  echo "/datadisk1 already added to fstab, ensuring UUID is correct"
  sudo sed -i "s#^UUID=.* /datadisk1#UUID=$UUID /datadisk1#" /etc/fstab
else
  echo UUID=$UUID /datadisk1 ext4 discard,defaults,noatime,nofail 0 2 | sudo tee -a /etc/fstab
fi

# writes timestamp and current zone to file
file=/datadisk1/hello.txt
sudo touch $file
sudo chmod a+rw $file
date "+%F %T" | tee -a $file
curl -s http://metadata.google.internal/computeMetadata/v1/instance/zone -H "Metadata-Flavor: Google" | tee -a $file
echo "" | tee -a $file


text:
namespace Microsoft.Azure.Management.ServiceBus.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Represents a filter which is a composition of an expression and an
    /// action that is executed in the pub/sub pipeline.
    /// </summary>
    public partial class SqlFilter
    {
        /// <summary>
        /// Initializes a new instance of the SqlFilter class.
        /// </summary>
        public SqlFilter()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the SqlFilter class.
        /// </summary>
        /// <param name="sqlExpression">The SQL expression. e.g.
        /// MyProperty='ABC'</param>
        /// <param name="compatibilityLevel">This property is reserved for
        /// future use. An integer value showing the compatibility level,
        /// currently hard-coded to 20.</param>
        /// <param name="requiresPreprocessing">Value that indicates whether
        /// the rule action requires preprocessing.</param>
        public SqlFilter(string sqlExpression = default(string), int? compatibilityLevel = default(int?), bool? requiresPreprocessing = default(bool?))
        {
            SqlExpression = sqlExpression;
            CompatibilityLevel = compatibilityLevel;
            RequiresPreprocessing = requiresPreprocessing;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the SQL expression. e.g. MyProperty='ABC'
        /// </summary>
        [JsonProperty(PropertyName = "sqlExpression")]
        public string SqlExpression { get; set; }

        /// <summary>
        /// Gets or sets this property is reserved for future use. An integer
        /// value showing the compatibility level, currently hard-coded to 20.
        /// </summary>
        [JsonProperty(PropertyName = "compatibilityLevel")]
        public int? CompatibilityLevel { get; set; }

        /// <summary>
        /// Gets or sets value that indicates whether the rule action requires
        /// preprocessing.
        /// </summary>
        [JsonProperty(PropertyName = "requiresPreprocessing")]
        public bool? RequiresPreprocessing { get; set; }

    }
}


text:
'use strict';
var when = require('when');
require('../lib/run')(when.promise);


text:
package com.zimbra.cs.account.callback;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.StringUtil;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.AttributeCallback;
import com.zimbra.cs.account.AttributeManager;
import com.zimbra.cs.account.Config;
import com.zimbra.cs.account.Entry;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;

public class CheckPortConflict extends AttributeCallback {

    private static final Set<String> sPortAttrs = new HashSet<String>();

    static {
        // TODO: use a flag in zimbra-attrs.xml and generate this map automatically
        sPortAttrs.add(Provisioning.A_zimbraAdminPort);
        sPortAttrs.add(Provisioning.A_zimbraAdminProxyPort);

        sPortAttrs.add(Provisioning.A_zimbraImapBindPort);
        sPortAttrs.add(Provisioning.A_zimbraImapSSLBindPort);
        sPortAttrs.add(Provisioning.A_zimbraImapProxyBindPort);
        sPortAttrs.add(Provisioning.A_zimbraImapSSLProxyBindPort);

        sPortAttrs.add(Provisioning.A_zimbraLmtpBindPort);

        sPortAttrs.add(Provisioning.A_zimbraMailPort);
        sPortAttrs.add(Provisioning.A_zimbraMailSSLPort);
        sPortAttrs.add(Provisioning.A_zimbraMailSSLClientCertPort);

        sPortAttrs.add(Provisioning.A_zimbraPop3BindPort);
        sPortAttrs.add(Provisioning.A_zimbraPop3SSLBindPort);
        sPortAttrs.add(Provisioning.A_zimbraPop3ProxyBindPort);
        sPortAttrs.add(Provisioning.A_zimbraPop3SSLProxyBindPort);

        sPortAttrs.add(Provisioning.A_zimbraRemoteManagementPort);

        sPortAttrs.add(Provisioning.A_zimbraMemcachedBindPort);

        sPortAttrs.add(Provisioning.A_zimbraMailProxyPort);
        sPortAttrs.add(Provisioning.A_zimbraMailSSLProxyPort);
        sPortAttrs.add(Provisioning.A_zimbraMailSSLProxyClientCertPort);

        sPortAttrs.add(Provisioning.A_zimbraMessageChannelPort);
    }

    @Override
    public void preModify(CallbackContext context, String attrName, Object attrValue,
            Map attrsToModify, Entry entry)
    throws ServiceException {

        if (entry != null && !(entry instanceof Server) && !(entry instanceof Config)) return;

        if (context.isDoneAndSetIfNot(CheckPortConflict.class)) {
            return;
        }

        // sanity check, zimbra-attrs.xml and the sPortAttrsToCheck map has to be in sync
        if (!sPortAttrs.contains(attrName) ||
            !AttributeManager.getInstance().isServerInherited(attrName))
            assert(false);

        // server == null means the server entry is being created
        if (entry == null || entry instanceof Server)
            checkServer((Server)entry, attrsToModify);
        else
            checkConfig((Config)entry, attrsToModify);
    }

    private void checkServer(Server server, Map<String, Object> serverAttrsToModify) throws ServiceException {
        Map<String, String> ports = new HashMap<String, String>();
        Map<String, Object> defaults = Provisioning.getInstance().getConfig().getServerDefaults();

        // collect current port values
        if (server != null) {
            for (String attrName : sPortAttrs) {
                if (!serverAttrsToModify.containsKey(attrName))
                    ports.put(server.getAttr(attrName), attrName);
            }
        }

        // check conflict for attrs being changed
        for (Map.Entry<String, Object> attrToModify : serverAttrsToModify.entrySet()) {
            String attrName = attrToModify.getKey();

            if (!sPortAttrs.contains(attrName))
                continue;

            SingleValueMod mod = singleValueMod(serverAttrsToModify, attrName);
            String newValue = null;
            if (mod.setting())
                newValue = mod.value();
            else {
                // unsetting, get default, which would become the new value
                Object defValue = defaults.get(attrName);
                if (defValue != null) {
                    if (defValue instanceof String)
                        newValue = (String)defValue;
                    else
                        ZimbraLog.misc.info("default value for " + attrName + " should be a single-valued attribute, invalid default value ignored");
                }
            }

            if (conflict(ports, newValue)) {
                String serverInfo = (server == null) ? "" : " on server " + server.getName();
                throw ServiceException.INVALID_REQUEST("port " + newValue + " conflict between " +
                                                       attrName + " and " + ports.get(newValue) + serverInfo, null);
            } else
                ports.put(newValue, attrName);
        }
    }

    private void checkConfig(Config config, Map<String, Object> configAttrsToModify) throws ServiceException {
        BiMap<String, String> newDefaults = HashBiMap.create();

        /*
         * First, make sure there is no conflict in the Config entry, even
         * if the value on the config entry might not be effective on a server.
         */
        for (String attrName : sPortAttrs) {
            if (!configAttrsToModify.containsKey(attrName))
                newDefaults.put(config.getAttr(attrName), attrName);
        }

        // check conflict for attrs being changed
        for (Map.Entry<String, Object> attrToModify : configAttrsToModify.entrySet()) {
            String attrName = attrToModify.getKey();

            if (!sPortAttrs.contains(attrName))
                continue;

            SingleValueMod mod = singleValueMod(configAttrsToModify, attrName);
            String newValue = null;
            if (mod.setting())
                newValue = mod.value();

            if (conflict(newDefaults, newValue)) {
                throw ServiceException.INVALID_REQUEST("port " + newValue + " conflict between " +
                        attrName + " and " + newDefaults.get(newValue) + " on global config", null);
            } else
                newDefaults.put(newValue, attrName);
        }

        /*
         * Then, iterate through all servers see if this port change on the Config
         * entry has impact on a server.
         */
        List<Server> servers = Provisioning.getInstance().getAllServers();
        for (Server server : servers) {
            checkServerWithNewDefaults(server, newDefaults, configAttrsToModify);
        }
    }

    private void checkServerWithNewDefaults(Server server, BiMap<String, String> newDefaults,
            Map<String, Object> configAttrsToModify)
    throws ServiceException {
        Map<String, String> ports = new HashMap<String, String>();

        for (String attrName : sPortAttrs) {
            String newValue = null;
            String curValue = server.getAttr(attrName, false); // value on the server entry
            if (curValue == null)
                newValue = newDefaults.inverse().get(attrName);  // will inherit from new default
            else
                newValue = curValue;

            if (conflict(ports, newValue)) {
                String conflictWith = ports.get(newValue);
                // throw only when the attr is one of the attrs being modified, otherwise, just let it pass.
                if (configAttrsToModify.containsKey(attrName) || configAttrsToModify.containsKey(conflictWith))
                    throw ServiceException.INVALID_REQUEST("port " + newValue + " conflict between " +
                        attrName + " and " + ports.get(newValue) + " on server " + server.getName(), null);
            } else
                ports.put(newValue, attrName);
        }
    }

    private boolean conflict(Map<String, String> ports, String port) {

        if (StringUtil.isNullOrEmpty(port))
            return false;
        else if (port.equals("0"))
            return false;
        else
            return ports.containsKey(port);
    }

    @Override
    public void postModify(CallbackContext context, String attrName, Entry entry) {
    }
}


text:
export const updateFilter = (filters, filter, oldId) => {
  const id = oldId || filter.id;
  const filterIndex = filters.findIndex((item) => item.id === id);
  if (filterIndex === -1) {
    return [...filters, filter];
  }
  const newFilters = [...filters];
  newFilters.splice(filterIndex, 1, filter);
  return newFilters;
};

export const addFilteringFieldToConditions = (conditions = {}) =>
  Object.keys(conditions).map((key) => ({ ...conditions[key], filteringField: key }));


text:
@interface NSDictionary (TXConversion)

//对象 转 字典
+ (NSDictionary*)dictionaryWithObject:(id)obj;

@end


text:
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    Contains javesi exception types.
</body>
</html>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <title>Notes</title>

    <link rel="stylesheet" href="js/lib/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="css/app.css">
    <link rel="stylesheet" href="js/lib/bootstrap/css/bootstrap-theme.css">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-target">
          Toggle navigation

        </button>
        Notes

              View

              Edit

              Delete

        <form class="nav navbar-nav navbar-right navbar-form-nonresp navbar-search region region-notes"
              role="search" style="display: none;">

            <input type="text" class="search-query form-control"
                   placeholder="Filter">

        </form>

                <input id="note-new-input"
                       class="form-control"
                       placeholder="Write a new note." autofocus>

                <button id="note-create"
                        type="button"
                        class="btn btn-default btn-sm pull-right">

                </button>


text:
"""
Script to calculate per-residue RSCCs for a model versus an EM map with an
arbitrary origin.
"""

from __future__ import division
from mmtbx import real_space_correlation
import iotbx.phil
from cctbx import crystal
from cctbx import maptbx
from scitbx.array_family import flex
import sys

master_phil_str = """
model = None
  .type = path
map = None
  .type = path
d_min = 3.0
  .type = float
  .help = Optional cutoff resolution for computing F(calc). This will not \
    affect the dimensions of the ultimate FC map.
atom_radius = 1.5
  .type = float
"""

def run (args, out=sys.stdout) :
  cmdline = iotbx.phil.process_command_line_with_files(
    args=args,
    master_phil_string=master_phil_str,
    pdb_file_def="model",
    map_file_def="map",
    usage_string="""\
em_rscc.py model.pdb map.ccp4

%s""" % __doc__)
  params = cmdline.work.extract()
  assert (not None in [params.model, params.map])
  pdb_in = cmdline.get_file(params.model).file_object
  m = cmdline.get_file(params.map).file_object
  print >> out, "Input electron density map:"
  print >> out, "m.all()   :", m.data.all()
  print >> out, "m.focus() :", m.data.focus()
  print >> out, "m.origin():", m.data.origin()
  print >> out, "m.nd()    :", m.data.nd()
  print >> out, "m.size()  :", m.data.size()
  print >> out, "m.focus_size_1d():", m.data.focus_size_1d()
  print >> out, "m.is_0_based()   :", m.data.is_0_based()
  print >> out, "map: min/max/mean:", flex.min(m.data), flex.max(m.data), flex.mean(m.data)
  print >> out, "unit cell:", m.unit_cell_parameters
  symm = crystal.symmetry(
    space_group_symbol="P1",
    unit_cell=m.unit_cell_parameters)
  xrs = pdb_in.input.xray_structure_simple(crystal_symmetry=symm)
  print >> out, "Setting up electron scattering table (d_min=%g)" % params.d_min
  xrs.scattering_type_registry(
    d_min=params.d_min,
    table="electron")
  fc = xrs.structure_factors(d_min=params.d_min).f_calc()
  cg = maptbx.crystal_gridding(
    unit_cell=symm.unit_cell(),
    space_group_info=symm.space_group_info(),
    pre_determined_n_real=m.data.all())
  fc_map = fc.fft_map(
    crystal_gridding=cg).apply_sigma_scaling().real_map_unpadded()
  assert (fc_map.all() == fc_map.focus() == m.data.all())
  em_data = m.data.as_double()
  unit_cell_for_interpolation = m.grid_unit_cell()
  frac_matrix = unit_cell_for_interpolation.fractionalization_matrix()
  sites_cart = xrs.sites_cart()
  sites_frac = xrs.sites_frac()
  print >> out, "PER-RESIDUE CORRELATION:"
  for chain in pdb_in.hierarchy.only_model().chains() :
    for residue_group in chain.residue_groups() :
      i_seqs = residue_group.atoms().extract_i_seq()
      values_em = flex.double()
      values_fc = flex.double()
      for i_seq in i_seqs :
        rho_em = maptbx.non_crystallographic_eight_point_interpolation(
          map=em_data,
          gridding_matrix=frac_matrix,
          site_cart=sites_cart[i_seq])
        rho_fc = fc_map.eight_point_interpolation(sites_frac[i_seq])
        values_em.append(rho_em)
        values_fc.append(rho_fc)
      cc = flex.linear_correlation(x=values_em, y=values_fc).coefficient()
      print >> out, residue_group.id_str(), cc

def exercise () :
  import mmtbx.regression
  from iotbx import file_reader
  from cStringIO import StringIO
  pdb_file = "tmp_em_rscc.pdb"
  map_file = "tmp_em_rscc.map"
  f = open(pdb_file, "w")
  for line in mmtbx.regression.model_1yjp.splitlines() :
    if line.startswith("ATOM") :
      f.write(line + "\n")
  f.close()
  pdb_in = file_reader.any_file(pdb_file).file_object
  symm = crystal.symmetry(
    space_group_symbol="P1",
    unit_cell=(30, 30, 30, 90, 90, 90))
  xrs = pdb_in.input.xray_structure_simple(crystal_symmetry=symm)
  xrs.scattering_type_registry(
    d_min=3.0,
    table="electron")
  fc = xrs.structure_factors(d_min=3.0).f_calc()
  fft_map = fc.fft_map(resolution_factor=1/3).apply_sigma_scaling()
  assert (fft_map.n_real() == (32,32,32))
  fft_map.as_ccp4_map(
    file_name=map_file,
    gridding_first=(-16,-16,-16),
    gridding_last=(15,15,15))
  out = StringIO()
  run(args=[pdb_file, map_file], out=out)
  assert ("""\
PER-RESIDUE CORRELATION:
 A   1  1.0
 A   2  1.0
 A   3  1.0
 A   4  1.0
 A   5  1.0
 A   6  1.0
 A   7  1.0
""" in out.getvalue()), out.getvalue()

if (__name__ == "__main__") :
  if ("--test" in sys.argv) :
    exercise()
    print "OK"
  else :
    run(sys.argv[1:])


text:
package com.newlandframework.avatarmq.broker.strategy;

import com.newlandframework.avatarmq.broker.ConsumerMessageListener;
import com.newlandframework.avatarmq.broker.ProducerMessageListener;
import com.newlandframework.avatarmq.model.MessageType;
import com.newlandframework.avatarmq.model.RequestMessage;
import com.newlandframework.avatarmq.model.ResponseMessage;
import com.newlandframework.avatarmq.model.RemoteChannelData;
import com.newlandframework.avatarmq.msg.SubscribeMessage;
import io.netty.channel.ChannelHandlerContext;

/**
 * @filename:BrokerSubscribeStrategy.java
 * @description:BrokerSubscribeStrategy功能模块
 * @author tangjie<https://github.com/tang-jie>
 * @blog http://www.cnblogs.com/jietang/
 * @since 2016-8-11
 */
public class BrokerSubscribeStrategy implements BrokerStrategy {

    private ConsumerMessageListener hookConsumer;
    private ChannelHandlerContext channelHandler;

    public BrokerSubscribeStrategy() {

    }

    public void messageDispatch(RequestMessage request, ResponseMessage response) {
        SubscribeMessage subcript = (SubscribeMessage) request.getMsgParams();
        String clientKey = subcript.getConsumerId();
        RemoteChannelData channel = new RemoteChannelData(channelHandler.channel(), clientKey);
        hookConsumer.hookConsumerMessage(subcript, channel);
        response.setMsgType(MessageType.AvatarMQConsumerAck);
        channelHandler.writeAndFlush(response);
    }

    public void setHookConsumer(ConsumerMessageListener hookConsumer) {
        this.hookConsumer = hookConsumer;
    }

    public void setChannelHandler(ChannelHandlerContext channelHandler) {
        this.channelHandler = channelHandler;
    }

    public void setHookProducer(ProducerMessageListener hookProducer) {

    }
}


text:
//Copyright 2017 Constantine Telesnin
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//	http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.

using System;

namespace kJson.Read
{
	public class ParseException : Exception
    {
        public Reader Reader { get; set; }

        public long Position { get; set; }

        public ParseException(Parser parser, string message = null, Exception innerException = null) : base(message, innerException)
        {
            Reader = parser.Input;
            Position = Reader.Position;
            Reader.Seek(0, System.IO.SeekOrigin.End);
        }

        public ParseException(Reader reader, string message = null, Exception innerException = null) : base(message, innerException)
        {
            Reader = reader;
            Position = Reader.Position;
            Reader.Seek(0, System.IO.SeekOrigin.End);
        }
    }
}


text:
@extends ('backend.layouts.master')

@section ('title', 'Role Management | Create Role')

@section ('before-styles-end')
    {!! HTML::style('css/plugin/jquery.onoff.css') !!}
@stop

@section('page-header')

        User Management
        Create Role

@endsection

@section ('breadcrumbs')

 Dashboard

{!! link_to_route('admin.access.users.index', 'User Management') !!}

{!! link_to_route('admin.access.roles.index', 'Role Management') !!}

{!! link_to_route('admin.access.roles.create', 'Create Role') !!}

@stop

@section('content')
    @include('backend.access.includes.partials.header-buttons')

    {!! Form::open(['route' => 'admin.access.roles.store', 'class' => 'form-horizontal', 'role' => 'form', 'method' => 'post']) !!}

            Role Name

                {!! Form::text('name', null, ['class' => 'form-control', 'placeholder' => 'Role Name']) !!}

            Associated Permissions

                @if (count($permissions) > 0)
                    @foreach($permissions as $perm)
                        {!! $perm->display_name !!}

                                <input type="checkbox" value="{{$perm->id}}" name="role_permissions[]" class="toggleBtn onoffswitch-checkbox" id="perm-{{$perm->id}}">
                                id}}" class="onoffswitch-label">

                    @endforeach
                @else
                    No permissions to set
                @endif

            Cancel

            <input type="submit" class="btn btn-success" value="Save" />

    {!! Form::close() !!}
@stop


text:
package com.android.base.utils.android;

import android.os.Environment;
import android.support.annotation.NonNull;

import com.android.base.utils.BaseUtils;

import java.io.File;

import timber.log.Timber;

public class DirectoryUtils {

    private DirectoryUtils() {
    }

    /**
     * 获取SD卡上私有的外部存储
     *
     * @return /storage/emulated/0/Android/data/包名/cache/
     */
    public static File getAppExternalCacheStorage() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return BaseUtils.getAppContext().getExternalCacheDir();
        } else {
            return BaseUtils.getAppContext().getCacheDir();
        }
    }

    /**
     * 获取SD卡上外部存储
     *
     * @return /storage/emulated/0/
     */
    public static File getExternalStorage() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return Environment.getExternalStorageDirectory();
        } else {
            return BaseUtils.getAppContext().getCacheDir();
        }
    }

    /**
     * 获取公共的外部存储目录
     *
     * @param type {@link Environment#DIRECTORY_DOWNLOADS},
     *             {@link Environment#DIRECTORY_DCIM}, ect
     * @return DIRECTORY_DCIM = /storage/sdcard0/DCIM ,
     * DIRECTORY_DOWNLOADS =  /storage/sdcard0/Download ...ect
     */
    public static File getExternalStoragePublicDirectory(@NonNull String type) {
        String state = Environment.getExternalStorageState();
        File dir;
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            dir = Environment.getExternalStoragePublicDirectory(type);
        } else {
            dir = new File(BaseUtils.getAppContext().getCacheDir(), type);
        }
        if (dir != null && !dir.exists()) {
            boolean mkdirs = dir.mkdirs();
            Timber.d("getExternalStoragePublicDirectory type = " + type + " mkdirs = " + mkdirs);
        }
        return dir;
    }

}


text:
package main

import (
	"testing"
	"time"
)

type configFlagTestTableRow struct {
	attrName string
	in       []string
	isGood   func(appConfig) bool
}

var configFlagTestTable = []configFlagTestTableRow{
	// MaxAgeOfImages
	{"MaxAgeOfImages", []string{}, func(c appConfig) bool { return c.MaxAgeOfImages == 168*time.Hour }},
	{"MaxAgeOfImages", []string{"--max-image-age=20m"}, func(c appConfig) bool { return c.MaxAgeOfImages == 20*time.Minute }},
	{"MaxAgeOfImages", []string{"--max-image-age", "7h"}, func(c appConfig) bool { return c.MaxAgeOfImages == 7*time.Hour }},
	{"MaxAgeOfImages", []string{"-m", "5h"}, func(c appConfig) bool { return c.MaxAgeOfImages == 5*time.Hour }},

	// SweeperTime
	{"SweeperTime", []string{}, func(c appConfig) bool { return c.SweeperTime == 15*time.Minute }},
	{"SweeperTime", []string{"--sweeper-time=11m"}, func(c appConfig) bool { return c.SweeperTime == 11*time.Minute }},
	{"SweeperTime", []string{"--sweeper-time", "2h"}, func(c appConfig) bool { return c.SweeperTime == 2*time.Hour }},
	{"SweeperTime", []string{"-s", "30s"}, func(c appConfig) bool { return c.SweeperTime == 30*time.Second }},

	// DangleSafeDuration
	{"DangleSafeDuration", []string{}, func(c appConfig) bool { return c.DangleSafeDuration == 30*time.Minute }},
	{"DangleSafeDuration", []string{"--dangle-safe-duration=11m"}, func(c appConfig) bool { return c.DangleSafeDuration == 11*time.Minute }},
	{"DangleSafeDuration", []string{"--dangle-safe-duration", "2h"}, func(c appConfig) bool { return c.DangleSafeDuration == 2*time.Hour }},
	{"DangleSafeDuration", []string{"-d", "30s"}, func(c appConfig) bool { return c.DangleSafeDuration == 30*time.Second }},

	// Quiet
	{"Quiet", []string{}, func(c appConfig) bool { return !c.Quiet }},
	{"Quiet", []string{"-q"}, func(c appConfig) bool { return c.Quiet }},
	{"Quiet", []string{"--quiet"}, func(c appConfig) bool { return c.Quiet }},
}

func TestConfigFlagTestTable(t *testing.T) {
	for _, tt := range configFlagTestTable {
		config, err := newAppConfig(tt.in)
		if err != nil {
			t.Errorf("args %q; got error %q", tt.in, err)
		}
		if !tt.isGood(config) {
			t.Errorf("args %v config => %+v", tt.in, config)
		}
	}
}

// See issue #4
func TestBogusFlag(t *testing.T) {
	args := []string{"--bogus-flag"}
	_, err := newAppConfig(args)
	if err == nil {
		t.Errorf("args %q; expected error, but got nothing", args)
	}
}


text:
class Report
  class Body
    class Column
      attr_reader :body
      attr_reader :name
      attr_reader :method_id
      attr_reader :blk
      attr_reader :faded
      attr_reader :row_options
      def initialize(*args, &blk)
        if block_given?
          @blk = blk
        end
        @body = args.shift
        @name = args.shift
        options = args.extract_options!
        @method_id = options.delete(:method_id) || args.shift
        @faded = options.delete(:faded)
        @row_options = options
      end
      def read(report, obj)
        if blk
          case blk.arity
          when 0
            obj.instance_eval(&blk)
          when 2
            blk.call report, obj
          else
            raise "column block should have 0 or 2 arguments"
          end
        elsif method_id
          obj.send method_id
        elsif from_name = guesses.detect { |m| obj.respond_to?(m) }
          obj.send from_name
        else
          raise "#{obj.inspect} does not respond to any of #{guesses.inspect}"
        end
      end
      def read_with_options(report, obj)
        v = read report, obj
        f = case faded
        when Symbol
          obj.send faded
        else
          faded
        end
        { :value => v, :faded => f }.merge row_options
      end
      private
      def guesses
        [
          name.gsub(' ', '_'),
          name.underscore.gsub(/[^\w\!\?]/, '_')
        ]
      end
    end
  end
end


text:
package v8

import (
	"encoding/json"
	"errors"
	"fmt"
	"math"
	"math/big"
	"reflect"
	"regexp"
	"runtime"
	"strings"
	"sync"
	"testing"
	"time"
)

func TestRunSimpleJS(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	res, err := ctx.Eval(`
		var a = 10;
		var b = 20;
		var c = a+b;
		c;
	`, "test.js")
	if err != nil {
		t.Fatalf("Error evaluating javascript, err: %v", err)
	}
	if num := res.Int64(); num != 30 {
		t.Errorf("Expected 30, got %v", res)
	}
}

func TestBoolConversion(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	testcases := []struct {
		js       string
		expected bool
		isBool   bool
	}{
		// These are the only values that are KindBoolean. Everything else below is
		// implicitly converted.
		{`true`, true, true},
		{`false`, false, true},

		// Super confusing in JS:
		//   !!(new Boolean(false)) == true
		//   !!(new Boolean(true)) == true
		// That's because a non-undefined non-null Object in JS is 'true'.
		// Also, neither of these are actually Boolean kinds -- they are
		// BooleanObject, though.
		{`new Boolean(true)`, true, false},
		{`new Boolean(false)`, true, false},
		{`undefined`, false, false},
		{`null`, false, false},
		{`[]`, true, false},
		{`[1]`, true, false},
		{`7`, true, false},
		{`"xyz"`, true, false},
		{`(() => 3)`, true, false},
	}

	for i, test := range testcases {
		res, err := ctx.Eval(test.js, "test.js")
		if err != nil {
			t.Errorf("%d %#q: Failed to run js: %v", i, test.js, err)
		} else if b := res.Bool(); b != test.expected {
			t.Errorf("%d %#q: Expected bool of %v, but got %v", i, test.js, test.expected, b)
		} else if res.IsKind(KindBoolean) != test.isBool {
			t.Errorf("%d %#q: Expected this to be a bool kind, but it's %v", i, test.js, res.kindMask)
		}
	}
}

func TestJsRegex(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	re, err := ctx.Eval(`/foo.*bar/`, "test.js")
	if err != nil {
		t.Fatal(err)
	}
	if re.String() != `/foo.*bar/` {
		t.Errorf("Bad stringification of regex: %#q", re)
	}
	if !re.IsKind(KindRegExp) {
		t.Errorf("Wrong kind for regex: %v", re.kindMask)
	}
}

func TestNumberConversions(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	res, err := ctx.Eval(`13`, "test.js")
	if err != nil {
		t.Fatal(err)
	}

	if !res.IsKind(KindNumber) {
		t.Errorf("Expected %q to be a number kind, but it's not: %q", res, res.kindMask)
	}
	if res.IsKind(KindFunction) {
		t.Errorf("Expected %q to NOT be a function kind, but it is: %q", res, res.kindMask)
	}

	if f64 := res.Float64(); f64 != 13.0 {
		t.Errorf("Expected %q to eq 13.0, but got %f", res, f64)
	}

	if i64 := res.Int64(); i64 != 13 {
		t.Errorf("Expected %q to eq 13.0, but got %d", res, i64)
	}
}

func TestNumberConversionsFailForNonNumbers(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	res, err := ctx.Eval(`undefined`, "test.js")
	if err != nil {
		t.Fatal(err)
	}

	if res.IsKind(KindNumber) {
		t.Errorf("Expected %q to NOT be a number kind, but it is: %q", res, res.kindMask)
	}

	if f64 := res.Float64(); !math.IsNaN(f64) {
		t.Errorf("Expected %q to be NaN, but got %f", res, f64)
	}

	if i64 := res.Int64(); i64 != 0 {
		t.Errorf("Expected %q to eq 0, but got %d", res, i64)
	}
}

func TestErrorRunningInvalidJs(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	res, err := ctx.Eval(`kajsdfa91j23e`, "junk.js")
	if err == nil {
		t.Errorf("Expected error, but got result: %v", res)
	}
}

func TestValueString(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	testcases := []struct{ jsCode, toString string }{
		// primitives:
		{`"some string"`, `some string`},
		{`5`, `5`},
		{`5.123`, `5.123`},
		{`true`, `true`},
		{`false`, `false`},
		{`null`, `null`},
		{`undefined`, `undefined`},
		// more complicated objects:
		{`(function x() { return 1 + 2; })`, `function x() { return 1 + 2; }`},
		{`([1,2,3])`, `1,2,3`},
		{`({x: 5})`, `[object Object]`},
		// basically a primitive, but an interesting case still:
		{`JSON.stringify({x: 5})`, `{"x":5}`},
	}

	for i, test := range testcases {
		res, err := ctx.Eval(test.jsCode, "test.js")
		if err != nil {
			t.Fatalf("Case %d: Error evaluating javascript %#q, err: %v",
				i, test.jsCode, err)
		}
		if res.String() != test.toString {
			t.Errorf("Case %d: Got %#q, expected %#q from running js %#q",
				i, res.String(), test.toString, test.jsCode)
		}
	}
}

func TestJsReturnStringWithEmbeddedNulls(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	res, err := ctx.Eval(`"foo\000bar"`, "test.js")
	if err != nil {
		t.Fatalf("Error evaluating javascript, err: %v", err)
	}
	if str := res.String(); str != "foo\000bar" {
		t.Errorf("Expected 'foo\\000bar', got %q", str)
	}
}

func TestJsReturnUndefined(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	res, err := ctx.Eval(``, "undefined.js")
	if err != nil {
		t.Fatalf("Error evaluating javascript, err: %v", err)
	}
	if str := res.String(); str != "undefined" {
		t.Errorf("Expected 'undefined', got %q", str)
	}
	if b := res.Bytes(); b != nil {
		t.Errorf("Expected failure to map to bytes but got byte array of length %d", len(b))
	}
}

func TestJsReturnArrayBuffer(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	res, err := ctx.Eval(`new ArrayBuffer(5)`, "undefined.js")
	if err != nil {
		t.Fatalf("Error evaluating javascript, err: %v", err)
	}
	b := res.Bytes()
	if b == nil {
		t.Errorf("Expected non-nil byte array but got nil buffer")
	}
	if len(b) != 5 {
		t.Errorf("Expected byte array of length 5 but got %d", len(b))
	}
}

func TestJsThrowString(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	res, err := ctx.Eval(`throw 'badness'`, "my_file.js")
	if err == nil {
		t.Fatalf("It worked but it wasn't supposed to: %v", res.String())
	}
	match, _ := regexp.MatchString("Uncaught exception: badness", err.Error())
	if !match {
		t.Error("Expected 'Uncaught exception: badness', got: ", err.Error())
	}
}

func TestJsThrowError(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	res, err := ctx.Eval(`throw new Error('ooopsie')`, "my_file.js")
	if err == nil {
		t.Fatalf("It worked but it wasn't supposed to: %v", res.String())
	}
	match, _ := regexp.MatchString("Uncaught exception: Error: ooopsie", err.Error())
	if !match {
		t.Error("Expected 'Uncaught exception: Error: ooopsie', got: ", err.Error())
	}
}

func TestReadFieldFromObject(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	res, err := ctx.Eval(`({foo:"bar"})`, "my_file.js")
	if err != nil {
		t.Fatalf("Error evaluating javascript, err: %v", err)
	}
	val, err := res.Get("foo")
	if err != nil {
		t.Fatalf("Error trying to get field: %v", err)
	}
	if str := val.String(); str != "bar" {
		t.Errorf("Expected 'bar', got %q", str)
	}
}

func TestReadAndWriteIndexFromArrayBuffer(t *testing.T) {
	t.Parallel()

	ctx := NewIsolate().NewContext()
	val, err := ctx.Create(struct {
		Data []byte `v8:"arraybuffer"`
	}{[]byte{1, 2, 3}})
	if err != nil {
		t.Fatal(err)
	}

	data, err := val.Get("Data")
	if err != nil {
		t.Fatal(err)
	}

	v, err := data.GetIndex(1)
	if err != nil {
		t.Fatal(err)
	} else if num := v.Int64(); num != 2 {
		t.Errorf("Wrong value, expected 2, got %v (%v)", num, v)
	}

	v2, err := data.GetIndex(17)
	if err != nil {
		t.Fatal(err)
	} else if str := v2.String(); str != "undefined" {
		t.Errorf("Expected undefined, got %s", str)
	}

	v3, err := data.GetIndex(2)
	if err != nil {
		t.Fatal(err)
	} else if num := v3.Int64(); num != 3 {
		t.Errorf("Expected undefined, got %v (%v)", num, v3)
	}

	data.SetIndex(2, v)
	v2, err = data.GetIndex(2)
	if err != nil {
		t.Fatal(err)
	} else if num := v2.Int64(); num != 2 {
		t.Errorf("Expected 2, got %v (%v)", num, v2)
	}

	largeValue, err := ctx.Create(int(500))
	if err != nil {
		t.Fatal(err)
	}

	// 500 truncates to 500 % 256 == 244
	data.SetIndex(2, largeValue)
	v4, err := data.GetIndex(2)
	if err != nil {
		t.Fatal(err)
	} else if num := v4.Int64(); num != 244 {
		t.Errorf("Expected 244, got %v (%v)", num, v4)
	}

	negativeValue, err := ctx.Create(int(-55))
	if err != nil {
		t.Fatal(err)
	}

	// -55 "truncates" to -55 % 256 == 201
	data.SetIndex(2, negativeValue)
	v5, err := data.GetIndex(2)
	if err != nil {
		t.Fatal(err)
	} else if num := v5.Int64(); num != 201 {
		t.Errorf("Expected 201, got %v (%v)", num, v5)
	}
}

func TestReadAndWriteIndexFromArray(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	val, err := ctx.Create([]int{1, 2, 3})
	if err != nil {
		t.Fatal(err)
	}

	v, err := val.GetIndex(1)
	if err != nil {
		t.Fatal(err)
	} else if num := v.Int64(); num != 2 {
		t.Errorf("Wrong value, expected 2, got %v (%v)", num, v)
	}

	v2, err := val.GetIndex(17)
	if err != nil {
		t.Fatal(err)
	} else if str := v2.String(); str != "undefined" {
		t.Errorf("Expected undefined, got %s", str)
	}

	val.SetIndex(17, v)
	v2, err = val.GetIndex(17)
	if err != nil {
		t.Fatal(err)
	} else if num := v2.Int64(); num != 2 {
		t.Errorf("Expected 2, got %v (%v)", num, v2)
	}
}

func TestReadFieldFromNonObjectFails(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	res, err := ctx.Eval(`17`, "my_file.js")
	if err != nil {
		t.Fatalf("Error evaluating javascript, err: %v", err)
	}
	val, err := res.Get("foo")
	if err == nil {
		t.Fatalf("Missing error trying to get field, got %v", val)
	}
	val, err = res.GetIndex(3)
	if err == nil {
		t.Fatalf("Missing error trying to get field, got %v", val)
	}
}

func TestReadFieldFromGlobal(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	_, err := ctx.Eval(`foo = "bar";`, "my_file.js")
	if err != nil {
		t.Fatalf("Error evaluating javascript, err: %v", err)
	}
	val, err := ctx.Global().Get("foo")
	if err != nil {
		t.Fatalf("Error trying to get field: %v", err)
	}
	if str := val.String(); str != "bar" {
		t.Errorf("Expected 'bar', got %q", str)
	}
}

func TestSetField(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	three, err := ctx.Eval(`(3)`, "")
	if err != nil {
		t.Fatal(err)
	}

	if err := ctx.Global().Set("foo", three); err != nil {
		t.Fatal(err)
	}

	res, err := ctx.Eval(`foo`, "")
	if err != nil {
		t.Fatal(err)
	}
	if num := res.Int64(); num != 3 {
		t.Errorf("Expected 3, got %v (%v)", num, res)
	}
}

func TestRunningCodeInContextAfterThrowingError(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	_, err := ctx.Eval(`
		function fail(a,b) {
			this.c = a+b;
			throw "some failure";
		}
		function work(a,b) {
			this.c = a+b+2;
		}
		x = new fail(3,5);`, "file1.js")
	if err == nil {
		t.Fatal("Expected an exception.")
	}

	res, err := ctx.Eval(`y = new work(3,6); y.c`, "file2.js")
	if err != nil {
		t.Fatal("Expected it to work, but got:", err)
	}

	if num := res.Int64(); num != 11 {
		t.Errorf("Expected 11, got: %v (%v)", num, res)
	}
}

func TestManyContextsThrowingErrors(t *testing.T) {
	t.Parallel()

	prog := `
		function work(N, depth, fail) {
			if (depth == 0) { return 1; }
			var sum = 0;
			for (i = 0; i < N; i++) { sum *= work(N, depth-1); }
			if (fail) {
				throw "Failed";
			}
			return sum;
		}`

	const N = 100 // num parallel contexts
	runtime.GOMAXPROCS(N)

	var done sync.WaitGroup

	iso := NewIsolate()

	done.Add(N)
	for i := 0; i < N; i++ {
		ctx := iso.NewContext()

		ctx.Eval(prog, "prog.js")
		go func(ctx *Context, i int) {
			cmd := fmt.Sprintf(`work(10000,100,%v)`, i%5 == 0)
			ctx.Eval(cmd, "<inline>")
			ctx.Eval(cmd, "<inline>")
			ctx.Eval(cmd, "<inline>")
			done.Done()
		}(ctx, i)
	}
	done.Wait()
}

func TestErrorsInNativeCode(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	_, err := ctx.Eval(`[].map(undefined);`, "map_undef.js")
	if err == nil {
		t.Fatal("Expected error.")
	}
	t.Log("Got expected error: ", err)
}

func TestCallFunctionWithExplicitThis(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	this, _ := ctx.Eval(`(function(){ this.z = 3; return this; })()`, "")
	add, _ := ctx.Eval(`((x,y)=>(x+y+this.z))`, "")
	one, _ := ctx.Eval(`1`, "")
	two, _ := ctx.Eval(`2`, "")
	res, err := add.Call(this, one, two)
	if err != nil {
		t.Fatal(err)
	} else if num := res.Int64(); num != 6 {
		t.Errorf("Expected 6, got %v (%v)", num, res)
	}
}

func TestCallFunctionWithGlobalScope(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	ctx.Eval(`z = 4`, "")
	add, _ := ctx.Eval(`((x,y)=>(x+y+this.z))`, "")
	one, _ := ctx.Eval(`1`, "")
	two, _ := ctx.Eval(`2`, "")
	res, err := add.Call(nil, one, two)
	if err != nil {
		t.Fatal(err)
	} else if num := res.Int64(); num != 7 {
		t.Errorf("Expected 7, got %v (%v)", num, res)
	}
}

func TestCallFunctionFailsOnNonFunction(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	ob, _ := ctx.Eval(`({x:3})`, "")
	res, err := ob.Call(nil)
	if err == nil {
		t.Fatalf("Expected err, but got %v", res)
	} else if err.Error() != "Not a function" {
		t.Errorf("Wrong error message: %q", err)
	}
}

func TestNewFunction(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	cons, _ := ctx.Eval(`(function(){ this.x = 1; })`, "")
	obj, err := cons.New()
	if err != nil {
		t.Fatal(err)
	}
	res, err := obj.Get("x")
	if err != nil {
		t.Fatal(err)
	} else if num := res.Int64(); num != 1 {
		t.Errorf("Expected 1, got %v (%v)", num, res)
	}
}

func TestNewFunctionThrows(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	cons, _ := ctx.Eval(`(function(){ throw "oops"; })`, "")
	obj, err := cons.New()
	if err == nil {
		t.Fatalf("Expected err, but got %v", obj)
	} else if !strings.HasPrefix(err.Error(), "Uncaught exception: oops") {
		t.Errorf("Wrong error message: %q", err)
	}
}

func TestNewFunctionWithArgs(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	cons, _ := ctx.Eval(`(function(x, y){ this.x = x + y; })`, "")
	one, _ := ctx.Eval(`1`, "")
	two, _ := ctx.Eval(`2`, "")
	obj, err := cons.New(one, two)
	if err != nil {
		t.Fatal(err)
	}
	res, err := obj.Get("x")
	if err != nil {
		t.Fatal(err)
	} else if num := res.Int64(); num != 3 {
		t.Errorf("Expected 3, got %v (%v)", num, res)
	}
}

func TestNewFunctionFailsOnNonFunction(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	ob, _ := ctx.Eval(`({x:3})`, "")
	res, err := ob.New()
	if err == nil {
		t.Fatalf("Expected err, but got %v", res)
	} else if err.Error() != "Not a function" {
		t.Errorf("Wrong error message: %q", err)
	}
}

func TestBind(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	var expectedLoc Loc

	getLastCb := func(in CallbackArgs) (*Value, error) {
		if in.Caller != expectedLoc {
			t.Errorf("Wrong source location: %#v", in.Caller)
		}
		t.Logf("Args: %s", in.Args)
		return in.Args[len(in.Args)-1], nil
	}

	getLast := ctx.Bind("foo", getLastCb)
	ctx.Global().Set("last", getLast)

	expectedLoc = Loc{"doit", "somefile.js", 3, 11}
	res, err := ctx.Eval(`
		function doit() {
			return last(1,2,3);
		}
		doit()
	`, "somefile.js")
	if err != nil {
		t.Fatal(err)
	} else if num := res.Int64(); num != 3 {
		t.Errorf("Expected 3, got %v (%v)", num, res)
	}

	expectedLoc = Loc{"", "", 0, 0} // empty when called directly from Go
	abc, _ := ctx.Eval("'abc'", "unused_filename.js")
	xyz, _ := ctx.Eval("'xyz'", "unused_filename.js")
	res, err = getLast.Call(nil, res, abc, xyz)
	if err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "xyz" {
		t.Errorf("Expected xyz, got %q", str)
	}
}

func TestBindReturnsError(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	fails := ctx.Bind("fails", func(CallbackArgs) (*Value, error) {
		return nil, errors.New("borked")
	})
	res, err := fails.Call(nil)
	if err == nil {
		t.Fatalf("Expected error, but got %q instead", res)
	} else if !strings.HasPrefix(err.Error(), "Uncaught exception: Error: borked") {
		t.Errorf("Wrong error message: %q", err)
	}
}

func TestBindPanics(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	panic := ctx.Bind("panic", func(CallbackArgs) (*Value, error) { panic("aaaah!!") })
	ctx.Global().Set("panic", panic)
	res, err := ctx.Eval(`panic();`, "esplode.js")
	if err == nil {
		t.Error("Expected error, got ", res)
	} else if matched, _ := regexp.MatchString("panic.*aaaah!!", err.Error()); !matched {
		t.Errorf("Error should mention a panic and 'aaaah!!', but doesn't: %v", err)
	}
}

func TestBindName(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	xyz := ctx.Bind("xyz", func(CallbackArgs) (*Value, error) { return nil, nil })
	if str := xyz.String(); str != "function xyz() { [native code] }" {
		t.Errorf("Wrong function signature: %q", str)
	}
}

func TestBindNilReturn(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	xyz := ctx.Bind("xyz", func(CallbackArgs) (*Value, error) { return nil, nil })
	res, err := xyz.Call(nil)
	if err != nil {
		t.Error(err)
	}
	if str := res.String(); str != "undefined" {
		t.Errorf("Expected undefined, got %q", res)
	}
}

func TestTerminate(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	waitUntilRunning := make(chan bool)
	notify := ctx.Bind("notify", func(CallbackArgs) (*Value, error) {
		waitUntilRunning <- true
		return nil, nil
	})
	ctx.Global().Set("notify", notify)

	go func() {
		<-waitUntilRunning
		ctx.Terminate()
	}()

	done := make(chan bool)

	go func() {
		res, err := ctx.Eval(`
			notify();
			while(1) {}
		`, "test.js")

		if err == nil {
			t.Error("Expected an error, but got result: ", res)
		}

		done <- true
	}()

	select {
	case <-done:
		// yay, it worked!
	case <-time.After(time.Second):
		t.Fatal("Terminate didn't terminate :/")
	}
}

func TestSnapshot(t *testing.T) {
	t.Parallel()
	snapshot := CreateSnapshot("zzz='hi there!';")
	ctx := NewIsolateWithSnapshot(snapshot).NewContext()

	res, err := ctx.Eval(`zzz`, "script.js")
	if err != nil {
		t.Fatal(err)
	}
	if str := res.String(); str != "hi there!" {
		t.Errorf("Expected 'hi there!' got %s", str)
	}
}

func TestSnapshotBadJs(t *testing.T) {
	t.Parallel()
	snapshot := CreateSnapshot("This isn't yo mama's snapshot!")

	if snapshot.data.ptr != nil {
		t.Error("Expected nil ptr")
	}

	ctx := NewIsolateWithSnapshot(snapshot).NewContext()

	_, err := ctx.Eval(`zzz`, "script.js")
	if err == nil {
		t.Fatal("Expected error because zzz should be undefined.")
	}
}

func TestEs6Destructuring(t *testing.T) {
	if Version.Major < 5 {
		t.Skip("V8 versions before 5.* don't support destructuring.")
	}

	t.Parallel()
	ctx := NewIsolate().NewContext()

	bar, err := ctx.Eval(`
		const f = (n) => ({foo:n, bar:n+1});
		var {foo, bar} = f(5);
		bar
	`, "test.js")
	if err != nil {
		t.Fatal(err)
	}
	if num := bar.Int64(); num != 6 {
		t.Errorf("Expected 6, got %v (%v)", num, bar)
	}
}

func TestJsonExport(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	var json_stringify *Value
	if json, err := ctx.Global().Get("JSON"); err != nil {
		t.Fatal(err)
	} else if json_stringify, err = json.Get("stringify"); err != nil {
		t.Fatal(err)
	}

	some_result, err := ctx.Eval("(() => ({a:3,b:'xyz',c:true}))()", "test.js")
	if err != nil {
		t.Fatal(err)
	}

	res, err := json_stringify.Call(json_stringify, some_result)
	if err != nil {
		t.Fatal(err)
	}

	if str := res.String(); str != `{"a":3,"b":"xyz","c":true}` {
		t.Errorf("Wrong JSON result, got: %s", str)
	}
}

func TestValueReleaseMoreThanOnceIsOk(t *testing.T) {
	t.Parallel()
	iso := NewIsolate()
	ctx := iso.NewContext()

	res, err := ctx.Eval("5", "test.js")
	if err != nil {
		t.Fatal(err)
	}
	res.release()
	res.release()
	res.release()
	res.release()

	ctx.release()
	iso.release()
	ctx.release()
	ctx.release()
	iso.release()
	iso.release()
}

func TestSharingValuesAmongContextsInAnIsolate(t *testing.T) {
	t.Parallel()
	iso := NewIsolate()
	ctx1, ctx2 := iso.NewContext(), iso.NewContext()

	//  Create a value in ctx1
	foo, err := ctx1.Eval(`foo = {x:6,y:true,z:"asdf"}; foo`, "ctx1.js")
	if err != nil {
		t.Fatal(err)
	}

	// Set that value into ctx2
	err = ctx2.Global().Set("bar", foo)
	if err != nil {
		t.Fatal(err)
	}
	// ...and verify that it has the same value.
	res, err := ctx2.Eval(`bar.z`, "ctx2.js")
	if err != nil {
		t.Fatal(err)
	}
	if str := res.String(); str != "asdf" {
		t.Errorf("Expected 'asdf', got %q", str)
	}

	// Now modify that value in ctx2
	_, err = ctx2.Eval("bar.z = 'xyz';", "ctx2b.js")
	if err != nil {
		t.Fatal(err)
	}

	// ...and verify that it got changed in ctx1 as well!
	res, err = ctx1.Eval("foo.z", "ctx1b.js")
	if err != nil {
		t.Fatal(err)
	}
	if str := res.String(); str != "xyz" {
		t.Errorf("Expected 'xyz', got %q", str)
	}
}

func TestCreateSimple(t *testing.T) {
	t.Parallel()
	iso := NewIsolate()
	ctx := iso.NewContext()

	callback := func(CallbackArgs) (*Value, error) { return nil, nil }

	tm := time.Date(2018, 5, 8, 3, 4, 5, 17, time.Local)

	var testcases = []struct {
		val interface{}
		str string
	}{
		{nil, "undefined"},
		{3, "3"},
		{3.7, "3.7"},
		{true, "true"},
		{"asdf", "asdf"},
		{callback, "function v8.TestCreateSimple.func1() { [native code] }"},
		{map[string]int{"foo": 1, "bar": 2}, "[object Object]"},
		{struct {
			Foo int
			Bar bool
		}{3, true}, "[object Object]"},
		{[]interface{}{1, true, "three"}, "1,true,three"},
		{tm, tm.Format("Mon Jan 02 2006 15:04:05 GMT-0700 (MST)")},
		{&tm, tm.Format("Mon Jan 02 2006 15:04:05 GMT-0700 (MST)")},
	}

	for i, test := range testcases {
		val, err := ctx.Create(test.val)
		if err != nil {
			t.Errorf("%d: Failed to create %#v: %v", i, test, err)
			continue
		}
		if str := val.String(); str != test.str {
			t.Errorf("Expected %q, got %q", test.str, str)
		}
	}
}

func TestCreateComplex(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	fn := func(CallbackArgs) (*Value, error) { return ctx.Create("abc") }
	type Struct struct {
		Val    string
		secret bool
		Sub    interface{}
	}

	zzz1 := &Struct{Val: "BOOM!"}
	zzz2 := &zzz1
	zzz3 := &zzz2
	zzz4 := &zzz3
	zzz5 := &zzz4 // zzz5 is a *****Struct.  Make sure pointers work!

	fn2 := ctx.Bind("fn2", fn)

	val, err := ctx.Create([]Struct{
		{"asdf", false, nil},
		{"foo", true, map[string]interface{}{
			"num":    123.123,
			"fn":     fn,
			"fn2":    fn2,
			"list":   []float64{1, 2, 3},
			"valArr": []*Value{fn2},
		}},
		{"*****Struct", false, zzz5},
		{"bufbuf", false, struct {
			Data []byte `v8:"arraybuffer"`
		}{[]byte{1, 2, 3, 4}}},
		{"emptybuf", false, struct {
			Data []byte `v8:"arraybuffer"`
		}{[]byte{}}},
		{"structWithValue", false, struct{ *Value }{fn2}},
	})
	if err != nil {
		t.Fatal(err)
	}

	if fn2.ptr == nil {
		t.Error("Create should not release *Values allocated prior to the call.")
	}

	ctx.Global().Set("mega", val)

	if res, err := ctx.Eval(`mega[1].Sub.fn2()`, "test.js"); err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "abc" {
		t.Errorf("Expected abc, got %q", str)
	}

	if res, err := ctx.Eval(`mega[1].Sub.fn()`, "test.js"); err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "abc" {
		t.Errorf("Expected abc, got %q", str)
	}

	if res, err := ctx.Eval(`mega[1].secret`, "test.js"); err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "undefined" {
		t.Errorf("Expected undefined trying to access non-existent field 'secret', but got %q", str)
	}

	if res, err := ctx.Eval(`mega[2].Sub.Val`, "test.js"); err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "BOOM!" {
		t.Errorf("Expected 'BOOM1', but got %q", str)
	}

	if res, err := ctx.Eval(`mega[3].Sub.Data.byteLength`, "test.js"); err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "4" {
		t.Errorf("Expected array buffer length of '4', but got %q", str)
	}

	if res, err := ctx.Eval(`new Uint8Array(mega[3].Sub.Data)[2]`, "test.js"); err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "3" {
		t.Errorf("Expected array buffer value at index 2 of '3', but got %q", str)
	}

	if res, err := ctx.Eval(`mega[4].Sub.Data.byteLength`, "test.js"); err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "0" {
		t.Errorf("Expected empty array buffer length of '0', but got %q", str)
	}
}

func TestJsCreateArrayBufferRoundtrip(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	val, err := ctx.Create(struct {
		Data []byte `v8:"arraybuffer"`
	}{[]byte{1, 2, 3, 4}})
	if err != nil {
		t.Fatal(err)
	}

	ctx.Global().Set("buf", val)

	if _, err := ctx.Eval(`
		var view = new Uint8Array(buf.Data)
		view[3] = view[0] + view[1] + view[2]
		`, "test.js"); err != nil {
		t.Fatal(err)
	}

	data, err := val.Get("Data")
	if err != nil {
		t.Fatal(err)
	}

	v1, err := data.GetIndex(0)
	if err != nil {
		t.Fatal(err)
	} else if str := v1.String(); str != "1" {
		t.Errorf("Expected first value of '1' but got %q", str)
	}

	v2, err := data.GetIndex(3)
	if err != nil {
		t.Fatal(err)
	} else if str := v2.String(); str != "6" {
		t.Errorf("Expected fourth value of '6' but got %q", str)
	}

	err = data.SetIndex(2, v1)
	if err != nil {
		t.Fatal(err)
	}

	v3, err := data.GetIndex(2)
	if err != nil {
		t.Fatal(err)
	} else if str := v3.String(); str != "1" {
		t.Errorf("Expected third value of '1' but got %q", str)
	}

	bytes := data.Bytes()
	if !reflect.DeepEqual(bytes, []byte{1, 2, 1, 6}) {
		t.Errorf("Expected byte array [1,2,1,6] but got %q", bytes)
	}

	// Out of range
	err = data.SetIndex(7, v1)
	if err == nil {
		t.Errorf("Expected error assigning out of range of array buffer")
	}
}

func TestTypedArrayBuffers(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	uint8Array, err := ctx.Eval(`
		new Uint8Array(4).fill(4, 1, 3) // taken from a MDN example
	`, "test.js")
	if err != nil {
		t.Fatal(err)
	}

	bytes := uint8Array.Bytes()
	if !reflect.DeepEqual(bytes, []byte{0, 4, 4, 0}) {
		t.Errorf("Expected byte array [0,4,4,0] but got %q", bytes)
	}
}

func TestCreateJsonTags(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	type A struct {
		Embedded    string `json:"embedded"`
		AlsoIngored string `json:"-"`
	}
	type Nil struct{ Missing string }
	type B struct {
		*A
		*Nil
		Ignored     string `json:"-"`
		Renamed     string `json:"foo"`
		DefaultName string `json:",omitempty"`
		Bar         string
	}

	var x = B{&A{"a", "x"}, nil, "y", "b", "c", "d"}
	val, err := ctx.Create(x)
	if err != nil {
		t.Fatal(err)
	}

	const expected = `{"embedded":"a","foo":"b","DefaultName":"c","Bar":"d"}`
	if data, err := json.Marshal(val); err != nil {
		t.Fatal(err)
	} else if string(data) != expected {
		t.Errorf("Incorrect object:\nExp: %s\nGot: %s", expected, data)
	}
}

func TestParseJson(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	val, err := ctx.ParseJson(`{"foo":"bar","bar":3}`)
	if err != nil {
		t.Fatal(err)
	}
	if res, err := val.Get("foo"); err != nil {
		t.Fatal(err)
	} else if str := res.String(); str != "bar" {
		t.Errorf("Expected 'bar', got %q", str)
	}

	// Make sure it fails if the data is not actually json.
	val, err = ctx.ParseJson(`this is not json`)
	if err == nil {
		t.Errorf("Expected an error, but got %s", val)
	}
}

func TestJsonMarshal(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	val, err := ctx.Eval(`(()=>({
		blah: 3,
		muck: true,
		label: "lala",
		missing: () => ( "functions get dropped" )
	}))()`, "test.js")
	if err != nil {
		t.Fatal(err)
	}

	data, err := json.Marshal(val)
	if err != nil {
		t.Fatal(err)
	}
	const expected = `{"blah":3,"muck":true,"label":"lala"}`
	if string(data) != expected {
		t.Errorf("Expected: %q\nGot     : %q", expected, string(data))
	}
}

func TestCallbackProvideCorrectContext(t *testing.T) {
	t.Parallel()

	// greet is a generate callback handler that is not associated with a
	// particular context -- it uses the provided context to create a value
	// to return, even when used from different isolates.
	greet := func(in CallbackArgs) (*Value, error) {
		return in.Context.Create("Hello " + in.Arg(0).String())
	}

	ctx1, ctx2 := NewIsolate().NewContext(), NewIsolate().NewContext()
	ctx1.Global().Set("greet", ctx1.Bind("greet", greet))
	ctx2.Global().Set("greet", ctx2.Bind("greet", greet))

	alice, err1 := ctx1.Eval("greet('Alice')", "ctx1.js")
	if err1 != nil {
		t.Errorf("Context 1 failed: %v", err1)
	} else if str := alice.String(); str != "Hello Alice" {
		t.Errorf("Bad result: %q", str)
	}

	bob, err2 := ctx2.Eval("greet('Bob')", "ctx2.js")
	if err2 != nil {
		t.Errorf("Context 2 failed: %v", err2)
	} else if str := bob.String(); str != "Hello Bob" {
		t.Errorf("Bad result: %q", str)
	}
}

func TestCircularReferenceJsonMarshalling(t *testing.T) {
	t.Parallel()

	ctx := NewIsolate().NewContext()
	circ, err := ctx.Eval("var test = {}; test.blah = test", "circular.js")
	if err != nil {
		t.Fatalf("Failed to create object with circular ref: %v", err)
	}
	data, err := circ.MarshalJSON()
	if err == nil {
		t.Fatalf("Expected error marshalling circular ref, but got: `%s`", data)
	} else if !strings.Contains(err.Error(), "circular") {
		t.Errorf("Expected a circular reference error, but got: %v", err)
	}
}

func TestIsolateFinalizer(t *testing.T) {
	t.Parallel()
	iso := NewIsolate()

	fin := make(chan bool)
	// Reset the finalizer so we test if it is working
	runtime.SetFinalizer(iso, nil)
	runtime.SetFinalizer(iso, func(iso *Isolate) {
		close(fin)
		iso.release()
	})
	iso = nil

	if !runGcUntilReceivedOrTimedOut(fin, 4*time.Second) {
		t.Fatal("finalizer of iso didn't run, no context is associated with the iso.")
	}

	iso = NewIsolate()
	iso.NewContext()

	fin = make(chan bool)
	// Reset the finalizer so we test if it is working
	runtime.SetFinalizer(iso, nil)
	runtime.SetFinalizer(iso, func(iso *Isolate) {
		close(fin)
		iso.release()
	})
	iso = nil

	if !runGcUntilReceivedOrTimedOut(fin, 4*time.Second) {
		t.Fatal("finalizer of iso didn't run, iso created one context.")
	}
}

func TestContextFinalizer(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	fin := make(chan bool)
	// Reset the finalizer so we test if it is working
	runtime.SetFinalizer(ctx, nil)
	runtime.SetFinalizer(ctx, func(ctx *Context) {
		close(fin)
		ctx.release()
	})
	ctx = nil

	if !runGcUntilReceivedOrTimedOut(fin, 4*time.Second) {
		t.Fatal("finalizer of ctx didn't run")
	}
}

func TestContextFinalizerWithValues(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	greet := func(in CallbackArgs) (*Value, error) {
		return in.Context.Create("Hello " + in.Arg(0).String())
	}
	ctx.Global().Set("greet", ctx.Bind("greet", greet))
	val, err := ctx.Eval("greet('bob')", "")
	if err != nil {
		t.Fatal(err)
	}
	t.Log(val.String())

	fin := make(chan bool)
	// Reset the finalizer so we test if it is working
	runtime.SetFinalizer(ctx, nil)
	runtime.SetFinalizer(ctx, func(ctx *Context) {
		close(fin)
		ctx.release()
	})
	ctx = nil

	if !runGcUntilReceivedOrTimedOut(fin, 4*time.Second) {
		t.Fatal("finalizer of ctx didn't run after creating a value")
	}
}

func TestIsolateGetHeapStatistics(t *testing.T) {
	iso := NewIsolate()
	initHeap := iso.GetHeapStatistics()
	if initHeap.TotalHeapSize <= 0 {
		t.Fatalf("expected heap to be more than zero, got: %d\n", initHeap.TotalHeapSize)
	}

	ctx := iso.NewContext()
	for i := 0; i < 10000; i++ {
		ctx.Create(map[string]interface{}{
			"hello": map[string]interface{}{
				"world": []string{"foo", "bar"},
			},
		})
	}

	midHeap := iso.GetHeapStatistics()
	if midHeap.TotalHeapSize <= initHeap.TotalHeapSize {
		t.Fatalf("expected heap to grow after creating context, got: %d\n", midHeap.TotalHeapSize)
	}

	beforeNotifyHeap := iso.GetHeapStatistics()

	iso.SendLowMemoryNotification()

	finalHeap := iso.GetHeapStatistics()
	if finalHeap.TotalHeapSize >= beforeNotifyHeap.TotalHeapSize {
		t.Fatalf("expected heap to reduce after terminating context, got: %d\n", finalHeap.TotalHeapSize)
	}

}

func runGcUntilReceivedOrTimedOut(signal <-chan bool, timeout time.Duration) bool {
	expired := time.After(timeout)
	for {
		select {
		case <-signal:
			return true
		case <-expired:
			return false
		case <-time.After(10 * time.Millisecond):
			runtime.GC()
		}
	}
}

// This is bad, and should be fixed! See https://github.com/augustoroman/v8/issues/21
func TestMicrotasksIgnoreUnhandledPromiseRejection(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()
	var logs []string
	ctx.Global().Set("log", ctx.Bind("log", func(in CallbackArgs) (*Value, error) {
		logs = append(logs, in.Arg(0).String())
		return nil, nil
	}))
	output, err := ctx.Eval(`
		log('start');
		let p = new Promise((_, reject) => { log("reject:'err'"); reject('err'); });
		p.then(v => log('then:'+v));
		log('done');
	`, `test.js`)

	expectedLogs := []string{
		"start",
		"reject:'err'",
		"done",
	}

	if !reflect.DeepEqual(logs, expectedLogs) {
		t.Errorf("Wrong logs.\nGot: %#q\nExp: %#q", logs, expectedLogs)
	}

	// output should be 'undefined' because log('done') doesn't return anything.
	if output.String() != "undefined" {
		t.Errorf("Unexpected output value: %v", output)
	}

	if err != nil {
		t.Errorf("Expected err to be nil since we ignore unhandled promise rejections. "+
			"In the future, hopefully we'll handle these better -- in fact, maybe err "+
			"is not-nil right now because you fixed that!  Got err = %v", err)
	}
}

func TestValueKind(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	// WASM: This wasm code corresponds to the WAT:
	//   (module
	//      (func $add (param $x i32) (param $y i32) (result i32)
	//          (i32.add (get_local $x) (get_local $y)))
	//      (export "add" $add))
	// That exports an "add(a,b int32) int32" function.
	const wasmCode = `
		new Uint8Array([0,97,115,109,1,0,0,0,1,135,128,128,128,0,1,96,2,127,127,1,127,3,130,128,128,
			128,0,1,0,6,129,128,128,128,0,0,7,135,128,128,128,0,1,3,97,100,100,0,0,10,141,128,128,128,
			0,1,135,128,128,128,0,0,32,0,32,1,106,11])`

	const wasmModule = `new WebAssembly.Module(` + wasmCode + `)`

	toTest := map[string]kindMask{
		`undefined`:                        mask(KindUndefined),
		`null`:                             mask(KindNull),
		`"test"`:                           unionKindString,
		`Symbol("test")`:                   unionKindSymbol,
		`(function(){})`:                   unionKindFunction,
		`[]`:                               unionKindArray,
		`new Object()`:                     mask(KindObject),
		`true`:                             mask(KindBoolean),
		`false`:                            mask(KindBoolean),
		`1`:                                mask(KindNumber, KindInt32, KindUint32),
		`new Date()`:                       unionKindDate,
		`(function(){return arguments})()`: unionKindArgumentsObject,
		`new Boolean`:                      unionKindBooleanObject,
		`new Number`:                       unionKindNumberObject,
		`new String`:                       unionKindStringObject,
		`new Object(Symbol("test"))`:       unionKindSymbolObject,
		`/regexp/`:                         unionKindRegExp,
		`new Promise((res, rjt)=>{})`:      unionKindPromise,
		`new Map()`:                        unionKindMap,
		`new Set()`:                        unionKindSet,
		`new ArrayBuffer(0)`:               unionKindArrayBuffer,
		`new Uint8Array(0)`:                unionKindUint8Array,
		`new Uint8ClampedArray(0)`:         unionKindUint8ClampedArray,
		`new Int8Array(0)`:                 unionKindInt8Array,
		`new Uint16Array(0)`:               unionKindUint16Array,
		`new Int16Array(0)`:                unionKindInt16Array,
		`new Uint32Array(0)`:               unionKindUint32Array,
		`new Int32Array(0)`:                unionKindInt32Array,
		`new Float32Array(0)`:              unionKindFloat32Array,
		`new Float64Array(0)`:              unionKindFloat64Array,
		`new DataView(new ArrayBuffer(0))`: unionKindDataView,
		`new SharedArrayBuffer(0)`:         unionKindSharedArrayBuffer,
		`new Proxy({}, {})`:                unionKindProxy,
		`new WeakMap`:                      unionKindWeakMap,
		`new WeakSet`:                      unionKindWeakSet,
		`(async function(){})`:             unionKindAsyncFunction,
		`(function* (){})`:                 unionKindGeneratorFunction,
		`function* gen(){}; gen()`:         unionKindGeneratorObject,
		`new Map()[Symbol.iterator]()`:     unionKindMapIterator,
		`new Set()[Symbol.iterator]()`:     unionKindSetIterator,
		`new EvalError`:                    unionKindNativeError,
		wasmModule:                         unionKindWebAssemblyCompiledModule,

		// TODO!
		// ``: KindExternal,
	}

	for script, kindMask := range toTest {
		v, err := ctx.Eval(script, "kind_test.js")
		if err != nil {
			t.Errorf("%#q: failed: %v", script, err)
		} else if v.kindMask != kindMask {
			t.Errorf("%#q: expected result to be %q, but got %q", script, kindMask, v.kindMask)
		}
	}
}

func TestDate(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	res, err := ctx.Eval(`new Date("2018-05-08T08:16:46.918Z")`, "date.js")
	if err != nil {
		t.Fatal(err)
	}

	tm, err := res.Date()
	if err != nil {
		t.Error(err)
	} else if tm.UnixNano() != 1525767406918*1e6 {
		t.Errorf("Wrong date: %q", tm)
	}
}

func TestPromise(t *testing.T) {
	t.Parallel()
	ctx := NewIsolate().NewContext()

	// Pending
	v, err := ctx.Eval(`new Promise((resolve, reject)=>{})`, "pending-promise.js")
	if err != nil {
		t.Fatal(err)
	}

	if state, result, err := v.PromiseInfo(); err != nil {
		t.Error(err)
	} else if state != PromiseStatePending {
		t.Errorf("Expected promise to be pending, but got %v", state)
	} else if result != nil {
		t.Errorf("Expected nil result since it's pending, but got %v", result)
	}

	// Resolved
	v, err = ctx.Eval(`new Promise((resolve, reject)=>{resolve(42)})`, "resolved-promise.js")
	if err != nil {
		t.Fatal(err)
	}

	if state, result, err := v.PromiseInfo(); err != nil {
		t.Error(err)
	} else if state != PromiseStateResolved {
		t.Errorf("Expected promise to be resolved, but got %v", state)
	} else if result == nil {
		t.Errorf("Expected a result since it's resolved, but got nil")
	} else if !result.IsKind(KindNumber) {
		t.Errorf("Expected the result to be a number, but it's: %v (%v)", result.kindMask, result)
	} else if result.Int64() != 42 {
		t.Errorf("Expected the result to be 42, but got %v", result)
	}

	// Rejected
	v, err = ctx.Eval(`new Promise((resolve, reject)=>{reject(new Error("nope"))})`, "rejected-promise.js")
	if err != nil {
		t.Fatal(err)
	}

	if state, result, err := v.PromiseInfo(); err != nil {
		t.Error(err)
	} else if state != PromiseStateRejected {
		t.Errorf("Expected promise to be rejected, but got %v", state)
	} else if result == nil {
		t.Errorf("Expected an error result since it's rejected, but got nil")
	} else if !result.IsKind(KindNativeError) {
		t.Errorf("Expected the result to be an error, but it's: %v (%v)", result.kindMask, result)
	} else if result.String() != `Error: nope` {
		t.Errorf("Expected the error message to be 'nope', but got %#q", result)
	}

	// Not a promise
	v, err = ctx.Eval(`new Error('x')`, "not-a-promise.js")
	if err != nil {
		t.Fatal(err)
	}

	if state, result, err := v.PromiseInfo(); err == nil {
		t.Errorf("Expected an error, but got nil and state=%#v result=%#v", state, result)
	}
}

func TestPanicHandling(t *testing.T) {
	// v8 runtime can register its own signal handlers which would interfere
	// with Go's signal handlers which are needed for panic handling
	defer func() {
		if r := recover(); r != nil {
			// if we reach this point, Go's panic mechanism is still intact
			_, ok := r.(runtime.Error)
			if !ok {
				t.Errorf("expected runtime error, actual %v", r)
			}
		}
	}()

	var f *big.Float
	_ = NewIsolate()
	_ = *f
}


text:
;(function ($, Formstone, undefined) {

	"use strict";

	/**
	 * @method private
	 * @name setup
	 * @description Setup plugin.
	 */

	function setup() {
		$Locks = $("html, body");
	}

	/**
	 * @method private
	 * @name construct
	 * @description Builds instance.
	 * @param data [object] "Instance data"
	 */

	function construct(data) {
		// guid
		data.handleGuid   = RawClasses.handle + data.guid;

		data.isToggle     = (data.type === "toggle");
		data.open         = false;

		if (data.isToggle) {
			data.gravity  = "";
		}

		var baseClass     = RawClasses.base,
			typeClass     = [baseClass, data.type].join("-"),
			gravityClass  = data.gravity ? [typeClass, data.gravity].join("-") : "",
			classGroup    = [data.rawGuid, data.customClass].join(" ");

		data.handle       = this.data(Namespace + "-handle");
		data.content      = this.data(Namespace + "-content");

		data.handleClasses = [
			RawClasses.handle,
			RawClasses.handle.replace(baseClass, typeClass),
			gravityClass ? RawClasses.handle.replace(baseClass, gravityClass) : "",
			data.handleGuid,
			classGroup
		].join(" ");

		data.navClasses = [
			RawClasses.nav.replace(baseClass, typeClass),
			gravityClass ? RawClasses.nav.replace(baseClass, gravityClass) : "",
			classGroup
		].join(" ");

		data.contentClasses = [
			RawClasses.content.replace(baseClass, typeClass),
			gravityClass ? RawClasses.content.replace(baseClass, gravityClass) : "",
			classGroup
		].join(" ");

		// DOM

		data.$nav        = this.addClass(data.navClasses);
		data.$handle     = $(data.handle).addClass(data.handleClasses);
		data.$content    = $(data.content).addClass(data.contentClasses);
		data.$animate    = $().add(data.$nav).add(data.$content);

		cacheLabel(data);

		// toggle

		data.$handle.attr("data-swap-target", data.dotGuid)
					.attr("data-swap-linked", "." + data.handleGuid)
					.attr("data-swap-group", RawClasses.base)
					.on("activate.swap" + data.dotGuid, data, onOpen)
					.on("deactivate.swap" + data.dotGuid, data, onClose)
					.on("enable.swap" + data.dotGuid, data, onEnable)
					.on("disable.swap" + data.dotGuid, data, onDisable)
					.swap({
						maxWidth: data.maxWidth,
						classes: {
							target  : data.dotGuid,
							enabled : Classes.enabled,
							active  : Classes.open,
							raw: {
								target  : data.rawGuid,
								enabled : RawClasses.enabled,
								active  : RawClasses.open
							}
						}
					});
	}

	/**
	 * @method private
	 * @name destruct
	 * @description Tears down instance.
	 * @param data [object] "Instance data"
	 */

	function destruct(data) {
		data.$content.removeClass(data.contentClasses)
					 .off(Events.namespace);

		data.$handle.removeAttr("data-swap-target")
					.removeData("swap-target")
					.removeAttr("data-swap-linked")
					.removeData("swap-linked")
					.removeClass(data.handleClasses)
					.off(data.dotGuid)
					.text(data.originalLabel)
					.swap("destroy");

		restoreLabel(data);

		clearLocks(data);

		this.removeClass(data.navClasses)
			.off(Events.namespace);
	}

	/**
	 * @method
	 * @name open
	 * @description Opens instance.
	 * @example $(".target").navigation("open");
	 */

	function open(data) {
		data.$handle.swap("activate");
	}

	/**
	 * @method
	 * @name close
	 * @description Closes instance.
	 * @example $(".target").navigation("close");
	 */

	function close(data) {
		data.$handle.swap("deactivate");
	}

	/**
	 * @method
	 * @name enable
	 * @description Enables instance.
	 * @example $(".target").navigation("enable");
	 */

	function enable(data) {
		data.$handle.swap("enable");
	}

	/**
	 * @method
	 * @name disable
	 * @description Disables instance.
	 * @example $(".target").navigation("disable");
	 */

	function disable(data) {
		data.$handle.swap("disable");
	}

	/**
	 * @method private
	 * @name onOpen
	 * @description Handles nav open event.
	 * @param e [object] "Event data"
	 */

	function onOpen(e) {
		if (!e.originalEvent) { // thanks IE :/
			var data = e.data;

			if (!data.open) {
				data.$el.trigger(Events.open);

				data.$content.addClass(RawClasses.open)
							 .one(Events.clickTouchStart, function() {
								close(data);
							 });

				if (data.label) {
					data.$handle.text(data.labels.open);
				}

				addLocks(data);

				data.open = true;
			}
		}
	}

	/**
	 * @method private
	 * @name onClose
	 * @description Handles nav close event.
	 * @param e [object] "Event data"
	 */

	function onClose(e) {
		if (!e.originalEvent) { // thanks IE :/
			var data = e.data;

			if (data.open) {
				data.$el.trigger(Events.close);

				data.$content.removeClass(RawClasses.open)
							 .off(Events.namespace);

				if (data.label) {
					data.$handle.text(data.labels.closed);
				}

				clearLocks(data);

				data.open = false;
			}
		}
	}

	/**
	 * @method private
	 * @name onEnable
	 * @description Handles nav enable event.
	 * @param e [object] "Event data"
	 */

	function onEnable(e) {
		var data = e.data;

		data.$content.addClass(RawClasses.enabled);

		setTimeout(function() {
			data.$animate.addClass(RawClasses.animated);
		}, 0);

		if (data.label) {
			data.$handle.text(data.labels.closed);
		}
	}

	/**
	 * @method private
	 * @name onDisable
	 * @description Handles nav disable event.
	 * @param e [object] "Event data"
	 */

	function onDisable(e) {
		var data = e.data;

		data.$content.removeClass(RawClasses.enabled, RawClasses.animated);
		data.$animate.removeClass(RawClasses.animated);

		restoreLabel(data);

		clearLocks(data);
	}

	/**
	 * @method private
	 * @name addLocks
	 * @description Locks scrolling
	 * @param data [object] "Instance data"
	 */

	function addLocks(data) {
		if (!data.isToggle) {
			$Locks.addClass(RawClasses.lock);
		}
	}

	/**
	 * @method private
	 * @name clearLocks
	 * @description Unlocks scrolling
	 * @param data [object] "Instance data"
	 */

	function clearLocks(data) {
		if (!data.isToggle) {
			$Locks.removeClass(RawClasses.lock);
		}
	}

	/**
	 * @method private
	 * @name cacheLabel
	 * @description Sets handle labels
	 * @param data [object] "Instance data"
	 */

	function cacheLabel(data) {
		if (data.label) {
			if (data.$handle.length > 1) {
				data.originalLabel = [];

				for (var i = 0, count = data.$handle.length; i < count; i++) {
					data.originalLabel[i] = data.$handle.eq(i).text();
				}
			} else {
				data.originalLabel = data.$handle.text();
			}
		}
	}

	/**
	 * @method private
	 * @name restoreLabel
	 * @description restores handle labels
	 * @param data [object] "Instance data"
	 */

	function restoreLabel(data) {
		if (data.label) {
			if (data.$handle.length > 1) {
				for (var i = 0, count = data.$handle.length; i < count; i++) {
					data.$handle.eq(i).text(data.originalLabel[i]);
				}
			} else {
				data.$handle.text(data.originalLabel);
			}
		}
	}

	/**
	 * @plugin
	 * @name Navigation
	 * @description A jQuery plugin for simple responsive navigation.
	 * @type widget
	 * @dependency core.js
	 * @dependency mediaquery.js
	 * @dependency swap.js
	 * @dependency touch.js
	 */

	var Plugin = Formstone.Plugin("navigation", {
			widget: true,

			/**
			 * @options
			 * @param customClass [string] <''> "Class applied to instance"
			 * @param gravity [string] <'left'> "Gravity of 'push', 'reveal' and 'overlay' navigation; 'right', 'left'"
			 * @param label [boolean] <true> "Display handle width label"
			 * @param labels.closed [string] <'Menu'> "Closed state text"
			 * @param labels.open [string] <'Close'> "Open state text"
			 * @param maxWidth [string] <'980px'> "Width at which to auto-disable plugin"
			 * @param type [string] <'toggle'> "Type of navigation; 'toggle', 'push', 'reveal', 'overlay'"
			 */

			defaults: {
				customClass    : "",
				gravity        : "left",
				label          : true,
				labels: {
					closed     : "Menu",
					open       : "Close"
				},
				maxWidth       : "980px",
				type           : "toggle"
			},

			classes: [
				"handle",
				"nav",
				"content",
				"animated",
				"enabled",
				"open",
				"toggle",
				"push",
				"reveal",
				"overlay",
				"left",
				"right",
				"lock"
			],

			/**
			 * @events
			 * @event open.navigation "Navigation opened"
			 * @event close.navigation "Navigation closed"
			 */

			events: {
				tap      : "tap",
				open     : "open",
				close    : "close"
			},

			methods: {
				_setup        : setup,
				_construct    : construct,
				_destruct     : destruct,

				// Public Methods

				open          : open,
				close         : close,
				enable        : enable,
				disable       : disable
			}
		}),

		// Localize References

		Namespace     = Plugin.namespace,
		Classes       = Plugin.classes,
		RawClasses    = Classes.raw,
		Events        = Plugin.events,
		Functions     = Plugin.functions,

		// Internal

		$Locks        = null;

})(jQuery, Formstone);


text:
package netutil

import (
	"fmt"
	"runtime"
)

// GetDefaultHost fetches the a resolvable name that corresponds
// to the machine's default routable interface
func GetDefaultHost() (string, error) {
	return "", fmt.Errorf("default host not supported on %s_%s", runtime.GOOS, runtime.GOARCH)
}

// GetDefaultInterfaces fetches the device name of default routable interface.
func GetDefaultInterfaces() (map[string]uint8, error) {
	return nil, fmt.Errorf("default host not supported on %s_%s", runtime.GOOS, runtime.GOARCH)
}


text:
use crate::errors::*;
use crate::providers::vmware::VmwareProvider;
use crate::providers::MetadataProvider;
use std::fs::File;
use std::io::Write;

/// Path to cmdline.d fragment for network kernel arguments.
static KARGS_PATH: &str = "/etc/cmdline.d/50-afterburn-network-kargs.conf";

/// Fetch network kargs for the given provider.
pub(crate) fn fetch_network_kargs(provider: &str) -> Result<Option<String>> {
    match provider {
        "vmware" => VmwareProvider::try_new()?.rd_network_kargs(),
        _ => Ok(None),
    }
}

/// Write network kargs into a cmdline.d fragment.
pub(crate) fn write_network_kargs(kargs: &str) -> Result<()> {
    let mut fragment_file =
        File::create(KARGS_PATH).chain_err(|| format!("failed to create file {:?}", KARGS_PATH))?;

    fragment_file
        .write_all(kargs.as_bytes())
        .chain_err(|| "failed to write network arguments fragment")?;

    Ok(())
}


text: not cleaned up whatsoever


text:
'use strict';

var lint = require('./_lint');

var file = lint.file('variable-for-property.scss');

describe('variable for property', function () {
  it('[]', function (done) {
    lint.test(file, {
      'variable-for-property': 1
    }, function (data) {
      lint.assert.equal(0, data.warningCount);
      done();
    });
  });
  it('[properties]', function (done) {
    lint.test(file, {
      'variable-for-property': [
        1,
        {
          'properties': [
            'margin',
            'content'
          ]
        }
      ]
    }, function (data) {
      lint.assert.equal(4, data.warningCount);
      done();
    });
  });
});


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="<?php echo base_url();?>assets/imgs/greentaxi.ico">

    <title>Greentaxi</title>

    <!-- Bootstrap core CSS echo base_url -- spraviť linky -->

    <link rel="stylesheet" href="http://bootswatch.com/cyborg/bootstrap.min.css">

    <!-- Custom styles for this template -->
    <link href=<?php echo base_url();?>assets/css/custom.css rel="stylesheet">

</head>
<body>


text:
package com.google.cloud.tasks.v2beta2.samples;

// [START cloudtasks_v2beta2_generated_CloudTasks_ListTasks_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.tasks.v2beta2.CloudTasksClient;
import com.google.cloud.tasks.v2beta2.ListTasksRequest;
import com.google.cloud.tasks.v2beta2.QueueName;
import com.google.cloud.tasks.v2beta2.Task;

public class AsyncListTasks {

  public static void main(String[] args) throws Exception {
    asyncListTasks();
  }

  public static void asyncListTasks() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudTasksClient cloudTasksClient = CloudTasksClient.create()) {
      ListTasksRequest request =
          ListTasksRequest.newBuilder()
              .setParent(QueueName.of("[PROJECT]", "[LOCATION]", "[QUEUE]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .build();
      ApiFuture<Task> future = cloudTasksClient.listTasksPagedCallable().futureCall(request);
      // Do something.
      for (Task element : future.get().iterateAll()) {
        // doThingsWith(element);
      }
    }
  }
}
// [END cloudtasks_v2beta2_generated_CloudTasks_ListTasks_async]


text:
<?php
$ds = DIRECTORY_SEPARATOR;  //1 step

$storeFolder = 'uploads/';   //Put your target upload Folder(or create an uploads forder where your upload.php file present)

if (!empty($_FILES)) {

    $tempFile = $_FILES['file']['tmp_name'];          //3 step (form field name)

    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;  //4 step

    $targetFile =  $targetPath. $_FILES['file']['name'];  //5 step

    move_uploaded_file($tempFile,$targetFile); //6 step

}

?>