text:
A 2.1mm DC adapter pack with battery bypass and any-polarity to any-polarity connectors.

![Build](./assets/Any2AnyPowerPack_build.jpg?raw=true)

## Notes

I recently got a flamenco metronome that has a 2.1mm power connector but in centre-negative configuration.
Unfortunately I don't have any centre-negative power packs on hand. I could of course just rewire one,
but decided it might be the time to make up a generic any-to-any connector.

Features I'll add:

* centre-positive and centre-negative output plugs
* 9V battery bypass
* polarity rectifier, so that the input supports both centre-positive and centre-negative connections
* a power switch
* an LED power indicator

### Input Power Rectifier

To protect against reverse polarity input power, I could just add a single rectifier diode in series.
That would prevent the connection of power with the wrong polarity.

A little more fancy is a rectifier bridge that allows connection in either polarity.
There is a price to pay however: loss of two diode drops from the power supply.

Since I'm not dealing with huge voltages here (planning for 5-9V), and DC operation so switching speed is irrelevant,
there's a broad choice of rectifiers possible e.g.

* 1N4001-7 standard go-to rectifiers with a pretty high average Vf of 0.8V, but extremely low reverse current of 30µA
* 1N5819 offers extremely low Vf (0.34 V at 100mA), however the maximum reverse current at rated voltage is pretty high at 1mA

I decided to use the 1N5819 in the bridge rectifier to get the low forward voltage benefit.
The reverse current is a little high, but at low voltages and currents perhaps negligible enough and in practice this
should be swallowed by the bridge rectifier (just showing up as a reduced efficiency)

Some measurements to back that up:

| Diode  | Input Voltage | Output Voltage, No Load | 1kΩ Load | 10kΩ Load | 100kΩ Load |
|--------|---------------|-------------------------|----------|-----------|------------|
| 1N4007 | 8.72V         | 8.13V                   | 6.88V    | 7.54V     | 7.78V      |
| 1N5819 | 8.72V         | 8.62V                   | 7.97V    | 8.29V     | 8.43V      |

PS: the "evils" of centre-negative jacks has now been explored in [EEVblog #1015](https://www.youtube.com/watch?v=ix2fR-rh1vc) - some great background
and demonstration of how these work.

## Circuit

![Breadboard](./assets/Any2AnyPowerPack_bb.jpg?raw=true)

![Schematic](./assets/Any2AnyPowerPack_schematic.jpg?raw=true)

## Construction

![Any2AnyPowerPack_construction_1](./assets/Any2AnyPowerPack_construction_1.jpg?raw=true)

![Any2AnyPowerPack_construction_2](./assets/Any2AnyPowerPack_construction_2.jpg?raw=true)

![Build](./assets/Any2AnyPowerPack_build.jpg?raw=true)

## Credits and References

* [EEVblog #1015 - Beware Evil (But Clever) DC Jacks!](https://www.youtube.com/watch?v=ix2fR-rh1vc)
* [1N5819 Datasheet](https://www.futurlec.com/Diodes/1N5819.shtml)
* [1N4001-7 Datasheet](https://www.futurlec.com/Diodes/1N4001.shtml)
* [..as mentioned on my blog](https://blog.tardate.com/2017/08/leap330-any-to-an-polarity-dc-power-adapter.html)


text:
template<std::size_t dim, typename T, typename A>
void update_overlap(const mpl::cartesian_communicator &cartesian_communicator,
                    mpl::distributed_grid<dim, T, A> &grid, mpl::tag_t tag = mpl::tag_t()) {
  for (std::size_t i{0}; i < dim; ++i) {
    // send to left
    auto [source_l, destination_l] = cartesian_communicator.shift(i, -1);
    cartesian_communicator.sendrecv(grid.data(), grid.left_border_layout(i), destination_l,
                                    tag, grid.data(), grid.right_mirror_layout(i), source_l,
                                    tag);
    // send to right
    auto [source_r, destination_r] = cartesian_communicator.shift(i, +1);
    cartesian_communicator.sendrecv(grid.data(), grid.right_border_layout(i), destination_r,
                                    tag, grid.data(), grid.left_mirror_layout(i), source_r,
                                    tag);
  }
}

int main() {
  const mpl::communicator &comm_world{mpl::environment::comm_world()};
  {
    // build a one-dimensional Cartesian communicator
    // Cartesian is non-cyclic
    mpl::cartesian_communicator::dimensions size{mpl::cartesian_communicator::non_periodic};
    mpl::cartesian_communicator comm_c{comm_world, mpl::dims_create(comm_world.size(), size)};
    // create a distributed grid of 31 total grid points and 2 shadow grid points
    // to mirror data between adjacent processes
    mpl::distributed_grid<1, int> grid{comm_c, {{31, 2}}};
    // fill local grid including shadow grid points
    for (auto i{grid.obegin(0)}, i_end{grid.oend(0)}; i < i_end; ++i)
      grid(i) = comm_c.rank();
    // get shadow data from adjacent processes
    update_overlap(comm_c, grid);
    // print local grid including shadow grid points
    for (int k{0}; k < comm_c.size(); ++k) {
      if (k == comm_c.rank()) {
        for (auto i{grid.obegin(0)}, i_end{grid.oend(0)}; i < i_end; ++i)
          std::cout << grid(i);
        std::cout << std::endl;
      }
      comm_c.barrier();  // barrier may avoid overlapping output
    }
  }
  {
    // build a two-dimensional Cartesian communicator
    // Cartesian is cyclic along 1st dimension, non-cyclic along 2nd dimension
    mpl::cartesian_communicator::dimensions size{mpl::cartesian_communicator::periodic,
                                                 mpl::cartesian_communicator::non_periodic};
    mpl::cartesian_communicator comm_c{comm_world, mpl::dims_create(comm_world.size(), size)};
    // create a distributed grid of 11x13 total grid points and 2 respectively 1
    // shadow grid points to mirror data between adjacent processes
    mpl::distributed_grid<2, int> grid{comm_c, {{11, 2}, {13, 1}}};
    // fill local grid including shadow grid points
    for (auto j{grid.obegin(1)}, j_end{grid.oend(1)}; j < j_end; ++j)
      for (auto i{grid.obegin(0)}, i_end{grid.oend(0)}; i < i_end; ++i)
        grid(i, j) = comm_c.rank();
    // get shadow data from adjacent processes
    update_overlap(comm_c, grid);
    // print local grid including shadow grid points
    for (int k{0}; k < comm_c.size(); ++k) {
      if (k == comm_c.rank()) {
        std::cout << std::endl;
        for (auto j{grid.obegin(1)}, j_end{grid.oend(1)}; j < j_end; ++j) {
          for (auto i{grid.obegin(0)}, i_end{grid.oend(0)}; i < i_end; ++i)
            std::cout << grid(i, j);
          std::cout << std::endl;
        }
      }
      comm_c.barrier();  // barrier may avoid overlapping output
    }
  }
  return EXIT_SUCCESS;
}

redpajama_set_name: RedPajamaGithub


text:
namespace dronecode_sdk {
namespace backend {

template<typename DronecodeSDK> class ConnectionInitiator {
public:
    ConnectionInitiator() {}
    ~ConnectionInitiator() {}

    bool start(DronecodeSDK &dc, const int port)
    {
        init_mutex();
        init_timeout_logging(dc);

        _discovery_future = wrapped_register_on_discover(dc);

        if (!add_udp_connection(dc, port)) {
            return false;
        }

        return true;
    }

    void wait() { _discovery_future.wait(); }

private:
    void init_mutex() { _discovery_promise = std::make_shared<std::promise<uint64_t>>(); }

    void init_timeout_logging(DronecodeSDK &dc) const
    {
        dc.register_on_timeout(
            [](uint64_t uuid) { LogInfo() << "System timed out [UUID: " << uuid << "]"; });
    }

    bool add_udp_connection(DronecodeSDK &dc, const int port)
    {
        dronecode_sdk::ConnectionResult connection_result = dc.add_udp_connection(port);

        if (connection_result != ConnectionResult::SUCCESS) {
            LogErr() << "Connection failed: " << connection_result_str(connection_result);
            return false;
        }

        return true;
    }

    std::future<uint64_t> wrapped_register_on_discover(DronecodeSDK &dc)
    {
        auto future = _discovery_promise->get_future();

        LogInfo() << "Waiting to discover system...";

        dc.register_on_discover([this](uint64_t uuid) {
            std::call_once(_discovery_flag, [this, uuid]() {
                LogInfo() << "System discovered [UUID: " << uuid << "]";
                _discovery_promise->set_value(uuid);
            });
        });

        return future;
    }

    std::once_flag _discovery_flag{};
    std::shared_ptr<std::promise<uint64_t>> _discovery_promise{};
    std::future<uint64_t> _discovery_future{};
};

} // namespace backend
} // namespace dronecode_sdk


text:
package cn.momia.mapi.api.im;

import cn.momia.api.course.CourseServiceApi;
import cn.momia.api.course.dto.course.CourseSku;
import cn.momia.api.im.ImServiceApi;
import cn.momia.api.im.dto.Group;
import cn.momia.api.im.dto.GroupMember;
import cn.momia.api.im.dto.UserGroup;
import cn.momia.api.user.TeacherServiceApi;
import cn.momia.api.user.UserServiceApi;
import cn.momia.api.user.dto.Teacher;
import cn.momia.api.user.dto.User;
import cn.momia.common.core.http.MomiaHttpResponse;
import cn.momia.common.core.util.TimeUtil;
import cn.momia.mapi.api.AbstractApi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/v1/im")
public class ImV1Api extends AbstractApi {
    @Autowired private ImServiceApi imServiceApi;
    @Autowired private CourseServiceApi courseServiceApi;
    @Autowired private UserServiceApi userServiceApi;
    @Autowired private TeacherServiceApi teacherServiceApi;

    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public MomiaHttpResponse generateImToken(@RequestParam String utoken) {
        if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
        return MomiaHttpResponse.SUCCESS(doGenerateImToken(userServiceApi.get(utoken)));
    }

    private String doGenerateImToken(User user) {
        String imToken = imServiceApi.generateImToken(user.getId(), user.getNickName(), completeSmallImg(user.getAvatar()));
        if (!StringUtils.isBlank(imToken)) userServiceApi.updateImToken(user.getToken(), imToken);

        return imToken;
    }

    @RequestMapping(value = "/token", method = RequestMethod.GET)
    public MomiaHttpResponse getImToken(@RequestParam String utoken) {
        if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;

        User user = userServiceApi.get(utoken);
        String imToken = user.getImToken();
        if (StringUtils.isBlank(imToken)) imToken = doGenerateImToken(user);

        return MomiaHttpResponse.SUCCESS(imToken);
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public MomiaHttpResponse getImUserInfo(@RequestParam(value = "uid") long userId) {
        if (userId <= 0) return MomiaHttpResponse.FAILED("无效的用户ID");

        User user = userServiceApi.get(userId);
        JSONObject imUserInfoJson = createImUserInfo(user);

        List<String> latestImgs = courseServiceApi.getLatestCommentImgs(userId);
        if (!latestImgs.isEmpty()) imUserInfoJson.put("imgs", completeMiddleImgs(latestImgs));

        return MomiaHttpResponse.SUCCESS(imUserInfoJson);
    }

    private JSONObject createImUserInfo(User user) {
        JSONObject imUserInfoJson = new JSONObject();
        imUserInfoJson.put("id", user.getId());
        imUserInfoJson.put("nickName", user.getNickName());
        imUserInfoJson.put("avatar", completeSmallImg(user.getAvatar()));
        imUserInfoJson.put("role", user.getRole());

        return imUserInfoJson;
    }

    @RequestMapping(value = "/user/group", method = RequestMethod.GET)
    public MomiaHttpResponse listUserGroups(@RequestParam String utoken) {
        if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;

        User user = userServiceApi.get(utoken);
        List<UserGroup> userGroups = imServiceApi.listUserGroups(user.getId());

        Set<Long> courseIds = new HashSet<Long>();
        for (UserGroup group : userGroups) {
            courseIds.add(group.getCourseId());
        }
        Map<Long, String> tipsOfCourses = courseServiceApi.queryTips(courseIds);

        List<JSONObject> result = new ArrayList<JSONObject>();
        for (UserGroup userGroup : userGroups) {
            JSONObject userGroupJson = (JSONObject) JSON.toJSON(userGroup);
            userGroupJson.put("addTime", TimeUtil.STANDARD_DATE_FORMAT.format(userGroup.getAddTime()));
            userGroupJson.put("tips", tipsOfCourses.get(String.valueOf(userGroup.getCourseId())));

            result.add(userGroupJson);
        }

        return MomiaHttpResponse.SUCCESS(result);
    }

    @RequestMapping(value = "/group", method = RequestMethod.GET)
    public MomiaHttpResponse getGroupInfo(@RequestParam(value = "id") long groupId) {
        if (groupId <= 0) return MomiaHttpResponse.FAILED("无效的群组ID");

        Group group = imServiceApi.getGroup(groupId);
        CourseSku sku = courseServiceApi.getSku(group.getCourseId(), group.getCourseSkuId());

        JSONObject groupInfo = new JSONObject();
        groupInfo.put("groupId", group.getGroupId());
        groupInfo.put("groupName", group.getGroupName());
        groupInfo.put("tips", courseServiceApi.queryTips(Sets.newHashSet(group.getCourseId())).get(String.valueOf(group.getCourseId())));
        groupInfo.put("time", sku.getTime());
        groupInfo.put("route", sku.getRoute());
        groupInfo.put("address", sku.getPlace().getAddress());

        return MomiaHttpResponse.SUCCESS(groupInfo);
    }

    @RequestMapping(value = "/group/member", method = RequestMethod.GET)
    public MomiaHttpResponse listGroupMembers(@RequestParam String utoken, @RequestParam(value = "id") long groupId) {
        if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
        if (groupId <= 0) return MomiaHttpResponse.FAILED("无效的群组ID");

        User user = userServiceApi.get(utoken);
        List<GroupMember> groupMembers = imServiceApi.listGroupMembers(user.getId(), groupId);

        Set<Long> teacherUserIds = new HashSet<Long>();
        Set<Long> customerUserIds = new HashSet<Long>();
        for (GroupMember groupMember : groupMembers) {
            if (groupMember.isTeacher()) teacherUserIds.add(groupMember.getUserId());
            else customerUserIds.add(groupMember.getUserId());
        }

        List<Teacher> teachers = teacherServiceApi.listByUserIds(teacherUserIds);
        Map<Long, Teacher> teachersMap = new HashMap<Long, Teacher>();
        for (Teacher teacher : teachers) {
            teachersMap.put(teacher.getUserId(), teacher);
        }

        List<User> customers = userServiceApi.list(customerUserIds, User.Type.BASE);
        Map<Long, User> customersMap = new HashMap<Long, User>();
        for (User customer : customers) {
            customersMap.put(customer.getId(), customer);
        }

        List<JSONObject> teacherJsons = new ArrayList<JSONObject>();
        List<JSONObject> customerJsons = new ArrayList<JSONObject>();
        for (GroupMember groupMember : groupMembers) {
            if (groupMember.isTeacher()) {
                Teacher teacher = teachersMap.get(groupMember.getUserId());
                if (teacher == null) continue;

                JSONObject imTeacherJson = createImTeacherInfo(teacher);
                teacherJsons.add(imTeacherJson);
            } else {
                User customer = customersMap.get(groupMember.getUserId());
                if (customer == null) continue;

                JSONObject imUserJson = createImUserInfo(customer);
                customerJsons.add(imUserJson);
            }
        }

        JSONObject responseJson = new JSONObject();
        responseJson.put("teachers", teacherJsons);
        responseJson.put("customers", customerJsons);

        return MomiaHttpResponse.SUCCESS(responseJson);
    }

    private JSONObject createImTeacherInfo(Teacher teacher) {
        JSONObject imTeacherInfoJson = new JSONObject();
        imTeacherInfoJson.put("id", teacher.getUserId());
        imTeacherInfoJson.put("nickName", teacher.getName());
        imTeacherInfoJson.put("avatar", completeSmallImg(teacher.getAvatar()));
        imTeacherInfoJson.put("role", User.Role.TEACHER);

        return imTeacherInfoJson;
    }
}


text:
"""
Copyright 2010-2017 University Of Southern California

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.

Program to set up a full validation run on the epicenter cluster
"""

# Import Python modules
import os
import sys
import math
import random
import shutil
import optparse
import tempfile

# Import Broadband modules
from install_cfg import InstallCfg
import validation_cfg
import bband_utils

# Constants
BATCH_SIM_FILE = "batch_run_bbp_sims.log"
CORES_PER_NODE = 8
MAX_SIMULATIONS = 200
CODEBASES = ["gp", "ucsb", "sdsu", "exsim", "csm", "irikura"]

def generate_src_files(numsim, source_file, srcdir, prefix, hypo_rand):
    """
    Generates num_sim source files in the srcdir using different
    random seeds
    """
    src_props = bband_utils.parse_properties(source_file)
    # Delete "seed" from the property set
    if "seed" in src_props:
        src_props.pop("seed")
    # Get FAULT_LENGTH and FAULT_WIDTH from the SRC file
    try:
        flen = float(src_props["fault_length"])
        fwid = float(src_props["fault_width"])
    except KeyError:
        raise bband_utils.ParameterError("Cannot read fault_length/fault_width"
                                         " parameters from SRC file!")
    if hypo_rand:
        # Delete HYPO_ALONG_STK and HYPO_DOWN_DIP
        if "hypo_along_stk" in src_props:
            src_props.pop("hypo_along_stk")
        if "hypo_down_dip" in src_props:
            src_props.pop("hypo_down_dip")
    # Create common list of keys for all files
    output = ""
    for key in src_props:
        output = output + "%s = %s\n" % (key.upper(), src_props[key])
    for sim in range(0, numsim):
        random.seed(sim + 1)
        seed = int(math.exp(7 * math.log(10.0)) * random.random())
        hypo_along_stk = flen * (0.2 + 0.6 * random.random() - 0.5)
        hypo_down_dip = fwid * (0.2 + 0.6 * random.random())
        srcfile = os.path.join(srcdir, "%s-%04d.src" % (prefix, sim))
        outfile = open(srcfile, 'w')
        outfile.write(output)
        if hypo_rand:
            outfile.write("HYPO_ALONG_STK = %.2f\n" % (hypo_along_stk))
            outfile.write("HYPO_DOWN_DIP = %.2f\n" % (hypo_down_dip))
        outfile.write("SEED = %d\n" % (seed))
        outfile.close()

def generate_xml(install, numsim, srcdir, xmldir,
                 logdir, event, codebase, prefix,
                 skip_rupgen):
    """
    Generates xml files in the xmldir for numsim simulations whose
    source files are in the srcdir using the validation event and
    codebase specified
    """
    tmpdir = tempfile.mkdtemp(prefix="bbp-")
    bbproot = "%s/run_bbp.py" % (install.A_COMP_DIR)
    bfn = os.path.join(xmldir, BATCH_SIM_FILE)
    batchfile = open(bfn, 'w')
    for sim in range(0, numsim):
        srcfile = os.path.join(srcdir, "%s-%04d.src" % (prefix, sim))
        ofn = os.path.join(tmpdir, "bbp.optfile")
        optfile = open(ofn, 'w')
        optfile.write('y\n') # Validation
        optfile.write('%s\n' % (event)) # Validation event
        optfile.write('%s\n' % (codebase)) # Codebase to use
        if codebase != "exsim" and codebase != "csm":
            if skip_rupgen:
                optfile.write('n\n') # Skip rupture generator
            else:
                optfile.write('y\n') # Run rupture generator
        if not skip_rupgen:
            optfile.write('y\n') # Provide custom source file
            optfile.write('2\n') # Enter path to source file
            optfile.write('%s\n' % (srcfile)) # Source file
        optfile.write('1\n') # All validation stations
        if codebase == "exsim":
            # Don't specify custom ExSIM template file
            optfile.write('n\n')
        if (codebase != "exsim" and
            codebase != "csm" and
            codebase != "irikura"):
            # Skip site response
            optfile.write('n\n')
        optfile.write('y\n') # Plot velocity seismograms
        optfile.write('y\n') # Plot acceleration seismograms
        optfile.write('y\n') # Generate GMPE comparison plot
        optfile.write('1\n') # Run GP_GOF
        optfile.flush()
        optfile.close()
        # Run BBP and generate the xml file
        bband_utils.runprog("export BBP_DATA_DIR=%s; %s -o %s -s %d -g" %
                            (tmpdir, bbproot, ofn, sim+1))
        # Copy the xml file
        srcxml = os.path.join(tmpdir, "xml", "%d.xml" % (sim+1))
        dstxml = os.path.join(xmldir, "%s-%04d.xml" % (prefix, sim))
        shutil.copy2(srcxml, dstxml)
        # Add entry to the batch file
        bbp_sim = 10000000 + sim
        logbase = os.path.join(logdir, str(bbp_sim))
        logfile = os.path.join(logbase, "%d_%s.log" %
                               (bbp_sim, prefix))
        # Make sure logdir exists
        os.makedirs(logbase)
        batchfile.write("%s -x %s -s %d -l %s\n" %
                        (bbproot, dstxml, bbp_sim, logfile))
    # Close batch file
    batchfile.flush()
    batchfile.close()
    # Clean-up
    shutil.rmtree(tmpdir)

def write_pbs(install, numsim, simdir, xmldir, email, prefix):
    """
    Write the pbs script
    """
    # Calculate how many nodes we need
    nodes = int(math.ceil(1.0 * numsim / CORES_PER_NODE))
    # Some path names
    outfile = os.path.join(simdir, "%s.out" % (prefix))
    errfile = os.path.join(simdir, "%s.err" % (prefix))
    bfn = os.path.join(xmldir, BATCH_SIM_FILE)
    # Let's create the pbs file
    pbsfn = os.path.join(simdir, "%s.pbs" % (prefix))
    pbsfile = open(pbsfn, 'w')
    pbsfile.write("#!/bin/bash\n")
    pbsfile.write("\n")
    pbsfile.write("#PBS -l walltime=300:00:00,nodes=%d:ppn=%d\n" %
                  (nodes, CORES_PER_NODE))
    pbsfile.write("#PBS -V\n")
    pbsfile.write("#PBS -m abe -M %s\n" % (email))
    pbsfile.write("#PBS -e %s\n" % (errfile))
    pbsfile.write("#PBS -o %s\n" % (outfile))
    pbsfile.write("\n")
    pbsfile.write("BBP_DIR=%s\n" % (install.A_INSTALL_ROOT))
    pbsfile.write("PYTHONPATH=%s\n" % (install.A_COMP_DIR))
    pbsfile.write("BBP_DATA_DIR=/scratch/$PBS_JOBID/bbpruns\n")
    pbsfile.write("BBP_BASE_DIR=/scratch/$PBS_JOBID\n")
    pbsfile.write("HOME=%s\n" % (simdir))
    pbsfile.write("\n")
    pbsfile.write("mkdir -p $BBP_DATA_DIR\n")
    pbsfile.write("mkdir -p $HOME/Sims/indata\n")
    pbsfile.write("mkdir -p $HOME/Sims/logs\n")
    pbsfile.write("mkdir -p $HOME/Sims/outdata\n")
    pbsfile.write("mkdir -p $HOME/Sims/tmpdata\n")
    pbsfile.write("\n")
    pbsfile.write('echo "Jobs start"\n')
    pbsfile.write("date\n")
    pbsfile.write('echo "BBP_DATA_DIR = $BBP_DATA_DIR"\n')
    pbsfile.write("\n")
    pbsfile.write("cd $HOME\n")
    pbsfile.write("\n")
    pbsfile.write("python $BBP_DIR/utils/batch/run_parallel.py $BBP_DIR/utils/batch/setup_bbp_epicenter_env.sh %s $PBS_NODEFILE 1\n" %
                  (bfn))
    pbsfile.write("\n")
    pbsfile.write('echo "Processing end"\n')
    pbsfile.write("date\n")
    pbsfile.write("\n")
    for dir_to_copy in ['outdata', 'indata', 'logs', 'tmpdata']:
        pbsfile.write('python $BBP_DIR/utils/batch/command_parallel.py $BBP_DIR/utils/batch/setup_bbp_epicenter_env.sh "cp -frp $BBP_DATA_DIR/%s/* $HOME/Sims/%s/." $PBS_NODEFILE\n' %
                      (dir_to_copy, dir_to_copy))
    pbsfile.write('python $BBP_DIR/utils/batch/command_parallel.py $BBP_DIR/utils/batch/setup_bbp_epicenter_env.sh "rm -rf $BBP_BASE_DIR" $PBS_NODEFILE\n')
    pbsfile.write("\n")
    pbsfile.write('echo "Jobs end"\n')
    pbsfile.write("date\n")
    pbsfile.flush()
    pbsfile.close()

    # All done!
    print
    print "Validation run is set up on: %s" % (simdir)
    print
    print "To start the validation run, just type: "
    print "$ qsub %s" % (pbsfn)
    print

def main():
    """
    Parse command line options and create the needed files/directories
    """
    # Detect BBP installation
    bbp_install = InstallCfg.getInstance()

    prog_base = os.path.basename(sys.argv[0])
    usage = "usage: %s [options]" % (prog_base)
    parser = optparse.OptionParser(usage)
    parser.add_option("-c", "--codebase", type="string", action="store",
                      dest="codebase",
                      help="Codebase for the simulation: %s" %
                      (CODEBASES))
    parser.add_option("-e", "--event", type="string", action="store",
                      dest="event",
                      help="Validation event (should be configured in BBP)")
    parser.add_option("-d", "--dir", type="string", action="store",
                      dest="simdir",
                      help="Simulation directory")
    parser.add_option("--skip-rupgen", action="store_true", dest="skiprupgen",
                      help="Skip the rupture generator, run only 1 simulation")
    parser.add_option("--hypo-rand", action="store_true", dest="hyporand",
                      help="Enables hypocenter randomization")
    parser.add_option("--no-hypo-rand", action="store_false", dest="hyporand",
                      help="Disables hypocenter randomization")
    parser.add_option("-n", "--num-simulations", type="int", action="store",
                      dest="numsim", help="Number of simulations to run")
    parser.add_option("--email", type="string", action="store",
                      dest="email", help="Email for job notifications")
    (options, args) = parser.parse_args()

    # Validate codebase to use
    codebase = options.codebase
    if codebase is None:
        print "Please specify a codebase!"
        sys.exit(1)
    codebase = codebase.lower()
    if codebase not in CODEBASES:
        print "Codebase needs to be one of: %s" % (CODEBASES)

    # Check for event
    event = options.event
    if event is None:
        print "Please provide a validation event!"
        sys.exit(1)
    event_names = validation_cfg.VE_EVENTS.get_all_names()
    events = [v_event.lower() for v_event in event_names]
    if event.lower() not in events:
        print ("Event %s does not appear to be properly configured on BBP" %
               (event))
        print ("Available options are: %s" % (event_names))
        print "Please provide another event or check your BBP installation."
        sys.exit(1)
    val_obj = validation_cfg.VE_EVENTS.get_event_by_print_name(event)

    # Check if we want to run the rupture generator
    skip_rupgen = options.skiprupgen

    # Check for hypocenter randomization
    if options.hyporand is None:
        print "Please specify --hypo-rand or --no-hypo-rand!"
        sys.exit(1)

    if options.hyporand:
        hypo_rand = True
    else:
        hypo_rand = False

    if not skip_rupgen:
        # Get source file
        try:
            source_file = val_obj.get_input(codebase, "source").strip()
        except KeyError:
            print ("Unable to get source file for event %s, codebase %s!" %
                   (event, codebase))
            sys.exit(1)
        if not source_file:
            print ("Source file for event %s, codebase %s not specified!" %
                   (event, codebase))
            sys.exit(1)
    else:
        # No need to get the source file, we start from the srf
        source_file = None
        try:
            srf_file = val_obj.get_input(codebase, "srf").strip()
        except KeyError:
            print ("Event %s does not have a srf file for codebase %s!" %
                   (event, codebase))
            sys.exit(1)
        if not srf_file:
            print ("Event %s does not have a srf file for codebase %s!" %
                   (event, codebase))
            sys.exit(1)
        # Force number of simulations to 1
        options.numsim = 1

    # Check for the simulation directory
    simdir = options.simdir
    if simdir is None:
        print "Please provide a simulation directory!"
        sys.exit(1)
    simdir = os.path.abspath(simdir)
    if os.path.exists(simdir):
        print "Simulation directory exists: %s" % (simdir)
        opt = raw_input("Do you want to delete its contents (y/n)? ")
        if opt.lower() != "y":
            print "Please provide another simulation directory!"
            sys.exit(1)
        opt = raw_input("ARE YOU SURE (y/n)? ")
        if opt.lower() != "y":
            print "Please provide another simulation directory!"
            sys.exit(1)
        # Delete existing directory (we already asked the user twice!!!)
        shutil.rmtree(simdir)

    # Pick up number of simulations to run
    numsim = options.numsim
    if numsim < 1 or numsim > MAX_SIMULATIONS:
        print ("Number of simulations should be between 1 and %d" %
               (MAX_SIMULATIONS))
        sys.exit(1)

    # Check for e-mail address
    email = options.email
    if email is None:
        print "Please provide an e-mail address for job notifications"
        sys.exit(1)

    # Make sure user has configured the setup_bbp_epicenter_env.sh script
    setup_bbp_env = os.path.join(bbp_install.A_INSTALL_ROOT,
                                 "utils/batch/setup_bbp_epicenter_env.sh")
    if not os.path.exists(setup_bbp_env):
        print ("Cannot find setup_bbp_epicenter_env.sh script!")
        print ("Expected at: %s" % (setup_bbp_env))
        sys.exit(1)
    # Create simulation directories
    prefix = "%s-%s" % (event.lower(), codebase.lower())
    # Make sure we remove spaces from prefix (e.g. for the "Loma Prieta" event)
    prefix = prefix.replace(" ", '')
    os.makedirs(simdir)
    indir = os.path.join(simdir, "Sims", "indata")
    outdir = os.path.join(simdir, "Sims", "outdata")
    tmpdir = os.path.join(simdir, "Sims", "tmpdata")
    logsdir = os.path.join(simdir, "Sims", "logs")
    xmldir = os.path.join(simdir, "Xml")
    srcdir = os.path.join(simdir, "Src")
    for mdir in [indir, outdir, tmpdir, logsdir, xmldir, srcdir]:
        os.makedirs(mdir)
    # Generate source files if needed
    if source_file is not None:
        generate_src_files(numsim, source_file, srcdir, prefix, hypo_rand)
    # Generate xml files
    generate_xml(bbp_install, numsim, srcdir, xmldir,
                 logsdir, event, codebase, prefix,
                 skip_rupgen)
    # Write pbs file
    write_pbs(bbp_install, numsim, simdir, xmldir, email, prefix)

if __name__ == "__main__":
    main()


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardUseCompatPadding="true"
    app:cardPreventCornerOverlap="true">
    <TextView android:id="@+id/sample_text_view"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:maxLines="1"
              style="?attr/spinnerDropDownItemStyle"/>
</android.support.v7.widget.CardView>


text:
r"""
This code was generated by
\ / _    _  _|   _  _
 | (_)\/(_)(_|\/| |(/_  v1.0.0
      /       /
"""

from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.autopilot.v1.assistant.field_type.field_value import FieldValueList

class FieldTypeList(ListResource):
    """ PLEASE NOTE that this class contains preview products that are subject
    to change. Use them with caution. If you currently do not have developer
    preview access, please contact help@twilio.com. """

    def __init__(self, version, assistant_sid):
        """
        Initialize the FieldTypeList

        :param Version version: Version that contains the resource
        :param assistant_sid: The SID of the Assistant that is the parent of the resource

        :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeList
        """
        super(FieldTypeList, self).__init__(version)

        # Path Solution
        self._solution = {'assistant_sid': assistant_sid, }
        self._uri = '/Assistants/{assistant_sid}/FieldTypes'.format(**self._solution)

    def stream(self, limit=None, page_size=None):
        """
        Streams FieldTypeInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param int limit: Upper limit for the number of records to return. stream()
                          guarantees to never return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, stream() will attempt to read the
                              limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance]
        """
        limits = self._version.read_limits(limit, page_size)

        page = self.page(page_size=limits['page_size'], )

        return self._version.stream(page, limits['limit'])

    def list(self, limit=None, page_size=None):
        """
        Lists FieldTypeInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param int limit: Upper limit for the number of records to return. list() guarantees
                          never to return more than limit.  Default is no limit
        :param int page_size: Number of records to fetch per request, when not set will use
                              the default value of 50 records.  If no page_size is defined
                              but a limit is defined, list() will attempt to read the limit
                              with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        :rtype: list[twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance]
        """
        return list(self.stream(limit=limit, page_size=page_size, ))

    def page(self, page_token=values.unset, page_number=values.unset,
             page_size=values.unset):
        """
        Retrieve a single page of FieldTypeInstance records from the API.
        Request is executed immediately

        :param str page_token: PageToken provided by the API
        :param int page_number: Page Number, this value is simply for client state
        :param int page_size: Number of records to return, defaults to 50

        :returns: Page of FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypePage
        """
        data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, })

        response = self._version.page(method='GET', uri=self._uri, params=data, )

        return FieldTypePage(self._version, response, self._solution)

    def get_page(self, target_url):
        """
        Retrieve a specific page of FieldTypeInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypePage
        """
        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return FieldTypePage(self._version, response, self._solution)

    def create(self, unique_name, friendly_name=values.unset):
        """
        Create the FieldTypeInstance

        :param unicode unique_name: An application-defined string that uniquely identifies the new resource
        :param unicode friendly_name: A string to describe the new resource

        :returns: The created FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        """
        data = values.of({'UniqueName': unique_name, 'FriendlyName': friendly_name, })

        payload = self._version.create(method='POST', uri=self._uri, data=data, )

        return FieldTypeInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], )

    def get(self, sid):
        """
        Constructs a FieldTypeContext

        :param sid: The unique string that identifies the resource

        :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext
        """
        return FieldTypeContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, )

    def __call__(self, sid):
        """
        Constructs a FieldTypeContext

        :param sid: The unique string that identifies the resource

        :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext
        """
        return FieldTypeContext(self._version, assistant_sid=self._solution['assistant_sid'], sid=sid, )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Autopilot.V1.FieldTypeList>'

class FieldTypePage(Page):
    """ PLEASE NOTE that this class contains preview products that are subject
    to change. Use them with caution. If you currently do not have developer
    preview access, please contact help@twilio.com. """

    def __init__(self, version, response, solution):
        """
        Initialize the FieldTypePage

        :param Version version: Version that contains the resource
        :param Response response: Response from the API
        :param assistant_sid: The SID of the Assistant that is the parent of the resource

        :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypePage
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypePage
        """
        super(FieldTypePage, self).__init__(version, response)

        # Path Solution
        self._solution = solution

    def get_instance(self, payload):
        """
        Build an instance of FieldTypeInstance

        :param dict payload: Payload response from the API

        :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        """
        return FieldTypeInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], )

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Autopilot.V1.FieldTypePage>'

class FieldTypeContext(InstanceContext):
    """ PLEASE NOTE that this class contains preview products that are subject
    to change. Use them with caution. If you currently do not have developer
    preview access, please contact help@twilio.com. """

    def __init__(self, version, assistant_sid, sid):
        """
        Initialize the FieldTypeContext

        :param Version version: Version that contains the resource
        :param assistant_sid: The SID of the Assistant that is the parent of the resource to fetch
        :param sid: The unique string that identifies the resource

        :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext
        """
        super(FieldTypeContext, self).__init__(version)

        # Path Solution
        self._solution = {'assistant_sid': assistant_sid, 'sid': sid, }
        self._uri = '/Assistants/{assistant_sid}/FieldTypes/{sid}'.format(**self._solution)

        # Dependents
        self._field_values = None

    def fetch(self):
        """
        Fetch the FieldTypeInstance

        :returns: The fetched FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        """
        payload = self._version.fetch(method='GET', uri=self._uri, )

        return FieldTypeInstance(
            self._version,
            payload,
            assistant_sid=self._solution['assistant_sid'],
            sid=self._solution['sid'],
        )

    def update(self, friendly_name=values.unset, unique_name=values.unset):
        """
        Update the FieldTypeInstance

        :param unicode friendly_name: A string to describe the resource
        :param unicode unique_name: An application-defined string that uniquely identifies the resource

        :returns: The updated FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        """
        data = values.of({'FriendlyName': friendly_name, 'UniqueName': unique_name, })

        payload = self._version.update(method='POST', uri=self._uri, data=data, )

        return FieldTypeInstance(
            self._version,
            payload,
            assistant_sid=self._solution['assistant_sid'],
            sid=self._solution['sid'],
        )

    def delete(self):
        """
        Deletes the FieldTypeInstance

        :returns: True if delete succeeds, False otherwise
        :rtype: bool
        """
        return self._version.delete(method='DELETE', uri=self._uri, )

    @property
    def field_values(self):
        """
        Access the field_values

        :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
        """
        if self._field_values is None:
            self._field_values = FieldValueList(
                self._version,
                assistant_sid=self._solution['assistant_sid'],
                field_type_sid=self._solution['sid'],
            )
        return self._field_values

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
        return '<Twilio.Autopilot.V1.FieldTypeContext {}>'.format(context)

class FieldTypeInstance(InstanceResource):
    """ PLEASE NOTE that this class contains preview products that are subject
    to change. Use them with caution. If you currently do not have developer
    preview access, please contact help@twilio.com. """

    def __init__(self, version, payload, assistant_sid, sid=None):
        """
        Initialize the FieldTypeInstance

        :returns: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        """
        super(FieldTypeInstance, self).__init__(version)

        # Marshaled Properties
        self._properties = {
            'account_sid': payload.get('account_sid'),
            'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
            'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
            'friendly_name': payload.get('friendly_name'),
            'links': payload.get('links'),
            'assistant_sid': payload.get('assistant_sid'),
            'sid': payload.get('sid'),
            'unique_name': payload.get('unique_name'),
            'url': payload.get('url'),
        }

        # Context
        self._context = None
        self._solution = {'assistant_sid': assistant_sid, 'sid': sid or self._properties['sid'], }

    @property
    def _proxy(self):
        """
        Generate an instance context for the instance, the context is capable of
        performing various actions.  All instance actions are proxied to the context

        :returns: FieldTypeContext for this FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeContext
        """
        if self._context is None:
            self._context = FieldTypeContext(
                self._version,
                assistant_sid=self._solution['assistant_sid'],
                sid=self._solution['sid'],
            )
        return self._context

    @property
    def account_sid(self):
        """
        :returns: The SID of the Account that created the resource
        :rtype: unicode
        """
        return self._properties['account_sid']

    @property
    def date_created(self):
        """
        :returns: The RFC 2822 date and time in GMT when the resource was created
        :rtype: datetime
        """
        return self._properties['date_created']

    @property
    def date_updated(self):
        """
        :returns: The RFC 2822 date and time in GMT when the resource was last updated
        :rtype: datetime
        """
        return self._properties['date_updated']

    @property
    def friendly_name(self):
        """
        :returns: The string that you assigned to describe the resource
        :rtype: unicode
        """
        return self._properties['friendly_name']

    @property
    def links(self):
        """
        :returns: A list of the URLs of related resources
        :rtype: unicode
        """
        return self._properties['links']

    @property
    def assistant_sid(self):
        """
        :returns: The SID of the Assistant that is the parent of the resource
        :rtype: unicode
        """
        return self._properties['assistant_sid']

    @property
    def sid(self):
        """
        :returns: The unique string that identifies the resource
        :rtype: unicode
        """
        return self._properties['sid']

    @property
    def unique_name(self):
        """
        :returns: An application-defined string that uniquely identifies the resource
        :rtype: unicode
        """
        return self._properties['unique_name']

    @property
    def url(self):
        """
        :returns: The absolute URL of the FieldType resource
        :rtype: unicode
        """
        return self._properties['url']

    def fetch(self):
        """
        Fetch the FieldTypeInstance

        :returns: The fetched FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        """
        return self._proxy.fetch()

    def update(self, friendly_name=values.unset, unique_name=values.unset):
        """
        Update the FieldTypeInstance

        :param unicode friendly_name: A string to describe the resource
        :param unicode unique_name: An application-defined string that uniquely identifies the resource

        :returns: The updated FieldTypeInstance
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.FieldTypeInstance
        """
        return self._proxy.update(friendly_name=friendly_name, unique_name=unique_name, )

    def delete(self):
        """
        Deletes the FieldTypeInstance

        :returns: True if delete succeeds, False otherwise
        :rtype: bool
        """
        return self._proxy.delete()

    @property
    def field_values(self):
        """
        Access the field_values

        :returns: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
        :rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueList
        """
        return self._proxy.field_values

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
        return '<Twilio.Autopilot.V1.FieldTypeInstance {}>'.format(context)


text:
@interface GRHttpUtils : NSObject

+ (NSString *)queryStringWithDictionary:(NSDictionary *)params;
+ (NSData *)formUrlencodedBodyWithDictionary:(NSDictionary *)params;
+ (NSData *)jsonBodyWithDictionary:(NSDictionary *)params;
+ (NSData *)multipartBodyWithDictionary:(NSDictionary *)params;

@end


text:
<!DOCTYPE html>
<html>
 <head>
  <meta name="package-mapping" content="my:com.addon.mypackage"/>
 </head>
 <body>
  <v-vertical-layout width="500px">
   <v-horizontal-layout>
    <v-label plain-text caption="FooBar"></v-label>
    <v-native-button _id=firstButton>Native click me</v-native-button>
	<v-native-button id = secondButton _id="localID">Another button</v-native-button>
	<v-native-button>Yet another button</v-native-button>
    <v-button plain-text width = "150px">Click me</v-button>
   </v-horizontal-layout>
   <v-text-field caption = "Text input"/>
   <v-text-area caption = "Text area" height="200px" width="300px"/>
  </v-vertical-layout>
 </body>
</html>


text:
import("cache_utils.syncedWithCache");
import("sqlbase.sqlcommon.*");
import("jsutils.*");
import("etherpad.log");

jimport("java.lang.System.out.println");
jimport("java.sql.Statement");
jimport("java.util.ArrayList");
jimport("java.sql.Types");

function _withCache(name, fn) {
  return syncedWithCache('sqlobj.'+name, fn);
}

function getIdColspec() {
  return ('INT NOT NULL '+autoIncrementClause()+' PRIMARY KEY');
}

function getLongtextColspec(extra) {
  var spec = getSqlBase().longTextType();
  if (extra) {
    spec = (spec + " " + extra);
  }
  return spec;
}

function getBoolColspec(extra) {
  var spec;
  if (isMysql()) {
    spec = 'TINYINT(1)';
  } else {
    spec = 'SMALLINT';
  }
  if (extra) {
    spec = (spec + " " + extra);
  }
  return spec;
}

function getDateColspec(extra) {
  var spec;
  if (isMysql()) {
    spec = 'DATETIME';
  } else {
    spec = 'TIMESTAMP';
  }
  if (extra) {
    spec = (spec + " " + extra);
  }
  return spec;
}

function _bq(x) { return btquote(x); }

/*
 * for debugging queries
 */
function _qdebug(q, c) {
  if (appjet.config.debugSQL == "true") {
    println(q);
    if (c) {
      println(JSON.stringify(c));
    }
  }
}

/** executeFn is either "execute" or "executeUpdate" "executeQuery" */
function _execute(stmnt, executeFn) {
  if (!executeFn) {
    executeFn = 'execute';
  }
  return withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt);
    return closing(pstmnt, function() {
      _qdebug(stmnt);
      return pstmnt[executeFn]();
    });
  });
}

function _executeUpdate(stmnt) {
  return _execute(stmnt, 'executeUpdate');
}

function _executeQuery(stmnt) {
  return _execute(stmnt, 'executeQuery');
}

/*
 * Not all SQL/JS types supported.
 */
function _getJsValFromResultSet(rs, type, colName) {
  var r;
  if (type == java.sql.Types.VARCHAR ||
      type == java.sql.Types.LONGVARCHAR ||
      type == java.sql.Types.CHAR) {
    r = String(rs.getString(colName));
  } else if (type == java.sql.Types.TIMESTAMP) {
    var t = rs.getTimestamp(colName);
    if (t) {
      r = new Date(t.getTime());
    } else {
      r = null;
    }
  } else if (type == java.sql.Types.BIGINT ||
             type == java.sql.Types.INTEGER ||
             type == java.sql.Types.SMALLINT ||
             type == java.sql.Types.TINYINT) {
    r = rs.getInt(colName);
  } else if (type == java.sql.Types.DECIMAL) {
    r = rs.getFloat(colName);
  } else if (type == java.sql.Types.BIT) {
    r = rs.getBoolean(colName);
  } else {
    throw Error("Cannot fetch sql type ID "+type+" (columnName = "+colName+")");
  }

  if (rs.wasNull()) {
    r = null;
  }
  return r;
}

function _getJsValFromResultSetFast(rs, typeId, colName) {
  var r;
  if (typeId == 1) {
    r = String(rs.getString(colName));
  } else if (typeId == 2) {
    var t = rs.getTimestamp(colName);
    if (t) {
      r = new Date(t.getTime());
    } else {
      r = null;
    }
  } else if (typeId == 3) {
    r = rs.getInt(colName);
  } else if (typeId == 4) {
    r = rs.getFloat(colName);
  } else if (typeId == 5) {
    r = rs.getBoolean(colName);
  } else {
    throw Error("Cannot fetch sql type ID "+type+" (columnName = "+colName+")");
  }

  if (rs.wasNull()) {
    r = null;
  }
  return r;
}

function _lookupColumnType(tableName, columnName) {
  return withConnection(function(conn) {
    var metadata = conn.getMetaData();
    var rs = metadata.getColumns(null, null, tableName, columnName);
    if (!rs) {
      throw Error("Table '"+tableName+"' does not appear to have colum '"+columnName+"'.");
    }
    var rsmd = rs.getMetaData();
    var colCount = rsmd.getColumnCount();
//    rs.first();
    rs.next();
    var type = rs.getInt("DATA_TYPE");
    return type;
  });
}

/* cached, on misses calls _lookuParameterType */
function _getParameterType(tableName, columnName) {
  var key = [tableName, columnName].join(".");
  return _withCache('column-types', function(cache) {
    if (!cache[key]) {
      cache[key] = _lookupColumnType(tableName, columnName);
    }
    return cache[key];
  });
}

/*
 * Not all SQL/JS types supported.
 */
function _setPreparedValues(tableName, pstmnt, keyList, obj, indexOffset) {
  if (!indexOffset) { indexOffset = 0; }

  for (var i = 1; i <= keyList.length; i++) {
    var k = keyList[i-1];
    var v = obj[k];
    var j = i + indexOffset;

    if (v === undefined) {
      throw Error("value is undefined for key "+k);
    }

    if (v === null) {
      var type = _getParameterType(tableName, k);
      pstmnt.setNull(j, type);
    } else if (typeof(v) == 'string') {
      pstmnt.setString(j, v);
    } else if (typeof(v) == 'number') {
      pstmnt.setInt(j, v);
    } else if (v instanceof Array) {
      for (var l=0; l<v.length; l++) {
        // only increment after the first value
        if (l > 0) {
          indexOffset = indexOffset + 1;
        }
        j = i + indexOffset;

        if (typeof(v[l]) == 'string') {
          pstmnt.setString(j, v[l]);
        } else if (typeof(v[l]) == 'number') {
          pstmnt.setInt(j, v[l]);
        } else if (v[l].valueOf && v[l].getDate && v[l].getHours) {
          pstmnt.setTimestamp(j, new java.sql.Timestamp(+v[l]));
        }
      }
    } else if (typeof(v) == 'boolean') {
      pstmnt.setBoolean(j, v);
    } else if (v.valueOf && v.getDate && v.getHours) {
      pstmnt.setTimestamp(j, new java.sql.Timestamp(+v));
    } else {
      throw Error("Cannot insert this type of javascript object: "+typeof(v)+" (key="+k+", value = "+v+")");
    }
  }
}

function _resultRowToJsObj(resultSet) {
  var resultObj = {};

  var metaData = resultSet.getMetaData();
  var colCount = metaData.getColumnCount();

  for (var i = 1; i <= colCount; i++) {
    var colName = metaData.getColumnLabel(i);
    var type = metaData.getColumnType(i);
    // this call is really slow at scale
    resultObj[colName] = _getJsValFromResultSet(resultSet, type, colName);
  }

  return resultObj;
}

function _resultRowToJsObjFast(resultSet, metaData, colCount, colNames, types) {
  var resultObj = {};
  for (var i = 1; i <= colCount; i++) {
    resultObj[colNames[i]] = _getJsValFromResultSetFast(resultSet, types[i], colNames[i]);
  }
  return resultObj;
}

/*
 * Inserts the object into the given table, and returns auto-incremented ID if any.
 */
function insert(tableName, obj) {
  var keyList = keys(obj);

  var stmnt = "INSERT INTO "+_bq(tableName)+" (";
  stmnt += keyList.map(function(k) { return _bq(k); }).join(', ');
  stmnt += ") VALUES (";
  stmnt += keyList.map(function(k) { return '?'; }).join(', ');
  stmnt += ")";

  return withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt, Statement.RETURN_GENERATED_KEYS);
    return closing(pstmnt, function() {
      _setPreparedValues(tableName, pstmnt, keyList, obj, 0);
      _qdebug(stmnt);
      pstmnt.executeUpdate();
      return _getGeneratedKeyFromStatement(pstmnt);
    });
  });
};

function _buildSelectWithConstraints(tableName, constraints) {
  var stmnt = "SELECT * FROM "+_bq(tableName)+" ";

  var constraintKeys = keys(constraints);
  if (constraintKeys.length > 0) {
    stmnt += "WHERE (";
    stmnt += constraintKeys.map(function(key) {
        return _makeConstraintString(key, constraints[key]);
      }).join(' AND ');
    stmnt += ')';
  }
  return stmnt;
}

/*
 * Selects a single object given the constraintMap.  If there are more
 * than 1 objects that match, it will return a single one of them
 * (unspecified which one).  If no objects match, returns null.
 *
 * constraints is a javascript object of column names to values.
 *  Currently only supports string equality of constraints.
 */
function selectSingle(tableName, constraints) {
  var keyList = keys(constraints);

  var stmnt = _buildSelectWithConstraints(tableName, constraints);

  if (isMysql()) {
    stmnt += ' LIMIT 1';
  }

  return withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt);
    return closing(pstmnt, function() {
      _setPreparedValues(tableName, pstmnt, keyList, _preparedValuesConstraints(constraints), 0);
      _qdebug(stmnt, constraints);
      var resultSet = pstmnt.executeQuery();
      return closing(resultSet, function() {
        if (!resultSet.next()) {
          return null;
        }
        return _resultRowToJsObj(resultSet);
      });
    });
  });
}

function _makeConstraintString(key, value) {
  if (typeof(value) != 'object' || ! (value instanceof Array)) {
    return '('+_bq(key)+' = ?)';
  } else {
    var comparator = value[0];
    if (comparator.toLowerCase() == 'between') {
      return '('+_bq(key)+' '+comparator+' ? and ?)';
    }  else {
      var questions = "?";
      if (value[1] instanceof Array) {
        questions = "(" + value[1].map(function(){return "?"}).join(",") + ")";
      }
      return '('+_bq(key)+' '+comparator+' '+ questions+ ')';
    }
  }
}

function _preparedValuesConstraints(constraints) {
  var c = {};
  eachProperty(constraints, function(k, v) {
    c[k] = (typeof(v) != 'object' || ! (v instanceof Array) ? v : v[1]);
  });
  return c;
}

function selectMulti(tableName, constraints, options) {
  if (!options) {
    options = {};
  }

  // if there's an empty IN constraint, return no results
  for (key in constraints) {
    if (constraints[key] instanceof Array &&
        constraints[key][0].toLowerCase() == "in" &&
        constraints[key][1].length == 0) {
          return [];
    }
  }

  var stmnt = _buildSelectWithConstraints(tableName, constraints);

  if (options.orderBy) {
    var orderEntries = [];
    options.orderBy.split(",").forEach(function(orderBy) {
      var asc = "ASC";
      if (orderBy.charAt(0) == '-') {
        orderBy = orderBy.substr(1);
        asc = "DESC";
      }
      orderEntries.push(_bq(orderBy)+" "+asc);
    });
    stmnt += " ORDER BY "+orderEntries.join(", ");
  }

  if (options.groupBy) {
    var groupEntries = [];
    options.groupBy.split(",").forEach(function(groupBy) {
      groupEntries.push(_bq(groupBy));
    });
    stmnt += " GROUP BY "+groupEntries.join(", ");
  }

  if (options.limit) {
    stmnt += " LIMIT "+options.limit;
  }

  var constraintKeys = keys(constraints);

  return withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt);
    return closing(pstmnt, function() {
      _setPreparedValues(
        tableName, pstmnt, constraintKeys,
        _preparedValuesConstraints(constraints), 0);

      _qdebug(stmnt, constraints);
      var resultSet = pstmnt.executeQuery();
      return closing(resultSet, function() {
        return _getResultsFromResultSet(resultSet);
      });
    });
  });
}

// a more efficient way of processing lots of result rows
function _getResultsFromResultSet(resultSet){
  var resultArray = [];

  /*
  old slow way:
  while(resultSet.next()) {
    resultArray.push(_resultRowToJsObj(resultSet));
  }
  return resultArray;*/

  if (resultSet.next()) {
    var metaData = resultSet.getMetaData();
    var colCount = metaData.getColumnCount();
    var colNames = [];
    var types = [];

    for (var i = 1; i <= colCount; i++) {
      colNames[i] = metaData.getColumnLabel(i);
      switch (metaData.getColumnType(i)) {
        case java.sql.Types.VARCHAR:
          types[i]=1; break;
        case java.sql.Types.LONGVARCHAR:
          types[i]=1; break;
        case java.sql.Types.CHAR:
          types[i]=1; break;
        case java.sql.Types.TIMESTAMP:
          types[i]=2; break;
        case java.sql.Types.BIGINT:
          types[i]=3; break;
        case java.sql.Types.INTEGER:
          types[i]=3; break;
        case java.sql.Types.SMALLINT:
          types[i]=3; break;
        case java.sql.Types.TINYINT:
          types[i]=3; break;
        case java.sql.Types.DECIMAL:
          types[i]=4; break;
        case java.sql.Types.BIT:
          types[i]=5; break;
      }
    }
    do {
      resultArray.push(_resultRowToJsObjFast(resultSet, metaData, colCount, colNames, types));
    } while (resultSet.next());
  }
  return resultArray;
}

function _getGeneratedKeyFromStatement(pstmnt) {
  var rs = pstmnt.getGeneratedKeys();
  if (rs != null) {
    return closing(rs, function() {
      if (rs.next()) {
        return rs.getInt(1);
      }else {
        // This returns null instead of undefined because the withConnection function returns
        // the string "undefined".
        // TODO: Investigate why withConnection returns the string "undefined"
        // when the passed function block returns undefined
        return null;
      }
    });
  }
}

function _setStatementParams(pstmnt, params) {
  for (var i = 0; i < params.length; i++) {
    var v = params[i];

    if (v === undefined) {
      throw Error("value is undefined for key "+i);
    }

    if (typeof(v) == 'object' && v.isnull) {
      pstmnt.setNull(i+1, v.type);
    } else if (typeof(v) == 'string') {
      pstmnt.setString(i+1, v);
    } else if (typeof(v) == 'number') {
      pstmnt.setInt(i+1, v);
    } else if (typeof(v) == 'boolean') {
      pstmnt.setBoolean(i+1, v);
    } else if (v.valueOf && v.getDate && v.getHours) {
      pstmnt.setTimestamp(i+1, new java.sql.Timestamp(+v));
    } else {
      throw Error("Cannot insert this type of javascript object: "+typeof(v)+" (key="+i+", value = "+v+")");
    }
  }
}

function executeRawInsert(stmnt, params) {
  return withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt, Statement.RETURN_GENERATED_KEYS);
    return closing(pstmnt, function() {
      _setStatementParams(pstmnt, params);
      _qdebug(stmnt, params);
      pstmnt.executeUpdate();
      return _getGeneratedKeyFromStatement(pstmnt);
    });
  });
}

function executeRaw(stmnt, params, isUpdate) {
  return withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt);
    return closing(pstmnt, function() {
      _setStatementParams(pstmnt, params);
      _qdebug(stmnt, params);
      if (isUpdate) {
        return pstmnt.executeUpdate();
      }
      var resultSet = pstmnt.executeQuery();

      return closing(resultSet, function() {
        return _getResultsFromResultSet(resultSet);
      });
    });
  });
}

/* returns number of rows updated */
function update(tableName, constraints, obj) {
  var objKeys = keys(obj);
  var constraintKeys = keys(constraints);

  var stmnt = "UPDATE "+_bq(tableName)+" SET ";
  stmnt += objKeys.map(function(k) { return ''+_bq(k)+' = ?'; }).join(', ');
  stmnt += " WHERE (";
  stmnt += constraintKeys.map(function(k) { return '('+_bq(k)+' = ?)'; }).join(' AND ');
  stmnt += ')';

  return withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt);
    return closing(pstmnt, function() {
      _setPreparedValues(tableName, pstmnt, objKeys, obj, 0);
      _setPreparedValues(tableName, pstmnt, constraintKeys, constraints, objKeys.length);
      _qdebug(stmnt, constraints);
      return pstmnt.executeUpdate();
    });
  });
}

/* returns number of rows updated */
function insertOrUpdate(tableName, obj) {
  var keyList = keys(obj);

  var stmnt = "INSERT INTO "+_bq(tableName)+" (";
  stmnt += keyList.map(function(k) { return _bq(k); }).join(', ');
  stmnt += ") VALUES (";
  stmnt += keyList.map(function(k) { return '?'; }).join(', ');
  stmnt += ") ON DUPLICATE KEY UPDATE ";
  stmnt += keyList.map(function(k) { return ''+_bq(k)+' = ?'; }).join(', ');

  return withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt, Statement.RETURN_GENERATED_KEYS);
    return closing(pstmnt, function() {
      _setPreparedValues(tableName, pstmnt, keyList.concat(keyList), obj, 0);
      _qdebug(stmnt);
      pstmnt.executeUpdate();
      return _getGeneratedKeyFromStatement(pstmnt);
    });
  });
}

function updateSingle(tableName, constraints, obj) {
  var count = update(tableName, constraints, obj);
  if (count != 1) {
    throw Error("save count != 1.  instead, count = "+count);
  }
}

function deleteRows(tableName, constraints) {
  var constraintKeys = keys(constraints);
  var stmnt = "DELETE FROM "+_bq(tableName)+" WHERE (";
  stmnt += constraintKeys.map(function(key) {
    return _makeConstraintString(key, constraints[key]);
  }).join(' AND ');
  stmnt += ')';
  withConnection(function(conn) {
    var pstmnt = conn.prepareStatement(stmnt);
    closing(pstmnt, function() {
      _setPreparedValues(tableName, pstmnt, constraintKeys, _preparedValuesConstraints(constraints));
      _qdebug(stmnt);
      pstmnt.executeUpdate();
    });
  })
}

//----------------------------------------------------------------
// table management
//----------------------------------------------------------------

/*
 * Create a SQL table, specifying column names and types with a
 * javascript object.
 */
function createTable(tableName, colspec, indices) {
  if (doesTableExist(tableName)) {
    return;
  }

  var stmnt = "CREATE TABLE "+_bq(tableName)+ " (";
  stmnt += keys(colspec).map(function(k) { return (_bq(k) + ' ' + colspec[k]); }).join(', ');
  if (indices) {
    stmnt += ', ' + keys(indices).map(function(k) { return 'INDEX (' + _bq(k) + ')'; }).join(', ');
  }
  stmnt += ')'+createTableOptions();
  _execute(stmnt);
}

function dropTable(tableName) {
  _execute("DROP TABLE "+_bq(tableName));
}

function dropAndCreateTable(tableName, colspec, indices) {
  if (doesTableExist(tableName)) {
    dropTable(tableName);
  }

  return createTable(tableName, colspec, indices);
}

function renameTable(oldName, newName) {
  _executeUpdate("RENAME TABLE "+_bq(oldName)+" TO "+_bq(newName));
}

function modifyColumn(tableName, columnName, newSpec) {
  _executeUpdate("ALTER TABLE "+_bq(tableName)+" MODIFY "+_bq(columnName)+" "+newSpec);
}

function alterColumn(tableName, columnName, alteration) {
  var q = "ALTER TABLE "+_bq(tableName)+" ALTER COLUMN "+_bq(columnName)+" "+alteration;
  _executeUpdate(q);
}

function changeColumn(tableName, columnName, newSpec) {
  var q = ("ALTER TABLE "+_bq(tableName)+" CHANGE COLUMN "+_bq(columnName)
           +" "+newSpec);
  _executeUpdate(q);
}

function addColumns(tableName, colspec) {
  inTransaction(function(conn) {
    eachProperty(colspec, function(name, definition) {
      var stmnt = "ALTER TABLE "+_bq(tableName)+" ADD COLUMN "+_bq(name)+" "+definition;
      _executeUpdate(stmnt);
    });
  });
}

function dropColumn(tableName, columnName) {
  var stmnt = "ALTER TABLE "+_bq(tableName)+" DROP COLUMN "+_bq(columnName);
  _executeUpdate(stmnt);
}

function listTables() {
  return withConnection(function(conn) {
    var metadata = conn.getMetaData();
    var resultSet = metadata.getTables(null, null, null, null);
    var resultArray = [];

    return closing(resultSet, function() {
      while (resultSet.next()) {
        resultArray.push(resultSet.getString("TABLE_NAME"));
      }
      return resultArray;
    });
  });
}

function setTableEngine(tableName, engineName) {
  var stmnt = "ALTER TABLE "+_bq(tableName)+" ENGINE="+_bq(engineName);
  _executeUpdate(stmnt);
}

function getTableEngine(tableName) {
  if (!isMysql()) {
    throw Error("getTableEngine() only supported by MySQL database type.");
  }

  var tableEngines = {};

  withConnection(function(conn) {
    var stmnt = "show table status";
    var pstmnt = conn.prepareStatement(stmnt);
    closing(pstmnt, function() {
      _qdebug(stmnt);
      var resultSet = pstmnt.executeQuery();
      closing(resultSet, function() {
        while (resultSet.next()) {
          var n = resultSet.getString("Name");
          var eng = resultSet.getString("Engine");
          tableEngines[n] = eng;
        }
      });
    });
  });

  return tableEngines[tableName];
}

function createIndex(tableName, columns, type) {
  var indexName = "idx_"+(columns.join("_"));
  var stmnt = "CREATE "+(type||"")+" INDEX "+_bq(indexName)+" on "+_bq(tableName)+" (";
  stmnt += columns.map(_bq).join(", ");
  stmnt += ")";
  _executeUpdate(stmnt);
}

function dropIndex(tableName, indexName) {
  var stmnt = "DROP INDEX "+_bq(indexName)+" ON "+_bq(tableName);
  _executeUpdate(stmnt);
}


text:
OpenLayers version {{versionNumber}} - Cesium

        <geo-map-config
                config-value="config"
                template-path="../configmap.html"
                pre-config="preConfigInit(config)">
        </geo-map-config>


text:
from __future__ import absolute_import, division, print_function, with_statement
import tornado.escape

from tornado.escape import utf8, xhtml_escape, xhtml_unescape, url_escape, url_unescape, to_unicode, json_decode, json_encode, squeeze, recursive_unicode
from tornado.util import u, unicode_type
from tornado.test.util import unittest

linkify_tests = [
    # (input, linkify_kwargs, expected_output)

    ("hello http://world.com/!", {},
     u('hello http://world.com/!')),

    ("hello http://world.com/with?param=true&stuff=yes", {},
     u('hello http://world.com/with?param=true&stuff=yes')),

    # an opened paren followed by many chars killed Gruber's regex
    ("http://url.com/w(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", {},
     u('http://url.com/w(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')),

    # as did too many dots at the end
    ("http://url.com/withmany.......................................", {},
     u('http://url.com/withmany.......................................')),

    ("http://url.com/withmany((((((((((((((((((((((((((((((((((a)", {},
     u('http://url.com/withmany((((((((((((((((((((((((((((((((((a)')),

    # some examples from http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
    # plus a fex extras (such as multiple parentheses).
    ("http://foo.com/blah_blah", {},
     u('http://foo.com/blah_blah')),

    ("http://foo.com/blah_blah/", {},
     u('http://foo.com/blah_blah/')),

    ("(Something like http://foo.com/blah_blah)", {},
     u('(Something like http://foo.com/blah_blah)')),

    ("http://foo.com/blah_blah_(wikipedia)", {},
     u('http://foo.com/blah_blah_(wikipedia)')),

    ("http://foo.com/blah_(blah)_(wikipedia)_blah", {},
     u('http://foo.com/blah_(blah)_(wikipedia)_blah')),

    ("(Something like http://foo.com/blah_blah_(wikipedia))", {},
     u('(Something like http://foo.com/blah_blah_(wikipedia))')),

    ("http://foo.com/blah_blah.", {},
     u('http://foo.com/blah_blah.')),

    ("http://foo.com/blah_blah/.", {},
     u('http://foo.com/blah_blah/.')),

    ("<http://foo.com/blah_blah>", {},
     u('<http://foo.com/blah_blah>')),

    ("<http://foo.com/blah_blah/>", {},
     u('<http://foo.com/blah_blah/>')),

    ("http://foo.com/blah_blah,", {},
     u('http://foo.com/blah_blah,')),

    ("http://www.example.com/wpstyle/?p=364.", {},
     u('http://www.example.com/wpstyle/?p=364.')),

    ("rdar://1234",
     {"permitted_protocols": ["http", "rdar"]},
     u('rdar://1234')),

    ("rdar:/1234",
     {"permitted_protocols": ["rdar"]},
     u('rdar:/1234')),

    ("http://userid:password@example.com:8080", {},
     u('http://userid:password@example.com:8080')),

    ("http://userid@example.com", {},
     u('http://userid@example.com')),

    ("http://userid@example.com:8080", {},
     u('http://userid@example.com:8080')),

    ("http://userid:password@example.com", {},
     u('http://userid:password@example.com')),

    ("message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e",
     {"permitted_protocols": ["http", "message"]},
     u('message://%3c330e7f8409726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e')),

    (u("http://\u27a1.ws/\u4a39"), {},
     u('http://\u27a1.ws/\u4a39')),

    ("<tag>http://example.com</tag>", {},
     u('<tag>http://example.com</tag>')),

    ("Just a www.example.com link.", {},
     u('Just a www.example.com link.')),

    ("Just a www.example.com link.",
     {"require_protocol": True},
     u('Just a www.example.com link.')),

    ("A http://reallylong.com/link/that/exceedsthelenglimit.html",
     {"require_protocol": True, "shorten": True},
     u('A http://reallylong.com/link...')),

    ("A http://reallylongdomainnamethatwillbetoolong.com/hi!",
     {"shorten": True},
     u('A http://reallylongdomainnametha...!')),

    ("A file:///passwords.txt and http://web.com link", {},
     u('A file:///passwords.txt and http://web.com link')),

    ("A file:///passwords.txt and http://web.com link",
     {"permitted_protocols": ["file"]},
     u('A file:///passwords.txt and http://web.com link')),

    ("www.external-link.com",
     {"extra_params": 'rel="nofollow" class="external"'},
     u('www.external-link.com')),

    ("www.external-link.com and www.internal-link.com/blogs extra",
     {"extra_params": lambda href: 'class="internal"' if href.startswith("http://www.internal-link.com") else 'rel="nofollow" class="external"'},
     u('www.external-link.com and www.internal-link.com/blogs extra')),

    ("www.external-link.com",
     {"extra_params": lambda href: '    rel="nofollow" class="external"  '},
     u('www.external-link.com')),
]

class EscapeTestCase(unittest.TestCase):
    def test_linkify(self):
        for text, kwargs, html in linkify_tests:
            linked = tornado.escape.linkify(text, **kwargs)
            self.assertEqual(linked, html)

    def test_xhtml_escape(self):
        tests = [
            ("<foo>", "<foo>"),
            (u("<foo>"), u("<foo>")),
            (b"<foo>", b"<foo>"),

            ("<>&\"'", "<>&"'"),
            ("&", "&amp;"),

            (u("<\u00e9>"), u("<\u00e9>")),
            (b"<\xc3\xa9>", b"<\xc3\xa9>"),
        ]
        for unescaped, escaped in tests:
            self.assertEqual(utf8(xhtml_escape(unescaped)), utf8(escaped))
            self.assertEqual(utf8(unescaped), utf8(xhtml_unescape(escaped)))

    def test_url_escape_unicode(self):
        tests = [
            # byte strings are passed through as-is
            (u('\u00e9').encode('utf8'), '%C3%A9'),
            (u('\u00e9').encode('latin1'), '%E9'),

            # unicode strings become utf8
            (u('\u00e9'), '%C3%A9'),
        ]
        for unescaped, escaped in tests:
            self.assertEqual(url_escape(unescaped), escaped)

    def test_url_unescape_unicode(self):
        tests = [
            ('%C3%A9', u('\u00e9'), 'utf8'),
            ('%C3%A9', u('\u00c3\u00a9'), 'latin1'),
            ('%C3%A9', utf8(u('\u00e9')), None),
        ]
        for escaped, unescaped, encoding in tests:
            # input strings to url_unescape should only contain ascii
            # characters, but make sure the function accepts both byte
            # and unicode strings.
            self.assertEqual(url_unescape(to_unicode(escaped), encoding), unescaped)
            self.assertEqual(url_unescape(utf8(escaped), encoding), unescaped)

    def test_url_escape_quote_plus(self):
        unescaped = '+ #%'
        plus_escaped = '%2B+%23%25'
        escaped = '%2B%20%23%25'
        self.assertEqual(url_escape(unescaped), plus_escaped)
        self.assertEqual(url_escape(unescaped, plus=False), escaped)
        self.assertEqual(url_unescape(plus_escaped), unescaped)
        self.assertEqual(url_unescape(escaped, plus=False), unescaped)
        self.assertEqual(url_unescape(plus_escaped, encoding=None),
                         utf8(unescaped))
        self.assertEqual(url_unescape(escaped, encoding=None, plus=False),
                         utf8(unescaped))

    def test_escape_return_types(self):
        # On python2 the escape methods should generally return the same
        # type as their argument
        self.assertEqual(type(xhtml_escape("foo")), str)
        self.assertEqual(type(xhtml_escape(u("foo"))), unicode_type)

    def test_json_decode(self):
        # json_decode accepts both bytes and unicode, but strings it returns
        # are always unicode.
        self.assertEqual(json_decode(b'"foo"'), u("foo"))
        self.assertEqual(json_decode(u('"foo"')), u("foo"))

        # Non-ascii bytes are interpreted as utf8
        self.assertEqual(json_decode(utf8(u('"\u00e9"'))), u("\u00e9"))

    def test_json_encode(self):
        # json deals with strings, not bytes.  On python 2 byte strings will
        # convert automatically if they are utf8; on python 3 byte strings
        # are not allowed.
        self.assertEqual(json_decode(json_encode(u("\u00e9"))), u("\u00e9"))
        if bytes is str:
            self.assertEqual(json_decode(json_encode(utf8(u("\u00e9")))), u("\u00e9"))
            self.assertRaises(UnicodeDecodeError, json_encode, b"\xe9")

    def test_squeeze(self):
        self.assertEqual(squeeze(u('sequences     of    whitespace   chars')), u('sequences of whitespace chars'))

    def test_recursive_unicode(self):
        tests = {
            'dict': {b"foo": b"bar"},
            'list': [b"foo", b"bar"],
            'tuple': (b"foo", b"bar"),
            'bytes': b"foo"
        }
        self.assertEqual(recursive_unicode(tests['dict']), {u("foo"): u("bar")})
        self.assertEqual(recursive_unicode(tests['list']), [u("foo"), u("bar")])
        self.assertEqual(recursive_unicode(tests['tuple']), (u("foo"), u("bar")))
        self.assertEqual(recursive_unicode(tests['bytes']), u("foo"))


text:
describe RuboCop::Cop::Lint::UselessElseWithoutRescue do
  subject(:cop) { described_class.new }

  before do
    inspect_source(cop, source)
  end

  context 'with `else` without `rescue`' do
    let(:source) do
      <<-RUBY.strip_indent
        begin
          do_something
        else
          handle_unknown_errors
        end
      RUBY
    end

    it 'registers an offense' do
      expect(cop.offenses.size).to eq(1)
      expect(cop.offenses.first.message)
        .to eq('`else` without `rescue` is useless.')
      expect(cop.highlights).to eq(['else'])
    end
  end

  context 'with `else` with `rescue`' do
    let(:source) do
      <<-RUBY.strip_indent
        begin
          do_something
        rescue ArgumentError
          handle_argument_error
        else
          handle_unknown_errors
        end
      RUBY
    end

    it 'accepts' do
      expect_no_offenses(<<-RUBY.strip_indent)
        begin
          do_something
        rescue ArgumentError
          handle_argument_error
        else
          handle_unknown_errors
        end
      RUBY
    end
  end
end


text:
package main_test

import (
	"bytes"
	"testing"

	"github.com/neofight/govps"
	"github.com/neofight/govps/io"
)

func TestParserInsufficientArguments(t *testing.T) {

	buffer := &bytes.Buffer{}
	io.StdOut = buffer

	_, ok := main.Parse([]string{"govps", "one"})

	if ok {
		t.Error("Expected command with one argument to be rejected but was accepted")
	}

	if buffer.String() != main.Usage+"\n" {
		t.Error("Expected command help to be printed but it was not")
	}
}

func TestParserExcessiveArguments(t *testing.T) {

	buffer := &bytes.Buffer{}
	io.StdOut = buffer

	_, ok := main.Parse([]string{"govps", "one", "two", "three"})

	if ok {
		t.Error("Expected command with three arguments to be rejected but was accepted")
	}

	if buffer.String() != main.Usage+"\n" {
		t.Error("Expected command help to be printed but it was not")
	}

	if buffer.String() != main.Usage+"\n" {
		t.Error("Expected command help to be printed but it was not")
	}
}

var illegalCharacters = []string{";", "'", "\"", "\r", "\n", "`"}

func TestParserIllegalCharactersInHost(t *testing.T) {

	buffer := &bytes.Buffer{}
	io.StdOut = buffer

	for _, character := range illegalCharacters {

		_, ok := main.Parse([]string{"govps", character, "test.com"})

		if ok {
			t.Errorf("Expected host %v to be rejected but was accepted", character)

			if buffer.String() != main.Usage+"\n" {
				t.Error("Expected command help to be printed but it was not")
			}

			buffer.Reset()
		}
	}
}

func TestParserIllegalCharactersInDomain(t *testing.T) {

	buffer := &bytes.Buffer{}
	io.StdOut = buffer

	for _, character := range illegalCharacters {

		_, ok := main.Parse([]string{"govps", "test.com", character})

		if ok {
			t.Errorf("Expected domain %v to be rejected but was accepted", character)
		}

		if buffer.String() != main.Usage+"\n" {
			t.Error("Expected command help to be printed but it was not")
		}

		buffer.Reset()
	}
}

func TestParserHappyPath(t *testing.T) {

	buffer := &bytes.Buffer{}
	io.StdOut = buffer

	result, ok := main.Parse([]string{"govps", "host.com", "domain.com"})

	if !ok {
		t.Fatal("Expected commmand to be parsed but it was not")
	}

	if result.Host != "host.com" {
		t.Errorf("Expected host host.com but saw %v", result.Host)
	}

	if result.Domain != "domain.com" {
		t.Errorf("Expected domain domain.com but saw %v", result.Domain)
	}

	if buffer.String() != "" {
		t.Errorf("Expected no output but some was printed:\n%v", buffer.String())
	}
}


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Control.Monad.Read
       ( MonadRead (..)
       , contents
       ) where

import Control.Applicative
import Control.Lens
import qualified Control.Monad.ST.Lazy.Safe as Lazy
import Control.Monad.ST.Safe
import Control.Monad.Trans.Class
import Data.IORef
import Data.STRef
import qualified Data.STRef.Lazy as Lazy
import Prelude (IO, Monad (..), (.))

class (Applicative m, Monad m) => MonadRead var m where
  read :: var a -> m a

#ifndef HLINT
  default read :: (MonadTrans t, MonadRead var m) => var a -> t m a
  {-# INLINE read #-}
  read = lift . read
#endif

contents :: MonadRead var m => IndexPreservingAction m (var a) a
{-# INLINE contents #-}
contents = act read

instance MonadRead IORef IO where
  {-# INLINE read #-}
  read = readIORef

instance MonadRead (STRef s) (ST s) where
  {-# INLINE read #-}
  read = readSTRef

instance MonadRead (STRef s) (Lazy.ST s) where
  {-# INLINE read #-}
  read = Lazy.readSTRef


text:
[![CI Status](http://img.shields.io/travis/Arnav/AVFonts.svg?style=flat)](https://travis-ci.org/Arnav/AVFonts)
[![Version](https://img.shields.io/cocoapods/v/AVFonts.svg?style=flat)](http://cocoapods.org/pods/AVFonts)
[![License](https://img.shields.io/cocoapods/l/AVFonts.svg?style=flat)](http://cocoapods.org/pods/AVFonts)
[![Platform](https://img.shields.io/cocoapods/p/AVFonts.svg?style=flat)](http://cocoapods.org/pods/AVFonts)

### What's that for

AVFonts allows you to do anything you want to do with the fonts anywhere and everywhere in the app.

### Why should you use this?

AVFonts can easily swap the system font or specific font you are using with the new font throughout the app. You can increment or decrement font size if needed, too. Now there's no need to select custom fonts in the Interface Builder. Save time by simply configuring its size and style, and then change "system font" to your "new font" everywhere with a single line of code. It's that easy.

![](AVFonts.gif?raw=true "AVFonts screenshot")                            ![](AVFonts2.gif?raw=true "AVFonts  italic screenshot")

### Usage

**1.** import `AVFonts` to `AppDelegate`.

**2.** In `didFinishLaunchingwithOptions` change the font :

**a)** This will swap/change font from system or **currentFontName** to **newFontName** everywhere in the app.
```bash
AVFonts.changeFont(toFont: "Avenir-Heavy")
AVFonts.swapFont(currentFont: "Avenir-Light", toFont: "Avenir-Heavy")
```
**b)** Font swap/change for **types provided** i.e. [ .button, .label, .textField, .textView] throughout the app.

```bash
AVFonts.changeFont(toFont: "Avenir-Heavy", [.button, .label])
AVFonts.swapFont(currentFont: "Avenir-Light", toFont: "Avenir-Heavy", [.button, .label])
```
**c)** **increment/decrement** your orignal font size.

```bash
AVFonts.changeFont(toFont: "Avenir-Heavy", [.button,.label,.textfield], increment: 2)
AVFonts.changeFont(toFont: "Avenir-Heavy", [.button,.label,.textfield], increment: -2)

AVFonts.swapFont(currentFont: "Avenir-Light", toFont: "Avenir-Heavy", [.button, .label, .textfield], increment: 2)
AVFonts.swapFont(currentFont: "Avenir-Light", toFont: "Avenir-Heavy", [.button, .label, .textfield, .textview], increment: -2)

```
**3.** Call **AVFonts.applyAVFonts()** to apply all the changes.

###  Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
- Xcode 10.2
- Swift 5.0

## Installation

### CocoaPods

[CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command:

```bash
$ gem install cocoapods
```

> CocoaPods 1.1.0+ is required to build  AVFonts.

To integrate AVFonts into your Xcode project using CocoaPods, specify it in your `Podfile`:

```ruby
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target '<Your Target Name>' do
pod "AVFonts"
end
```

Then run the following command:

```bash
$ pod install
```

## Author

Arnav Gupta, arnavgupta180@gmail.com

## License

AVFonts is available under the MIT license. See the LICENSE file for more info.


text:
angular.module('security.service', [
  'ngStorage',
  'ui.bootstrap.modal',

  'security.retryQueue',
  'security.login'
]).factory('security', ['$http', '$q', '$location', '$localStorage', 'securityRetryQueue', '$modal', 'API_CONFIG', function($http, $q, $location, $storage, queue, $modal, API_CONFIG) {

    function redirect(url) {
      url = url || '/';
      $location.path(url);
    }

    var loginDialog = null;

    var openLoginDialog = function() {
      if(loginDialog) {
        throw new Error('Trying to open a dialog that is already open!');
      }

      loginDialog = $modal.open({
        templateUrl: '/user/login',
        controller: 'LoginFormCtrl'
      });

      loginDialog.result.then(onLoginDialogClose);
    };

    var closeLoginDialog = function(success) {
      if(loginDialog) {
        loginDialog.close(success);
      }
    };

    var onLoginDialogClose = function(success) {
      loginDialog = null;

      if (success) {
        queue.retryAll();
      } else {
        queue.cancelAll();
        redirect();
      }
    };

    queue.onItemAddedCallbacks.push(function(retryItem) {
      if (queue.hasMore()) {
        service.showLogin();
      }
    });

    $storage.user = $storage.user || null;

    var service = {
      user: null,

      token: null,

      showLogin: function() {
        openLoginDialog();
      },

      cancelLogin: function() {
        closeLoginDialog();

        redirect();
      },

      login: function(username, password, token) {
        var request = $http.post(API_CONFIG.api.protocol + API_CONFIG.api.url + '/user/login_check', {
          username: username,
          password: password,
          token: token
        });

        return request.then(function(response) {
          $storage.user = response.data;

          service.requestCurrentUser();

          if (service.isAuthenticated()) {
            closeLoginDialog(true);
          }

          return service.isAuthenticated();
        });
      },

      logout: function() {
        $storage.user = null;

        redirect();
      },

      requestCurrentUser: function() {
        if(service.isAuthenticated() && !!service.user) {
          return $q.when(service.user);
        } else {
          return $http.get(API_CONFIG.api.protocol + API_CONFIG.api.url + '/me').then(function(response) {
            $storage.user = response.data;

            return $storage.user;
          });
        }
      },

      isAuthenticated: function() {
        return !!$storage.user;
      }
    };

    return service;
  }]
);