text:
// 'toS3' module

var ALREADY_EXISTS = 'file already exists on remote',
    SUCCESS_UPLOAD = 'file uploaded';

var s3 = require('s3'),
    knox = require('knox'),
    crypto = require('crypto'),
    Q = require('q'),
    path = require('path');

exports.upload = function (filePathToBackup, numberOfPathPartsToStrip, prependText, fileStream, awsBucket, awsAccessKey, awsSecretKey) {

    return exports.setInputOutputPaths(filePathToBackup, numberOfPathPartsToStrip, prependText)
    .then(function (results) {
        var inputPath = results.inputPath,
            outputPath = results.outputPath;

        console.log('About to upload ' + inputPath + ' to S3 as ' + outputPath);

        var client = knox.createClient({
            key: awsAccessKey,
            secret: awsSecretKey,
            bucket: awsBucket
        });

        return Q.all([
            exports.md5Calc(fileStream),
            exports.etagLookup(client, outputPath),
            Q({ inputPath: inputPath, outputPath: outputPath })
        ]);
    })
    .then(function (results) {
        /*

        returns promise.

        results = [ { md5: '095ccfae4084dc5133efb77efe851926' },
          { etag: '095ccfae4084dc5133efb77efe851926' }
          { inputPath: xxx, outputPath: yyy } ]

         */
        return exports.uploadIfNotAlreadyOnS3(results, awsAccessKey, awsSecretKey, awsBucket);
    })
    .then(function (results) {
        console.log(results);

        // // console.log("steps run: ", results);
        // if (searchStringInArray(ALREADY_EXISTS, results) > -1) {
        //     console.log('...skipping, already uploaded.');
        // }
        // if (searchStringInArray(SUCCESS_UPLOAD, results) > -1) {
        //     console.log('...uploaded successfully.');
        // }
        process.exit(0);
    })
    .catch(function (error) {
        console.log('CATCH ERROR > ', error);
        // console.log("steps run: ", results);
        process.exit(1);
    })
    .done();
};

exports.setInputOutputPaths = function (filepath, numberOfPathPartsToStrip, prependText) {
    newPath = exports.stripPath(filepath, numberOfPathPartsToStrip),
    inputPath = newPath.input,
    outputPath = newPath.output;

    if (prependText && typeof prependText === 'string' && prependText.length > 0) {
        outputPath = [prependText, outputPath].join('');
    }

    return Q({inputPath: inputPath, outputPath: outputPath});
};

exports.md5Calc = function (fileStream) {
    // console.log('START md5 calc');
    var deferred = Q.defer();
    var md5sum = crypto.createHash('md5');
    var s = fileStream;
    s.on('data', function (d) {
        md5sum.update(d);
    });
    s.on('error', function (e) {
        deferred.reject(new Error(e));
    });
    s.on('end', function () {
        md5 = md5sum.digest('hex');
        deferred.resolve({md5: md5});
    });
    return deferred.promise;
};

exports.etagLookup = function (client, filePathToBackup) {
    // console.log('START remote etag head request');
    var deferred = Q.defer();
    client.head(exports.encodeURI(filePathToBackup))
    .on('response', function (res) {
        etag = res.headers.etag;
        if (typeof etag === 'string' && etag.length > 0) {

            // Strip of doublequote that knox Client.head() returns around the etag string
            etag = etag.replace(/"/g, '');
            deferred.resolve({etag: etag});
        } else {
            deferred.resolve({etag: ''});
        }
    })
    .on('error', function (err) {
        deferred.reject(new Error("When checking remote file's etag, this error occurred: " + err + ". Not connected to internet?"));
    })
    .end();

    return deferred.promise;
};

// http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

// returns an object with an input and output key
exports.stripPath = function (filePathToBackup, numberOfPathPartsToStrip) {
    var basename = path.basename(filePathToBackup),
        input = filePathToBackup,
        output;

    if (numberOfPathPartsToStrip && isNumber(numberOfPathPartsToStrip)) {
        var newPathArray = path.dirname(filePathToBackup).split(path.sep),
            slicedPathArray = newPathArray.slice(numberOfPathPartsToStrip + 1); // skip leading / in array
        slicedPathArray.unshift('');    // add back leading /
        output = slicedPathArray.join(path.sep) + path.sep + basename;
    } else {
        output = input;
    }

    // console.log(input, output);
    return { input: input, output: output };
};

exports.uploadFile = function (client, inputPath, outputPath) {
    var deferred = Q.defer(),
        uploader = client.upload(inputPath, encodeURI(outputPath));

    uploader.on('error', function (err) {
        // console.error("unable to upload:", err);
        deferred.reject(new Error('unable to upload ' + inputPath + ' due to ' + err));
    });
    uploader.on('progress', function (amountDone, amountTotal) {
        console.log("progress: ", Math.round(Number((amountDone/amountTotal) * 100)), "%");
        deferred.notify("progress: " + Math.round(Number((amountDone/amountTotal) * 100)) + "%");
        //process.stdout.write(''+Math.round(Number((amountDone/amountTotal) * 100))+', ');
    });
    uploader.on('end', function (url) {
        // console.log("file available at", url);
        deferred.resolve({message: SUCCESS_UPLOAD});
    });
    return deferred.promise;
};

exports.searchStringInArray = function (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str)) return j;
    }
    return -1;
};

exports.encodeURI = function (path) {
    var newPath = path;
    if (path.charAt(0) === '/') {
        newPath = path.slice(1);
    }
    return encodeURIComponent(newPath);
};

exports.hashesAreTheSame = function (md5, etag) {
    if (md5 === etag) {
        return true;
    }
    return false;
};

exports.createS3Client = function (awsAccessKey, awsSecretKey, awsBucket) {
    return s3.createClient({
        key: awsAccessKey,
        secret: awsSecretKey,
        bucket: awsBucket
    });
};

exports.uploadIfNotAlreadyOnS3 = function (results, awsAccessKey, awsSecretKey, awsBucket) {
    var md5,
        etag,
        inputPath,
        outputPath;

    if (results && results.length === 3 && typeof results[0].md5 === 'string' && results[0].md5.length > 0) {
        md5 = results[0].md5;
        etag = results[1].etag;
        inputPath = results[2].inputPath;
        outputPath = results[2].outputPath;
        if (exports.hashesAreTheSame(md5, etag)) {
            return Q({message: 'file already uploaded'});
        } else {
            var client = exports.createS3Client(awsAccessKey, awsSecretKey, awsBucket);
            // upload a file to s3
            return exports.uploadFile(client, inputPath, outputPath);
        }
    } else {
        return Q.reject(new Error('results not expected'));
    }
};


text:
package org.jglfont.impl.format;

import java.util.Hashtable;
import java.util.Map;

/**
 * Informations for an individual character in a JGLAbstractFontData.
 * @author void
 */
public class JGLFontGlyphInfo {
  /**
   * id.
   */
  private int id;

  /**
   * x position.
   */
  private int x;

  /**
   * y position.
   */
  private int y;

  /**
   * width.
   */
  private int width;

  /**
   * height.
   */
  private int height;

  /**
   * xoffset.
   */
  private int xoffset;

  /**
   * yoffset.
   */
  private int yoffset;

  /**
   * xadvance.
   */
  private int xadvance;

  /**
   * page.
   */
  private String page;

  /**
   * kerning information.
   */
  private Map<Integer, Integer> kerning = new Hashtable<Integer, Integer>();

  /**
   * @return the id
   */
  public int getId() {
    return id;
  }

  /**
   * @param id the id to set
   */
  public void setId(final int id) {
    this.id = id;
  }

  /**
   * @return the x
   */
  public int getX() {
    return x;
  }

  /**
   * @param x the x to set
   */
  public void setX(final int x) {
    this.x = x;
  }

  /**
   * @return the y
   */
  public int getY() {
    return y;
  }

  /**
   * @param y the y to set
   */
  public void setY(final int y) {
    this.y = y;
  }

  /**
   * @return the width
   */
  public int getWidth() {
    return width;
  }

  /**
   * @param width the width to set
   */
  public void setWidth(final int width) {
    this.width = width;
  }

  /**
   * @return the height
   */
  public int getHeight() {
    return height;
  }

  /**
   * @param height the height to set
   */
  public void setHeight(final int height) {
    this.height = height;
  }

  /**
   * @return the xoffset
   */
  public int getXoffset() {
    return xoffset;
  }

  /**
   * @param xoffset the xoffset to set
   */
  public void setXoffset(final int xoffset) {
    this.xoffset = xoffset;
  }

  /**
   * @return the yoffset
   */
  public int getYoffset() {
    return yoffset;
  }

  /**
   * @param yoffset the yoffset to set
   */
  public void setYoffset(final int yoffset) {
    this.yoffset = yoffset;
  }

  /**
   * @return the xadvance
   */
  public int getXadvance() {
    return xadvance;
  }

  /**
   * @param xadvance the xadvance to set
   */
  public void setXadvance(final int xadvance) {
    this.xadvance = xadvance;
  }

  /**
   * @return the page
   */
  public String getPage() {
    return page;
  }

  /**
   * @param page the page to set
   */
  public void setPage(final String page) {
    this.page = page;
  }

  /**
   * @return the kerning
   */
  public Map<Integer, Integer> getKerning() {
    return kerning;
  }

  /**
   * @param kerning the kerning to set
   */
  public void addKerning(final Integer character, final Integer kerning) {
    this.kerning.put(character, kerning);
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using Grasshopper.Kernel;
using Grasshopper;
using Grasshopper.Kernel.Data;
using Grasshopper.Kernel.Types;
using IvyGh.Type;

namespace IvyGh
{
    public class Comp_InterpolateFields : GH_Component
    {
        GH_Grid ghGrid;
        IvyCore.MultiDimGrid.Point point;
        double[] coord;

        public override Guid ComponentGuid
        {
            get { return new Guid("{fb7a200f-ce71-4a54-9be1-d9374700b6e5}"); }
        }

        public Comp_InterpolateFields()
          : base("Field Lerp Interpolation", "Lerp",
              "Interpolate a list of fields (as a tree).",
              "Ivy", "Interpolation")
        {
        }

        protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
        {
            pManager.AddGenericParameter("Interpolants", "I", "A list of interpolant.", GH_ParamAccess.list);
            pManager.AddNumberParameter("Fields", "F", "The fields to interpolate.", GH_ParamAccess.tree);
            pManager[0].Optional = false;
            pManager[1].Optional = false;
        }

        protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
        {
            pManager.AddNumberParameter("Interpolated Fields", "IF", "The interpolated fields at the given point in the grid.", GH_ParamAccess.tree);
        }

        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var ghInterps = new List<GH_Interpolant>();
            var ghFields = new GH_Structure<GH_Number>();

            if (!DA.GetDataList(0, ghInterps)) { return; }
            if (!DA.GetDataTree(1, out ghFields)) { return; }

            var res = new DataTree<double>();

            int n = ghInterps.Count;

            // loop over interpolants
            for (int k = 0; k < n; k++)
            {
                var interpolant = ghInterps[k].Value;

                if (ghFields.Paths[0].Length == 1)
                {
                    // this is a scalar field (dim = 1)
                    // the tree is a list of list (1 level)
                    double fval;
                    for (int i = 0; i < ghFields.Branches.Count; i++)
                    {
                        var path = new GH_Path(k,i);
                        var field = ghFields.Branches[i].ConvertAll<double>(gh => gh.Value);
                        fval = interpolant.Lerp(field);
                        res.Add(fval, path);
                    }
                }
                else
                {
                    // this is a vector field
                    // the tree is 2 level 2 tree
                    int dim = ghFields.Branches[0].Count;
                    int fieldIndex = 0;
                    int nodeIndex = 0;
                    var field = new List<double[]>();
                    double[] fval;

                    for (int i = 0; i < ghFields.PathCount; i++)
                    {
                        var path = ghFields.Paths[i];
                        if (path[0] > fieldIndex)
                        {
                            fval = interpolant.Lerp(field);
                            res.AddRange(fval, new GH_Path(k,fieldIndex));
                            nodeIndex = 0;
                            fieldIndex = path[0];
                            field.Clear();
                        }

                        field.Add(ghFields.Branches[i].ConvertAll<double>(gh => gh.Value).ToArray());
                        nodeIndex += 1;

                    }
                    fval = interpolant.Lerp(field);
                    res.AddRange(fval, new GH_Path(k, fieldIndex));
                }
            }

            DA.SetDataTree(0, res);
        }

    }
}


text:
/**
 * ViewBase.js
 *
 * Application-specific tailorings of Backbone.View go here.
 *
 */
(function (spiderOakApp, window, undefined) {
  "use strict";
  var console = window.console || {};
  console.log = console.log || function(){};
  var Backbone    = window.Backbone,
      _           = window._,
      $           = window.$,
      s           = window.s;

  spiderOakApp.ViewBase = Backbone.View.extend({
    /** Compatability for pre-Backbone 1.1 versions. */
    constructor: function(options) {
      this.options = options;
      Backbone.View.apply(this, arguments);
    }
  });

})(window.spiderOakApp = window.spiderOakApp || {}, window);


text:
<!DOCTYPE html>

    <title></title>

Try touching within each box with multiple fingers

            Touches in this box will invoke default pan and zoom behaviors

            This box has touch-action set to none


text:
<template name="favoriteButton">
    {{#if isFavorite _id}}
        {{> favoriteButtonFavorited _id=_id}}
    {{else}}
        {{> favoriteButtonNotFavorited _id=_id}}
    {{/if}}
</template>

<template name="favoriteButtonFavorited">
     Favorito
</template>

<template name="favoriteButtonNotFavorited">

         Favorito
</template>


text:
package org.jenkinsci.remoting.protocol.impl;

import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.jenkinsci.remoting.protocol.FilterLayer;
import org.jenkinsci.remoting.util.ByteBufferUtils;

public class BatchSendBufferingFilterLayer extends FilterLayer implements Cloneable {

    private final ByteBuffer batch;
    private final Object lock = new Object();

    public BatchSendBufferingFilterLayer(int length) {
        this.batch = ByteBuffer.allocate(length);
    }

    public BatchSendBufferingFilterLayer clone() {
        return new BatchSendBufferingFilterLayer(batch.capacity());
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("BatchSendBufferingFilterLayer{");
        sb.append("length=").append(batch.capacity());
        sb.append('}');
        return sb.toString();
    }

    @Override
    public void onRecv(@NonNull ByteBuffer data) throws IOException {
        next().onRecv(data);
    }

    @Override
    public void doSend(@NonNull ByteBuffer data) throws IOException {
        synchronized (lock) {
            while (data.hasRemaining()) {
                if (batch.hasRemaining()) {
                    ByteBufferUtils.put(data, batch);
                }
                if (!batch.hasRemaining()) {
                    batch.flip();
                    while (batch.hasRemaining()) {
                        next().doSend(batch);
                    }
                    batch.clear();
                }
            }
        }
    }

    public void flush() throws IOException {
        synchronized (lock) {
            if (batch.position() > 0) {
                batch.flip();
                while (batch.hasRemaining()) {
                    next().doSend(batch);
                }
                batch.clear();
            }
        }
    }
}


text:
LambdaWars
==========

RoboWars in Haskell for the London Haskell User group.

The mailing list for this project is the [Lambda Wars Google Group](https://groups.google.com/forum/?fromgroups#!forum/lambdawars)

Check out the [project overview](https://github.com/andreyLevushkin/LambdaWars/wiki/Project-Overview) wiki page for the aims.

## How to run
    cabal install
    LambdaWars

... then visit [http://localhost:8000/](http://localhost:8000/).

if cabal complains about missing dependencies for example:
    cabal: At least the following dependencies are missing:
    snap-core ==0.9.2.2, snap-server ==0.9.2.4

Run cabal install ${list of missing dependencies}, in the above example that would be

    cabal install snap-core-0.9.2.2 snap-server-0.9.2.4

## How to run tests
    cabal configure --enable-tests
    cabal build
    cabal test

## To get up and running in GHCi
from the LambdaWars directory (just above src) run:

    ghci -i:src:tests:examples

and the you can use

    :l modulename

to load any of the modules.


text:
@class RDSManager;
@class NSManagedObject;
@class RDSObjectControllerConfiguration;

@interface RDSObjectViewController : UIViewController

@property (nonatomic, strong) RDSManager* _Nonnull rdsManager;
@property (nonatomic, strong, readonly) NSArray<RDSObjectControllerConfiguration*>* _Nonnull configurations;

- (void) addConfigurationWithObject:(NSManagedObject* _Nonnull )object keyPath:( NSString* _Nullable )keypath;

@end


text:
using mojo::ApplicationConnection;
using mojo::ApplicationImpl;
using mojo::Gpu;
using mojo::InterfaceRequest;
using mojo::ViewManagerRoot;
using mojo::ViewManagerService;

namespace view_manager {

ViewManagerApp::ViewManagerApp() : app_impl_(nullptr), is_headless_(false) {
}

ViewManagerApp::~ViewManagerApp() {}

void ViewManagerApp::Initialize(ApplicationImpl* app) {
  app_impl_ = app;
  tracing_.Initialize(app);

#if !defined(OS_ANDROID)
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  is_headless_ = command_line->HasSwitch(mojo::kUseHeadlessConfig);
  if (!is_headless_) {
    event_source_ = ui::PlatformEventSource::CreateDefault();
    if (command_line->HasSwitch(mojo::kUseTestConfig))
      gfx::GLSurface::InitializeOneOffForTests();
    else
      gfx::GLSurface::InitializeOneOff();
  }
#endif

  if (!gpu_state_.get())
    gpu_state_ = new gles2::GpuState;
  connection_manager_.reset(new ConnectionManager(this));
}

bool ViewManagerApp::ConfigureIncomingConnection(
    ApplicationConnection* connection) {
  connection->AddService<ViewManagerRoot>(this);
  connection->AddService<Gpu>(this);

  return true;
}

void ViewManagerApp::OnNoMoreRootConnections() {
  app_impl_->Terminate();
}

ClientConnection* ViewManagerApp::CreateClientConnectionForEmbedAtView(
    ConnectionManager* connection_manager,
    mojo::InterfaceRequest<mojo::ViewManagerService> service_request,
    mojo::ConnectionSpecificId creator_id,
    mojo::URLRequestPtr request,
    const ViewId& root_id) {
  mojo::ViewManagerClientPtr client;
  app_impl_->ConnectToService(request.Pass(), &client);

  scoped_ptr<ViewManagerServiceImpl> service(
      new ViewManagerServiceImpl(connection_manager, creator_id, root_id));
  return new DefaultClientConnection(service.Pass(), connection_manager,
                                     service_request.Pass(), client.Pass());
}

ClientConnection* ViewManagerApp::CreateClientConnectionForEmbedAtView(
    ConnectionManager* connection_manager,
    mojo::InterfaceRequest<mojo::ViewManagerService> service_request,
    mojo::ConnectionSpecificId creator_id,
    const ViewId& root_id,
    mojo::ViewManagerClientPtr view_manager_client) {
  scoped_ptr<ViewManagerServiceImpl> service(
      new ViewManagerServiceImpl(connection_manager, creator_id, root_id));
  return new DefaultClientConnection(service.Pass(), connection_manager,
                                     service_request.Pass(),
                                     view_manager_client.Pass());
}

void ViewManagerApp::Create(ApplicationConnection* connection,
                            InterfaceRequest<ViewManagerRoot> request) {
  DCHECK(connection_manager_.get());
  // TODO(fsamuel): We need to make sure that only the window manager can create
  // new roots.
  scoped_ptr<ViewManagerRootImpl> view_manager_root(
      new ViewManagerRootImpl(
          connection_manager_.get(),
          is_headless_,
          app_impl_,
          gpu_state_));

  mojo::ViewManagerClientPtr client;
  connection->ConnectToService(&client);

  // ViewManagerRootConnection manages its own lifetime.
  new ViewManagerRootConnectionImpl(request.Pass(),
                                    view_manager_root.Pass(),
                                    client.Pass(),
                                    connection_manager_.get());
}

void ViewManagerApp::Create(
    mojo::ApplicationConnection* connection,
    mojo::InterfaceRequest<Gpu> request) {
  if (!gpu_state_.get())
    gpu_state_ = new gles2::GpuState;
  new gles2::GpuImpl(request.Pass(), gpu_state_);
}

void ViewManagerApp::OnConnectionError() {
  app_impl_->Terminate();
}

}  // namespace view_manager


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.spi.api (BOM:  * : All 2.5.0.Final API)</title>
<meta name="date" content="2019-07-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.wildfly.swarm.spi.api

Interfaces

ArtifactLookup

ClassLoading

ConfigurationFilter

Customizer

DependenciesContainer

DeploymentProcessor

Fraction

JARArchive

JBossDeploymentStructureContainer

MarkerContainer

StageConfig

SwarmProperties

UserSpaceExtensionFactory

Classes

Defaultable

DefaultDeploymentFactory

Environment

JBossDeploymentStructureAsset

Module

OutboundSocketBinding

SocketBinding

SocketBindingGroup

Enums

Module.ServiceHandling


text:
namespace base {
class RunLoop;
}

namespace net {

class IOBuffer;

namespace internal {

class TestCompletionCallbackBaseInternal {
 public:
  TestCompletionCallbackBaseInternal(
      const TestCompletionCallbackBaseInternal&) = delete;
  TestCompletionCallbackBaseInternal& operator=(
      const TestCompletionCallbackBaseInternal&) = delete;
  bool have_result() const { return have_result_; }

 protected:
  TestCompletionCallbackBaseInternal();
  virtual ~TestCompletionCallbackBaseInternal();

  void DidSetResult();
  void WaitForResult();

 private:
  // RunLoop.  Only non-NULL during the call to WaitForResult, so the class is
  // reusable.
  std::unique_ptr<base::RunLoop> run_loop_;
  bool have_result_ = false;
};

template <typename R>
struct NetErrorIsPendingHelper {
  bool operator()(R status) const { return status == ERR_IO_PENDING; }
};

template <typename R, typename IsPendingHelper = NetErrorIsPendingHelper<R>>
class TestCompletionCallbackTemplate
    : public TestCompletionCallbackBaseInternal {
 public:
  TestCompletionCallbackTemplate(const TestCompletionCallbackTemplate&) =
      delete;
  TestCompletionCallbackTemplate& operator=(
      const TestCompletionCallbackTemplate&) = delete;
  ~TestCompletionCallbackTemplate() override = default;

  R WaitForResult() {
    TestCompletionCallbackBaseInternal::WaitForResult();
    return std::move(result_);
  }

  R GetResult(R result) {
    IsPendingHelper check_pending;
    if (!check_pending(result))
      return std::move(result);
    return WaitForResult();
  }

 protected:
  TestCompletionCallbackTemplate() : result_(R()) {}

  // Override this method to gain control as the callback is running.
  virtual void SetResult(R result) {
    result_ = std::move(result);
    DidSetResult();
  }

 private:
  R result_;
};

}  // namespace internal

class TestClosure : public internal::TestCompletionCallbackBaseInternal {
 public:
  using internal::TestCompletionCallbackBaseInternal::WaitForResult;

  TestClosure() = default;
  TestClosure(const TestClosure&) = delete;
  TestClosure& operator=(const TestClosure&) = delete;
  ~TestClosure() override;

  base::OnceClosure closure() {
    return base::BindOnce(&TestClosure::DidSetResult, base::Unretained(this));
  }
};

// Base class overridden by custom implementations of TestCompletionCallback.
typedef internal::TestCompletionCallbackTemplate<int>
    TestCompletionCallbackBase;

typedef internal::TestCompletionCallbackTemplate<int64_t>
    TestInt64CompletionCallbackBase;

class TestCompletionCallback : public TestCompletionCallbackBase {
 public:
  TestCompletionCallback() = default;
  TestCompletionCallback(const TestCompletionCallback&) = delete;
  TestCompletionCallback& operator=(const TestCompletionCallback&) = delete;
  ~TestCompletionCallback() override;

  CompletionOnceCallback callback() {
    return base::BindOnce(&TestCompletionCallback::SetResult,
                          base::Unretained(this));
  }
};

class TestInt64CompletionCallback : public TestInt64CompletionCallbackBase {
 public:
  TestInt64CompletionCallback() = default;
  TestInt64CompletionCallback(const TestInt64CompletionCallback&) = delete;
  TestInt64CompletionCallback& operator=(const TestInt64CompletionCallback&) =
      delete;
  ~TestInt64CompletionCallback() override;

  Int64CompletionOnceCallback callback() {
    return base::BindOnce(&TestInt64CompletionCallback::SetResult,
                          base::Unretained(this));
  }
};

// Makes sure that the buffer is not referenced when the callback runs.
class ReleaseBufferCompletionCallback: public TestCompletionCallback {
 public:
  explicit ReleaseBufferCompletionCallback(IOBuffer* buffer);
  ReleaseBufferCompletionCallback(const ReleaseBufferCompletionCallback&) =
      delete;
  ReleaseBufferCompletionCallback& operator=(
      const ReleaseBufferCompletionCallback&) = delete;
  ~ReleaseBufferCompletionCallback() override;

 private:
  void SetResult(int result) override;

  raw_ptr<IOBuffer> buffer_;
};

}  // namespace net

#endif  // NET_BASE_TEST_COMPLETION_CALLBACK_H_


text:
set -e

cd $1

echo "(ns test.runner (:require [doo.runner :refer-macros [doo-all-tests]] \
                                [module.core])) (doo-all-tests)" > test/runner.cljs
LEIN_ROOT=1 lein test && lein doo phantom debug once


text:
package gavilcode.bot.rpg;

public class ThingResult {

public final boolean ok;
public final String fullThing;

public ThingResult(String fullThing, boolean ok) {
  this.ok = ok;
  this.fullThing = fullThing;
}

public ThingResult(String fullThing) {
  this(fullThing, true);
}

public static ThingResult error(String message) {
  return new ThingResult(message, false);
}

public static ThingResult ok(String message) {
  return new ThingResult(message);
}
}


text:
=============
 UserHandler
=============

``ackward::logging::UserHandler`` allows you to define new ``Handler``
types in C++. To use ``UserHandler``, you first define a type with an
``emit()`` method. You then define a new ``UserHandler``
template-instantiation using this type. When the ``UserHandler``\ 's
``emit()`` is called, the ``LogRecord`` will be forwarded to the the
``emit()`` defined in type you defined earlier.

Example
=======

.. literalinclude:: ../../../../../examples/logging/UserHandler.cpp
   :language: c++
   :linenos:

API
===

.. doxygenclass:: ackward::logging::UserHandler
   :members:


text:
#include "tensorflow/core/grappler/optimizers/loop_optimizer.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/inputs/trivial_test_graph_input_yielder.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/grappler/utils/grappler_test.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace grappler {

class LoopOptimizerTest : public GrapplerTest {
 protected:
  // These helpers always sets T=DT_FLOAT.
  void AddEnterNode(const string& name, const string& frame,
                    const bool is_constant, const int piterations,
                    const std::vector<string>& inputs, GraphDef* graph) const {
    std::vector<std::pair<string, AttrValue>> attributes;
    AttrValue type;
    type.set_type(DT_FLOAT);
    attributes.emplace_back("T", type);
    AttrValue frame_name;
    frame_name.set_s(frame);
    attributes.emplace_back("frame_name", frame_name);
    AttrValue is_const;
    is_const.set_b(is_constant);
    attributes.emplace_back("is_constant", is_const);
    AttrValue parallel_iterations;
    parallel_iterations.set_i(piterations);
    attributes.emplace_back("parallel_iterations", parallel_iterations);
    AddNode(name, "Enter", inputs, attributes, graph);
  }

  void AddSimpleNode(const string& name, const string& op,
                     const std::vector<string>& inputs, GraphDef* graph) const {
    std::vector<std::pair<string, AttrValue>> attributes;
    AttrValue type;
    type.set_type(DT_FLOAT);
    attributes.emplace_back("T", type);
    AddNode(name, op, inputs, attributes, graph);
  }

  void DisableAllStages(LoopOptimizer* optimizer) {
    LoopOptimizer::LoopOptimizerOptions options;
    options.enable_loop_invariant_node_motion = false;
    options.enable_stack_push_removal = false;
    optimizer->options_ = options;
  }

  void EnableOnlyLoopInvariantNodeMotion(LoopOptimizer* optimizer) {
    DisableAllStages(optimizer);
    optimizer->options_.enable_loop_invariant_node_motion = true;
  }

  void EnableOnlyStackPushRemoval(LoopOptimizer* optimizer) {
    DisableAllStages(optimizer);
    optimizer->options_.enable_stack_push_removal = true;
  }
};

TEST_F(LoopOptimizerTest, Basic) {
  GraphDef graph;
  AddSimpleNode("In", "Identity", {}, &graph);
  AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"},
               &graph);
  AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"},
                &graph);
  AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph);
  AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph);
  AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph);
  AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph);
  AddSimpleNode("Less", "Less", {"VariantAdd", "Less/y"}, &graph);
  AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph);
  AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph);
  AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph);
  AddSimpleNode("NextIteration", "NextIteration", {"VariantAdd"}, &graph);
  AddSimpleNode("Exit", "Exit", {"Switch"}, &graph);
  AddSimpleNode("Out", "Identity", {"Exit"}, &graph);

  GrapplerItem item;
  item.graph = graph;

  LoopOptimizer optimizer;
  EnableOnlyLoopInvariantNodeMotion(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  std::unique_ptr<NodeMap> node_map;
  std::unordered_map<const NodeDef*, std::vector<int>> frames;
  int num_frames;

  node_map.reset(new NodeMap(&graph));
  EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd")).back(), 0);

  node_map.reset(new NodeMap(&output));
  EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 0);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd")).back(), 0);
}

TEST_F(LoopOptimizerTest, Const) {
  GraphDef graph;
  AddSimpleNode("In", "Identity", {}, &graph);
  AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"},
               &graph);
  AddSimpleNode("Const", "Const", {"^Identity"}, &graph);
  AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "Const"}, &graph);
  AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph);
  AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph);
  AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph);
  AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph);
  AddSimpleNode("Less", "Less", {"VariantAdd", "Less/y"}, &graph);
  AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph);
  AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph);
  AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph);
  AddSimpleNode("NextIteration", "NextIteration", {"VariantAdd"}, &graph);
  AddSimpleNode("Exit", "Exit", {"Switch"}, &graph);
  AddSimpleNode("Out", "Identity", {"Exit"}, &graph);

  GrapplerItem item;
  item.graph = graph;

  LoopOptimizer optimizer;
  EnableOnlyLoopInvariantNodeMotion(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  std::unique_ptr<NodeMap> node_map;
  std::unordered_map<const NodeDef*, std::vector<int>> frames;
  int num_frames;

  node_map.reset(new NodeMap(&graph));
  EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0);
  EXPECT_EQ(frames.at(node_map->GetNode("Const")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("Const")).back(), 0);

  node_map.reset(new NodeMap(&output));
  EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 0);
  EXPECT_EQ(frames.at(node_map->GetNode("Const")).size(), 0);
}

TEST_F(LoopOptimizerTest, ControlOutput) {
  GraphDef graph;
  AddSimpleNode("In", "Identity", {}, &graph);
  AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"},
               &graph);
  AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"},
                &graph);
  AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph);
  AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph);
  AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph);
  AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph);
  AddSimpleNode("Less", "Less", {"VariantAdd", "Less/y", "^InvariantAdd"},
                &graph);
  AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph);
  AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph);
  AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph);
  AddSimpleNode("NextIteration", "NextIteration", {"VariantAdd"}, &graph);
  AddSimpleNode("Exit", "Exit", {"Switch"}, &graph);
  AddSimpleNode("Out", "Identity", {"Exit"}, &graph);

  GrapplerItem item;
  item.graph = graph;

  LoopOptimizer optimizer;
  EnableOnlyLoopInvariantNodeMotion(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  std::unique_ptr<NodeMap> node_map;
  std::unordered_map<const NodeDef*, std::vector<int>> frames;
  int num_frames;

  node_map.reset(new NodeMap(&graph));
  EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0);

  node_map.reset(new NodeMap(&output));
  EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0);
}

TEST_F(LoopOptimizerTest, NestedLoop1) {
  GraphDef graph;
  AddSimpleNode("In", "Identity", {}, &graph);
  AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"},
               &graph);
  AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"},
                &graph);
  AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph);
  AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph);
  AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph);
  AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph);
  AddSimpleNode("Less", "Less", {"Exit2", "Less/y"}, &graph);
  AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph);
  AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph);
  AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph);
  AddSimpleNode("NextIteration", "NextIteration", {"Exit2"}, &graph);
  AddSimpleNode("Exit", "Exit", {"Switch"}, &graph);
  AddSimpleNode("Out", "Identity", {"Exit"}, &graph);

  AddEnterNode("InvariantEnter2", "while/while/while_context", true, 1,
               {"VariantAdd"}, &graph);
  AddSimpleNode("InvariantAdd2", "Add", {"InvariantEnter2", "InvariantEnter2"},
                &graph);
  AddSimpleNode("VariantAdd2", "Add", {"InvariantAdd2", "Identity2"}, &graph);
  AddEnterNode("VariantEnter2", "while/while/while_context", false, 1,
               {"VariantEnter"}, &graph);
  AddSimpleNode("Merge2", "Merge", {"VariantEnter2", "NextIteration2"}, &graph);
  AddSimpleNode("Less2/y", "Const", {"^Identity2"}, &graph);
  AddSimpleNode("Less2", "Less", {"VariantAdd2", "Less2/y"}, &graph);
  AddSimpleNode("LoopCond2", "LoopCond", {"Less2"}, &graph);
  AddSimpleNode("Switch2", "Switch", {"Merge2", "LoopCond2"}, &graph);
  AddSimpleNode("Identity2", "Identity", {"Switch2:1"}, &graph);
  AddSimpleNode("NextIteration2", "NextIteration", {"VariantAdd2"}, &graph);
  AddSimpleNode("Exit2", "Exit", {"Switch2"}, &graph);

  GrapplerItem item;
  item.graph = graph;

  LoopOptimizer optimizer;
  EnableOnlyLoopInvariantNodeMotion(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  std::unique_ptr<NodeMap> node_map;
  std::unordered_map<const NodeDef*, std::vector<int>> frames;
  int num_frames;

  node_map.reset(new NodeMap(&graph));
  EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).back(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0);

  node_map.reset(new NodeMap(&output));
  EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 0);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).back(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 0);
}

TEST_F(LoopOptimizerTest, NestedLoop2) {
  GraphDef graph;
  AddSimpleNode("In", "Identity", {}, &graph);
  AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"},
               &graph);
  AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"},
                &graph);
  AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph);
  AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph);
  AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph);
  AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph);
  AddSimpleNode("Less", "Less", {"Exit2", "Less/y"}, &graph);
  AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph);
  AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph);
  AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph);
  AddSimpleNode("NextIteration", "NextIteration", {"Exit2"}, &graph);
  AddSimpleNode("Exit", "Exit", {"Switch"}, &graph);
  AddSimpleNode("Out", "Identity", {"Exit"}, &graph);

  AddEnterNode("InvariantEnter2", "while/while/while_context", true, 1,
               {"InvariantAdd"}, &graph);
  AddSimpleNode("InvariantAdd2", "Add", {"InvariantEnter2", "InvariantEnter2"},
                &graph);
  AddSimpleNode("VariantAdd2", "Add", {"InvariantAdd2", "Identity2"}, &graph);
  AddEnterNode("VariantEnter2", "while/while/while_context", false, 1,
               {"VariantEnter"}, &graph);
  AddSimpleNode("Merge2", "Merge", {"VariantEnter2", "NextIteration2"}, &graph);
  AddSimpleNode("Less2/y", "Const", {"^Identity2"}, &graph);
  AddSimpleNode("Less2", "Less", {"VariantAdd2", "Less2/y"}, &graph);
  AddSimpleNode("LoopCond2", "LoopCond", {"Less2"}, &graph);
  AddSimpleNode("Switch2", "Switch", {"Merge2", "LoopCond2"}, &graph);
  AddSimpleNode("Identity2", "Identity", {"Switch2:1"}, &graph);
  AddSimpleNode("NextIteration2", "NextIteration", {"VariantAdd2"}, &graph);
  AddSimpleNode("Exit2", "Exit", {"Switch2"}, &graph);

  GrapplerItem item;
  item.graph = graph;

  LoopOptimizer optimizer;
  EnableOnlyLoopInvariantNodeMotion(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  std::unique_ptr<NodeMap> node_map;
  std::unordered_map<const NodeDef*, std::vector<int>> frames;
  int num_frames;

  node_map.reset(new NodeMap(&graph));
  EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).back(), 1);

  node_map.reset(new NodeMap(&output));
  EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 0);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).back(), 1);
}

TEST_F(LoopOptimizerTest, NestedLoopConst1) {
  GraphDef graph;
  AddSimpleNode("In", "Identity", {}, &graph);
  AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"},
               &graph);
  AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"},
                &graph);
  AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph);
  AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph);
  AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph);
  AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph);
  AddSimpleNode("Less", "Less", {"Exit2", "Less/y"}, &graph);
  AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph);
  AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph);
  AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph);
  AddSimpleNode("NextIteration", "NextIteration", {"Exit2"}, &graph);
  AddSimpleNode("Exit", "Exit", {"Switch"}, &graph);
  AddSimpleNode("Out", "Identity", {"Exit"}, &graph);

  AddEnterNode("InvariantEnter2", "while/while/while_context", true, 1,
               {"VariantAdd"}, &graph);
  AddSimpleNode("Const2", "Const", {"^Identity2"}, &graph);
  AddSimpleNode("InvariantAdd2", "Add", {"InvariantEnter2", "Const2"}, &graph);
  AddSimpleNode("VariantAdd2", "Add", {"InvariantAdd2", "Identity2"}, &graph);
  AddEnterNode("VariantEnter2", "while/while/while_context", false, 1,
               {"VariantEnter"}, &graph);
  AddSimpleNode("Merge2", "Merge", {"VariantEnter2", "NextIteration2"}, &graph);
  AddSimpleNode("Less2/y", "Const", {"^Identity2"}, &graph);
  AddSimpleNode("Less2", "Less", {"VariantAdd2", "Less2/y"}, &graph);
  AddSimpleNode("LoopCond2", "LoopCond", {"Less2"}, &graph);
  AddSimpleNode("Switch2", "Switch", {"Merge2", "LoopCond2"}, &graph);
  AddSimpleNode("Identity2", "Identity", {"Switch2:1"}, &graph);
  AddSimpleNode("NextIteration2", "NextIteration", {"VariantAdd2"}, &graph);
  AddSimpleNode("Exit2", "Exit", {"Switch2"}, &graph);

  GrapplerItem item;
  item.graph = graph;

  LoopOptimizer optimizer;
  EnableOnlyLoopInvariantNodeMotion(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  std::unique_ptr<NodeMap> node_map;
  std::unordered_map<const NodeDef*, std::vector<int>> frames;
  int num_frames;

  node_map.reset(new NodeMap(&graph));
  EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("Const2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("Const2")).back(), 1);

  node_map.reset(new NodeMap(&output));
  EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 0);
  EXPECT_EQ(frames.at(node_map->GetNode("Const2")).size(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("Const2")).back(), 0);
}

TEST_F(LoopOptimizerTest, NestedLoopConst2) {
  GraphDef graph;
  AddSimpleNode("In", "Identity", {}, &graph);
  AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"},
               &graph);
  AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"},
                &graph);
  AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph);
  AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph);
  AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph);
  AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph);
  AddSimpleNode("Less", "Less", {"Exit2", "Less/y"}, &graph);
  AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph);
  AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph);
  AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph);
  AddSimpleNode("NextIteration", "NextIteration", {"Exit2"}, &graph);
  AddSimpleNode("Exit", "Exit", {"Switch"}, &graph);
  AddSimpleNode("Out", "Identity", {"Exit"}, &graph);

  AddEnterNode("InvariantEnter2", "while/while/while_context", true, 1,
               {"InvariantAdd"}, &graph);
  AddSimpleNode("Const2", "Const", {"^Identity2"}, &graph);
  AddSimpleNode("InvariantAdd2", "Add", {"InvariantEnter2", "Const2"}, &graph);
  AddSimpleNode("VariantAdd2", "Add", {"InvariantAdd2", "Identity2"}, &graph);
  AddEnterNode("VariantEnter2", "while/while/while_context", false, 1,
               {"VariantEnter"}, &graph);
  AddSimpleNode("Merge2", "Merge", {"VariantEnter2", "NextIteration2"}, &graph);
  AddSimpleNode("Less2/y", "Const", {"^Identity2"}, &graph);
  AddSimpleNode("Less2", "Less", {"VariantAdd2", "Less2/y"}, &graph);
  AddSimpleNode("LoopCond2", "LoopCond", {"Less2"}, &graph);
  AddSimpleNode("Switch2", "Switch", {"Merge2", "LoopCond2"}, &graph);
  AddSimpleNode("Identity2", "Identity", {"Switch2:1"}, &graph);
  AddSimpleNode("NextIteration2", "NextIteration", {"VariantAdd2"}, &graph);
  AddSimpleNode("Exit2", "Exit", {"Switch2"}, &graph);

  GrapplerItem item;
  item.graph = graph;

  LoopOptimizer optimizer;
  EnableOnlyLoopInvariantNodeMotion(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  std::unique_ptr<NodeMap> node_map;
  std::unordered_map<const NodeDef*, std::vector<int>> frames;
  int num_frames;

  node_map.reset(new NodeMap(&graph));
  EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 1);
  EXPECT_EQ(frames.at(node_map->GetNode("Const2")).size(), 2);
  EXPECT_EQ(frames.at(node_map->GetNode("Const2")).back(), 1);

  node_map.reset(new NodeMap(&output));
  EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok());
  EXPECT_EQ(num_frames, 2);
  EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 0);
  EXPECT_EQ(frames.at(node_map->GetNode("Const2")).size(), 0);
}

void VerifyGraphsEqual(const GraphDef& original_graph,
                       const GraphDef& optimized_graph, const string& func) {
  EXPECT_EQ(original_graph.node_size(), optimized_graph.node_size()) << func;
  for (int i = 0; i < original_graph.node_size(); ++i) {
    const NodeDef& original = original_graph.node(i);
    const NodeDef& optimized = optimized_graph.node(i);
    EXPECT_EQ(original.name(), optimized.name()) << func;
    EXPECT_EQ(original.op(), optimized.op()) << func;
    EXPECT_EQ(original.input_size(), optimized.input_size()) << func;
    for (int j = 0; j < original.input_size(); ++j) {
      EXPECT_EQ(original.input(j), optimized.input(j)) << func;
    }
  }
}

TEST_F(LoopOptimizerTest, NoOp) {
  // This trivial graph is so basic there's nothing to optimize.
  TrivialTestGraphInputYielder fake_input(4, 1, 10, false, {"CPU:0"});
  GrapplerItem item;
  CHECK(fake_input.NextItem(&item));

  LoopOptimizer optimizer;
  EnableOnlyStackPushRemoval(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  VerifyGraphsEqual(item.graph, output, __FUNCTION__);
}

TEST_F(LoopOptimizerTest, RemovePush_NoOp) {
  GrapplerItem item;
  GraphDef& graph = item.graph;
  AddSimpleNode("c", "Const", {}, &graph);
  // Stack with corresponding push/pop.
  AddSimpleNode("stack1", "StackV2", {}, &graph);
  AddSimpleNode("push1", "StackPushV2", {"stack1", "c"}, &graph);
  AddSimpleNode("pop1", "StackPopV2", {"stack1"}, &graph);
  AddSimpleNode("id1", "Identity", {"pop1"}, &graph);
  // Stack with corresponding push/pop behind Enter.
  AddSimpleNode("stack2", "StackV2", {}, &graph);
  AddEnterNode("enter2_c", "frame_name", false, 1, {"c"}, &graph);
  AddEnterNode("enter2_stack2", "frame_name", false, 1, {"stack2"}, &graph);
  AddSimpleNode("push2", "StackPushV2", {"enter2_stack2", "enter2_c"}, &graph);
  AddSimpleNode("pop2", "StackPopV2", {"enter2_stack2"}, &graph);
  AddSimpleNode("id2", "Identity", {"pop2"}, &graph);
  // Stack with unexpected op type in fanout of Stack.
  AddSimpleNode("stack3", "StackV2", {}, &graph);
  AddSimpleNode("push3", "StackPushV2", {"stack3", "c"}, &graph);
  AddSimpleNode("stop", "StopGradient", {"stack3"}, &graph);

  LoopOptimizer optimizer;
  EnableOnlyStackPushRemoval(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);
  VerifyGraphsEqual(item.graph, output, __FUNCTION__);
}

TEST_F(LoopOptimizerTest, RemovePush_NoPopButStackLives) {
  GrapplerItem item;
  GraphDef& graph = item.graph;
  AddSimpleNode("c", "Const", {}, &graph);
  // Stack with corresponding push
  AddSimpleNode("stack1", "StackV2", {}, &graph);
  AddSimpleNode("push1", "StackPushV2", {"stack1", "c"}, &graph);
  // Stack with corresponding push behind Enter.
  AddSimpleNode("stack2", "StackV2", {}, &graph);
  AddEnterNode("enter2_c", "frame_name", false, 1, {"c"}, &graph);
  AddEnterNode("enter2_stack2", "frame_name", false, 1, {"stack2"}, &graph);
  AddSimpleNode("push2", "StackPushV2", {"enter2_stack2", "enter2_c"}, &graph);
  item.keep_ops.push_back("stack1");
  item.keep_ops.push_back("stack2");

  LoopOptimizer optimizer;
  EnableOnlyStackPushRemoval(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);
  VerifyGraphsEqual(item.graph, output, __FUNCTION__);
}

TEST_F(LoopOptimizerTest, RemovePushWithoutMatchingPop) {
  GrapplerItem item;
  GraphDef& graph = item.graph;
  AddSimpleNode("c", "Const", {}, &graph);
  // Push without Pop.
  AddSimpleNode("stack1", "StackV2", {}, &graph);
  AddSimpleNode("push1", "StackPushV2", {"stack1", "c"}, &graph);
  // Push without Pop behind Enter.
  AddSimpleNode("stack2", "StackV2", {}, &graph);
  AddEnterNode("enter_c", "frame_name", false, 1, {"c"}, &graph);
  AddEnterNode("enter_stack2", "frame_name", false, 1, {"stack2"}, &graph);
  AddSimpleNode("push2", "StackPushV2", {"enter_stack2", "enter_c"}, &graph);
  // Pop without consumer.
  AddSimpleNode("stack3", "StackV2", {}, &graph);
  AddSimpleNode("push3", "StackPushV2", {"stack3", "c"}, &graph);
  AddSimpleNode("pop3", "StackPopV2", {"stack3"}, &graph);
  // Push for a Pop without consumer that is fetched should not be removed.
  AddSimpleNode("stack4", "StackV2", {}, &graph);
  AddSimpleNode("push4", "StackPushV2", {"stack4", "c"}, &graph);
  AddSimpleNode("pop4", "StackPopV2", {"stack4"}, &graph);

  item.fetch.push_back("pop4");

  LoopOptimizer optimizer;
  EnableOnlyStackPushRemoval(&optimizer);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);

  EXPECT_EQ(13, output.node_size());
  for (int i = 0; i < output.node_size(); ++i) {
    const NodeDef& node = output.node(i);
    if (node.name() == "push1") {
      EXPECT_EQ("Identity", node.op());
      EXPECT_EQ(2, node.input_size());
      EXPECT_EQ("c", node.input(0));
      EXPECT_EQ("^stack1", node.input(1));
    } else if (node.name() == "push2") {
      EXPECT_EQ("Identity", node.op());
      EXPECT_EQ(2, node.input_size());
      EXPECT_EQ("enter_c", node.input(0));
      EXPECT_EQ("^enter_stack2", node.input(1));
    } else if (node.name() == "push3") {
      EXPECT_EQ("Identity", node.op());
      EXPECT_EQ(2, node.input_size());
      EXPECT_EQ("c", node.input(0));
      EXPECT_EQ("^stack3", node.input(1));
    } else {
      const NodeDef& orig_node = item.graph.node(i);
      EXPECT_EQ(orig_node.ShortDebugString(), node.ShortDebugString());
    }
  }
}

TEST_F(LoopOptimizerTest, RemoveDeadBranches_ConstantCondition) {
  Scope scope = Scope::NewRootScope();
  Output v_in = ops::Variable(scope.WithOpName("v_in"), {3}, DT_FLOAT);

  Output ctrl1 = ops::Const(scope.WithOpName("ctrl1"), false, TensorShape({}));
  ops::Switch s1(scope.WithOpName("switch1"), v_in, ctrl1);
  Output square1 = ops::Square(scope.WithOpName("square1"), s1.output_false);
  Output sqrt1 = ops::Sqrt(scope.WithOpName("sqrt1"), s1.output_true);

  Output ctrl2 = ops::Const(scope.WithOpName("ctrl2"), true, TensorShape({}));
  ops::Switch s2(scope.WithOpName("switch2"), v_in, ctrl2);
  Output square2 = ops::Square(scope.WithOpName("square2"), s2.output_false);
  Output sqrt2 = ops::Sqrt(scope.WithOpName("sqrt2"), s2.output_true);

  Output ctrl3 = ops::Const(scope.WithOpName("ctrl3"), false, TensorShape({}));
  ops::Switch s3(scope.WithOpName("switch3"), v_in, ctrl3);
  Output square3 = ops::Square(scope.WithOpName("square3"), s3.output_false);
  Output sqrt3 = ops::Sqrt(scope.WithOpName("sqrt3"), s3.output_true);

  Output ctrl4 = ops::Const(scope.WithOpName("ctrl4"), false, TensorShape({}));
  ops::Switch s4(scope.WithOpName("switch4"), v_in, ctrl4);
  Output square4 = ops::Square(scope.WithOpName("square4"), s4.output_false);
  Output sqrt4 = ops::Sqrt(scope.WithOpName("sqrt4"), s4.output_true);

  ops::Merge m1(scope.WithOpName("m1"), {square1, sqrt1});
  ops::Merge m2(scope.WithOpName("m2"), {v_in, square1});
  ops::Merge m3(scope.WithOpName("m3"), {v_in, sqrt1});
  ops::Merge m4(scope.WithOpName("m4"), {square1, sqrt2});
  ops::Merge m5(scope.WithOpName("m5"), {square2, sqrt1});
  ops::Merge m6(scope.WithOpName("m6").WithControlDependencies(sqrt2),
                {v_in, square1});
  ops::Merge m7(scope.WithOpName("m7").WithControlDependencies(sqrt1),
                {v_in, square1});

  ops::Switch s5(scope.WithOpName("switch5"), v_in, ctrl1);
  Output id1 = ops::Identity(scope.WithOpName("id1"), s5.output_false);
  Output id2 = ops::Identity(scope.WithOpName("id2"), s5.output_true);
  ops::Merge m8(scope.WithOpName("m8"), {id1, id2});

  ops::Switch s6(scope.WithOpName("switch6"), v_in, ctrl1);
  Output id3 = ops::Identity(scope.WithOpName("id3"), s6.output_false);
  Output id4 = ops::Identity(scope.WithOpName("id4"), s6.output_true);
  ops::Merge m9(scope.WithOpName("m9"), {id3, id4});

  GrapplerItem item;
  item.fetch.push_back("m8");
  item.fetch.push_back("id4");

  TF_CHECK_OK(scope.ToGraphDef(&item.graph));

  LoopOptimizer optimizer(RewriterConfig::AGGRESSIVE, nullptr);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_CHECK_OK(status);

  for (const NodeDef& node : output.node()) {
    // These nodes should have been pruned
    EXPECT_NE("Square1", node.name());
    EXPECT_NE("Sqrt2", node.name());
    EXPECT_NE("m5", node.name());
    EXPECT_NE("m7", node.name());

    if (node.name() == "m1") {
      // sqrt1 is dead
      EXPECT_EQ("Identity", node.op());
      EXPECT_EQ(1, node.input_size());
      EXPECT_EQ("square1", node.input(0));
    } else if (node.name() == "m2") {
      // both inputs are alive
      EXPECT_EQ("Merge", node.op());
      EXPECT_EQ(2, node.input_size());
      EXPECT_EQ("v_in", node.input(0));
      EXPECT_EQ("square1", node.input(1));
    } else if (node.name() == "m3") {
      // sqrt1 is dead
      EXPECT_EQ("Identity", node.op());
      EXPECT_EQ(1, node.input_size());
      EXPECT_EQ("v_in", node.input(0));
    } else if (node.name() == "m4") {
      // both inputs are alive
      EXPECT_EQ("Merge", node.op());
      EXPECT_EQ(2, node.input_size());
      EXPECT_EQ("square1", node.input(0));
      EXPECT_EQ("sqrt2", node.input(1));
    } else if (node.name() == "m6") {
      // both inputs are alive and the control dependency can get triggered
      EXPECT_EQ("Merge", node.op());
      EXPECT_EQ(3, node.input_size());
      EXPECT_EQ("v_in", node.input(0));
      EXPECT_EQ("square1", node.input(1));
      EXPECT_EQ("^sqrt2", node.input(2));
    } else if (node.name() == "m8") {
      // The node is to be preserved because of a fetch
      EXPECT_EQ("Merge", node.op());
      EXPECT_EQ(2, node.input_size());
      EXPECT_EQ("id1", node.input(0));
      EXPECT_EQ("id2", node.input(1));
    } else if (node.name() == "m9") {
      // The node is to be preserved because of a fetch
      EXPECT_EQ("Merge", node.op());
      EXPECT_EQ(2, node.input_size());
      EXPECT_EQ("id3", node.input(0));
      EXPECT_EQ("id4", node.input(1));
    }
  }
}

TEST_F(LoopOptimizerTest, RemoveDeadBranches_ZeroIterWhile) {
  const string gdef_ascii = R"EOF(
node {
  name: "Const"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 20
      }
    }
  }
}
node {
  name: "while/Enter"
  op: "Enter"
  input: "Const"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "frame_name"
    value {
      s: "while/while/"
    }
  }
  attr {
    key: "is_constant"
    value {
      b: false
    }
  }
  attr {
    key: "parallel_iterations"
    value {
      i: 1
    }
  }
}
node {
  name: "while/Merge"
  op: "Merge"
  input: "while/Enter"
  input: "while/NextIteration"
  attr {
    key: "N"
    value {
      i: 2
    }
  }
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "while/Less/y"
  op: "Const"
  input: "^while/Merge"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 10
      }
    }
  }
}
node {
  name: "while/Less"
  op: "Less"
  input: "while/Merge"
  input: "while/Less/y"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "while/LoopCond"
  op: "LoopCond"
  input: "while/Less"
}
node {
  name: "while/Switch"
  op: "Switch"
  input: "while/Merge"
  input: "while/LoopCond"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "_class"
    value {
      list {
        s: "loc:@while/Merge"
      }
    }
  }
}
node {
  name: "while/Identity"
  op: "Identity"
  input: "while/Switch:1"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "while/add/y"
  op: "Const"
  input: "^while/Identity"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "while/add"
  op: "Add"
  input: "while/Identity"
  input: "while/add/y"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "while/NextIteration"
  op: "NextIteration"
  input: "while/add"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
node {
  name: "while/Exit"
  op: "Exit"
  input: "while/Switch"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
versions {
  producer: 21
}
  )EOF";

  GrapplerItem item;
  CHECK(protobuf::TextFormat::ParseFromString(gdef_ascii, &item.graph));
  item.fetch = {"while/Exit"};
  auto tensors_expected = EvaluateNodes(item.graph, item.fetch);
  EXPECT_EQ(1, tensors_expected.size());

  LoopOptimizer optimizer(RewriterConfig::AGGRESSIVE, nullptr);
  GraphDef output;
  Status status = optimizer.Optimize(nullptr, item, &output);
  TF_CHECK_OK(status);
  auto tensors_got = EvaluateNodes(output, item.fetch);
  EXPECT_EQ(1, tensors_got.size());
  test::ExpectTensorEqual<int32>(tensors_expected[0], tensors_got[0]);

  int nodes_present = 0;
  for (const NodeDef& node : output.node()) {
    // All nodes connected to Switch's positive check should be pruned.
    if (node.name() == "while/add") {
      LOG(ERROR) << "while/add is present after optimization";
    } else if (node.name() == "while/add/y") {
      LOG(ERROR) << "while/add/y is present after optimization";
    } else if (node.name() == "while/NextIteration") {
      LOG(ERROR) << "while/NextIteration is present after optimization";
    } else if (node.name() == "while/Identity") {
      LOG(ERROR) << "while/Identity is present after optimization";
    }
    ++nodes_present;
  }
  EXPECT_EQ(8, nodes_present);
}

}  // namespace grappler
}  // namespace tensorflow


text:
package iso20022

// Choice of format for the type of document format.
type DocumentFormat1Choice struct {

	// Document format.
	//
	Code *ExternalDocumentFormat1Code `xml:"Cd"`

	// Document format expressed as a proprietary code.
	Proprietary *GenericIdentification1 `xml:"Prtry"`
}

func (d *DocumentFormat1Choice) SetCode(value string) {
	d.Code = (*ExternalDocumentFormat1Code)(&value)
}

func (d *DocumentFormat1Choice) AddProprietary() *GenericIdentification1 {
	d.Proprietary = new(GenericIdentification1)
	return d.Proprietary
}


text: See tweets and shit


text:
<?php
/**
 * Sorts elements in the element tree
 *
 * @param json $data The JSON encoded data from the tree
 *
 * @package modx
 * @subpackage processors.layout.tree.element
 */
class modElementSortProcessor extends modProcessor {
    public function checkPermissions() {
        return $this->modx->hasPermission('element_tree');
    }
    public function getLanguageTopics() {
        return array('category');
    }

    public function process() {
        $data = $this->getData();
        if (empty($data)) return $this->failure();

        if (!empty($data['n_category']) && is_array($data['n_category'])) {
            $this->handleCategoryDrop($data['n_category']);
        } else if (!empty($data)) {
            $this->handleSubCategoryDrop($data);
        }

        return $this->success();
    }

    /**
     * Get the data formatted and ready for sorting
     * @return array
     */
    public function getData() {
        $data = $this->getProperty('data');
        $data = urldecode($data);
        $data = $this->modx->fromJSON($data);

        $this->sortNodes('modTemplate','template',$data);
        $this->sortNodes('modTemplateVar','tv',$data);
        $this->sortNodes('modChunk','chunk',$data);
        $this->sortNodes('modSnippet','snippet',$data);
        $this->sortNodes('modPlugin','plugin',$data);
        return $data;
    }

    /**
     * Handle dropping of Elements or Categories onto Categories
     *
     * @param array $data
     * @return void
     */
    public function handleCategoryDrop(array $data) {
        /* if dropping an element onto a category, do that here */
        foreach ($data as $key => $elements) {
            if (!is_array($elements) || empty($elements)) continue;

            $key = explode('_',$key);
            if (empty($key[1]) || empty($key[2]) || $key[1] != 'category') continue;

            foreach ($elements as $elKey => $elArray) {
                $elKey = explode('_',$elKey);
                if (empty($elKey[1]) || empty($elKey[3])) continue;

                $className = 'mod'.ucfirst($elKey[1]);
                if ($className == 'modTv') $className = 'modTemplateVar';

                /** @var modElement $element */
                $element = $this->modx->getObject($className,$elKey[3]);
                if ($element) {
                    $element->set('category',$key[2]);
                    $element->save();
                }
            }
        }

        /* if sorting categories, do that here */
        $cdata = array();
        $this->getNodesFormatted($cdata,$data);
        foreach ($cdata as $categoryArray) {
            if ($categoryArray['type'] != 'category') continue;
            /** @var modCategory $category */
            $category = $this->modx->getObject('modCategory',$categoryArray['id']);
            if ($category && $categoryArray['parent'] != $category->get('parent')) {
                $category->set('parent',$categoryArray['parent']);
                $category->save();
            }
        }
    }

    /**
     * Handle dropping of Categories onto other Categories
     * @param array $data
     * @return void
     */
    public function handleSubCategoryDrop(array $data) {
        $cdata = array();
        foreach ($data as $typeKey => $type) {
            if (!empty($type)) {
                $this->getCategoryNodeDrop($cdata,$type);
            }
        }
        foreach ($cdata as $item) {
            if (empty($item['class']) || empty($item['pk'])) continue;

            if ($item['class'] == 'modCategory') {
                /** @var modCategory $category */
                $category = $this->modx->getObject('modCategory',$item['pk']);
                if ($category) {
                    $category->set('parent',$item['category']);
                    $category->save();
                }
            }
        }
    }

    /**
     * Properly sort the data
     * @param string $xname
     * @param string $type
     * @param array $data
     * @return void
     */
    public function sortNodes($xname,$type,$data) {
        $s = $data['n_type_'.$type];
        if (is_array($s)) {
            $this->sortNodesHelper($s,$xname);
        }
    }

    public function sortNodesHelper($objs,$xname,$currentCategoryId = 0) {
        foreach ($objs as $objar => $kids) {
            $oar = explode('_',$objar);
            $nodeArray = $this->processID($oar);

            if ($nodeArray['type'] == 'category') {
                $this->sortNodesHelper($kids,$xname,$nodeArray['pk']);

            } elseif ($nodeArray['type'] == 'element') {
                /** @var modElement $element */
                $element = $this->modx->getObject($xname,$nodeArray['pk']);
                if (empty($element)) continue;

                $element->set('category',$currentCategoryId);
                $element->save();
            }
        }
    }

    public function processID($ar) {
        return array(
            'elementType' => $ar[1],
            'type' => $ar[2],
            'pk' => $ar[3],
            'elementCatId' => isset($ar[4]) ? $ar[4] : 0,
        );
    }

    public function getNodesFormatted(&$ar_nodes,$cur_level,$parent = 0) {
        $order = 0;
        foreach ($cur_level as $nodeId => $children) {
            $ar = explode('_',$nodeId);
            if (empty($ar[1]) || empty($ar[2])) continue;

            $ar_nodes[] = array(
                'id' => $ar[2],
                'type' => $ar[1],
                'parent' => $parent,
                'order' => $order,
            );
            $order++;
            $this->getNodesFormatted($ar_nodes,$children,$ar[2]);
        }
    }

    public function getCategoryNodeDrop(&$cdata,$type = array(),$currentParent = 0) {
        foreach ($type as $itemKey => $item) {
            $nar = explode('_',$itemKey);
            $pk = !empty($nar[3]) ? $nar[3] : 0;
            $cdata[] = array(
                'type' => $nar[1],
                'class' => 'mod'.ucfirst($nar[2]),
                'pk' => $pk,
                'category' => $currentParent,
            );
            if (!empty($item)) {
                $this->getCategoryNodeDrop($cdata,$item,$pk);
            }
        }
    }
}
return 'modElementSortProcessor';


text:
title: 			"Meteor Contentful"
description:	"Meteor package to connect Meteor and Contentful."
synopsis:		"This is a package I built to synchronise data from Contentful to MeteorJS based single page applications and websites."
liveurl:		"https://atmospherejs.com/matfin/meteor-contentful"
github:			"https://github.com/matfin/meteor-contentful"
date:			"2015-08-01"
duration:		"30 days"
identifier:		"projects"
languages:
- Javascript
frameworks:
- MeteorJS
infrastructure:
- NodeJS
- MongoDB
tools:
- Sublime Text
- Git
- TravisCI
- AtmosphereJS
- JSLint
- ChaiJS
- Mocha
- SinonJS
---

## The brief
Contentful is a web based PaaS that provides content management services along with an API to manage this content.

When I was building several MeteorJS based websites I had the need to make content editing much easier.

I needed a solution that was easy for non-technical people to work with and modular so I could integrate it into many projects.

I also wanted to be able to easily push changes from their service to my module so the website being edited would receive updates without the need to redeploy.

## Project planning
After researching the options available to me at the time, I opted for Contentful for the following reasons:

- Their system was nice, neat and easy to use for a non technical person.
- They had impressive image asset management capabilities.
- They had a well documented REST api service that was easy to use.
- They used Markdown for content editing, which was nice and clean and ideal for our use.
- A webhook service was provided to push new changes, negating the need to build an automated sync tool.

When working on a portfolio website, I started to build the basics of a package that would interact with Contentful and keep content in sync.

Once I had this working, I separated out the code and created a standalone package I could then add to other projects.

## Features this package offered
- Content, in the form of entries and assets were fetched and synched on startup.
- Optional functionality to listen to changes from the Contentful webhook facilitated real time content updates.
- Resized images could be generated given a configuration, thus removing the burden to do this on the content author.

## Development, testing and deployment
As this package was being developed, I used the [Ngrok](https://ngrok.com/) HTTP tunneling tool so I could expose my local development machine to Contentful.

Testing was carried out using a combination of [SinonJS](http://sinonjs.org/) for creating stubs and spies, [Chai](http://chaijs.com/) for assertions and [Mocha](https://mochajs.org/) as the test runner.

The package can be found on [Atmosphere](https://atmospherejs.com/matfin/meteor-contentful).


text:
<?php
namespace SRESTO;
class Response{
    protected $status=200;
    protected $response='';
    protected $headers=array(
        'Content-type'=>'text/plain',
        'X-Powered-By'=>'SRESTO'
        );
    protected $flushed=FALSE;
    //public function __construct(){}
    public function status($st){
        $this->status=$st;
        return $this;
    }
    public function send($text){
        $this->response=$text;
        return $this;
    }
    /*public function xml($obj){
        $this->headers['Content-type']='application/xml';
        $this->response=xml_encode($obj);
        return $this;
    }*/
    public function json($obj){
        $this->headers['Content-type']='application/json';
        $this->response=json_encode($obj);
        return $this;
    }
    public function location($str){
        $this->headers['Location']=$str;
        return $this;
    }
    public function header($key,$val){
        $this->headers[$key]=$val;
        return $this;
    }
    public function flush(){
        if($this->flushed) return;
        foreach($this->headers as $key=>$val)
            header($key.": ".$val);
        if($this->status!=200)
            http_response_code($this->status);
        echo $this->response;
        $this->flushed=TRUE;
    }
    public function message($msg){
        $this->json(array('message'=>$msg));
        return $this;
    }
    protected function isObject($val){
        return is_array($val)?TRUE:(is_scalar($val)?FALSE:TRUE);
    }
}


text:
using System;
using ByteArray = com.google.zxing.common.ByteArray;
namespace com.google.zxing.qrcode.encoder
{

	sealed class BlockPair
	{
		public ByteArray DataBytes
		{
			get
			{
				return dataBytes;
			}

		}
		public ByteArray ErrorCorrectionBytes
		{
			get
			{
				return errorCorrectionBytes;
			}

		}

		//UPGRADE_NOTE: Final was removed from the declaration of 'dataBytes '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
		private ByteArray dataBytes;
		//UPGRADE_NOTE: Final was removed from the declaration of 'errorCorrectionBytes '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
		private ByteArray errorCorrectionBytes;

		internal BlockPair(ByteArray data, ByteArray errorCorrection)
		{
			dataBytes = data;
			errorCorrectionBytes = errorCorrection;
		}
	}
}


text:
package org.apache.airavata.registry.core.entities.replicacatalog;

import javax.persistence.*;
import java.io.Serializable;

/**
 * The persistent class for the data_product_metadata database table.
 */
@Entity
@Table(name = "DATA_PRODUCT_METADATA")
@IdClass(DataProductMetadataPK.class)
public class DataProductMetadataEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "PRODUCT_URI")
    private String productUri;

    @Id
    @Column(name = "METADATA_KEY")
    private String metadataKey;

    @Column(name = "METADATA_VALUE")
    private String metadataValue;

    public String getProductUri() {
        return productUri;
    }

    public void setProductUri(String productUri) {
        this.productUri = productUri;
    }

    public String getMetadataKey() {
        return metadataKey;
    }

    public void setMetadataKey(String metadataKey) {
        this.metadataKey = metadataKey;
    }

    public String getMetadataValue() {
        return metadataValue;
    }

    public void setMetadataValue(String metadataValue) {
        this.metadataValue = metadataValue;
    }

}


text:
<!--
  ~ Copyright (c) 2008-2016 Haulmont.
  ~
  ~ 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.
  ~
  -->

<window
        xmlns="http://schemas.haulmont.com/cuba/window.xsd"
        class="com.haulmont.cuba.gui.app.core.appproperties.AppPropertiesExport"
        messagesPack="com.haulmont.cuba.gui.app.core.appproperties"
        caption="msg://exportCaption">

    <dsContext/>

    <layout expand="scriptArea" spacing="true">
        <textArea id="scriptArea" width="100%"/>
    </layout>
</window>


text:
package org.apache.sysml.test.integration.functions.unary.matrix;

import org.junit.Test;
import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;

public class NegationTest extends AutomatedTestBase
{

	private static final String TEST_DIR = "functions/unary/matrix/";
	private static final String TEST_CLASS_DIR = TEST_DIR + NegationTest.class.getSimpleName() + "/";

	@Override
	public void setUp() {
		addTestConfiguration("PositiveTest",
				new TestConfiguration(TEST_CLASS_DIR, "NegationTest", new String[] { "vector", "matrix" }));
		addTestConfiguration("NegativeTest",
				new TestConfiguration(TEST_CLASS_DIR, "NegationTest", new String[] { "vector", "matrix" }));
		addTestConfiguration("RandomTest",
				new TestConfiguration(TEST_CLASS_DIR, "NegationTest", new String[] { "vector", "matrix" }));
	}

	@Test
	public void testPositive() {
		if(shouldSkipTest())
			return;

		int rows = 10;
		int cols = 10;

		TestConfiguration config = availableTestConfigurations.get("PositiveTest");
		config.addVariable("rows", rows);
		config.addVariable("cols", cols);

		loadTestConfiguration(config);

		double[][] vector = getRandomMatrix(rows, 1, 0, 1, 1, -1);
		double[][] negativeVector = new double[rows][1];
		for(int i = 0; i < rows; i++) {
			negativeVector[i][0] = -vector[i][0];
		}
		writeInputMatrix("vector", vector);
		writeExpectedMatrix("vector", negativeVector);

		double[][] matrix = getRandomMatrix(rows, cols, 0, 1, 1, -1);
		double[][] negativeMatrix = new double[rows][cols];
		for(int i = 0; i < rows; i++) {
			for(int j = 0; j < cols; j++) {
				negativeMatrix[i][j] = -matrix[i][j];
			}
		}
		writeInputMatrix("matrix", matrix);
		writeExpectedMatrix("matrix", negativeMatrix);

		runTest();

		compareResults();
	}

	@Test
	public void testNegative() {
		if(shouldSkipTest())
			return;

		int rows = 10;
		int cols = 10;

		TestConfiguration config = availableTestConfigurations.get("NegativeTest");
		config.addVariable("rows", rows);
		config.addVariable("cols", cols);

		loadTestConfiguration(config);

		double[][] vector = getRandomMatrix(rows, 1, -1, 0, 1, -1);
		double[][] negativeVector = new double[rows][1];
		for(int i = 0; i < rows; i++) {
			negativeVector[i][0] = -vector[i][0];
		}
		writeInputMatrix("vector", vector);
		writeExpectedMatrix("vector", negativeVector);

		double[][] matrix = getRandomMatrix(rows, cols, -1, 0, 1, -1);
		double[][] negativeMatrix = new double[rows][cols];
		for(int i = 0; i < rows; i++) {
			for(int j = 0; j < cols; j++) {
				negativeMatrix[i][j] = -matrix[i][j];
			}
		}
		writeInputMatrix("matrix", matrix);
		writeExpectedMatrix("matrix", negativeMatrix);

		runTest();

		compareResults();
	}

	@Test
	public void testRandom() {
		if(shouldSkipTest())
			return;

		int rows = 10;
		int cols = 10;

		TestConfiguration config = availableTestConfigurations.get("RandomTest");
		config.addVariable("rows", rows);
		config.addVariable("cols", cols);

		loadTestConfiguration(config);

		double[][] vector = getRandomMatrix(rows, 1, -1, 1, 1, -1);
		double[][] negativeVector = new double[rows][1];
		for(int i = 0; i < rows; i++) {
			negativeVector[i][0] = -vector[i][0];
		}
		writeInputMatrix("vector", vector);
		writeExpectedMatrix("vector", negativeVector);

		double[][] matrix = getRandomMatrix(rows, cols, -1, 1, 1, -1);
		double[][] negativeMatrix = new double[rows][cols];
		for(int i = 0; i < rows; i++) {
			for(int j = 0; j < cols; j++) {
				negativeMatrix[i][j] = -matrix[i][j];
			}
		}
		writeInputMatrix("matrix", matrix);
		writeExpectedMatrix("matrix", negativeMatrix);

		runTest();

		compareResults();
	}

}


text:
package org.hl7.fhir.instance.model.valuesets;

// Generated on Sat, Aug 22, 2015 23:00-0400 for FHIR v0.5.0

public enum V3ContextControl {

        /**
         * The association adds to the existing context associated with the Act.  Both this association and any associations propagated from ancestor Acts are interpreted as being related to this Act.
         */
        _CONTEXTCONTROLADDITIVE,
        /**
         * The association adds to the existing context associated with the Act, but will not propagate to any descendant Acts reached by conducting ActRelationships (see contextControlCode). Examples: If an 'Author' Participation were marked as "Additive, Non-Propagating" it means that the author will be added to the set of author participations that have propagated from ancestor Acts for the purpose of this Act. However only the previously propagated authors will propagate to any child Acts that allow context to be propagated.
         */
        AN,
        /**
         * The association adds to the existing context associated with the Act, and will propagate to any descendant Acts reached by conducting ActRelationships (see contextControlCode). Examples: If an 'Author' Participation were marked as "Additive, Propagating" it means that the author will be added to the set of author participations that have propagated from ancestor Acts, and will itself propagate with the other authors to any child Acts that allow context to be propagated.
         */
        AP,
        /**
         * The association applies only to the current Act and will not propagate to any child Acts that are related via a conducting ActRelationship (refer to contextConductionInd).
         */
        _CONTEXTCONTROLNONPROPAGATING,
        /**
         * The association is added to the existing context associated with the Act, but overrides an association with the same typeCode. However, this overriding association will not propagate to any descendant Acts reached by conducting ActRelationships (see contextControlCode). Examples: If an 'Author' Participation were marked as "Overriding, Non-Propagating" it means that the author will replace the set of author participations that have propagated from ancestor Acts. Furthermore, no author participations whatsoever will propagate to any child Acts that allow context to be propagated.
         */
        ON,
        /**
         * The association adds to the existing context associated with the Act, but replaces associations propagated from ancestor Acts whose typeCodes are the same or more specific.
         */
        _CONTEXTCONTROLOVERRIDING,
        /**
         * The association is added to the existing context associated with the Act, but overrides an association with the same typeCode. This overriding association will propagate to any descendant Acts reached by conducting ActRelationships (see contextControlCode). Examples: If an 'Author' Participation were marked as "Overriding, Propagating" it means that the author will replace the set of author participations that have propagated from ancestor Acts, and will itself be the only author to propagate to any child Acts that allow context to be propagated.
         */
        OP,
        /**
         * The association propagates to any child Acts that are related via a conducting ActRelationship (refer to contextConductionInd).
         */
        _CONTEXTCONTROLPROPAGATING,
        /**
         * added to help the parsers
         */
        NULL;
        public static V3ContextControl fromCode(String codeString) throws Exception {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("_ContextControlAdditive".equals(codeString))
          return _CONTEXTCONTROLADDITIVE;
        if ("AN".equals(codeString))
          return AN;
        if ("AP".equals(codeString))
          return AP;
        if ("_ContextControlNonPropagating".equals(codeString))
          return _CONTEXTCONTROLNONPROPAGATING;
        if ("ON".equals(codeString))
          return ON;
        if ("_ContextControlOverriding".equals(codeString))
          return _CONTEXTCONTROLOVERRIDING;
        if ("OP".equals(codeString))
          return OP;
        if ("_ContextControlPropagating".equals(codeString))
          return _CONTEXTCONTROLPROPAGATING;
        throw new Exception("Unknown V3ContextControl code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case _CONTEXTCONTROLADDITIVE: return "_ContextControlAdditive";
            case AN: return "AN";
            case AP: return "AP";
            case _CONTEXTCONTROLNONPROPAGATING: return "_ContextControlNonPropagating";
            case ON: return "ON";
            case _CONTEXTCONTROLOVERRIDING: return "_ContextControlOverriding";
            case OP: return "OP";
            case _CONTEXTCONTROLPROPAGATING: return "_ContextControlPropagating";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/v3/ContextControl";
        }
        public String getDefinition() {
          switch (this) {
            case _CONTEXTCONTROLADDITIVE: return "The association adds to the existing context associated with the Act.  Both this association and any associations propagated from ancestor Acts are interpreted as being related to this Act.";
            case AN: return "The association adds to the existing context associated with the Act, but will not propagate to any descendant Acts reached by conducting ActRelationships (see contextControlCode). Examples: If an 'Author' Participation were marked as \"Additive, Non-Propagating\" it means that the author will be added to the set of author participations that have propagated from ancestor Acts for the purpose of this Act. However only the previously propagated authors will propagate to any child Acts that allow context to be propagated.";
            case AP: return "The association adds to the existing context associated with the Act, and will propagate to any descendant Acts reached by conducting ActRelationships (see contextControlCode). Examples: If an 'Author' Participation were marked as \"Additive, Propagating\" it means that the author will be added to the set of author participations that have propagated from ancestor Acts, and will itself propagate with the other authors to any child Acts that allow context to be propagated.";
            case _CONTEXTCONTROLNONPROPAGATING: return "The association applies only to the current Act and will not propagate to any child Acts that are related via a conducting ActRelationship (refer to contextConductionInd).";
            case ON: return "The association is added to the existing context associated with the Act, but overrides an association with the same typeCode. However, this overriding association will not propagate to any descendant Acts reached by conducting ActRelationships (see contextControlCode). Examples: If an 'Author' Participation were marked as \"Overriding, Non-Propagating\" it means that the author will replace the set of author participations that have propagated from ancestor Acts. Furthermore, no author participations whatsoever will propagate to any child Acts that allow context to be propagated.";
            case _CONTEXTCONTROLOVERRIDING: return "The association adds to the existing context associated with the Act, but replaces associations propagated from ancestor Acts whose typeCodes are the same or more specific.";
            case OP: return "The association is added to the existing context associated with the Act, but overrides an association with the same typeCode. This overriding association will propagate to any descendant Acts reached by conducting ActRelationships (see contextControlCode). Examples: If an 'Author' Participation were marked as \"Overriding, Propagating\" it means that the author will replace the set of author participations that have propagated from ancestor Acts, and will itself be the only author to propagate to any child Acts that allow context to be propagated.";
            case _CONTEXTCONTROLPROPAGATING: return "The association propagates to any child Acts that are related via a conducting ActRelationship (refer to contextConductionInd).";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case _CONTEXTCONTROLADDITIVE: return "ContextControlAdditive";
            case AN: return "additive, non-propagating";
            case AP: return "additive, propagating";
            case _CONTEXTCONTROLNONPROPAGATING: return "ContextControlNonPropagating";
            case ON: return "overriding, non-propagating";
            case _CONTEXTCONTROLOVERRIDING: return "ContextControlOverriding";
            case OP: return "overriding, propagating";
            case _CONTEXTCONTROLPROPAGATING: return "ContextControlPropagating";
            default: return "?";
          }
    }

}


text:
define([
    'views/buyEmail',
    'controllers/common/mainFunctions'
], function(view, mainFunctions){
    function BuyEmail(parent, widgetType) {
        this.parent     = parent;
        this.product    = parent.product;
        this.account    = parent.account;
        this.el         = $('#' + parent.contentID);
        this.step       = 'buyEmail';
        this.view       = view;
        this.widgetType = widgetType;
    }
    BuyEmail.prototype = Object.create( mainFunctions.prototype );

    BuyEmail.prototype.nextStep = function(){
        $.ajax({
                url: window.klicklyURL + '/api/v1/account/checkClientEmail',
                data: this.account.toJSON()
            })
            .done(this.success.bind(this))
            .error(this.error.bind(this));
    };
    BuyEmail.prototype.error = function(response){
        var text = (response.responseJSON && response.responseJSON.message) || 'Unknown server error';
        this.view.showError(text);
    };
    BuyEmail.prototype.success = function(){
        if (this.widgetType === 'shipping_first' && this.product.get('type') == 'product') {
            this.parent.initView('buyAddress');
        } else if (this.product.get('type') === 'promotion') {
            this.parent.initView('buyConfirm');
        } else {
            this.parent.initView('buyCard');
        }
    };

    return BuyEmail;
});


text:
package com.swifts.frame.modules.sys.dao;

import java.util.List;

import com.swifts.frame.common.persistence.CrudDao;
import com.swifts.frame.common.persistence.annotation.MyBatisDao;
import com.swifts.frame.modules.sys.entity.Dict;

/**
 * 字典DAO接口
 * @author ThinkGem
 * @version 2014-05-16
 */
@MyBatisDao
public interface DictDao extends CrudDao<Dict> {

	public List<String> findTypeList(Dict dict);

}


text:
<?php

namespace api\modules\api\v1\controllers;

use Yii;
use yii\web\Response;
use yii\rest\ActiveController;
use yii\filters\VerbFilter;
use yii\filters\ContentNegotiator;

class BaseController extends ActiveController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                    'application/xml' => Response::FORMAT_XML,
                ],
            ],
            'verbFilter' => [
                'class' => VerbFilter::className(),
                'actions' => $this->verbs(),
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        Yii::$app->response->headers->add('Access-Control-Allow-Origin', '*');
        Yii::$app->response->headers->add('Access-Control-Allow-Headers', 'Accept, Authorization');
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function runAction($id, $params = [])
    {
        try {
            $result = parent::runAction($id, $params);
        } catch (\yii\web\HttpException $e) {
            if ($e->getCode() > 0) {
                throw $e;
            }
            $excClass  = get_class($e);
            $exception = ($excClass == 'yii\web\HttpException')
                ? new $excClass($e->statusCode, $e->getMessage(), $e->statusCode)
                : new $excClass($e->getMessage(), $e->statusCode)
                ;
            throw $exception;
        }

        return $result;
    }
}


text:
package org.chaston.oakfunds.model;

import org.chaston.oakfunds.storage.AttributeMethod;
import org.chaston.oakfunds.storage.RecordType;

/**
 * TODO(mchaston): write JavaDocs
 */
public interface AnnualRecurringEvent extends RecurringEvent<AnnualRecurringEvent> {

  static final RecordType<AnnualRecurringEvent> TYPE =
      RecordType.builder("annual_recurring_event", AnnualRecurringEvent.class)
          .extensionOf(RecurringEvent.TYPE)
          .build();

  String ATTRIBUTE_PAYMENT_MONTH = "payment_month";

  @AttributeMethod(attribute = ATTRIBUTE_PAYMENT_MONTH, required = true)
  int getPaymentMonth();
}


text:
import axios from "axios";
import * as type from "../constants/ActionTypes";
const apiKey = "d330b017d2ee6e4d377e7641733ce77c";

export function getNowPlayingList(page) {
  const request = axios.get(
    `https://api.themoviedb.org/3/movie/now_playing?api_key=${apiKey}&language=en-US&page=${page}`
  );
  return {
    type: type.RETRIEVE_NOWPLAYING_LIST,
    payload: request
  };
}

export function getMovieDetail(id) {
  const request = axios.get(
    `https://api.themoviedb.org/3/movie/${id}?api_key=${apiKey}&language=en-US`
  );
  return {
    type: type.RETRIEVE_MOVIE_DETAIL,
    payload: request
  };
}

export function getVideo(id) {
  const request = axios.get(
    `https://api.themoviedb.org/3/movie/${id}/videos?api_key=${apiKey}&language=en-US`
  );
  return {
    type: type.RETRIEVE_VIDEO,
    payload: request
  };
}

export function getReview(id) {
  const request = axios.get(
    `https://api.themoviedb.org/3/movie/${id}/reviews?api_key=${apiKey}&language=en-US&page=1`
  );
  return {
    type: type.RETRIEVE_REVIEW,
    payload: request
  };
}

export function searchByGenre(id) {
  const request = axios.get(
    `https://api.themoviedb.org/3/genre/${id}/movies?api_key=${apiKey}&language=en-US&include_adult=false&sort_by=created_at.asc`
  );
  return {
    type: type.SEARCH_BY_GENRE,
    payload: request
  };
}

export function getGenreData() {
  const request = axios.get(
    `https://api.themoviedb.org/3/genre/movie/list?api_key=${apiKey}&language=en-US`
  );
  return {
    type: type.RETRIEVE_GENRE,
    payload: request
  };
}

export function getUpcoming(page) {
  const request = axios.get(
    `https://api.themoviedb.org/3/movie/upcoming?api_key=${apiKey}&language=en-US&page=${page}`
  );
  return {
    type: type.RETRIVE_UPCOMING,
    payload: request
  };
}

export function saveMovie(movieInfo) {
  const request = axios.post("/api/movie/", movieInfo);
  return {
    type: type.SAVE_MOVIE,
    payload: request
  };
}
export function getSavedMovie() {
  const request = axios.get("/api/movie");
  return {
    type: type.RETRIVE_SAVED_MOVIE,
    payload: request
  };
}


text:
"""
This module contains classes and functions for predicting promoters in a genome.
"""

"""
Copyright 2010 Jarl Haggerty

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.
"""

from neofelis import utils
import re
import urllib
import functools
import os.path

#Make sure the directory for BPROM results exists.
if not os.path.isdir("promoterPredictions"):
  os.mkdir("promoterPredictions")

class Promoter():
  """
  Class for storing information about a promoter.
  """
  def __init__(self, start, stop, score):
    self.location = [start, stop]
    self.score = score

  def __str__(self):
    result = "<"
    result += "location = " + str(map(str, self.location)) + ", "
    result += "score = " + str(self.score)
    result += ">"
    return result

def parseFruitfly(fruitflyData):
  """
  bpromData: Contents of the body of a Fruitfly prediction.

  return:    A list of Promoter objects representing the results of the BPROM prediction
  """
  fruitflyData = fruitflyData.replace("", "").replace("", "")
  forwardPromoters = re.findall(r"\s*(\d+)\s+\d+\s+(\d?\.?\d+)\s+([ACGT]+)
", fruitflyData[:fruitflyData.find("Predictions for the reverse strand")])
  print "Hi Joe", len(forwardPromoters)
  reversePromoters = re.findall(r"\s*\d+\s+(\d+)\s+(\d?\.?\d+)\s+([ACGT]+)
", fruitflyData[fruitflyData.find("Predictions for the reverse strand"):])
  result = map(lambda x: Promoter(int(x[0]), int(x[0])+len(x[2])-1, float(x[1])), forwardPromoters)
  result += map(lambda x: Promoter(int(x[0])+len(x[2]), int(x[0])+1, float(x[1])), reversePromoters)
  return result

def cachedPrediction(genome, fileName):
  """
  genome:   Genome as a string.
  fileName: File to save the prediction results in.

  return:   Results of the promoter prediction stored in a list of Promoter objects.

  If the file specified by fileName already exists then this function simply parses the file
  already there.
  """
  if not os.path.isfile(fileName):
    results = urllib.urlopen("http://www.fruitfly.org/cgi-bin/seq_tools/promoter.pl",
                             urllib.urlencode({"organism" : "prokaryote", "reverse" : "yes", "threshold" : "0.9", "text" : genome}))
    resultString = results.read()
    results.close()
    output = open(fileName, "w")
    output.write(resultString)
    output.close()
  input = open(fileName, "r")
  results = parseFruitfly(input.read())
  input.close()
  return results

def findPromoters(query, name):
  """
  query:     Name of the query file.
  name:      Name of the genome.

  return:    A list of Promoter objects for the forward and reverse strands.

  This function uses the Berkeley Drosophila Genome Project website to predict promoters and parses the results into the list of Promoter objects
  that are returned.
  """
  genome = utils.loadGenome(query)
  return cachedPrediction(genome, "promoterPredictions/" + name + ".html")