text:
package org.apache.accumulo.fate.zookeeper;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;

import java.util.List;

import org.apache.accumulo.core.clientImpl.AcceptableThriftTableOperationException;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeExistsPolicy;
import org.apache.accumulo.fate.zookeeper.ZooUtil.NodeMissingPolicy;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;

public class ZooReaderWriter extends ZooReader {
  public interface Mutator {
    byte[] mutate(byte[] currentValue) throws AcceptableThriftTableOperationException;
  }

  public ZooReaderWriter(AccumuloConfiguration conf) {
    this(conf.get(Property.INSTANCE_ZK_HOST),
        (int) conf.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT),
        conf.get(Property.INSTANCE_SECRET));
  }

  private final String secret;
  private final byte[] auth;

  ZooReaderWriter(String keepers, int timeoutInMillis, String secret) {
    super(keepers, timeoutInMillis);
    this.secret = requireNonNull(secret);
    this.auth = ("accumulo:" + secret).getBytes(UTF_8);
  }

  @Override
  public ZooReaderWriter asWriter(String secret) {
    if (this.secret.equals(secret)) {
      return this;
    }
    return super.asWriter(secret);
  }

  @Override
  public ZooKeeper getZooKeeper() {
    return ZooSession.getAuthenticatedSession(keepers, timeout, "digest", auth);
  }

  /**
   * Retrieve the ACL list that was on the node
   */
  public List<ACL> getACL(String zPath) throws KeeperException, InterruptedException {
    return retryLoop(zk -> zk.getACL(zPath, null));
  }

  /**
   * Create a persistent node with the default ACL
   *
   * @return true if the data was set on a new node or overwritten, and false if an existing node
   *         was skipped
   */
  public boolean putPersistentData(String zPath, byte[] data, NodeExistsPolicy policy)
      throws KeeperException, InterruptedException {
    return putPersistentData(zPath, data, policy, ZooUtil.PUBLIC);
  }

  /**
   * Create a persistent node with the private ACL
   *
   * @return true if the data was set on a new node or overwritten, and false if an existing node
   *         was skipped
   */
  public boolean putPrivatePersistentData(String zPath, byte[] data, NodeExistsPolicy policy)
      throws KeeperException, InterruptedException {
    return putPersistentData(zPath, data, policy, ZooUtil.PRIVATE);
  }

  /**
   * Create a persistent node with the provided ACLs
   *
   * @return true if the data was set on a new node or overwritten, and false if an existing node
   *         was skipped
   */
  public boolean putPersistentData(String zPath, byte[] data, NodeExistsPolicy policy,
      List<ACL> acls) throws KeeperException, InterruptedException {
    // zk allows null ACLs, but it's probably a bug in Accumulo if we see it used in our code
    requireNonNull(acls);
    requireNonNull(policy);
    return retryLoop(zk -> {
      try {
        zk.create(zPath, data, acls, CreateMode.PERSISTENT);
        return true;
      } catch (KeeperException e) {
        if (e.code() == Code.NODEEXISTS) {
          switch (policy) {
            case SKIP:
              return false;
            case OVERWRITE:
              zk.setData(zPath, data, -1);
              return true;
            case FAIL:
            default:
              // re-throw below
          }
        }
        throw e;
      }
    },
        // if OVERWRITE policy is used, create() can fail with NODEEXISTS;
        // then, the node can be deleted, causing setData() to fail with NONODE;
        // if that happens, the following code ensures we retry
        e -> e.code() == Code.NONODE && policy == NodeExistsPolicy.OVERWRITE);
  }

  /**
   * Overwrite a persistent node if the data version matches.
   *
   * @param zPath
   *          the zookeeper path
   * @param data
   *          the byte array data
   * @param expectedVersion
   *          the expected data version of the zookeeper node.
   * @return true if the data was set, false if the version does not match expected.
   * @throws KeeperException
   *           if a KeeperException occurs (no node most likely)
   * @throws InterruptedException
   *           if the zookeeper write is interrupted.
   */
  public boolean overwritePersistentData(String zPath, byte[] data, final int expectedVersion)
      throws KeeperException, InterruptedException {
    return retryLoop(zk -> {
      try {
        zk.setData(zPath, data, expectedVersion);
        return true;
      } catch (KeeperException.BadVersionException ex) {
        return false;
      }
    });
  }

  /**
   * Create a persistent sequential node with the default ACL
   *
   * @return the actual path of the created node
   */
  public String putPersistentSequential(String zPath, byte[] data)
      throws KeeperException, InterruptedException {
    return retryLoop(
        zk -> zk.create(zPath, data, ZooUtil.PUBLIC, CreateMode.PERSISTENT_SEQUENTIAL));
  }

  /**
   * Create an ephemeral node with the default ACL
   */
  public void putEphemeralData(String zPath, byte[] data)
      throws KeeperException, InterruptedException {
    retryLoop(zk -> zk.create(zPath, data, ZooUtil.PUBLIC, CreateMode.EPHEMERAL));
  }

  /**
   * Create an ephemeral sequential node with the default ACL
   *
   * @return the actual path of the created node
   */
  public String putEphemeralSequential(String zPath, byte[] data)
      throws KeeperException, InterruptedException {
    return retryLoop(zk -> zk.create(zPath, data, ZooUtil.PUBLIC, CreateMode.EPHEMERAL_SEQUENTIAL));
  }

  /**
   * Recursively copy any persistent data from the source to the destination, using the default ACL
   * to create any missing nodes and skipping over any ephemeral data.
   */
  public void recursiveCopyPersistentOverwrite(String source, String destination)
      throws KeeperException, InterruptedException {
    var stat = new Stat();
    byte[] data = getData(source, stat);
    // only copy persistent data
    if (stat.getEphemeralOwner() != 0) {
      return;
    }
    putPersistentData(destination, data, NodeExistsPolicy.OVERWRITE);
    if (stat.getNumChildren() > 0) {
      for (String child : getChildren(source)) {
        recursiveCopyPersistentOverwrite(source + "/" + child, destination + "/" + child);
      }
    }
  }

  /**
   * Update an existing ZK node using the provided mutator function. If it's possible the node
   * doesn't exist yet, use {@link #mutateOrCreate(String, byte[], Mutator)} instead.
   *
   * @return the value set on the node
   */
  public byte[] mutateExisting(String zPath, Mutator mutator)
      throws KeeperException, InterruptedException, AcceptableThriftTableOperationException {
    requireNonNull(mutator);
    return retryLoopMutator(zk -> {
      var stat = new Stat();
      byte[] data = zk.getData(zPath, null, stat);
      // this mutator can throw AcceptableThriftTableOperationException
      data = mutator.mutate(data);
      if (data != null) {
        zk.setData(zPath, data, stat.getVersion());
      }
      return data;
    }, e -> e.code() == Code.BADVERSION); // always retry if bad version
  }

  /**
   * Create a new {@link CreateMode#PERSISTENT} ZK node with the default ACL if it does not exist.
   * If it does already exist, then update it with the provided mutator function. If it is known to
   * exist already, use {@link #mutateExisting(String, Mutator)} instead.
   *
   * @return the value set on the node
   */
  public byte[] mutateOrCreate(String zPath, byte[] createValue, Mutator mutator)
      throws KeeperException, InterruptedException, AcceptableThriftTableOperationException {
    requireNonNull(mutator);
    return putPersistentData(zPath, createValue, NodeExistsPolicy.SKIP) ? createValue
        : mutateExisting(zPath, mutator);
  }

  /**
   * Ensure the provided path exists, using persistent nodes, empty data, and the default ACL for
   * any missing path elements.
   */
  public void mkdirs(String path) throws KeeperException, InterruptedException {
    if (path.equals("")) {
      // terminal condition for recursion
      return;
    }
    if (!path.startsWith("/")) {
      throw new IllegalArgumentException(path + "does not start with /");
    }
    if (exists(path)) {
      return;
    }
    String parent = path.substring(0, path.lastIndexOf("/"));
    mkdirs(parent);
    putPersistentData(path, new byte[0], NodeExistsPolicy.SKIP);
  }

  /**
   * Delete the specified node, and ignore NONODE exceptions.
   */
  public void delete(String path) throws KeeperException, InterruptedException {
    try {
      deleteStrict(path, -1);
    } catch (KeeperException e) {
      if (e.code() != Code.NONODE) {
        throw e;
      }
    }
  }

  /**
   * Delete the specified node if the version matches the provided version. All underlying
   * exceptions are thrown back to the caller.
   *
   * @param path
   *          the path of the ZooKeeper node.
   * @param version
   *          the expected version of the ZooKeeper node.
   */
  public void deleteStrict(final String path, final int version)
      throws KeeperException, InterruptedException {
    retryLoop(zk -> {
      zk.delete(path, version);
      return null;
    });
  }

  /**
   * This method will delete a node and all its children.
   */
  public void recursiveDelete(String zPath, NodeMissingPolicy policy)
      throws KeeperException, InterruptedException {
    ZooUtil.recursiveDelete(getZooKeeper(), zPath, policy);
  }
}


text:
package cgeo.geocaching.connector.oc;

import cgeo.geocaching.connector.AbstractLoggingManager;
import cgeo.geocaching.connector.ImageResult;
import cgeo.geocaching.connector.LogResult;
import cgeo.geocaching.enumerations.Loaders;
import cgeo.geocaching.log.LogCacheActivity;
import cgeo.geocaching.log.LogType;
import cgeo.geocaching.log.ReportProblemType;
import cgeo.geocaching.log.TrackableLog;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.AsyncTaskLoader;
import androidx.loader.content.Loader;

import java.util.Calendar;
import java.util.Collections;
import java.util.List;

public class OkapiLoggingManager extends AbstractLoggingManager implements LoaderManager.LoaderCallbacks<OkapiClient.InstallationInformation> {

    @NonNull
    private final OCApiLiveConnector connector;
    @NonNull
    private final Geocache cache;
    @NonNull
    private final LogCacheActivity activity;
    private boolean hasLoaderError = true;
    private OkapiClient.InstallationInformation installationInformation;

    public OkapiLoggingManager(@NonNull final LogCacheActivity activity, @NonNull final OCApiLiveConnector connector, @NonNull final Geocache cache) {
        this.connector = connector;
        this.cache = cache;
        this.activity = activity;
    }

    @Override
    public void init() {
        LoaderManager.getInstance(activity).initLoader(Loaders.LOGGING_GEOCHACHING.getLoaderId(), null, this);
    }

    @Nullable
    @Override
    public Loader<OkapiClient.InstallationInformation> onCreateLoader(final int arg0, final Bundle arg1) {
        activity.onLoadStarted();
        return new AsyncTaskLoader<OkapiClient.InstallationInformation>(activity.getBaseContext()) {
            @Override
            protected void onStartLoading() {
                forceLoad();
            }

            @Override
            public OkapiClient.InstallationInformation loadInBackground() {
                return OkapiClient.getInstallationInformation(connector);
            }
        };
    }

    @Override
    public void onLoadFinished(@NonNull final Loader<OkapiClient.InstallationInformation> loader, final OkapiClient.InstallationInformation data) {
        if (data == null) {
            hasLoaderError = true;
        } else {
            installationInformation = data;
            if (connector.isLoggedIn()) {
                hasLoaderError = false;
            }
        }
        activity.onLoadFinished();
    }

    @Override
    public void onLoaderReset(@NonNull final Loader<OkapiClient.InstallationInformation> loader) {
        // nothing to do
    }

    @Override
    @NonNull
    public final LogResult postLog(@NonNull final LogType logType, @NonNull final Calendar date, @NonNull final String log, @Nullable final String logPassword, @NonNull final List<TrackableLog> trackableLogs, @NonNull final ReportProblemType reportProblem) {
        final LogResult result = OkapiClient.postLog(cache, logType, date, log, logPassword, connector, reportProblem);
        connector.login(null, null);
        return result;
    }

    @Override
    @NonNull
    public final ImageResult postLogImage(final String logId, final Image image) {
        return OkapiClient.postLogImage(logId, image, connector);
    }

    @Override
    @NonNull
    public List<LogType> getPossibleLogTypes() {
        if (hasLoaderError) {
            return Collections.emptyList();
        }
        return connector.getPossibleLogTypes(cache);
    }

    @Override
    public boolean hasLoaderError() {
        return hasLoaderError;
    }

    @Override
    public Long getMaxImageUploadSize() {
        return installationInformation != null ? installationInformation.imageMaxUploadSize : null;
    }

    @Override
    public boolean isImageCaptionMandatory() {
        return true;
    }

    @NonNull
    @Override
    public List<ReportProblemType> getReportProblemTypes(@NonNull final Geocache geocache) {
        if (geocache.isEventCache()) {
            return Collections.emptyList();
        }

        return Collections.singletonList(ReportProblemType.NEEDS_MAINTENANCE);
    }

}

redpajama_set_name: RedPajamaGithub


text:
	Ecosystem
	ES6 Introduction - Promises

	To understand how that works, you just need to have a good understanding of the
	javascript asynchronism

The promise is returned before it is resolved

And the calbacks are set before the resolve method is called

Finally, the resolve/reject methods are references to the callbacks set on the promise

<editor>
	<editortab title="work-with-function.js" fileType="js">

let retrieveFriends= function(person){

	return new Promise(function(resolve, reject){

		var req = new XMLHttpRequest();
		req.open('GET', '/get/users', true);
		req.onreadystatechange = function (aEvt) {
		  if (req.readyState == 4) {
		     if(req.status == 200)
		      resolve(req.responseText);
		     else
		      reject('error');
		  }
		};
		req.send(null);

	});
};

retrieveFriends(user)
.then(function success(data){
	//...
}), function failure(msg){
	//...
});

	</editortab>
</editor>


text:
require 'rack/test'

RSpec.describe FakeBsmobil::Api do
  subject(:app) { described_class.freeze.app }
  include Rack::Test::Methods

  def post(uri, body, env = {})
    super uri, body, env.merge('CONTENT_TYPE' => 'application/json',
                               'HTTP_ACCEPT' => 'application/vnd.idk.bsmobil-v2+json')
  end

  describe 'sessions' do
    it 'returns error on empty user/password' do
      response = post '/bsmobil/api/session', '{"deviceInfo":"iOSNative iPhone 8.2 NATIVE_APP 15.2.0","password":"","userName":"","newDevice":false,"contract":"","brand":"SAB","devicePrint":"","requestId":"SDK","geolocationData":"{\"DeviceSystemVersion\":\"8.2\",\"HardwareID\":\"FAB70832-3893-4471-BC3C-3C984A852E49\",\"ScreenSize\":\"320 x 568\",\"Languages\":\"en\",\"MultitaskingSupported\":true,\"DeviceModel\":\"iPhone\",\"RSA_ApplicationKey\":\"42D7D0F93CE15214780F4DED46BAD347\",\"TIMESTAMP\":\"2015-04-06T10:10:34Z\",\"Emulator\":0,\"OS_ID\":\"46CC0D94-5F6F-44B7-B25D-055A8B093D81\",\"Compromised\":0,\"DeviceSystemName\":\"iPhone OS\",\"DeviceName\":\"bank_scrap\",\"SDK_VERSION\":\"2.0.0\"}","loginType":5}'

      expect(response.body).to eq('{"errorMessage":"Z23226: The USERNAME or ACCESS CODE is incorrect. Please enter details again.","code":""}')
      expect(response.status).to eq(500)
    end

    it 'sets a cookie' do
      response = post '/bsmobil/api/session', '{"deviceInfo":"iOSNative iPhone 8.2 NATIVE_APP 15.2.0","password":"a","userName":"b","newDevice":false,"contract":"","brand":"SAB","devicePrint":"","requestId":"SDK","geolocationData":"{\"DeviceSystemVersion\":\"8.2\",\"HardwareID\":\"FAB70832-3893-4471-BC3C-3C984A852E49\",\"ScreenSize\":\"320 x 568\",\"Languages\":\"en\",\"MultitaskingSupported\":true,\"DeviceModel\":\"iPhone\",\"RSA_ApplicationKey\":\"42D7D0F93CE15214780F4DED46BAD347\",\"TIMESTAMP\":\"2015-04-06T10:10:34Z\",\"Emulator\":0,\"OS_ID\":\"46CC0D94-5F6F-44B7-B25D-055A8B093D81\",\"Compromised\":0,\"DeviceSystemName\":\"iPhone OS\",\"DeviceName\":\"bank_scrap\",\"SDK_VERSION\":\"2.0.0\"}","loginType":5}'

      expect(response.status).to eq(201)
      expect(response.headers['Set-Cookie']).to match(%r{JSESSIONID=.+?; path=/bsmobil})
    end
  end
end


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.linroid.sky31radio.ui.SearchActivity"
    android:orientation="vertical"
    android:fitsSystemWindows="true">
    <include layout="@layout/toolbar"/>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <FrameLayout
            android:id="@+id/program_list_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
        <include layout="@layout/toolbar_shadow"/>
    </FrameLayout>
</LinearLayout>


text:
package units

import (
	"fmt"
	"time"
)

// HumanDuration returns a human-readable approximation of a duration
// (eg. "About a minute", "4 hours ago", etc.).
func HumanDuration(d time.Duration) string {
	if seconds := int(d.Seconds()); seconds < 1 {
		return "Less than a second"
	} else if seconds == 1 {
		return "1 second"
	} else if seconds < 60 {
		return fmt.Sprintf("%d seconds", seconds)
	} else if minutes := int(d.Minutes()); minutes == 1 {
		return "About a minute"
	} else if minutes < 46 {
		return fmt.Sprintf("%d minutes", minutes)
	} else if hours := int(d.Hours() + 0.5); hours == 1 {
		return "About an hour"
	} else if hours < 48 {
		return fmt.Sprintf("%d hours", hours)
	} else if hours < 24*7*2 {
		return fmt.Sprintf("%d days", hours/24)
	} else if hours < 24*30*2 {
		return fmt.Sprintf("%d weeks", hours/24/7)
	} else if hours < 24*365*2 {
		return fmt.Sprintf("%d months", hours/24/30)
	}
	return fmt.Sprintf("%d years", int(d.Hours())/24/365)
}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// This file is manually converted from PROJ4

// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.

// This file was modified by Oracle on 2017, 2018.
// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// This file is converted from PROJ4, http://trac.osgeo.org/proj
// PROJ4 is originally written by Gerald Evenden (then of the USGS)
// PROJ4 is maintained by Frank Warmerdam
// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)

// Original copyright notice:

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

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

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

#ifndef BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_INIT_HPP
#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_INIT_HPP

#include <cstdlib>
#include <string>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/range.hpp>
#include <boost/type_traits/is_same.hpp>

#include <boost/geometry/util/math.hpp>
#include <boost/geometry/util/condition.hpp>

#include <boost/geometry/srs/projections/impl/dms_parser.hpp>
#include <boost/geometry/srs/projections/impl/pj_datum_set.hpp>
#include <boost/geometry/srs/projections/impl/pj_datums.hpp>
#include <boost/geometry/srs/projections/impl/pj_ell_set.hpp>
#include <boost/geometry/srs/projections/impl/pj_param.hpp>
#include <boost/geometry/srs/projections/impl/pj_units.hpp>
#include <boost/geometry/srs/projections/impl/projects.hpp>
#include <boost/geometry/srs/projections/proj4.hpp>

namespace boost { namespace geometry { namespace projections
{

namespace detail
{

template <typename BGParams, typename T>
inline void pj_push_defaults(BGParams const& /*bg_params*/, parameters<T>& pin)
{
    pin.params.push_back(pj_mkparam<T>("ellps", "WGS84"));

    if (pin.name == "aea")
    {
        pin.params.push_back(pj_mkparam<T>("lat_1", "29.5"));
        pin.params.push_back(pj_mkparam<T>("lat_2", "45.5 "));
    }
    else if (pin.name == "lcc")
    {
        pin.params.push_back(pj_mkparam<T>("lat_1", "33"));
        pin.params.push_back(pj_mkparam<T>("lat_2", "45"));
    }
    else if (pin.name == "lagrng")
    {
        pin.params.push_back(pj_mkparam<T>("W", "2"));
    }
}

template <BOOST_GEOMETRY_PROJECTIONS_DETAIL_TYPENAME_PX, typename T>
inline void pj_push_defaults(srs::static_proj4<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> const& /*bg_params*/,
                             parameters<T>& pin)
{
    typedef srs::static_proj4<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> static_parameters_type;
    typedef typename srs::par4::detail::pick_proj_tag
        <
            static_parameters_type
        >::type proj_tag;

    // statically defaulting to WGS84
    //pin.params.push_back(pj_mkparam("ellps", "WGS84"));

    if (BOOST_GEOMETRY_CONDITION((boost::is_same<proj_tag, srs::par4::aea>::value)))
    {
        pin.params.push_back(pj_mkparam<T>("lat_1", "29.5"));
        pin.params.push_back(pj_mkparam<T>("lat_2", "45.5 "));
    }
    else if (BOOST_GEOMETRY_CONDITION((boost::is_same<proj_tag, srs::par4::lcc>::value)))
    {
        pin.params.push_back(pj_mkparam<T>("lat_1", "33"));
        pin.params.push_back(pj_mkparam<T>("lat_2", "45"));
    }
    else if (BOOST_GEOMETRY_CONDITION((boost::is_same<proj_tag, srs::par4::lagrng>::value)))
    {
        pin.params.push_back(pj_mkparam<T>("W", "2"));
    }
}

template <typename T>
inline void pj_init_units(std::vector<pvalue<T> > const& params,
                          std::string const& sunits,
                          std::string const& sto_meter,
                          T & to_meter,
                          T & fr_meter,
                          T const& default_to_meter,
                          T const& default_fr_meter)
{
    std::string s;
    std::string units = pj_get_param_s(params, sunits);
    if (! units.empty())
    {
        const int n = sizeof(pj_units) / sizeof(pj_units[0]);
        int index = -1;
        for (int i = 0; i < n && index == -1; i++)
        {
            if(pj_units[i].id == units)
            {
                index = i;
            }
        }

        if (index == -1) {
            BOOST_THROW_EXCEPTION( projection_exception(error_unknow_unit_id) );
        }
        s = pj_units[index].to_meter;
    }

    if (s.empty())
    {
        s = pj_get_param_s(params, sto_meter);
    }

    if (! s.empty())
    {
        std::size_t const pos = s.find('/');
        if (pos == std::string::npos)
        {
            to_meter = geometry::str_cast<T>(s);
        }
        else
        {
            T const numerator = geometry::str_cast<T>(s.substr(0, pos));
            T const denominator = geometry::str_cast<T>(s.substr(pos + 1));
            if (numerator == 0.0 || denominator == 0.0)
            {
                BOOST_THROW_EXCEPTION( projection_exception(error_unit_factor_less_than_0) );
            }
            to_meter = numerator / denominator;
        }
        if (to_meter == 0.0)
        {
            BOOST_THROW_EXCEPTION( projection_exception(error_unit_factor_less_than_0) );
        }
        fr_meter = 1. / to_meter;
    }
    else
    {
        to_meter = default_to_meter;
        fr_meter = default_fr_meter;
    }
}

/************************************************************************/
/*                              pj_init()                               */
/*                                                                      */
/*      Main entry point for initialing a PJ projections                */
/*      definition.  Note that the projection specific function is      */
/*      called to do the initial allocation so it can be created        */
/*      large enough to hold projection specific parameters.            */
/************************************************************************/
template <typename T, typename BGParams, typename R>
inline parameters<T> pj_init(BGParams const& bg_params, R const& arguments, bool use_defaults = true)
{
    parameters<T> pin;
    for (std::vector<std::string>::const_iterator it = boost::begin(arguments);
        it != boost::end(arguments); it++)
    {
        pin.params.push_back(pj_mkparam<T>(*it));
    }

    // maybe TODO: handle "init" parameter
    /* check if +init present */
    //std::string sinit;
    //if (pj_param_s(pin.params, "init", sinit))
    //{
    //    //if (!(curr = get_init(&arguments, curr, sinit)))
    //}

    // find projection -> implemented in projection factory
    pin.name = pj_get_param_s(pin.params, "proj");
    // exception thrown in projection<>
    // TODO: consider throwing here both projection_unknown_id_exception and
    // projection_not_named_exception in order to throw before other exceptions
    //if (pin.name.empty())
    //{ BOOST_THROW_EXCEPTION( projection_not_named_exception() ); }

    // set defaults, unless inhibited
    // GL-Addition, if use_defaults is false then defaults are ignored
    if (use_defaults && ! pj_get_param_b(pin.params, "no_defs"))
    {
        // proj4 gets defaults from "proj_def.dat", file of 94/02/23 with a few defaults.
        // Here manually
        pj_push_defaults(bg_params, pin);
        //curr = get_defaults(&arguments, curr, name);
    }

    /* allocate projection structure */
    // done by BGParams constructor:
    // pin.is_latlong = 0;
    // pin.is_geocent = 0;
    // pin.long_wrap_center = 0.0;
    // pin.long_wrap_center = 0.0;
    pin.is_long_wrap_set = false;

    /* set datum parameters */
    pj_datum_set(bg_params, pin.params, pin);

    /* set ellipsoid/sphere parameters */
    pj_ell_set(bg_params, pin.params, pin.a, pin.es);

    pin.a_orig = pin.a;
    pin.es_orig = pin.es;

    pin.e = sqrt(pin.es);
    pin.ra = 1. / pin.a;
    pin.one_es = 1. - pin.es;
    if (pin.one_es == 0.) {
        BOOST_THROW_EXCEPTION( projection_exception(error_eccentricity_is_one) );
    }
    pin.rone_es = 1./pin.one_es;

    /* Now that we have ellipse information check for WGS84 datum */
    if( pin.datum_type == datum_3param
        && pin.datum_params[0] == 0.0
        && pin.datum_params[1] == 0.0
        && pin.datum_params[2] == 0.0
        && pin.a == 6378137.0
        && geometry::math::abs(pin.es - 0.006694379990) < 0.000000000050 )/*WGS84/GRS80*/
    {
        pin.datum_type = datum_wgs84;
    }

    /* set pin.geoc coordinate system */
    pin.geoc = (pin.es && pj_get_param_b(pin.params, "geoc"));

    /* over-ranging flag */
    pin.over = pj_get_param_b(pin.params, "over");

    /* longitude center for wrapping */
    pin.is_long_wrap_set = pj_param_r(pin.params, "lon_wrap", pin.long_wrap_center);

    /* central meridian */
    pin.lam0 = pj_get_param_r(pin.params, "lon_0");

    /* central latitude */
    pin.phi0 = pj_get_param_r(pin.params, "lat_0");

    /* false easting and northing */
    pin.x0 = pj_get_param_f(pin.params, "x_0");
    pin.y0 = pj_get_param_f(pin.params, "y_0");

    /* general scaling factor */
    if (pj_param_f(pin.params, "k_0", pin.k0)) {
        /* empty */
    } else if (pj_param_f(pin.params, "k", pin.k0)) {
        /* empty */
    } else
        pin.k0 = 1.;
    if (pin.k0 <= 0.) {
        BOOST_THROW_EXCEPTION( projection_exception(error_k_less_than_zero) );
    }

    /* set units */
    pj_init_units(pin.params, "units", "to_meter",
                  pin.to_meter, pin.fr_meter, 1., 1.);
    pj_init_units(pin.params, "vunits", "vto_meter",
                  pin.vto_meter, pin.vfr_meter, pin.to_meter, pin.fr_meter);

    /* prime meridian */
    std::string pm = pj_get_param_s(pin.params, "pm");
    if (! pm.empty())
    {
        std::string value;

        int n = sizeof(pj_prime_meridians) / sizeof(pj_prime_meridians[0]);
        for (int i = 0; i < n ; i++)
        {
            if(pj_prime_meridians[i].id == pm)
            {
                value = pj_prime_meridians[i].defn;
                break;
            }
        }

        dms_parser<T, true> parser;

        // TODO: Is this try-catch needed?
        // In other cases the bad_str_cast exception is simply thrown
        BOOST_TRY
        {
            if (value.empty()) {
                pin.from_greenwich = parser.apply(pm).angle();
            } else {
                pin.from_greenwich = parser.apply(value).angle();
            }
        }
        BOOST_CATCH(geometry::bad_str_cast const&)
        {
            BOOST_THROW_EXCEPTION( projection_exception(error_unknown_prime_meridian) );
        }
        BOOST_CATCH_END
    }
    else
    {
        pin.from_greenwich = 0.0;
    }

    return pin;
}

/************************************************************************/
/*                            pj_init_plus()                            */
/*                                                                      */
/*      Same as pj_init() except it takes one argument string with      */
/*      individual arguments preceeded by '+', such as "+proj=utm       */
/*      +zone=11 +ellps=WGS84".                                         */
/************************************************************************/
template <typename T, typename BGParams>
inline parameters<T> pj_init_plus(BGParams const& bg_params, std::string const& definition, bool use_defaults = true)
{
    const char* sep = " +";

    /* split into arguments based on '+' and trim white space */

    // boost::split splits on one character, here it should be on " +", so implementation below
    // todo: put in different routine or sort out
    std::vector<std::string> arguments;
    std::string def = boost::trim_copy(definition);
    boost::trim_left_if(def, boost::is_any_of(sep));

    std::string::size_type loc = def.find(sep);
    while (loc != std::string::npos)
    {
        std::string par = def.substr(0, loc);
        boost::trim(par);
        if (! par.empty())
        {
            arguments.push_back(par);
        }

        def.erase(0, loc);
        boost::trim_left_if(def, boost::is_any_of(sep));
        loc = def.find(sep);
    }

    if (! def.empty())
    {
        arguments.push_back(def);
    }

    /*boost::split(arguments, definition, boost::is_any_of("+"));
    for (std::vector<std::string>::iterator it = arguments.begin(); it != arguments.end(); it++)
    {
        boost::trim(*it);
    }*/
    return pj_init<T>(bg_params, arguments, use_defaults);
}

} // namespace detail
}}} // namespace boost::geometry::projections

#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_INIT_HPP


text:
from touchdown.core.resource import Resource
from touchdown.core.plan import Plan, Present
from touchdown.core import argument, serializers

from ..common import SimpleDescribe, SimpleApply, SimpleDestroy
from .. import cloudwatch
from .auto_scaling_group import AutoScalingGroup

class Policy(Resource):

    resource_name = "policy"

    name = argument.String(field="PolicyName")
    auto_scaling_group = argument.Resource(AutoScalingGroup, field="AutoScalingGroupName")

    min_adjustment_step = argument.Integer(field="MinAdjustmentStep")
    adjustment_type = argument.String(
        choices=["ChangeInCapacity", "ExactCapacity", "PercentChangeInCapacity"],
        default="ChangeInCapacity",
        field="AdjustmentType"
    )
    scaling_adjustment = argument.Integer(default=1, field="ScalingAdjustment")
    cooldown = argument.Integer(default=30, field="Cooldown")

    # alarms = argument.ResourceList("touchdown.aws.cloudwatch.Alarm", field="Alarms")

class Describe(SimpleDescribe, Plan):

    resource = Policy
    service_name = 'autoscaling'
    describe_action = "describe_policies"
    describe_envelope = "ScalingPolicies"
    key = 'PolicyName'

    def get_describe_filters(self):
        asg = self.runner.get_plan(self.resource.auto_scaling_group)
        if not asg.resource_id:
            return None

        return {
            "AutoScalingGroupName": self.resource.auto_scaling_group.name,
            "PolicyNames": [self.resource.name]
        }

class Apply(SimpleApply, Describe):

    create_action = "put_scaling_policy"
    create_response = "not-that-useful"

    signature = (
        Present("name"),
        Present("auto_scaling_group"),
    )

class Destroy(SimpleDestroy, Describe):

    destroy_action = "delete_policy"

    def get_destroy_serializer(self):
        return serializers.Dict(
            AutoScalingGroupName=self.resource.auto_scaling_group.name,
            PolicyName=self.resource.name,
        )

class AlarmDestination(cloudwatch.AlarmDestination):

    resource_name = "alarm_destination"
    input = Policy

    def get_serializer(self, runner, **kwargs):
        return serializers.Context(
            serializers.Const(self.adapts),
            serializers.Property("PolicyARN"),
        )


text:
namespace enterprise_management {
class DeviceManagementResponse;
class DeviceRegisterRequest;
class DeviceStatusReportRequest;
class PolicyFetchRequest;
class PolicyFetchResponse;
class SessionStatusReportRequest;
}

namespace policy {

class DeviceManagementRequestJob;
class DeviceManagementService;

// Implements the core logic required to talk to the device management service.
// Also keeps track of the current state of the association with the service,
// such as whether there is a valid registration (DMToken is present in that
// case) and whether and what errors occurred in the latest request.
//
// Note that CloudPolicyClient doesn't do any validation of policy responses
// such as signature and time stamp checks. These happen once the policy gets
// installed in the cloud policy cache.
class CloudPolicyClient {
 public:
  // Observer interface for state and policy changes.
  class Observer {
   public:
    virtual ~Observer();

    // Called when a policy fetch completes successfully. If a policy fetch
    // triggers an error, OnClientError() will fire.
    virtual void OnPolicyFetched(CloudPolicyClient* client) = 0;

    // Called upon registration state changes. This callback is invoked for
    // successful completion of registration and unregistration requests.
    virtual void OnRegistrationStateChanged(CloudPolicyClient* client) = 0;

    // Indicates there's been an error in a previously-issued request.
    virtual void OnClientError(CloudPolicyClient* client) = 0;
  };

  // Delegate interface for supplying status information to upload to the server
  // as part of the policy fetch request.
  class StatusProvider {
   public:
    virtual ~StatusProvider();

    // Retrieves status information to send with the next policy fetch.
    // Implementations must return true if status information was filled in.
    virtual bool GetDeviceStatus(
        enterprise_management::DeviceStatusReportRequest* status) = 0;
    virtual bool GetSessionStatus(
        enterprise_management::SessionStatusReportRequest* status) = 0;

    // Called after the status information has successfully been submitted to
    // the server.
    virtual void OnSubmittedSuccessfully() = 0;
  };

  // |provider| and |service| are weak pointers and it's the caller's
  // responsibility to keep them valid for the lifetime of CloudPolicyClient.
  CloudPolicyClient(const std::string& machine_id,
                    const std::string& machine_model,
                    UserAffiliation user_affiliation,
                    PolicyScope scope,
                    StatusProvider* provider,
                    DeviceManagementService* service);
  virtual ~CloudPolicyClient();

  // Sets the DMToken, thereby establishing a registration with the server. A
  // policy fetch is not automatically issued but can be requested by calling
  // FetchPolicy().
  virtual void SetupRegistration(const std::string& dm_token,
                                 const std::string& client_id);

  // Attempts to register with the device management service. Results in a
  // registration change or error notification.
  virtual void Register(const std::string& auth_token);

  // Requests a policy fetch. The client being registered is a prerequisite to
  // this operation and this call will CHECK if the client is not in registered
  // state. FetchPolicy() triggers a policy fetch from the cloud. A policy
  // change notification is reported to the observers and the new policy blob
  // can be retrieved once the policy fetch operation completes. In case of
  // multiple requests to fetch policy, new requests will cancel any pending
  // requests and the latest request will eventually trigger notifications.
  virtual void FetchPolicy();

  // Sends an unregistration request to the server.
  virtual void Unregister();

  // Adds an observer to be called back upon policy and state changes.
  void AddObserver(Observer* observer);

  // Removes the specified observer.
  void RemoveObserver(Observer* observer);

  void set_submit_machine_id(bool submit_machine_id) {
    submit_machine_id_ = submit_machine_id;
  }

  void set_last_policy_timestamp(const base::Time& timestamp) {
    last_policy_timestamp_ = timestamp;
  }

  void set_public_key_version(int public_key_version) {
    public_key_version_ = public_key_version;
    public_key_version_valid_ = true;
  }

  void clear_public_key_version() {
    public_key_version_valid_ = false;
  }

  // Whether the client is registered with the device management service.
  bool is_registered() const { return !dm_token_.empty(); }

  // The policy response as obtained by the last request to the cloud. This
  // policy blob hasn't gone through verification, so it's contents cannot be
  // trusted. Use CloudPolicyStore::policy() and CloudPolicyStore::policy_map()
  // instead for making policy decisions.
  const enterprise_management::PolicyFetchResponse* policy() const {
    return policy_.get();
  }

  DeviceManagementStatus status() const {
    return status_;
  }

 protected:
  // Sets the registration type suitable for the policy scope used.
  void SetRegistrationType(
      enterprise_management::DeviceRegisterRequest* request) const;

  // Sets the appropriate policy type in the fetch request.
  void SetPolicyType(enterprise_management::PolicyFetchRequest* request) const;

  // Callback for registration requests.
  void OnRegisterCompleted(
      DeviceManagementStatus status,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for policy fetch requests.
  void OnPolicyFetchCompleted(
      DeviceManagementStatus status,
      const enterprise_management::DeviceManagementResponse& response);

  // Callback for unregistration requests.
  void OnUnregisterCompleted(
      DeviceManagementStatus status,
      const enterprise_management::DeviceManagementResponse& response);

  // Observer notification helpers.
  void NotifyPolicyFetched();
  void NotifyRegistrationStateChanged();
  void NotifyClientError();

  // Data necessary for constructing policy requests.
  const std::string machine_id_;
  const std::string machine_model_;
  const UserAffiliation user_affiliation_;
  const PolicyScope scope_;

  std::string dm_token_;
  std::string client_id_;
  bool submit_machine_id_;
  base::Time last_policy_timestamp_;
  int public_key_version_;
  bool public_key_version_valid_;

  // Used for issuing requests to the cloud.
  DeviceManagementService* service_;
  scoped_ptr<DeviceManagementRequestJob> request_job_;

  // Status upload data is produced by |status_provider_|.
  StatusProvider* status_provider_;

  // The policy blob returned by the last policy fetch operation.
  scoped_ptr<enterprise_management::PolicyFetchResponse> policy_;
  DeviceManagementStatus status_;

  ObserverList<Observer, true> observers_;

 private:
  DISALLOW_COPY_AND_ASSIGN(CloudPolicyClient);
};

}  // namespace policy

#endif  // CHROME_BROWSER_POLICY_CLOUD_POLICY_CLIENT_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.alternativeinfrastructures.noise.views.SettingsActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:id="@+id/content_settings_placeholder"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>


text:
CREATE DATABASE `memberships`;

USE `memberships`;

CREATE TABLE `vo_memberships` (
    `eppn` VARCHAR(30) NOT NULL,
    `vo_name` VARCHAR(30) NOT NULL,
    PRIMARY KEY(`eppn`, `vo_name`)
);

INSERT INTO `vo_memberships` VALUES ("jsmith@vagrant.test", "AllowedUsers");
INSERT INTO `vo_memberships` VALUES ("jsmith@vagrant.test", "AnotherGroup");
INSERT INTO `vo_memberships` VALUES ("jbrown@vagrant.test", "AllowedUsers");
INSERT INTO `vo_memberships` VALUES ("jamesj@vagrant.test", "GroupTwo");


text:
/*
 * RegistryEvent.h
 *
 *  Created on: Apr 26, 2012
 *      Author: augcampos
 */

#ifndef REGISTRYEVENT_H_
#define REGISTRYEVENT_H_

#include "ManagerEvent.h"

namespace asteriskcpp {

    /**
     * A RegistryEvent is triggered when this asterisk server attempts to register
     * as a client at another SIP or IAX server.

     * This event is implemented in channels/chan_iax2.c and
     * channels/chan_sip.c
     */
    class RegistryEvent : public ManagerEvent {
    public:
        RegistryEvent(const std::string & values);
        virtual ~RegistryEvent();

        /**
         * Returns the type of channel that is registered, that is "IAX2" for an IAX2
         * channel or "SIP" for a SIP channel.
         *
         * @return the type of channel that is registered.
         * @since 1.0.0
         */
        const std::string& getChannelType() const;

        /**
         * Returns the type of channel that is registered, that is "IAX2" for an IAX2
         * channel or "SIP" for a SIP channel.
         *
         * @see #getChannelType()
         * @since 0.3
         * @deprecated
         */
        const std::string& getChannelDriver() const;

        /**
         * Returns the type of channel that is registered, that is "IAX2" for an IAX2
         * channel or "SIP" for a SIP channel.
         *
         * @see #getChannelType()
         * @deprecated
         */
        const std::string& getChannel() const;

        /**
         * Returns the domain or host name of the SIP or IAX2 server.

         * This is the host part used in the register lines in
         * iax.conf and sip.conf.
         *
         * @return the domain or host name of the SIP or IAX2 server.
         */
        const std::string& getDomain() const;

        /**
         * Returns the username used for registration.

         * SIP send the username in case of a registration timeout, IAX2 in case of
         * a registration failure. Otherwise the username is null.
         *
         * @return the username used for registration.
         */
        const std::string& getUsername() const;

        /**
         * Returns the registration state.

         * For sip this may be one of (not sure if all of these are exposed via the
         * manager api, at least "Registered" and "Timeout" are used though)
         *

         *
Registered

         *
Unregistered

         *
Request Sent

         *
Auth. Sent

         *
Rejected

         *
Timeout

         *
No Authentication

         *
Unreachable

         *

         * IAX2 only uses
         *

         *
Rejected

         *

         * Successful IAX2 registrations do not use the this property at all.
         *
         * @return the registration state.
         */
        const std::string& getStatus() const;

        /**
         * Returns the cause of a rejected registration.
         *
         * @return the cause of a rejected registration or null if the cause is unknown.
         * @since 0.2
         */
        const std::string& getCause() const;

    };

} /* namespace asteriskcpp */
#endif /* REGISTRYEVENT_H_ */


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ManagerShop.Domain.Sys_Factory.Entities
{
    public class Fac_InvoiceOutStockRecordEntity : IEntity<String>
    {
        /// <summary>
        /// 出库记录
        /// </summary>
        public String M_Id { get; set; }
        /// <summary>
        /// 发票编号
        /// </summary>
        public String InvoiceNo { get; set; }
        /// <summary>
        /// 商品番号
        /// </summary>
        public String ProductNo { get; set; }
        /// <summary>
        /// 出庫数
        /// </summary>
        public int OutStock { get; set; }
        /// <summary>
        /// 商品入庫日
        /// </summary>
        public String ProductStockDateJson { get; set; }
        /// <summary>
        /// 帳票の情報
        /// </summary>
        public virtual Fac_InvoiceEntity Invoice { get; set; }
    }
}


text:
package store_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/frodenas/bosh-registry/server/store"

	boshlog "github.com/cloudfoundry/bosh-utils/logger"
)

var _ = Describe("Store", func() {
	var (
		config = Config{}
		logger = boshlog.NewLogger(boshlog.LevelNone)
	)

	Describe("NewStore", func() {
		It("returns error if Adapter is not supported", func() {
			config.Adapter = "fake-adapter"

			_, err := NewStore(config, logger)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("Registry Store adapter 'fake-adapter' not supported"))
		})

		Context("when adapter is bolt", func() {
			BeforeEach(func() {
				config.Adapter = "bolt"
				config.Options = nil
			})

			It("does not return error if bolt configuration is not valid", func() {
				boltConfig := map[string]interface{}{
					"DBFile": "fake-dbfile",
				}
				config.Options = boltConfig
				_, err := NewStore(config, logger)
				Expect(err).ToNot(HaveOccurred())
			})

			It("returns error if bolt configuration is not valid", func() {
				_, err := NewStore(config, logger)
				Expect(err).To(HaveOccurred())
				Expect(err.Error()).To(ContainSubstring("Validating Bolt Registry Store configuration"))
			})
		})
	})
})


text:
<?php

namespace Backend\Modules\Jobs\Ajax;

use Backend\Core\Engine\Base\AjaxAction as BackendBaseAJAXAction;
use Backend\Core\Engine\Language as BL;
use Backend\Modules\Jobs\Engine\Model as BackendJobsModel;

/**
 * Reorder categories
 *
 * @author Bart De Clercq <info@lexxweb.be>
 * @author Tim van Wolfswinkel <tim@webleads.nl>
 */
class Sequence extends BackendBaseAJAXAction
{
	/**
	 * Execute the action
	 */
	public function execute()
	{
		parent::execute();

		// get parameters
		$newIdSequence = trim(\SpoonFilter::getPostValue('new_id_sequence', null, '', 'string'));

		// list id
		$ids = (array) explode(',', rtrim($newIdSequence, ','));

		// loop id's and set new sequence
		foreach($ids as $i => $id)
		{
			// build item
			$item['id'] = (int) $id;

			// change sequence
			$item['sequence'] = $i + 1;

			// update sequence
			if(BackendJobsModel::existsCategory($item['id'])) BackendJobsModel::updateCategory($item);
		}

		// success output
		$this->output(self::OK, null, 'sequence updated');
	}
}


text:
class BrowseEventsController {
  constructor() {
    this.name = 'Browse Events';
  }
}

export default BrowseEventsController;


text:
/**
 * Created by johan on 11/11/2015.
 */
var router = require('express').Router();
var pwd = require('path');

router.get('/:name', function (req, res) {
    var pluginName = req.params.name;

    var data = req.query;

    console.log(data);

    var plugin: any = getModule(data.path, data.script);

    console.log('plugin : ' + pluginName);
    console.log('params : ' + JSON.stringify(req.body));

    if (!plugin) {
        console.log('Error in load plugin :' + pluginName);
        res.send(400);
        return;
    }

    plugin = new plugin.Index();

    plugin.action(data, function (response) {
        //console.log(response);

        res.send(response);
        //_actionPluginResponse(res, response);
    }, JSON.parse(data.config));

});

var getModule = function (pathPlugin, script) {
    var module = false;
    var path = false;

    path = pwd.normalize(pwd.join(__dirname, '..', pathPlugin, script));
    //delete require.cache[require.resolve(module)]
    //return require(module)

    module = requireUncached(path);
    //module = require(path);

    //initModule(module);
    //if (!module) {
    //    return false;
    //}

    return module;
};

var initModule = function (module, name) {
    try {
        if (!module) {
            return;
        }

        if (module.initialized) {
            return;
        }
        module.initialized = true;

        console.log('info', 'initModule: ', name);
        if (!module.init) {
            return;
        }

    } catch (ex) {
        console.log('warn', 'initModule: ' + ex.message);
    }
};

function requireUncached(module) {
    delete require.cache[require.resolve(module)]
    return require(module)
}
module.exports = router;


text:
from django.conf.urls import url
import missions.views
from django.contrib.auth.decorators import login_required

urlpatterns = [
    url(r'^$',
        login_required(missions.views.ListMissionView.as_view()), name='missions-list'),
    url(r'^new/$',
        login_required(missions.views.CreateMissionView.as_view()), name='missions-new'),
    url(r'^(?P<pk>\d+)/$',
        login_required(missions.views.EditMissionView.as_view()), name='missions-edit',),
    url(r'^(?P<pk>\d+)/delete/$',
        login_required(missions.views.DeleteMissionView.as_view()), name='missions-delete',),
    url(r'^(?P<mission>\d+)/report/$',
        login_required(missions.views.ReportMissionView.as_view()), name='mission-report',),
    url(r'^(?P<mission>\d+)/attachments/$',
        login_required(missions.views.ReportAttachmentsMissionView.as_view()), name='mission-attachments', ),
    url(r'^(?P<mission>\d+)/stats/$',
        login_required(missions.views.MissionStatsView.as_view()), name='mission-stats',),
    url(r'^(?P<mission_id>\d+)/hosts/$',
        login_required(missions.views.EditMissionHostsView.as_view()), name='mission-hosts'),

    url(r'^(?P<mission>\d+)/tests/$',
        login_required(missions.views.ListMissionTestsView.as_view()), name='mission-tests'),
    url(r'^(?P<mission>\d+)/tests/new/$',
        login_required(missions.views.CreateMissionTestView.as_view()), name='mission-test-new'),
    url(r'^(?P<mission>\d+)/tests/(?P<pk>\d+)/$',
        login_required(missions.views.EditMissionTestView.as_view()), name='mission-test-view'),
    url(r'^(?P<mission>\d+)/tests/(?P<pk>\d+)/edit$',
        login_required(missions.views.EditMissionTestView.as_view()), name='mission-test-edit'),
    url(r'^(?P<mission>\d+)/tests/(?P<pk>\d+)/delete/$',
        login_required(missions.views.DeleteMissionTestView.as_view()), name='mission-test-delete'),
    url(r'^(?P<mission>\d+)/tests/(?P<pk>\d+)/clone/$',
        login_required(missions.views.CloneMissionTestView.as_view()), name='mission-tests-clone'),
    url(r'^(?P<mission>\d+)/tests/reorder/$',
        login_required(missions.views.OrderMissionTestsView.as_view()), name='mission-tests-reorder'),
    url(r'^(?P<mission_id>\d+)/tests/(?P<test_id>\d+)/hosts',
        login_required(missions.views.test_host_handler), name='test-hosts'),

    url(r'^(?P<mission>\d+)/tests/(?P<test_detail>\d+)/data/$',
        login_required(missions.views.ListMissionTestsSupportingDataView.as_view()), name='test-data-list'),
    url(r'^(?P<mission>\d+)/tests/(?P<test_detail>\d+)/data/new/$',
        login_required(missions.views.CreateMissionTestsSupportingDataView.as_view()), name='test-data-new'),
    url(r'^(?P<mission>\d+)/tests/(?P<test_detail>\d+)/data/(?P<pk>\d+)/$',
        login_required(missions.views.EditMissionTestsSupportingDataView.as_view()), name='test-data-edit'),
    url(r'^(?P<mission>\d+)/tests/(?P<test_detail>\d+)/data/(?P<pk>\d+)/delete/$',
        login_required(missions.views.DeleteMissionTestsSupportingDataView.as_view()), name='test-data-delete'),
    url(r'^(?P<mission>\d+)/tests/(?P<test_detail>\d+)/data/reorder/$',
        login_required(missions.views.OrderMissionTestsSupportingDataView.as_view()), name='test-data-reorder'),

]


text:
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="bootstrap.min.css">

  <button type="button" id="enter-region-selection" class="btn btn-primary btn-block">Add new region</button>
  <button type="button" id="exit-region-selection" class="btn btn-danger btn-block">Cancel</button>


text:
Was für Gründe sprechen eigentlich dafür, Processing.py statt des »normalen« Processings zu nutzen? Nun, zum einen können es persönliche Gründe sein: Ich mag zum Beispiel keine Programmiersprachen, die Blöcke mit geschweiften Klammern (`{}`) trennen und vermeide sie, wo es nur geht. Zum anderen komme ich aus der [Pascal][3]-Ecke (Pascal und Algol 68 waren meine ersten Programmiersprachen überhaupt) und mag daher Programme, die so etwas sind wie »ausführbarer Pseudocode«. Aber der wichtigste Grund ist, Processing.py ist eben nicht nur Processing, sondern auch Python. Und Python kommt *»batteries included«*, es bringt eine große Anzahl von Standard-Bibliotheken mit, die man auch in Processing.py nutzen kann. Ich möchte das am Beispiel des Python-Moduls `datetime` einmal zeigen:

[![Screenshot](images/rentenuhr.jpg)](https://www.flickr.com/photos/schockwellenreiter/31675983150/)

Als erstes habe ich den freien ([Open Font Licence][6]) Font [Coda Heavy][5] von Googles Seiten heruntergeladen, entpackt und ihn dem Skript zugänglich gemacht, indem ich die `.ttf`-Datei einfach auf das IDE-Fenster geschoben habe. Processing legt dann automatisch im Skriptordner ein `data`-Vertzeichnis an und kopiert die Datei -- wie auch alle Bild- oder Audio-Datein dorthin. Die Skripte finden sie dann, zum Beispiel mit

~~~python
	font = createFont("Coda-Heavy.ttf", 96)
~~~

ohne eine spezielle Pfadangabe. Der zweite Parameter gibt die maximale Fontgröße vor. Am Anfang des Skriptes habe ich mit

~~~python
	import datetime as dt
~~~

das Python-Modul `datetime` aus der Standardbibliothek geladen und dann als erstes eine einfache Uhr gebastelt

~~~python
	myNow = dt.datetime.now()
	myHour = str(myNow.hour)
	myMinute = str(myNow.minute)
	mySecond = str(myNow.second)
~~~

und dann die `datetime`-Objekte in Strings verwandelt. Im eigentlichen Programm habe ich sie sogar noch ein wenig aufgehübscht und den einstelligen Sekunden und Minute eine führende Null verpaßt. Das könnt Ihr weiter unten im kompletten Quellcode nachlesen.

Jetzt kommt aber der eigentliche Gag: Mit den `datetime`-Objekten kann man nämlich rechnen! Und da ich am 31. Dezember 2018 in Rente gehe, wollte ich wissen, wieviele Tage ich noch ausharren muß

~~~python
    rente = dt.date(2018, 12, 31)
    heute = dt.date.today()
    differenz = rente - heute
    myDays = str(differenz.days)
    workingDays = float(myDays)/7.0 * 5
    workingDays = str(int(workingDays - 80))
~~~

und wieviele Tage davon Arbeitstage sind. Dazu habe ich einfach die Anzahl der Tage durch sieben geteilt und mit fünf multipliziert, was grob die Anzahl der Werktage ergibt. Und da ich noch 20 Tage Resturlaub in dieses Jahr mitgeschleppt habe und mir pro Jahr auch noch je 30 Tage regulärer Urlaub zusteht, habe ich diese 80 Tage auch noch abgezogen. Die Feiertage habe ich nicht berücksichtigt, mir reicht diese grobe Schätzung.

Da die Differenz zweier `datetime`-Objekte wieder ein `datetime`-Objekt ist, muß die Umwandlung in einen *String* explizit mittels *Typecasting* vorgenommen werden und bei der Division durch sieben ist zu beachten, daß das Processing.py zugrundelegende Jython ein Python 2.7 ist und deshalb bei einer Integer-Division alle Nachkommastellen abschneidet (zum Beispiel ergibt `13/7` eine `1`, dieses -- dokumentierte -- Verhalten wurde in Python 3 geändert). Um das zu vermeiden, habe ich durch `7.0` geteilt und so eine Float-Division erzwungen und durch ein anschließendes Runden das Ergebnis doch wieder in eine Integer-Zahl verwandelt.

Jetzt das komplette Skript zum Nachlesen und Nachprogrammieren:

~~~python
import datetime as dt

def setup():
    size(640, 480)
    font = createFont("Coda-Heavy.ttf", 96)
    textFont(font)

def draw():
    background("#000000")
    myNow = dt.datetime.now()
    myHour = str(myNow.hour)
    myMinute = str(myNow.minute).rjust(2, "0")
    mySecond = str(myNow.second).rjust(2, "0")
    myTime = myHour + " : " + myMinute + " : " + mySecond
    textSize(96)
    text(myTime, 60, 150)
    rente = dt.date(2018, 12, 31)
    heute = dt.date.today()
    differenz = rente - heute
    myDays = str(differenz.days)
    workingDays = float(myDays)/7.0 * 5
    workingDays = str(int(workingDays - 80))
    myText = u"Lieber Jörg, es sind nur noch " + myDays + \
    u" Tage bis zu Deiner Rente!\nDas sind etwa " + \
    workingDays + " Arbeits- tage. Das schaffst Du!"
    textSize(32)
    text(myText, 60, 200, 540, 300)
~~~

Wegen des Umlautes in meinem Vornamen, mußte ich mit `u"…"` die Umwandlung des Strings in einen UTF-8-String erzwingen (auch das ist Python 3 nicht mehr nötig), aber wie der obige Screenshot zeigt, wird dann der Umlaut auch brav angezeigt.

Die Funktion `text()` kann man in Processing einmal mit drei und einmal mit fünf Parametern aufrufen. Im ersten Fall übergibt man den Text und die x- und y-Koordinaten der linken Grundlinie des Textes. Im zweiten Fall kommen noch die Weite und die Höhe der Textbox hinzu. Damit erreicht man, daß ein langer String an den Textbox-Grenzen umgebrochen wird und der Text nicht aus dem Fenster herausläuft. Die Parameter habe ich durch einfaches Ausprobieren bekommen.

[3]: http://cognitiones.kantel-chaos-team.de/programmierung/pascal.html
[5]: https://fonts.google.com/specimen/Coda
[6]: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL_web


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _lodash = require('lodash.clonedeep');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var createPlotlyComponent = function createPlotlyComponent(plotlyInstance) {
  var _class, _temp;

  return _temp = _class = function (_React$Component) {
    _inherits(Plotly, _React$Component);

    function Plotly() {
      _classCallCheck(this, Plotly);

      return _possibleConstructorReturn(this, (Plotly.__proto__ || Object.getPrototypeOf(Plotly)).apply(this, arguments));
    }

    _createClass(Plotly, [{
      key: 'attachListeners',
      value: function attachListeners() {
        if (this.props.onClick) this.container.on('plotly_click', this.props.onClick);
        if (this.props.onBeforeHover) this.container.on('plotly_beforehover', this.props.onBeforeHover);
        if (this.props.onHover) this.container.on('plotly_hover', this.props.onHover);
        if (this.props.onUnHover) this.container.on('plotly_unhover', this.props.onUnHover);
        if (this.props.onSelected) this.container.on('plotly_selected', this.props.onSelected);
      }
    }, {
      key: 'shouldComponentUpdate',
      value: function shouldComponentUpdate(nextProps) {
        //TODO logic for detecting change in props
        return true;
      }
    }, {
      key: 'componentDidMount',
      value: function componentDidMount() {
        var _props = this.props,
            data = _props.data,
            layout = _props.layout,
            config = _props.config;

        plotlyInstance.newPlot(this.container, data, (0, _lodash2.default)(layout), config); //We clone the layout as plotly mutates it.
        this.attachListeners();
      }
    }, {
      key: 'componentDidUpdate',
      value: function componentDidUpdate(prevProps) {
        //TODO use minimal update for given changes
        if (prevProps.data !== this.props.data || prevProps.layout !== this.props.layout || prevProps.config !== this.props.config) {
          var _props2 = this.props,
              data = _props2.data,
              layout = _props2.layout,
              config = _props2.config;

          plotlyInstance.newPlot(this.container, data, (0, _lodash2.default)(layout), config); //We clone the layout as plotly mutates it.
          this.attachListeners();
        }
      }
    }, {
      key: 'componentWillUnmount',
      value: function componentWillUnmount() {
        plotlyInstance.purge(this.container);
      }
    }, {
      key: 'resize',
      value: function resize() {
        plotlyInstance.Plots.resize(this.container);
      }
    }, {
      key: 'render',
      value: function render() {
        var _this2 = this;

        var _props3 = this.props,
            data = _props3.data,
            layout = _props3.layout,
            config = _props3.config,
            other = _objectWithoutProperties(_props3, ['data', 'layout', 'config']);
        //Remove props that would cause React to warn for unknown props.

        delete other.onClick;
        delete other.onBeforeHover;
        delete other.onHover;
        delete other.onUnHover;
        delete other.onSelected;

        return _react2.default.createElement('div', _extends({}, other, { ref: function ref(node) {
            return _this2.container = node;
          } }));
      }
    }]);

    return Plotly;
  }(_react2.default.Component), _class.propTypes = {
    data: _propTypes2.default.array,
    layout: _propTypes2.default.object,
    config: _propTypes2.default.object,
    onClick: _propTypes2.default.func,
    onBeforeHover: _propTypes2.default.func,
    onHover: _propTypes2.default.func,
    onUnHover: _propTypes2.default.func,
    onSelected: _propTypes2.default.func
  }, _temp;
};

exports.default = createPlotlyComponent;


text:
<?php

/**
 * ezcMailParserShutDownHandler removes temporary files
 * and directories when PHP shuts down.
 *
 * Example:
 * <code>
 * ezcMailParserShutdownHandler::registerForRemoval( "/tmp/file.txt" );
 * </code>
 *
 * The code above will result in file.txt being removed from the system
 * (if it still exists) when PHP shuts down.
 *
 * @package Mail
 * @version 1.7.1
 * @access private
 */
class ezcMailParserShutdownHandler
{
    /**
     * Holds if the handler is registered or not.
     *
     * @var boolean
     */
    private static $isRegistered = false;

    /**
     * Holds the array of directories that are marked for removal
     * when PHP shuts down.
     *
     * @var array(string)
     */
    private static $directories = array();

    /**
     * Registers the directory $dir for removal when PHP shuts down.
     *
     * The directory and all of its contents will be removed recursively.
     *
     * @param string $dir
     */
    public static function registerForRemoval( $dir )
    {
        if ( self::$isRegistered === false )
        {
            register_shutdown_function( array( "ezcMailParserShutdownHandler", "shutdownCallback" ) );
            self::$isRegistered = true;
        }
        self::$directories[] = $dir;
    }

    /**
     * Recursively deletes all registered folders and any contents of the registered
     * directories.
     *
     * Files or directories that can't be deleted are left without warning.
     *
     * @return void
     */
    public static function shutdownCallback()
    {
        foreach ( self::$directories as $directory )
        {
            self::remove( $directory );
        }
    }

    /**
     * Recursively removes a directory and its contents or a file.
     *
     * Returns true on success and false on error.
     *
     * @param string $itemName
     * @return bool
     */
    public static function remove( $itemName )
    {
        $returnVar = true;
        if ( !is_dir( $itemName ) && file_exists( $itemName ) )
        {
            unlink( $itemName );
            return true;
        }

        if ( !file_exists( $itemName ) )
        {
            return true;
        }

        $dir = dir( $itemName );
        $item = $dir->read();
        while ( $item !== false )
        {
            if ( $item != '.' && $item != '..' )
            {
                self::remove( $dir->path . DIRECTORY_SEPARATOR . $item );
                $returnVar = false;
            }
            $item = $dir->read();
        }

        $dir->close();
        $returnVar = rmdir( $itemName ) && $returnVar ? true : false; // if rmdir succeeds and everything else succeeded
        return $returnVar;
    }
}

?>


text:
package org.apache.camel.component.yammer;

import java.util.Map;

import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;

/**
 * Represents the component that manages {@link YammerEndpoint}.
 */
public class YammerComponent extends DefaultComponent {

    private String consumerKey;
    private String consumerSecret;
    private String accessToken;
    private YammerConfiguration config;

    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        // by default use config for each endpoint; use from component level if one has been explicitly set
        YammerConfiguration endpointConfig = getConfig();
        if (endpointConfig == null) {
            endpointConfig = new YammerConfiguration();
        }

        // set options from component
        endpointConfig.setConsumerKey(consumerKey);
        endpointConfig.setConsumerSecret(consumerSecret);
        endpointConfig.setAccessToken(accessToken);
        endpointConfig.setFunction(remaining);
        endpointConfig.setFunctionType(YammerFunctionType.fromUri(remaining));

        // and then override from parameters
        setProperties(endpointConfig, parameters);

        Endpoint endpoint = new YammerEndpoint(uri, this, endpointConfig);
        setProperties(endpoint, parameters);
        return endpoint;
    }

    public String getConsumerKey() {
        return consumerKey;
    }

    public void setConsumerKey(String consumerKey) {
        this.consumerKey = consumerKey;
    }

    public String getConsumerSecret() {
        return consumerSecret;
    }

    public void setConsumerSecret(String consumerSecret) {
        this.consumerSecret = consumerSecret;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public YammerConfiguration getConfig() {
        return config;
    }

    public void setConfig(YammerConfiguration config) {
        this.config = config;
    }
}


text:
var gulp = require('gulp');
var uglify = require('gulp-uglify');

gulp.task('default',function(){
    gulp.src('./src/**/*.js')
        //.pipe(uglify())
        //.pipe()
        .pipe(gulp.dest('./js/libs/'))
});

var watcher = gulp.watch('src/**/*.js',['default']);
watcher.on('change',function(event){
    console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});


text:
'use strict';

var rhea = require('rhea');
var util = require('util');
var log = require("./log.js").logger();
var crypto = require('crypto');
var uuidv5 = require('uuid/v5');

module.exports.remove = function (list, predicate) {
    var count = 0;
    for (var i = 0; i < list.length;) {
        if (predicate(list[i])) {
            list.splice(i, 1);
            count++;
        } else {
            i++;
        }
    }
    return count;
};

module.exports.replace = function (list, object, match) {
    for (var i = 0; i < list.length; i++) {
        if (match(list[i])) {
            list[i] = object;
            return true;
        }
    }
    return false;
};

module.exports.merge = function () {
    return Array.prototype.slice.call(arguments).reduce(function (a, b) {
        for (var key in b) {
            a[key] = b[key];
        }
        return a;
    });
}

module.exports.basic_auth = function (request) {
    if (request.headers.authorization) {
        var parts = request.headers.authorization.split(' ');
        if (parts.length === 2 && parts[0].toLowerCase() === 'basic') {
            parts = new Buffer(parts[1], 'base64').toString().split(':');
            return { username: parts[0], password: parts[1] };
        } else {
            throw new Error('Cannot handle authorization header ' + request.headers.authorization);
        }
    }
}

function self(o) {
    return o;
}

module.exports.index = function (a, key, value) {
    var fk = key || self;
    var fv = value || self;
    var m = {};
    a.forEach(function (i) { m[fk(i)] = fv(i); });
    return m;
}

module.exports.values = function (map) {
    var v = [];
    for (var k in map) {
        v.push(map[k]);
    }
    return v;
}

module.exports.separate = function (map, predicate, a, b) {
    for (var k in map) {
        var v = map[k];
        if (predicate(v)) {
            a[k] = v;
        } else {
            b[k] = v;
        }
    }
}

module.exports.difference = function (a, b, equivalent) {
    var diff = {};
    for (var k in a) {
	if (!equivalent(b[k], a[k])) {
	    diff[k] = a[k];
	}
    }
    return diff;
}

module.exports.match_source_address = function (link, address) {
    return link && link.local && link.local.attach && link.local.attach.source
        && link.local.attach.source.value[0].toString() === address;
}

function hash(s) {
    var h = 0;
    for (var i = 0; i < s.length; i++) {
        h = ((h << 5) - h) + s.charCodeAt(i) | 0;
    }
    return h;
};

module.exports.hash = hash;

const MAX_KUBE_NAME = 63/*max allowed*/ - 3/*needed for kube to add stateful set qualifier*/;
module.exports.kubernetes_name = function (name) {
    var clean = name.toLowerCase().replace(/[^a-z0-9\-\.]/g, '');
    if (clean.length > MAX_KUBE_NAME) clean = clean.substring(0, MAX_KUBE_NAME);
    if (clean.charAt(0) === '-' || clean.charAt(0) === '.') clean = clean.substring(1);
    if (clean.charAt(clean.length-1) === '-' || clean.charAt(clean.length-1) === '.') clean = clean.substring(0,clean.length-1);

    var qualifier = rhea.generate_uuid();
    clean += '.' + qualifier;
    return clean;
}

module.exports.serialize = function (f, retry_timeout = 5000) {
    var in_progress = false;
    var pending = false;
    var timeout = null;
    function doIt() {
        if (in_progress) {
            pending = true;
        } else {
            in_progress = true;
            execute();
        }
    }
    function scheduleRetry (error) {
        if (retry_timeout) {
            log.warn("Rescheduling failed serialized func (%s) in %dms.", error, retry_timeout);
            timeout = setTimeout(doIt, retry_timeout);
        }
    }
    function cancelRetry() {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
    }
    function execute() {
        try {
            f().then(function () {
                if (pending) {
                    next();
                } else {
                    in_progress = false;
                }
            }).catch(function(error) {
                in_progress = false;
                scheduleRetry(error);
            });
        } catch (error) {
            in_progress = false;
            scheduleRetry(error);
        }
    }
    function next() {
        pending = false;
        setImmediate(execute);
    };
    return function() {
        cancelRetry();
        doIt();
    }
};

module.exports.string_compare = function (a, b) {
    if (a === b) return 0;
    else if (a < b) return -1;
    else return 1;
};

//return changes between two sorted lists
module.exports.changes = function (last, current, compare, unchanged, stringify) {
    let description = stringify || JSON.stringify;
    if (last === undefined) {
        return {
            added: current,
            removed: [],
            modified: [],
            description: util.format('initial %s', description(current))
        };
    } else {
        let d = {
            added: [],
            removed: [],
            modified: []
        };
        let i = 0, j = 0;
        while (i < last.length && j < current.length) {
            switch (compare(last[i], current[j])) {
            case 0:
                //same address, has it changed?
                if (unchanged && !unchanged(last[i], current[j])) {
                    d.modified.push(current[j]);
                }
                i++; j++;
                break;
            case 1:
                //current[j] comes before last[i], therefore it is not in last
                d.added.push(current[j++]);
                break;
            case -1:
                //last[i] comes before current[j], therefore it is not in current
                d.removed.push(last[i++]);
                break;
            }
        }
        while (i < last.length) {
            //remaining items were in last but not in current
            d.removed.push(last[i++]);
        }
        while (j < current.length) {
            //remaining items are in current but not in last
            d.added.push(current[j++]);
        }
        if (d.added.length || d.removed.length || d.modified.length) {
            var parts = [];
            for (let k in d) {
                if (d[k].length) {
                    parts.push(util.format('%s %s', k, description(d[k])));
                }
            }
            d.description = parts.join(', ');
            return d;
        } else {
            return undefined;
        }
    }
};

module.exports.coalesce = function (f, delay, max_delay) {
    var start, scheduled, timeout = undefined;
    var timeout = undefined;

    function fire() {
        start = undefined;
        timeout = undefined;
        f();
    }

    function can_delay() {
        return start && scheduled < (start + max_delay);
    }

    function schedule() {
        timeout = setTimeout(fire, delay);
        scheduled = Date.now() + delay;
    }

    return function () {
        if (timeout) {
            if (can_delay()) {
                clearTimeout(timeout);
                schedule();
            } // else just wait for previously scheduled call
        } else {
            start = Date.now();
            schedule();
        }
    }
};

module.exports.get = function (object, fields, default_value) {
    var o = object;
    for (var i = 0; o && i < fields.length; i++) {
        o = o[fields[i]];
    }
    return o || default_value;
};

var multipliers = {};
multipliers.B = 1;
multipliers.KB = ( multipliers.B * 1024 );
multipliers.MB = ( multipliers.KB * 1024 );
multipliers.GB = ( multipliers.MB * 1024 );
multipliers.TB = ( multipliers.GB * 1024 );
multipliers.PB = ( multipliers.TB * 1024 );
multipliers.EB = ( multipliers.PB * 1024 );
multipliers.ZB = ( multipliers.EB * 1024 );

module.exports.parseToBytes = function (input) {
    var unit = input.toUpperCase().match(/([KMGTPEZ]I?)?B$/);

    if (!unit) {
        log.warn( "parseToBytes input does not contain a supported unit of measurement.  Using 'B': %s", input );
        unit = "B";
    }
    unit = unit[ 0 ].replace( /i/i, "" );

    var value = parseFloat(input);
    if (isNaN(value)) {
        log.error( "parseToBytes input does not contain a numeric value: %s",input );
        return 0;
    }

    return( value * multipliers[unit] );
};

module.exports.same_status_messages = function(a, b) {
    if (a === b) {
        return true;
    } else if (a == null || b == null || a.length !== b.length) {
        return false;
    }

    for (var i in a) {
        if (!b.includes(a[i])) {
            return false;
        }
    }
    return true;
};

module.exports.same_ttl = function (a, b) {
    if (a === b) return true;
    return a && b && a.minimum === b.minimum && a.maximum === b.maximum;
};

module.exports.same_message_redelivery = function (a, b) {
    if (a === b) return true;
    return a && b && a.maximumDeliveryAttempts === b.maximumDeliveryAttempts
        && a.redeliveryDelay === b.redeliveryDelay
        && a.redeliveryDelayMultiplier === b.redeliveryDelayMultiplier
        && a.maximumDeliveryDelay === b.maximumDeliveryDelay;
};

module.exports.description = function description(list, name) {
    const max = 5;
    if (list.length > max) {
        return list.slice(0, max).map(name).join(', ') + ' and ' + (list.length - max) + ' more';
    } else {
        return JSON.stringify(list.map(name));
    }
};

module.exports.generate_stable_uuid = function() {
    var hash = crypto.createHash('sha1');
    for (var i = 0, j = arguments.length; i < j; i++){
        var argument = arguments[i];
        if (argument) {
            hash.update(argument);
        }
    }
    var ba = [];
    ba.push(...hash.digest().slice(0, 16));
    const ns = "3751f842-240e-48b9-89b5-5b47f04e931b";
    return uuidv5(ns, ba);
}