text:
package controllers

import kafka.manager.{KafkaVersion, ApiError, ClusterConfig}
import models.FollowLink
import models.form._
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.validation.{Valid, Invalid, Constraint}
import play.api.data.validation.Constraints._
import play.api.mvc._

import scala.concurrent.Future
import scala.util.{Success, Failure, Try}
import scalaz.{-\/, \/-}

/**
 * @author hiral
 */
object Cluster extends Controller {
  import play.api.libs.concurrent.Execution.Implicits.defaultContext

  private[this] val kafkaManager = KafkaManagerContext.getKafkaManager

  val validateName : Constraint[String] = Constraint("validate name") { name =>
    Try {
      ClusterConfig.validateName(name)
    } match {
      case Failure(t) => Invalid(t.getMessage)
      case Success(_) => Valid
    }
  }

  val validateZkHosts : Constraint[String] = Constraint("validate zookeeper hosts") { zkHosts =>
    Try {
      ClusterConfig.validateZkHosts(zkHosts)
    } match {
      case Failure(t) => Invalid(t.getMessage)
      case Success(_) => Valid
    }
  }

  val validateOperation : Constraint[String] = Constraint("validate operation value") {
    case "Enable" => Valid
    case "Disable" => Valid
    case "Delete" => Valid
    case "Update" => Valid
    case any: Any => Invalid(s"Invalid operation value: $any")
  }

  val validateKafkaVersion: Constraint[String] = Constraint("validate kafka version") { version =>
    Try {
      KafkaVersion(version)
    } match {
      case Failure(t) => Invalid(t.getMessage)
      case Success(_) => Valid
    }
  }

  val clusterConfigForm = Form(
    mapping(
      "name" -> nonEmptyText.verifying(maxLength(250), validateName),
      "kafkaVersion" -> nonEmptyText.verifying(validateKafkaVersion),
      "zkHosts" -> nonEmptyText.verifying(validateZkHosts),
      "zkMaxRetry" -> ignored(100 : Int),
      "jmxEnabled" -> boolean
    )(ClusterConfig.apply)(ClusterConfig.customUnapply)
  )

  val updateForm = Form(
    mapping(
      "operation" -> nonEmptyText.verifying(validateOperation),
      "name" -> nonEmptyText.verifying(maxLength(250), validateName),
      "kafkaVersion" -> nonEmptyText.verifying(validateKafkaVersion),
      "zkHosts" -> nonEmptyText.verifying(validateZkHosts),
      "zkMaxRetry" -> ignored(100 : Int),
      "jmxEnabled" -> boolean
    )(ClusterOperation.apply)(ClusterOperation.customUnapply)
  )

  def addCluster = Action.async { implicit request =>
    Future.successful(Ok(views.html.cluster.addCluster(clusterConfigForm)))
  }

  def updateCluster(c: String) = Action.async { implicit request =>
    kafkaManager.getClusterConfig(c).map { errorOrClusterConfig =>
      Ok(views.html.cluster.updateCluster(c,errorOrClusterConfig.map { cc =>
        updateForm.fill(ClusterOperation.apply(Update.toString,cc.name,cc.version.toString,cc.curatorConfig.zkConnect,cc.curatorConfig.zkMaxRetry,cc.jmxEnabled))
      }))
    }
  }

  def handleAddCluster = Action.async { implicit request =>
    clusterConfigForm.bindFromRequest.fold(
      formWithErrors => Future.successful(BadRequest(views.html.cluster.addCluster(formWithErrors))),
      clusterConfig => {
        kafkaManager.addCluster(clusterConfig.name, clusterConfig.version.toString, clusterConfig.curatorConfig.zkConnect, clusterConfig.jmxEnabled).map { errorOrSuccess =>
          Ok(views.html.common.resultOfCommand(
            views.html.navigation.defaultMenu(),
            models.navigation.BreadCrumbs.withView("Add Cluster"),
            errorOrSuccess,
            "Add Cluster",
            FollowLink("Go to cluster view.",routes.Application.cluster(clusterConfig.name).toString()),
            FollowLink("Try again.",routes.Cluster.addCluster().toString())
          ))
        }
      }
    )
  }

  def handleUpdateCluster(c: String) = Action.async { implicit request =>
    updateForm.bindFromRequest.fold(
      formWithErrors => Future.successful(BadRequest(views.html.cluster.updateCluster(c,\/-(formWithErrors)))),
      clusterOperation => clusterOperation.op match {
        case Enable =>
          kafkaManager.enableCluster(c).map { errorOrSuccess =>
            Ok(views.html.common.resultOfCommand(
              views.html.navigation.defaultMenu(),
              models.navigation.BreadCrumbs.withViewAndCluster("Enable Cluster",c),
              errorOrSuccess,
              "Enable Cluster",
              FollowLink("Go to cluster list.",routes.Application.index().toString()),
              FollowLink("Back to cluster list.",routes.Application.index().toString())
            ))
          }
        case Disable =>
          kafkaManager.disableCluster(c).map { errorOrSuccess =>
            Ok(views.html.common.resultOfCommand(
              views.html.navigation.defaultMenu(),
              models.navigation.BreadCrumbs.withViewAndCluster("Disable Cluster",c),
              errorOrSuccess,
              "Disable Cluster",
              FollowLink("Back to cluster list.",routes.Application.index().toString()),
              FollowLink("Back to cluster list.",routes.Application.index().toString())
            ))
          }
        case Delete =>
          kafkaManager.deleteCluster(c).map { errorOrSuccess =>
            Ok(views.html.common.resultOfCommand(
              views.html.navigation.defaultMenu(),
              models.navigation.BreadCrumbs.withViewAndCluster("Delete Cluster",c),
              errorOrSuccess,
              "Delete Cluster",
              FollowLink("Back to cluster list.",routes.Application.index().toString()),
              FollowLink("Back to cluster list.",routes.Application.index().toString())
            ))
          }
        case Update =>
          kafkaManager.updateCluster(
            clusterOperation.clusterConfig.name,
            clusterOperation.clusterConfig.version.toString,
            clusterOperation.clusterConfig.curatorConfig.zkConnect,
            clusterOperation.clusterConfig.jmxEnabled
          ).map { errorOrSuccess =>
            Ok(views.html.common.resultOfCommand(
              views.html.navigation.defaultMenu(),
              models.navigation.BreadCrumbs.withViewAndCluster("Update Cluster",c),
              errorOrSuccess,
              "Update Cluster",
              FollowLink("Go to cluster view.",routes.Application.cluster(clusterOperation.clusterConfig.name).toString()),
              FollowLink("Try again.",routes.Cluster.updateCluster(c).toString())
            ))
          }
        case Unknown(opString) =>
          Future.successful(Ok(views.html.common.resultOfCommand(
            views.html.navigation.defaultMenu(),
            models.navigation.BreadCrumbs.withViewAndCluster("Unknown Cluster Operation",c),
            -\/(ApiError(s"Unknown operation $opString")),
            "Unknown Cluster Operation",
            FollowLink("Back to cluster list.",routes.Application.index().toString()),
            FollowLink("Back to cluster list.",routes.Application.index().toString())
          )))
      }
    )
  }
}


text:
import PropTypes from 'prop-types';
import React from 'react';
import { NavLink } from 'react-router-dom';

// Redux
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as dashboardActions from 'app/reducers/dashboardReducer';
import * as global from 'app/reducers/globalReducer';

// UI
import { Row, Col, Card, CardImage, CardBody, CardTitle, CardText, Button, Fa } from 'mdbreact';
import { FloatingActionButton, IconMenu, IconButton, MenuItem } from 'material-ui';
import { DashboardFrame, Loading, Input, LoadingButton } from 'app/components';

const IMAGE_HEIGHT = 120;

class DashboardPage extends React.Component {
    state = {
        toggle: false,
        name: '',
        description: ''
    };
    render() {
        const { toggle, name, description } = this.state;
        const { groups, fetching, actions } = this.props;
        if (!groups) {
            return <Loading />;
        }
        const errors = {
            name: name.length === 0 ? 'required field' : '',
            description: description.length === 0 ? 'required field' : ''
        };
        return (
            <DashboardFrame
                bottom={
                    <Button
                        onTouchTap={() => this.setState({ toggle: true })}
                        color="indigo"
                        outline={toggle}
                    >+ New Group</Button>
                }
            >

Dashboard

                {groups.length === 0 &&

No groups.

                }
                <Row>
                    {groups.map((group, i) => {
                        return (
                            <Col className="mb-3" key={i} xs="12" sm="6" md="4" lg="4">
                                <Card
                                    onMouseEnter={() => this.setState({ mouse: i })}
                                    onMouseLeave={() => this.setState({ mouse: null })}
                                >

                                            <IconMenu
                                                iconButtonElement={<IconButton iconClassName="fa fa-ellipsis-v" />}
                                                anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
                                                targetOrigin={{ horizontal: 'right', vertical: 'top' }}
                                            >
                                                <MenuItem
                                                    onTouchTap={() => actions.deleteGroup(group.id)}
                                                    leftIcon={<Fa icon="trash" />}
                                                    primaryText="Delete"
                                                />
                                            </IconMenu>

                                        <CardImage
                                            height={IMAGE_HEIGHT + ''}
                                            className="obj-fit"
                                            src={`https://avatar.tobi.sh/${group.id}`}
                                        />

                                    <CardBody>
                                        <CardTitle>{group.title}</CardTitle>
                                        <CardText>{group.description}</CardText>
                                        <NavLink to={`/dashboard/group/${group.id}`}>
                                            <FloatingActionButton
                                                mini
                                            ><Fa icon="external-link" /></FloatingActionButton>
                                        </NavLink>
                                    </CardBody>
                                </Card>
                            </Col>
                        );
                    })}
                    {toggle &&
                        <Col className="mb-3" xs="12" sm="6" md="4" lg="4">
                            <Card>
                                <CardBody>
                                    <CardTitle>
                                        <Input
                                            autoFocus
                                            hint="Group Name"
                                            size="sm"
                                            type="text"
                                            value={name}
                                            onChange={(e) => this.setState({ name: e.target.value })}
                                        />
                                    </CardTitle>
                                    <CardText>
                                        <Input
                                            hint="Group Description"
                                            size="sm"
                                            type="text"
                                            value={description}
                                            onChange={(e) => this.setState({ description: e.target.value })}
                                        />
                                    </CardText>
                                    <LoadingButton
                                        loading={fetching}
                                        disabled={!!errors.name || !!errors.description}
                                        onTouchTap={() => actions.createGroup(name, description).then(() => this.setState({ toggle: false, name: '', description: '' }))}
                                        color="success"
                                        size="sm"
                                        outline={!!errors.name || !!errors.description}
                                    ><Fa icon="check" /></LoadingButton>
                                    <Button
                                        onTouchTap={() => this.setState({ toggle: false, name: '', description: '' })}
                                        size="sm"
                                        color="danger"
                                        outline
                                    ><Fa icon="times" /></Button>
                                </CardBody>
                            </Card>
                        </Col>
                    }
                </Row>
            </DashboardFrame>
        );
    }
}

DashboardPage.propTypes = {
    groups: PropTypes.array,
    fetching: PropTypes.bool.isRequired,
    actions: PropTypes.object.isRequired
};

const mapStateToProps = (state) => {
    return {
        groups: state.dashboard.groups,
        fetching: state.dashboard.fetching
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators({...dashboardActions, ...global}, dispatch)
    };
};

DashboardPage = connect(
    mapStateToProps,
    mapDispatchToProps
)(DashboardPage);

export default DashboardPage;

redpajama_set_name: RedPajamaGithub


text:
class Computer
  attr_accessor :team, :current_player

  INFINITY = 1.0/0.0

  def initialize(team)
    @team = team
    @current_player = nil
  end

  def negamax(rules,team,depth,alpha,beta)
    opponent = get_opponent(team)
    best_score = -1.0/0
    if rules.game_over?
      return board_score(rules, team) / depth
    else
      rules.board.get_moves.each do |move|
        rules.board.set_move(move,team)
        score = -negamax(rules, opponent, depth + 1,-beta,-alpha)
        rules.board.undo_move(move)
        if score > best_score
          best_score = score
        end
        if score > alpha
          alpha = score
        end
        if alpha >= beta
          break
        end
      end
      return best_score
    end
  end

  def make_move(rules, team)
    best_move = nil
    best_score = -INFINITY
    opponent = get_opponent(team)
    rules.board.get_moves.each do |move|
      rules.board.set_move(move,team)
      score = -negamax(rules, opponent, 1,-INFINITY, INFINITY)
      rules.board.undo_move(move)
      if score > best_score
        best_score = score
        best_move = move
      end
    end
    return best_move
  end

  def get_opponent(team)
    team == 'X' ? 'O' : 'X'
  end

  def board_score(rules, team)
    if rules.win_test(team)
      return 1.0
    elsif rules.win_test(get_opponent(team))
      return -1.0
    else
      return 0.0
    end
  end
end


text:
layout: page
title:
permalink: /news/
---

2021

<time datetime="2021-04">2021-04</time>
	Win the 3rd place in CVPR2021 Security AI Challenger Track1:
	White-box Adversarial Attacks on ML Defense Models

<time datetime="2021-04">2021-04</time>
	One paper BDD4BNN: A BDD-based Quantitative Analysis Framework for Binarized Neural Networks is accepted by CAV 2021.


text:
package com.rationaleemotions.grid.client;

import com.rationaleemotions.grid.session.SeleniumSessions;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.net.URI;

/**
 * @author IgorV Date: 13.2.2017
 */
public class RequestForwardingClient {

	private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

	private static final String NODE_HOST = "http://%s:%d";

	private final HttpClientProvider httpClientProvider;
	private final String endpoint;

	public RequestForwardingClient(String host, int port) {
		this(String.format(NODE_HOST, host, port), new HttpClientProvider());
	}

	public RequestForwardingClient(String endpoint, HttpClientProvider httpClientProvider) {
		this.httpClientProvider = httpClientProvider;
		this.endpoint = endpoint;
	}

	public void forwardRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
			throws IOException {
		try (CloseableHttpClient httpClient = httpClientProvider.provide()) {
			HttpRequestBase httpRequest = createHttpRequest(servletRequest);

			CloseableHttpResponse extensionResponse = httpClient.execute(httpRequest);
			HttpResponseConverter.copy(extensionResponse, servletResponse);
		}
	}

	private HttpRequestBase createHttpRequest(HttpServletRequest request) throws IOException {
		String method = request.getMethod();
		LOGGER.debug("Creating {} request to forward", method);
		HttpRequestBase httpRequestBase = null;
		switch (method) {
		case HttpPost.METHOD_NAME:
			httpRequestBase = createPostRequest(request);
			break;
		case HttpGet.METHOD_NAME:
			httpRequestBase = new HttpGet();
			break;
		case HttpPut.METHOD_NAME:
			httpRequestBase = new HttpPut();
			break;
		case HttpDelete.METHOD_NAME:
			httpRequestBase = new HttpDelete();
			break;
		default:
			break;
		}

		if (httpRequestBase == null) {
			throw new UnsupportedHttpMethodException(method);
		}
		URI uri = URI.create(endpoint + SeleniumSessions.trimSessionPath(request.getPathInfo()));
		LOGGER.debug("Trimming session id from path, new path: {}", uri);
		httpRequestBase.setURI(uri);

		return httpRequestBase;
	}

	private HttpRequestBase createPostRequest(HttpServletRequest request) throws IOException {
		HttpPost httpPost = new HttpPost();
		String strContentType = request.getContentType();
		LOGGER.debug("Posting request with mime-type: {}", strContentType);
		ContentType contentType = ContentType.getByMimeType(strContentType);
		if (null == contentType)
			contentType = ContentType.APPLICATION_OCTET_STREAM;
		LOGGER.debug("Posting request with mime-type {} handled as: {}", strContentType, contentType);
		InputStreamEntity entity = new InputStreamEntity(request.getInputStream(), request.getContentLength(),
				contentType);
		httpPost.setEntity(entity);

		return httpPost;
	}
}


text:
namespace google {
namespace cloud {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {

using ::google::cloud::testing_util::IsOk;
using ::google::cloud::testing_util::MockCompletionQueueImpl;
using ::testing::ReturnRef;

struct FakeRequest {
  std::string key;
};

struct FakeResponse {
  std::string key;
  std::string value;
};

using MockReturnType =
    std::unique_ptr<grpc::ClientAsyncReaderInterface<FakeResponse>>;

class MockReader : public grpc::ClientAsyncReaderInterface<FakeResponse> {
 public:
  MOCK_METHOD(void, Read, (FakeResponse*, void*), (override));
  MOCK_METHOD(void, Finish, (grpc::Status*, void*), (override));
  MOCK_METHOD(void, StartCall, (void*), (override));
  MOCK_METHOD(void, ReadInitialMetadata, (void*), (override));
};

class MockStub {
 public:
  MOCK_METHOD(MockReturnType, FakeRpc,
              (grpc::ClientContext*, FakeRequest const&,
               grpc::CompletionQueue*),
              ());
};

TEST(AsyncStreamingReadRpcTest, Basic) {
  MockStub mock;
  EXPECT_CALL(mock, FakeRpc)
      .WillOnce([](grpc::ClientContext*, FakeRequest const&,
                   grpc::CompletionQueue*) {
        auto stream = absl::make_unique<MockReader>();
        EXPECT_CALL(*stream, StartCall).Times(1);
        EXPECT_CALL(*stream, Read)
            .WillOnce([](FakeResponse* response, void*) {
              response->key = "key0";
              response->value = "value0_0";
            })
            .WillOnce([](FakeResponse*, void*) {});
        EXPECT_CALL(*stream, Finish).WillOnce([](grpc::Status* status, void*) {
          *status = grpc::Status::OK;
        });
        return stream;
      });

  auto mock_cq = std::make_shared<MockCompletionQueueImpl>();
  grpc::CompletionQueue grpc_cq;
  EXPECT_CALL(*mock_cq, cq).WillRepeatedly(ReturnRef(grpc_cq));

  std::deque<std::shared_ptr<AsyncGrpcOperation>> operations;
  auto notify_next_op = [&](bool ok = true) {
    auto op = std::move(operations.front());
    operations.pop_front();
    op->Notify(ok);
  };

  EXPECT_CALL(*mock_cq, StartOperation)
      .WillRepeatedly([&operations](std::shared_ptr<AsyncGrpcOperation> op,
                                    absl::FunctionRef<void(void*)> call) {
        void* tag = op.get();
        operations.push_back(std::move(op));
        call(tag);
      });

  auto user_project = [](std::string const& value) {
    return Options{}.set<UserProjectOption>(value);
  };
  auto check_read_span = [](std::string const& expected) {
    return [expected](future<absl::optional<FakeResponse>> f) {
      EXPECT_EQ(CurrentOptions().get<UserProjectOption>(), expected);
      return f.get();
    };
  };

  google::cloud::CompletionQueue cq(mock_cq);

  OptionsSpan span(user_project("create"));
  auto stream = MakeStreamingReadRpc<FakeRequest, FakeResponse>(
      cq, absl::make_unique<grpc::ClientContext>(), FakeRequest{},
      [&mock](grpc::ClientContext* context, FakeRequest const& request,
              grpc::CompletionQueue* cq) {
        return mock.FakeRpc(context, request, cq);
      });

  OptionsSpan start_span(user_project("start"));
  auto start = stream->Start().then([](future<bool> f) {
    EXPECT_EQ(CurrentOptions().get<UserProjectOption>(), "start");
    return f.get();
  });
  ASSERT_EQ(1, operations.size());
  OptionsSpan start_clear(Options{});
  notify_next_op();
  EXPECT_TRUE(start.get());

  OptionsSpan read0_span(user_project("read0"));
  auto read0 = stream->Read().then(check_read_span("read0"));
  ASSERT_EQ(1, operations.size());
  OptionsSpan read0_clear(Options{});
  notify_next_op();
  auto response0 = read0.get();
  ASSERT_TRUE(response0.has_value());
  EXPECT_EQ("key0", response0->key);
  EXPECT_EQ("value0_0", response0->value);

  OptionsSpan read1_span(user_project("read1"));
  auto read1 = stream->Read().then(check_read_span("read1"));
  ASSERT_EQ(1, operations.size());
  OptionsSpan read1_clear(Options{});
  notify_next_op(false);
  auto response1 = read1.get();
  EXPECT_FALSE(response1.has_value());

  OptionsSpan finish_span(user_project("finish"));
  auto finish = stream->Finish().then([](future<Status> f) {
    EXPECT_EQ(CurrentOptions().get<UserProjectOption>(), "finish");
    return f.get();
  });
  ASSERT_EQ(1, operations.size());
  OptionsSpan finish_clear(Options{});
  notify_next_op();
  EXPECT_THAT(finish.get(), IsOk());
}

TEST(AsyncStreamingReadRpcTest, Error) {
  auto stream = AsyncStreamingReadRpcError<FakeResponse>(
      Status(StatusCode::kPermissionDenied, "uh-oh"));

  stream.Cancel();
  EXPECT_FALSE(stream.Start().get());
  EXPECT_FALSE(stream.Read().get().has_value());
  EXPECT_EQ(Status(StatusCode::kPermissionDenied, "uh-oh"),
            stream.Finish().get());
}

}  // namespace
}  // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace cloud
}  // namespace google


text:
layout: one_column
is_e98: true
author_name: Mark Miyashita
author_url: http://markmiyashita.com
google_plus: 101180624276428786239
---

{{ content }}


text:
@implementation DCCustimizableCommand

@synthesize userInfo = _userInfo;

- (void)dealloc {
    self.userInfo = nil;

    [super dealloc];
}

- (void)execute {
}

- (void)undo {
}

@end


text:
<!DOCTYPE html>

	<meta charset="UTF-8" />
	<title>Draggable Visual Test : Draggable option iframeFix selector</title>
	<link rel="stylesheet" href="../visual.css" type="text/css" />
	<link rel="stylesheet" href="../../../themes/base/jquery.ui.all.css" type="text/css">

 Draggable


text:
package runtime

var Fadd64 = fadd64
var Fsub64 = fsub64
var Fmul64 = fmul64
var Fdiv64 = fdiv64
var F64to32 = f64to32
var F32to64 = f32to64
var Fcmp64 = fcmp64
var Fintto64 = fintto64
var F64toint = f64toint

func entersyscall()
func exitsyscall()
func golockedOSThread() bool

var Entersyscall = entersyscall
var Exitsyscall = exitsyscall
var LockedOSThread = golockedOSThread


text:
namespace syncer {

class KeyDerivationParams;
struct NigoriState;

// Interface representing an intended local change to the Nigori state that
// is pending a commit to the sync server.
class PendingLocalNigoriCommit {
 public:
  static std::unique_ptr<PendingLocalNigoriCommit> ForSetCustomPassphrase(
      const std::string& passphrase,
      const KeyDerivationParams& key_derivation_params);

  static std::unique_ptr<PendingLocalNigoriCommit> ForKeystoreInitialization();

  static std::unique_ptr<PendingLocalNigoriCommit> ForKeystoreReencryption();

  PendingLocalNigoriCommit() = default;

  PendingLocalNigoriCommit(const PendingLocalNigoriCommit&) = delete;
  PendingLocalNigoriCommit& operator=(const PendingLocalNigoriCommit&) = delete;

  virtual ~PendingLocalNigoriCommit() = default;

  // Attempts to modify |*state| to reflect the intended commit. Returns true if
  // the change was successfully applied (which may include the no-op case) or
  // false if it no longer applies (leading to OnFailure()).
  //
  // |state| must not be null.
  virtual bool TryApply(NigoriState* state) const = 0;

  // Invoked when the commit has been successfully acked by the server.
  // |observer| must not be null.
  virtual void OnSuccess(const NigoriState& state,
                         SyncEncryptionHandler::Observer* observer) = 0;

  // Invoked when the change no longer applies or was aborted for a different
  // reason (e.g. sync disabled). |observer| must not be null.
  virtual void OnFailure(SyncEncryptionHandler::Observer* observer) = 0;
};

}  // namespace syncer

#endif  // COMPONENTS_SYNC_NIGORI_PENDING_LOCAL_NIGORI_COMMIT_H_


text:
cask 'wavebox' do
  version '4.5.10'
  sha256 '0aac1be54b390f2c64c5bada798c97cf3683e795354eb990796191834dcec60c'

  # github.com/wavebox/waveboxapp was verified as official when first introduced to the cask
  url "https://github.com/wavebox/waveboxapp/releases/download/v#{version}/Wavebox_#{version.dots_to_underscores}_osx.dmg"
  appcast 'https://github.com/wavebox/waveboxapp/releases.atom'
  name 'Wavebox'
  homepage 'https://wavebox.io/'

  auto_updates true

  app 'Wavebox.app'

  uninstall quit:       'io.wavebox.wavebox',
            login_item: 'Wavebox'

  zap trash: [
               '~/Library/Application Support/wavebox',
               '~/Library/Caches/io.wavebox.wavebox',
               '~/Library/Caches/io.wavebox.wavebox.ShipIt',
               '~/Library/Preferences/io.wavebox.wavebox.helper.plist',
               '~/Library/Preferences/io.wavebox.wavebox.plist',
               '~/Library/Saved Application State/io.wavebox.wavebox.savedState',
             ]
end


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/winhttp.h>

#include "ncacn_http.h"
#include "rpc_client.h"

#include "rts.h"

/**
 * [MS-RPCH]: Remote Procedure Call over HTTP Protocol Specification:
 * http://msdn.microsoft.com/en-us/library/cc243950/
 */

/**
 *                                      Connection Establishment\n
 *
 *     Client                  Outbound Proxy           Inbound Proxy                 Server\n
 *        |                         |                         |                         |\n
 *        |-----------------IN Channel Request--------------->|                         |\n
 *        |---OUT Channel Request-->|                         |<-Legacy Server Response-|\n
 *        |                         |<--------------Legacy Server Response--------------|\n
 *        |                         |                         |                         |\n
 *        |---------CONN_A1-------->|                         |                         |\n
 *        |----------------------CONN_B1--------------------->|                         |\n
 *        |                         |----------------------CONN_A2--------------------->|\n
 *        |                         |                         |                         |\n
 *        |<--OUT Channel Response--|                         |---------CONN_B2-------->|\n
 *        |<--------CONN_A3---------|                         |                         |\n
 *        |                         |<---------------------CONN_C1----------------------|\n
 *        |                         |                         |<--------CONN_B3---------|\n
 *        |<--------CONN_C2---------|                         |                         |\n
 *        |                         |                         |                         |\n
 *
 */

BOOL rts_connect(rdpRpc* rpc)
{
	RPC_PDU* pdu;
	rpcconn_rts_hdr_t* rts;
	HttpResponse* http_response;

	/**
	 * Connection Opening
	 *
	 * When opening a virtual connection to the server, an implementation of this protocol MUST perform
	 * the following sequence of steps:
	 *
	 * 1. Send an IN channel request as specified in section 2.1.2.1.1, containing the connection timeout,
	 *    ResourceType UUID, and Session UUID values, if any, supplied by the higher-layer protocol or application.
	 *
	 * 2. Send an OUT channel request as specified in section 2.1.2.1.2.
	 *
	 * 3. Send a CONN/A1 RTS PDU as specified in section 2.2.4.2
	 *
	 * 4. Send a CONN/B1 RTS PDU as specified in section 2.2.4.5
	 *
	 * 5. Wait for the connection establishment protocol sequence as specified in 3.2.1.5.3.1 to complete
	 *
	 * An implementation MAY execute steps 1 and 2 in parallel. An implementation SHOULD execute steps
	 * 3 and 4 in parallel. An implementation MUST execute step 3 after completion of step 1 and execute
	 * step 4 after completion of step 2.
	 *
	 */

	rpc->VirtualConnection->State = VIRTUAL_CONNECTION_STATE_INITIAL;
	DEBUG_RTS("VIRTUAL_CONNECTION_STATE_INITIAL");

	rpc->client->SynchronousSend = TRUE;
	rpc->client->SynchronousReceive = TRUE;

	if (!rpc_ntlm_http_out_connect(rpc))
	{
		fprintf(stderr, "rpc_out_connect_http error!\n");
		return FALSE;
	}

	if (rts_send_CONN_A1_pdu(rpc) != 0)
	{
		fprintf(stderr, "rpc_send_CONN_A1_pdu error!\n");
		return FALSE;
	}

	if (!rpc_ntlm_http_in_connect(rpc))
	{
		fprintf(stderr, "rpc_in_connect_http error!\n");
		return FALSE;
	}

	if (rts_send_CONN_B1_pdu(rpc) != 0)
	{
		fprintf(stderr, "rpc_send_CONN_B1_pdu error!\n");
		return FALSE;
	}

	rpc->VirtualConnection->State = VIRTUAL_CONNECTION_STATE_OUT_CHANNEL_WAIT;
	DEBUG_RTS("VIRTUAL_CONNECTION_STATE_OUT_CHANNEL_WAIT");

	/**
	 * Receive OUT Channel Response
	 *
	 * A client implementation MUST NOT accept the OUT channel HTTP response in any state other than
	 * Out Channel Wait. If received in any other state, this HTTP response is a protocol error. Therefore,
	 * the client MUST consider the virtual connection opening a failure and indicate this to higher layers
	 * in an implementation-specific way. The Microsoft Windows® implementation returns
	 * RPC_S_PROTOCOL_ERROR, as specified in [MS-ERREF], to higher-layer protocols.
	 *
	 * If this HTTP response is received in Out Channel Wait state, the client MUST process the fields of
	 * this response as defined in this section.
	 *
	 * First, the client MUST determine whether the response indicates a success or a failure. If the status
	 * code is set to 200, the client MUST interpret this as a success, and it MUST do the following:
	 *
	 * 1. Ignore the values of all other header fields.
	 *
	 * 2. Transition to Wait_A3W state.
	 *
	 * 3. Wait for network events.
	 *
	 * 4. Skip the rest of the processing in this section.
	 *
	 * If the status code is not set to 200, the client MUST interpret this as a failure and follow the same
	 * processing rules as specified in section 3.2.2.5.6.
	 *
	 */

	http_response = http_response_recv(rpc->TlsOut);

	if (http_response->StatusCode != HTTP_STATUS_OK)
	{
		fprintf(stderr, "rts_connect error! Status Code: %d\n", http_response->StatusCode);
		http_response_print(http_response);
		http_response_free(http_response);

		if (http_response->StatusCode == HTTP_STATUS_DENIED)
		{
			if (!connectErrorCode)
			{
				connectErrorCode = AUTHENTICATIONERROR;
			}

			if (!freerdp_get_last_error(((freerdp*)(rpc->settings->instance))->context))
			{
				freerdp_set_last_error(((freerdp*)(rpc->settings->instance))->context, FREERDP_ERROR_AUTHENTICATION_FAILED);
			}
		}

		return FALSE;
	}

	//http_response_print(http_response);
	http_response_free(http_response);

	rpc->VirtualConnection->State = VIRTUAL_CONNECTION_STATE_WAIT_A3W;
	DEBUG_RTS("VIRTUAL_CONNECTION_STATE_WAIT_A3W");

	/**
	 * Receive CONN_A3 RTS PDU
	 *
	 * A client implementation MUST NOT accept the CONN/A3 RTS PDU in any state other than
	 * Wait_A3W. If received in any other state, this PDU is a protocol error and the client
	 * MUST consider the virtual connection opening a failure and indicate this to higher
	 * layers in an implementation-specific way.
	 *
	 * Set the ConnectionTimeout in the Ping Originator of the Client's IN Channel to the
	 * ConnectionTimeout in the CONN/A3 PDU.
	 *
	 * If this RTS PDU is received in Wait_A3W state, the client MUST transition the state
	 * machine to Wait_C2 state and wait for network events.
	 *
	 */

	rpc_client_start(rpc);

	pdu = rpc_recv_dequeue_pdu(rpc);

	if (!pdu)
		return FALSE;

	rts = (rpcconn_rts_hdr_t*) Stream_Buffer(pdu->s);

	if (!rts_match_pdu_signature(rpc, &RTS_PDU_CONN_A3_SIGNATURE, rts))
	{
		fprintf(stderr, "Unexpected RTS PDU: Expected CONN/A3\n");
		return FALSE;
	}

	rts_recv_CONN_A3_pdu(rpc, Stream_Buffer(pdu->s), Stream_Length(pdu->s));

	rpc_client_receive_pool_return(rpc, pdu);

	rpc->VirtualConnection->State = VIRTUAL_CONNECTION_STATE_WAIT_C2;
	DEBUG_RTS("VIRTUAL_CONNECTION_STATE_WAIT_C2");

	/**
	 * Receive CONN_C2 RTS PDU
	 *
	 * A client implementation MUST NOT accept the CONN/C2 RTS PDU in any state other than Wait_C2.
	 * If received in any other state, this PDU is a protocol error and the client MUST consider the virtual
	 * connection opening a failure and indicate this to higher layers in an implementation-specific way.
	 *
	 * If this RTS PDU is received in Wait_C2 state, the client implementation MUST do the following:
	 *
	 * 1. Transition the state machine to opened state.
	 *
	 * 2. Set the connection time-out protocol variable to the value of the ConnectionTimeout field from
	 *    the CONN/C2 RTS PDU.
	 *
	 * 3. Set the PeerReceiveWindow value in the SendingChannel of the Client IN Channel to the
	 *    ReceiveWindowSize value in the CONN/C2 PDU.
	 *
	 * 4. Indicate to higher-layer protocols that the virtual connection opening is a success.
	 *
	 */

	pdu = rpc_recv_dequeue_pdu(rpc);

	if (!pdu)
		return FALSE;

	rts = (rpcconn_rts_hdr_t*) Stream_Buffer(pdu->s);

	if (!rts_match_pdu_signature(rpc, &RTS_PDU_CONN_C2_SIGNATURE, rts))
	{
		fprintf(stderr, "Unexpected RTS PDU: Expected CONN/C2\n");
		return FALSE;
	}

	rts_recv_CONN_C2_pdu(rpc, Stream_Buffer(pdu->s), Stream_Length(pdu->s));

	rpc_client_receive_pool_return(rpc, pdu);

	rpc->VirtualConnection->State = VIRTUAL_CONNECTION_STATE_OPENED;
	DEBUG_RTS("VIRTUAL_CONNECTION_STATE_OPENED");

	rpc->client->SynchronousSend = TRUE;
	rpc->client->SynchronousReceive = TRUE;

	return TRUE;
}

#ifdef WITH_DEBUG_RTS

static const char* const RTS_CMD_STRINGS[] =
{
	"ReceiveWindowSize",
	"FlowControlAck",
	"ConnectionTimeout",
	"Cookie",
	"ChannelLifetime",
	"ClientKeepalive",
	"Version",
	"Empty",
	"Padding",
	"NegativeANCE",
	"ANCE",
	"ClientAddress",
	"AssociationGroupId",
	"Destination",
	"PingTrafficSentNotify"
};

#endif

/**
 * RTS PDU Header
 *
 * The RTS PDU Header has the same layout as the common header of the connection-oriented RPC
 * PDU as specified in [C706] section 12.6.1, with a few additional requirements around the contents
 * of the header fields. The additional requirements are as follows:
 *
 * All fields MUST use little-endian byte order.
 *
 * Fragmentation MUST NOT occur for an RTS PDU.
 *
 * PFC_FIRST_FRAG and PFC_LAST_FRAG MUST be present in all RTS PDUs, and all other PFC flags
 * MUST NOT be present.
 *
 * The rpc_vers and rpc_vers_minor fields MUST contain version information as described in
 * [MS-RPCE] section 1.7.
 *
 * PTYPE MUST be set to a value of 20 (0x14). This field differentiates RTS packets from other RPC packets.
 *
 * The packed_drep MUST indicate little-endian integer and floating-pointer byte order, IEEE float-point
 * format representation, and ASCII character format as specified in [C706] section 12.6.
 *
 * The auth_length MUST be set to 0.
 *
 * The frag_length field MUST reflect the size of the header plus the size of all commands, including
 * the variable portion of variable-sized commands.
 *
 * The call_id MUST be set to 0 by senders and MUST be 0 on receipt.
 *
 */

void rts_pdu_header_init(rpcconn_rts_hdr_t* header)
{
	header->rpc_vers = 5;
	header->rpc_vers_minor = 0;
	header->ptype = PTYPE_RTS;
	header->packed_drep[0] = 0x10;
	header->packed_drep[1] = 0x00;
	header->packed_drep[2] = 0x00;
	header->packed_drep[3] = 0x00;
	header->pfc_flags = PFC_FIRST_FRAG | PFC_LAST_FRAG;
	header->auth_length = 0;
	header->call_id = 0;
}

int rts_receive_window_size_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length, UINT32* ReceiveWindowSize)
{
	if (ReceiveWindowSize)
		*ReceiveWindowSize = *((UINT32*) &buffer[0]); /* ReceiveWindowSize (4 bytes) */

	return 4;
}

int rts_receive_window_size_command_write(BYTE* buffer, UINT32 ReceiveWindowSize)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_RECEIVE_WINDOW_SIZE; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = ReceiveWindowSize; /* ReceiveWindowSize (4 bytes) */
	}

	return 8;
}

int rts_flow_control_ack_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length,
		UINT32* BytesReceived, UINT32* AvailableWindow, BYTE* ChannelCookie)
{
	/* Ack (24 bytes) */

	if (BytesReceived)
		*BytesReceived = *((UINT32*) &buffer[0]); /* BytesReceived (4 bytes) */

	if (AvailableWindow)
		*AvailableWindow = *((UINT32*) &buffer[4]); /* AvailableWindow (4 bytes) */

	if (ChannelCookie)
		CopyMemory(ChannelCookie, &buffer[8], 16); /* ChannelCookie (16 bytes) */

	return 24;
}

int rts_flow_control_ack_command_write(BYTE* buffer, UINT32 BytesReceived, UINT32 AvailableWindow, BYTE* ChannelCookie)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_FLOW_CONTROL_ACK; /* CommandType (4 bytes) */

		/* Ack (24 bytes) */
		*((UINT32*) &buffer[4]) = BytesReceived; /* BytesReceived (4 bytes) */
		*((UINT32*) &buffer[8]) = AvailableWindow; /* AvailableWindow (4 bytes) */
		CopyMemory(&buffer[12], ChannelCookie, 16); /* ChannelCookie (16 bytes) */
	}

	return 28;
}

int rts_connection_timeout_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length, UINT32* ConnectionTimeout)
{
	if (ConnectionTimeout)
		*ConnectionTimeout = *((UINT32*) &buffer[0]); /* ConnectionTimeout (4 bytes) */

	return 4;
}

int rts_connection_timeout_command_write(BYTE* buffer, UINT32 ConnectionTimeout)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_CONNECTION_TIMEOUT; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = ConnectionTimeout; /* ConnectionTimeout (4 bytes) */
	}

	return 8;
}

int rts_cookie_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	/* Cookie (16 bytes) */

	return 16;
}

int rts_cookie_command_write(BYTE* buffer, BYTE* Cookie)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_COOKIE; /* CommandType (4 bytes) */
		CopyMemory(&buffer[4], Cookie, 16); /* Cookie (16 bytes) */
	}

	return 20;
}

int rts_channel_lifetime_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	/* ChannelLifetime (4 bytes) */

	return 4;
}

int rts_channel_lifetime_command_write(BYTE* buffer, UINT32 ChannelLifetime)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_CHANNEL_LIFETIME; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = ChannelLifetime; /* ChannelLifetime (4 bytes) */
	}

	return 8;
}

int rts_client_keepalive_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	/* ClientKeepalive (4 bytes) */

	return 4;
}

int rts_client_keepalive_command_write(BYTE* buffer, UINT32 ClientKeepalive)
{
	/**
	 * An unsigned integer that specifies the keep-alive interval, in milliseconds,
	 * that this connection is configured to use. This value MUST be 0 or in the inclusive
	 * range of 60,000 through 4,294,967,295. If it is 0, it MUST be interpreted as 300,000.
	 */

	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_CLIENT_KEEPALIVE; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = ClientKeepalive; /* ClientKeepalive (4 bytes) */
	}

	return 8;
}

int rts_version_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	/* Version (4 bytes) */

	return 4;
}

int rts_version_command_write(BYTE* buffer)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_VERSION; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = 1; /* Version (4 bytes) */
	}

	return 8;
}

int rts_empty_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	return 0;
}

int rts_empty_command_write(BYTE* buffer)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_EMPTY; /* CommandType (4 bytes) */
	}

	return 4;
}

int rts_padding_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	UINT32 ConformanceCount;

	ConformanceCount = *((UINT32*) &buffer[0]); /* ConformanceCount (4 bytes) */
	/* Padding (variable) */

	return ConformanceCount + 4;
}

int rts_padding_command_write(BYTE* buffer, UINT32 ConformanceCount)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_PADDING; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = ConformanceCount; /* ConformanceCount (4 bytes) */
		ZeroMemory(&buffer[8], ConformanceCount); /* Padding (variable) */
	}

	return 8 + ConformanceCount;
}

int rts_negative_ance_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	return 0;
}

int rts_negative_ance_command_write(BYTE* buffer)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_NEGATIVE_ANCE; /* CommandType (4 bytes) */
	}

	return 4;
}

int rts_ance_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	return 0;
}

int rts_ance_command_write(BYTE* buffer)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_ANCE; /* CommandType (4 bytes) */
	}

	return 4;
}

int rts_client_address_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	UINT32 AddressType;

	AddressType = *((UINT32*) &buffer[0]); /* AddressType (4 bytes) */

	if (AddressType == 0)
	{
		/* ClientAddress (4 bytes) */
		/* padding (12 bytes) */

		return 4 + 4 + 12;
	}
	else
	{
		/* ClientAddress (16 bytes) */
		/* padding (12 bytes) */

		return 4 + 16 + 12;
	}
}

int rts_client_address_command_write(BYTE* buffer, UINT32 AddressType, BYTE* ClientAddress)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_CLIENT_ADDRESS; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = AddressType; /* AddressType (4 bytes) */
	}

	if (AddressType == 0)
	{
		if (buffer)
		{
			CopyMemory(&buffer[8], ClientAddress, 4); /* ClientAddress (4 bytes) */
			ZeroMemory(&buffer[12], 12); /* padding (12 bytes) */
		}

		return 24;
	}
	else
	{
		if (buffer)
		{
			CopyMemory(&buffer[8], ClientAddress, 16); /* ClientAddress (16 bytes) */
			ZeroMemory(&buffer[24], 12); /* padding (12 bytes) */
		}

		return 36;
	}
}

int rts_association_group_id_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	/* AssociationGroupId (16 bytes) */

	return 16;
}

int rts_association_group_id_command_write(BYTE* buffer, BYTE* AssociationGroupId)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_ASSOCIATION_GROUP_ID; /* CommandType (4 bytes) */
		CopyMemory(&buffer[4], AssociationGroupId, 16); /* AssociationGroupId (16 bytes) */
	}

	return 20;
}

int rts_destination_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length, UINT32* Destination)
{
	if (Destination)
		*Destination = *((UINT32*) &buffer[0]); /* Destination (4 bytes) */

	return 4;
}

int rts_destination_command_write(BYTE* buffer, UINT32 Destination)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_DESTINATION; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = Destination; /* Destination (4 bytes) */
	}

	return 8;
}

int rts_ping_traffic_sent_notify_command_read(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	/* PingTrafficSent (4 bytes) */

	return 4;
}

int rts_ping_traffic_sent_notify_command_write(BYTE* buffer, UINT32 PingTrafficSent)
{
	if (buffer)
	{
		*((UINT32*) &buffer[0]) = RTS_CMD_PING_TRAFFIC_SENT_NOTIFY; /* CommandType (4 bytes) */
		*((UINT32*) &buffer[4]) = PingTrafficSent; /* PingTrafficSent (4 bytes) */
	}

	return 8;
}

void rts_generate_cookie(BYTE* cookie)
{
	RAND_pseudo_bytes(cookie, 16);
}

/* CONN/A Sequence */

int rts_send_CONN_A1_pdu(rdpRpc* rpc)
{
	BYTE* buffer;
	rpcconn_rts_hdr_t header;
	UINT32 ReceiveWindowSize;
	BYTE* OUTChannelCookie;
	BYTE* VirtualConnectionCookie;

	rts_pdu_header_init(&header);
	header.frag_length = 76;
	header.Flags = RTS_FLAG_NONE;
	header.NumberOfCommands = 4;

	DEBUG_RPC("Sending CONN_A1 RTS PDU");

	rts_generate_cookie((BYTE*) &(rpc->VirtualConnection->Cookie));
	rts_generate_cookie((BYTE*) &(rpc->VirtualConnection->DefaultOutChannelCookie));

	VirtualConnectionCookie = (BYTE*) &(rpc->VirtualConnection->Cookie);
	OUTChannelCookie = (BYTE*) &(rpc->VirtualConnection->DefaultOutChannelCookie);
	ReceiveWindowSize = rpc->VirtualConnection->DefaultOutChannel->ReceiveWindow;

	buffer = (BYTE*) malloc(header.frag_length);

	CopyMemory(buffer, ((BYTE*) &header), 20); /* RTS Header (20 bytes) */
	rts_version_command_write(&buffer[20]); /* Version (8 bytes) */
	rts_cookie_command_write(&buffer[28], VirtualConnectionCookie); /* VirtualConnectionCookie (20 bytes) */
	rts_cookie_command_write(&buffer[48], OUTChannelCookie); /* OUTChannelCookie (20 bytes) */
	rts_receive_window_size_command_write(&buffer[68], ReceiveWindowSize); /* ReceiveWindowSize (8 bytes) */

	rpc_out_write(rpc, buffer, header.frag_length);

	free(buffer);

	return 0;
}

int rts_recv_CONN_A3_pdu(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	UINT32 ConnectionTimeout;

	rts_connection_timeout_command_read(rpc, &buffer[24], length - 24, &ConnectionTimeout);

	DEBUG_RTS("ConnectionTimeout: %d", ConnectionTimeout);

	rpc->VirtualConnection->DefaultInChannel->PingOriginator.ConnectionTimeout = ConnectionTimeout;

	return 0;
}

/* CONN/B Sequence */

int rts_send_CONN_B1_pdu(rdpRpc* rpc)
{
	BYTE* buffer;
	UINT32 length;
	rpcconn_rts_hdr_t header;
	BYTE* INChannelCookie;
	BYTE* AssociationGroupId;
	BYTE* VirtualConnectionCookie;

	rts_pdu_header_init(&header);
	header.frag_length = 104;
	header.Flags = RTS_FLAG_NONE;
	header.NumberOfCommands = 6;

	DEBUG_RPC("Sending CONN_B1 RTS PDU");

	rts_generate_cookie((BYTE*) &(rpc->VirtualConnection->DefaultInChannelCookie));
	rts_generate_cookie((BYTE*) &(rpc->VirtualConnection->AssociationGroupId));

	VirtualConnectionCookie = (BYTE*) &(rpc->VirtualConnection->Cookie);
	INChannelCookie = (BYTE*) &(rpc->VirtualConnection->DefaultInChannelCookie);
	AssociationGroupId = (BYTE*) &(rpc->VirtualConnection->AssociationGroupId);

	buffer = (BYTE*) malloc(header.frag_length);

	CopyMemory(buffer, ((BYTE*) &header), 20); /* RTS Header (20 bytes) */
	rts_version_command_write(&buffer[20]); /* Version (8 bytes) */
	rts_cookie_command_write(&buffer[28], VirtualConnectionCookie); /* VirtualConnectionCookie (20 bytes) */
	rts_cookie_command_write(&buffer[48], INChannelCookie); /* INChannelCookie (20 bytes) */
	rts_channel_lifetime_command_write(&buffer[68], rpc->ChannelLifetime); /* ChannelLifetime (8 bytes) */
	rts_client_keepalive_command_write(&buffer[76], rpc->KeepAliveInterval); /* ClientKeepalive (8 bytes) */
	rts_association_group_id_command_write(&buffer[84], AssociationGroupId); /* AssociationGroupId (20 bytes) */

	length = header.frag_length;

	rpc_in_write(rpc, buffer, length);

	free(buffer);

	return 0;
}

/* CONN/C Sequence */

int rts_recv_CONN_C2_pdu(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	UINT32 offset;
	UINT32 ReceiveWindowSize;
	UINT32 ConnectionTimeout;

	offset = 24;
	offset += rts_version_command_read(rpc, &buffer[offset], length - offset) + 4;
	offset += rts_receive_window_size_command_read(rpc, &buffer[offset], length - offset, &ReceiveWindowSize) + 4;
	offset += rts_connection_timeout_command_read(rpc, &buffer[offset], length - offset, &ConnectionTimeout) + 4;

	DEBUG_RTS("ConnectionTimeout: %d", ConnectionTimeout);
	DEBUG_RTS("ReceiveWindowSize: %d", ReceiveWindowSize);

	/* TODO: verify if this is the correct protocol variable */
	rpc->VirtualConnection->DefaultInChannel->PingOriginator.ConnectionTimeout = ConnectionTimeout;

	rpc->VirtualConnection->DefaultInChannel->PeerReceiveWindow = ReceiveWindowSize;

	rpc->VirtualConnection->DefaultInChannel->State = CLIENT_IN_CHANNEL_STATE_OPENED;
	rpc->VirtualConnection->DefaultOutChannel->State = CLIENT_OUT_CHANNEL_STATE_OPENED;

	return 0;
}

/* Out-of-Sequence PDUs */

int rts_send_keep_alive_pdu(rdpRpc* rpc)
{
	BYTE* buffer;
	UINT32 length;
	rpcconn_rts_hdr_t header;

	rts_pdu_header_init(&header);
	header.frag_length = 28;
	header.Flags = RTS_FLAG_OTHER_CMD;
	header.NumberOfCommands = 1;

	DEBUG_RPC("Sending Keep-Alive RTS PDU");

	buffer = (BYTE*) malloc(header.frag_length);
	CopyMemory(buffer, ((BYTE*) &header), 20); /* RTS Header (20 bytes) */
	rts_client_keepalive_command_write(&buffer[20], rpc->CurrentKeepAliveInterval); /* ClientKeepAlive (8 bytes) */

	length = header.frag_length;

	rpc_in_write(rpc, buffer, length);
	free(buffer);

	return length;
}

int rts_send_flow_control_ack_pdu(rdpRpc* rpc)
{
	BYTE* buffer;
	UINT32 length;
	rpcconn_rts_hdr_t header;
	UINT32 BytesReceived;
	UINT32 AvailableWindow;
	BYTE* ChannelCookie;

	rts_pdu_header_init(&header);
	header.frag_length = 56;
	header.Flags = RTS_FLAG_OTHER_CMD;
	header.NumberOfCommands = 2;

	DEBUG_RPC("Sending FlowControlAck RTS PDU");

	BytesReceived = rpc->VirtualConnection->DefaultOutChannel->BytesReceived;
	AvailableWindow = rpc->VirtualConnection->DefaultOutChannel->AvailableWindowAdvertised;
	ChannelCookie = (BYTE*) &(rpc->VirtualConnection->DefaultOutChannelCookie);

	rpc->VirtualConnection->DefaultOutChannel->ReceiverAvailableWindow =
			rpc->VirtualConnection->DefaultOutChannel->AvailableWindowAdvertised;

	buffer = (BYTE*) malloc(header.frag_length);

	CopyMemory(buffer, ((BYTE*) &header), 20); /* RTS Header (20 bytes) */
	rts_destination_command_write(&buffer[20], FDOutProxy); /* Destination Command (8 bytes) */

	/* FlowControlAck Command (28 bytes) */
	rts_flow_control_ack_command_write(&buffer[28], BytesReceived, AvailableWindow, ChannelCookie);

	length = header.frag_length;

	rpc_in_write(rpc, buffer, length);
	free(buffer);

	return 0;
}

int rts_recv_flow_control_ack_pdu(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	UINT32 offset;
	UINT32 BytesReceived;
	UINT32 AvailableWindow;
	BYTE ChannelCookie[16];

	offset = 24;
	offset += rts_flow_control_ack_command_read(rpc, &buffer[offset], length - offset,
			&BytesReceived, &AvailableWindow, (BYTE*) &ChannelCookie) + 4;

#if 0
	fprintf(stderr, "BytesReceived: %d AvailableWindow: %d\n",
			BytesReceived, AvailableWindow);
	fprintf(stderr, "ChannelCookie: " RPC_UUID_FORMAT_STRING "\n", RPC_UUID_FORMAT_ARGUMENTS(ChannelCookie));
#endif

	rpc->VirtualConnection->DefaultInChannel->SenderAvailableWindow =
		AvailableWindow - (rpc->VirtualConnection->DefaultInChannel->BytesSent - BytesReceived);

	return 0;
}

int rts_recv_flow_control_ack_with_destination_pdu(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	UINT32 offset;
	UINT32 Destination;
	UINT32 BytesReceived;
	UINT32 AvailableWindow;
	BYTE ChannelCookie[16];

	/**
	 * When the sender receives a FlowControlAck RTS PDU, it MUST use the following formula to
	 * recalculate its Sender AvailableWindow variable:
	 *
	 * Sender AvailableWindow = Receiver AvailableWindow_from_ack - (BytesSent - BytesReceived_from_ack)
	 *
	 * Where:
	 *
	 * Receiver AvailableWindow_from_ack is the Available Window field in the Flow Control
	 * Acknowledgement Structure (section 2.2.3.4) in the PDU received.
	 *
	 * BytesReceived_from_ack is the Bytes Received field in the Flow Control Acknowledgement structure
	 * in the PDU received.
	 *
	 */

	offset = 24;
	offset += rts_destination_command_read(rpc, &buffer[offset], length - offset, &Destination) + 4;
	offset += rts_flow_control_ack_command_read(rpc, &buffer[offset], length - offset,
			&BytesReceived, &AvailableWindow, (BYTE*) &ChannelCookie) + 4;

#if 0
	fprintf(stderr, "Destination: %d BytesReceived: %d AvailableWindow: %d\n",
			Destination, BytesReceived, AvailableWindow);
	fprintf(stderr, "ChannelCookie: " RPC_UUID_FORMAT_STRING "\n", RPC_UUID_FORMAT_ARGUMENTS(ChannelCookie));
#endif

	rpc->VirtualConnection->DefaultInChannel->SenderAvailableWindow =
		AvailableWindow - (rpc->VirtualConnection->DefaultInChannel->BytesSent - BytesReceived);

	return 0;
}

int rts_send_ping_pdu(rdpRpc* rpc)
{
	BYTE* buffer;
	UINT32 length;
	rpcconn_rts_hdr_t header;

	rts_pdu_header_init(&header);
	header.frag_length = 20;
	header.Flags = RTS_FLAG_PING;
	header.NumberOfCommands = 0;

	DEBUG_RPC("Sending Ping RTS PDU");

	buffer = (BYTE*) malloc(header.frag_length);

	CopyMemory(buffer, ((BYTE*) &header), 20); /* RTS Header (20 bytes) */

	length = header.frag_length;

	rpc_in_write(rpc, buffer, length);
	free(buffer);

	return length;
}

int rts_command_length(rdpRpc* rpc, UINT32 CommandType, BYTE* buffer, UINT32 length)
{
	int CommandLength = 0;

	switch (CommandType)
	{
		case RTS_CMD_RECEIVE_WINDOW_SIZE:
			CommandLength = RTS_CMD_RECEIVE_WINDOW_SIZE_LENGTH;
			break;

		case RTS_CMD_FLOW_CONTROL_ACK:
			CommandLength = RTS_CMD_FLOW_CONTROL_ACK_LENGTH;
			break;

		case RTS_CMD_CONNECTION_TIMEOUT:
			CommandLength = RTS_CMD_CONNECTION_TIMEOUT_LENGTH;
			break;

		case RTS_CMD_COOKIE:
			CommandLength = RTS_CMD_COOKIE_LENGTH;
			break;

		case RTS_CMD_CHANNEL_LIFETIME:
			CommandLength = RTS_CMD_CHANNEL_LIFETIME_LENGTH;
			break;

		case RTS_CMD_CLIENT_KEEPALIVE:
			CommandLength =  RTS_CMD_CLIENT_KEEPALIVE_LENGTH;
			break;

		case RTS_CMD_VERSION:
			CommandLength = RTS_CMD_VERSION_LENGTH;
			break;

		case RTS_CMD_EMPTY:
			CommandLength = RTS_CMD_EMPTY_LENGTH;
			break;

		case RTS_CMD_PADDING: /* variable-size */
			CommandLength = rts_padding_command_read(rpc, buffer, length);
			break;

		case RTS_CMD_NEGATIVE_ANCE:
			CommandLength = RTS_CMD_NEGATIVE_ANCE_LENGTH;
			break;

		case RTS_CMD_ANCE:
			CommandLength = RTS_CMD_ANCE_LENGTH;
			break;

		case RTS_CMD_CLIENT_ADDRESS: /* variable-size */
			CommandLength = rts_client_address_command_read(rpc, buffer, length);
			break;

		case RTS_CMD_ASSOCIATION_GROUP_ID:
			CommandLength = RTS_CMD_ASSOCIATION_GROUP_ID_LENGTH;
			break;

		case RTS_CMD_DESTINATION:
			CommandLength = RTS_CMD_DESTINATION_LENGTH;
			break;

		case RTS_CMD_PING_TRAFFIC_SENT_NOTIFY:
			CommandLength = RTS_CMD_PING_TRAFFIC_SENT_NOTIFY_LENGTH;
			break;

		default:
			fprintf(stderr, "Error: Unknown RTS Command Type: 0x%x\n", CommandType);
			return -1;
			break;
	}

	return CommandLength;
}

int rts_recv_out_of_sequence_pdu(rdpRpc* rpc, BYTE* buffer, UINT32 length)
{
	UINT32 SignatureId;
	rpcconn_rts_hdr_t* rts;
	RtsPduSignature signature;

	rts = (rpcconn_rts_hdr_t*) buffer;

	rts_extract_pdu_signature(rpc, &signature, rts);
	SignatureId = rts_identify_pdu_signature(rpc, &signature, NULL);

	if (SignatureId == RTS_PDU_FLOW_CONTROL_ACK)
	{
		return rts_recv_flow_control_ack_pdu(rpc, buffer, length);
	}
	else if (SignatureId == RTS_PDU_FLOW_CONTROL_ACK_WITH_DESTINATION)
	{
		return rts_recv_flow_control_ack_with_destination_pdu(rpc, buffer, length);
	}
	else if (SignatureId == RTS_PDU_PING)
	{
		rts_send_ping_pdu(rpc);
	}
	else
	{
		fprintf(stderr, "Unimplemented signature id: 0x%08X\n", SignatureId);
		rts_print_pdu_signature(rpc, &signature);
	}

	return 0;
}


text:
/* globals describe, it */
import {expect} from 'chai';

import htmlToText from './html-to-text.js';

describe('htmlToText', () => {
    it('should convert html to text', () => {
        expect(htmlToText('
first-line
second-line
third-line
')).equal('first-line\nsecond-line\nthird-line');
    });

    it('should add end newlines to block nodes', () => {
        expect(htmlToText('

first
second
')).equal('first\nsecond');
    });

    it('should add correct newlines to successive block nodes', () => {
        expect(htmlToText('
first

second
')).equal('first\nsecond');
    });

    it('should add newlines for br and divs', () => {
        expect(htmlToText('
first

second

third')).equal('first\n\n\nsecond\n\nthird');
    });

    it('should add newlines for br inside inline nodes', () => {
        expect(htmlToText('first
second')).equal('first\nsecond');
    });

    it('should remove extra newlines from html', () => {
        expect(htmlToText('
first
\n\n
second
')).equal('first\nsecond');
    });

    it('should keep plain text links intact', () => {
        expect(htmlToText('https://www.briskine.com/')).equal('https://www.briskine.com/');
    });

    it('should keep plain text the same', () => {
        const content = 'line-one\n* bullet\nlink(https://briskine.com';
        expect(htmlToText(content)).equal(content);
    });

    it('should decorate lists', () => {
        expect(htmlToText('

one

two {
        expect(htmlToText('briskine')).equal('briskine [https://briskine.com/]');
    });

    it('should decorate links only with different urls', () => {
        expect(htmlToText('https://briskine.com/')).equal('https://briskine.com/');
    });

    it('should decorate images', () => {
        expect(htmlToText('')).equal('image alt [https://briskine.com/image.jpg]');
    });

    it('should add newlines for br tags', () => {
        expect(htmlToText('first

second

third')).equal('first\n\nsecond\n\nthird');
    });
});


text:
namespace Microsoft.Azure.Management.Search.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Network specific rules that determine how the Azure Cognitive Search
    /// service may be reached.
    /// </summary>
    public partial class NetworkRuleSet
    {
        /// <summary>
        /// Initializes a new instance of the NetworkRuleSet class.
        /// </summary>
        public NetworkRuleSet()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the NetworkRuleSet class.
        /// </summary>
        /// <param name="ipRules">A list of IP restriction rules that defines
        /// the inbound network(s) with allowing access to the search service
        /// endpoint. At the meantime, all other public IP networks are blocked
        /// by the firewall. These restriction rules are applied only when the
        /// 'publicNetworkAccess' of the search service is 'enabled';
        /// otherwise, traffic over public interface is not allowed even with
        /// any public IP rules, and private endpoint connections would be the
        /// exclusive access method.</param>
        public NetworkRuleSet(IList<IpRule> ipRules = default(IList<IpRule>))
        {
            IpRules = ipRules;
            CustomInit();
        }

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

        /// <summary>
        /// Gets or sets a list of IP restriction rules that defines the
        /// inbound network(s) with allowing access to the search service
        /// endpoint. At the meantime, all other public IP networks are blocked
        /// by the firewall. These restriction rules are applied only when the
        /// 'publicNetworkAccess' of the search service is 'enabled';
        /// otherwise, traffic over public interface is not allowed even with
        /// any public IP rules, and private endpoint connections would be the
        /// exclusive access method.
        /// </summary>
        [JsonProperty(PropertyName = "ipRules")]
        public IList<IpRule> IpRules { get; set; }

    }
}


text:
* `testURL` can be used to set the location of the jsdom environment.
* Updated all of jest's dependencies, now using jsdom 6.3.
* jest now uses the native `Promise` object.
* Fixed a bug when passed an empty `testPathIgnorePatterns`.
* Moved preprocessor cache into the haste cache directory.

## 0.5.0

* Added `--noStackTrace` option to disable stack traces.
* Jest now only works with iojs v2 and up. If you are still using node we
  recommend upgrading to iojs or keep using jest 0.4.0.
* Upgraded to jsdom 6.1.0 and removed all the custom jsdom overwrites.

## <=0.4.0

* See commit history for changes in previous versions of jest.


text:
function(doc) {
    if(doc.doc_type == 'Auction' && doc.status != 'draft' && !doc.mode) {
        var fields=['auctionPeriod', 'status', 'auctionID', 'lots', 'procurementMethodType', 'next_check'], data={};
        for (var i in fields) {
            if (doc[fields[i]]) {
                data[fields[i]] = doc[fields[i]]
            }
        }
        emit(doc.dateModified, data);
    }
}


text:
package edu.isi.karma.controller.command.cleaning;

import javax.servlet.http.HttpServletRequest;

import edu.isi.karma.controller.command.Command;
import edu.isi.karma.controller.command.CommandFactory;
import edu.isi.karma.rep.Workspace;

public class FetchTransformingDataFactory extends CommandFactory {

	private enum Arguments {
		worksheetId, hNodeId, selectionName
	}

	@Override
	public Command createCommand(HttpServletRequest request, Workspace workspace) {
		String hNodeId = request.getParameter(Arguments.hNodeId.name());
		String selectionName = request.getParameter(Arguments.selectionName.name());
		FetchTransformingDataCommand cmd = new FetchTransformingDataCommand(getNewId(workspace),
				getWorksheetId(request, workspace), hNodeId,
				selectionName);
		return cmd;
	}

	@Override
	public Class<? extends Command> getCorrespondingCommand()
	{
		return FetchTransformingDataCommand.class;
	}
}


text:
using Azure.Core;

#nullable disable

namespace Azure.Communication.JobRouter
{
    /// <summary> Jobs are distributed in order to workers, starting with the worker that is after the last worker to receive a job. </summary>
    [CodeGenModel("RoundRobinMode")]
    [CodeGenSuppress("RoundRobinMode", typeof(int), typeof(int))]
    public partial class RoundRobinMode : DistributionMode
    {
        /// <summary> Initializes a new instance of RoundRobinModePolicy. </summary>
        /// <param name="minConcurrentOffers"> (Optional) Governs the minimum desired number of active concurrent offers a job can have. By default, set to 1. </param>
        /// <param name="maxConcurrentOffers"> (Optional) Governs the maximum number of active concurrent offers a job can have. By default, set to 1. </param>
        /// <param name="bypassSelectors">
        /// (Optional)
        ///
        /// If set to true, then router will match workers to jobs even if they don't match label selectors.
        ///
        /// Warning: You may get workers that are not qualified for the job they are matched with if you set this
        ///
        /// variable to true. This flag is intended more for temporary usage.
        ///
        /// By default, set to false.
        /// </param>
        public RoundRobinMode(int minConcurrentOffers = 1, int maxConcurrentOffers = 1, bool? bypassSelectors = false)
            : this(null, minConcurrentOffers, maxConcurrentOffers, bypassSelectors)
        {
        }
    }
}


text:
require 'fileutils'
require './lib/bourbon/version.rb'
require 'nokogiri'
require 'sqlite3'

def generate_docset_dirs
  FileUtils.mkdir_p([docset_path, images_path])
end

def copy_plist_file
  FileUtils.cp_r("#{doc_assets_path}/Info.plist", contents_path)
end

def copy_docset_markup
  FileUtils.cp_r("#{site_path}/docset/index.html", docset_path)
  FileUtils.cp_r("#{site_path}/stylesheets/docs.css", docset_path)
  FileUtils.cp_r("#{site_path}/images/shared/", images_path)
  FileUtils.cp_r("#{site_path}/images/documentation/", images_path)
  FileUtils.cp_r("#{site_path}/js/docs.js", docset_path)
  `curl -s -o #{docset_path}/jquery.min.js http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js`
end

def delete_package_file
  FileUtils.rm_rf(package_path)
end

def generate_database
  database = SQLite3::Database.new database_file
  database.execute("CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT)")

  parse_elements.each_with_index do |element, index|
    name = element.css('h2').text.sub(%r((?i)view source), '').strip
    type = element['data-type'].capitalize
    path = "docset/index.html##{element['id']}"
    database.execute("INSERT INTO searchIndex (id, name, type, path) VALUES (?, ?, ?, ?)", [index+1, name, type, path])
  end
end

def generate_feed
  feed = Nokogiri::XML::Builder.new do |xml|
    xml.entry {
      xml.version Bourbon::VERSION
      xml.url "http://bourbon.io/docset/bourbon.tgz"
    }
  end

  File.open("#{root_path}/docset/Bourbon.xml", 'w') do |file|
    file << (feed.to_xml :save_with => 3) # Removes XML header
  end
end

def archive_package
  `cd #{root_path}/docset && tar --exclude='.DS_Store' -czf bourbon.tgz Bourbon.docset`
end

private

def root_path
  File.dirname(File.dirname(File.dirname(__FILE__)))
end

def package_path
  File.join(root_path, 'docset', 'Bourbon.docset')
end

def contents_path
  File.join(package_path, 'Contents')
end

def resources_path
  File.join(contents_path, 'Resources')
end

def documents_path
  File.join(resources_path, 'Documents')
end

def doc_assets_path
  File.join(root_path, 'gh-docs')
end

def site_path
  File.join(root_path, '_site')
end

def docset_path
  @docset_path ||= Pathname.new("#{documents_path}/docset")
end

def images_path
  @images_path ||= Pathname.new("#{documents_path}/images")
end

def docset_generated?
  File.exists?(docset_path)
end

def database_file
  File.join(resources_path, 'docSet.dsidx')
end

def parse_elements
  page = Nokogiri::HTML(open("#{docset_path}/index.html"))
  @elements = page.css('[data-type]')
end


text:
import {
  equals,
  length,
  pipe,
  replace,
  toString,
} from 'ramda'

const clean = replace(/[^0-9]+/g, '')

export default size => pipe(
  toString,
  clean,
  length,
  equals(size)
)


text:
import argparse
import sys
import os
from resources import command_map

__author__ = 'hikmat'

"""
Module docstring.
This serves as a long usage message.
"""

HADOOP_HOME = ""

def set_vars():
    global HADOOP_HOME
    HADOOP_HOME = os.getenv("HADOOP_HOME","NULL")

def validate_vars():
	if HADOOP_HOME == "NULL":
		print("HADOOP_HOME has not been set. Please set it.")
		exit()

def main():
    set_vars()
    validate_vars()

    parser = argparse.ArgumentParser(description='Processes commands aganist hadoop')
    parser.add_argument("command", help='hadoop command to be executed')
    args = parser.parse_args()
    cmd = args.command
    cmd_exec=''

    if cmd in command_map.keys():
       cmd_exec = command_map[cmd]
    else:
       print("Oops!!! Unknown command!!!")
       print("Valid commands are:")
       print("========================")
       print("$> pyhadoop start")
       print("$> pyhadoop stop")
       print("$> pyhadoop cp src dest")
       print("$> pyhadoop mv src dest")
       print("========================\n")
       sys.exit(1)

    cmd_exec = cmd_exec.replace("$HADOOP_HOME",HADOOP_HOME)

    print("Executing {} .........".format(cmd_exec))

    os.system(cmd_exec)

if __name__ == '__main__':
    sys.exit(main())


text:
from m5.params import *
from O3CPUInjectedFault import O3CPUInjectedFault

class IEWStageInjectedFault(O3CPUInjectedFault):
    type = 'IEWStageInjectedFault'

    tcontext = Param.Int(0, "Example Num")


text:
'''
Created on 2013-8-2

@author: lan (www.9miao.com)
'''
import os
if os.name!='nt':
    from twisted.internet import epollreactor
    epollreactor.install()

def println(a):
    print a

if __name__=="__main__":
    from firefly.master.master import Master
    master = Master()
    master.config('config.json','test_server_main.py')
    master.start()


text:
using System;
using System.ComponentModel.Composition;
using EnvDTE;

namespace NuGet.VisualStudio
{
    [PartCreationPolicy(CreationPolicy.Shared)]
    [Export(typeof(IVsPackageManagerFactory))]
    public class VsPackageManagerFactory : IVsPackageManagerFactory
    {
        private readonly IPackageRepositoryFactory _repositoryFactory;
        private readonly ISolutionManager _solutionManager;
        private readonly IFileSystemProvider _fileSystemProvider;
        private readonly IRepositorySettings _repositorySettings;
        private readonly IVsPackageSourceProvider _packageSourceProvider;
        private readonly VsPackageInstallerEvents _packageEvents;

        private RepositoryInfo _repositoryInfo;

        [ImportingConstructor]
        public VsPackageManagerFactory(ISolutionManager solutionManager,
                                       IPackageRepositoryFactory repositoryFactory,
                                       IVsPackageSourceProvider packageSourceProvider,
                                       IFileSystemProvider fileSystemProvider,
                                       IRepositorySettings repositorySettings,
                                       VsPackageInstallerEvents packageEvents)
        {
            if (solutionManager == null)
            {
                throw new ArgumentNullException("solutionManager");
            }
            if (repositoryFactory == null)
            {
                throw new ArgumentNullException("repositoryFactory");
            }
            if (packageSourceProvider == null)
            {
                throw new ArgumentNullException("packageSourceProvider");
            }
            if (fileSystemProvider == null)
            {
                throw new ArgumentNullException("fileSystemProvider");
            }
            if (repositorySettings == null)
            {
                throw new ArgumentNullException("repositorySettings");
            }
            if (packageEvents == null)
            {
                throw new ArgumentNullException("packageEvents");
            }

            _fileSystemProvider = fileSystemProvider;
            _repositorySettings = repositorySettings;
            _solutionManager = solutionManager;
            _repositoryFactory = repositoryFactory;
            _packageSourceProvider = packageSourceProvider;
            _packageEvents = packageEvents;

            _solutionManager.SolutionClosing += (sender, e) =>
            {
                _repositoryInfo = null;
            };
        }

        /// <summary>
        /// Creates an VsPackageManagerInstance that uses the Active Repository (the repository selected in the console drop down) and uses a fallback repository for dependencies.
        /// </summary>
        public IVsPackageManager CreatePackageManager()
        {
            return CreatePackageManager(ServiceLocator.GetInstance<IPackageRepository>(), useFallbackForDependencies: true);
        }

        public IVsPackageManager CreatePackageManager(IPackageRepository repository, bool useFallbackForDependencies)
        {
            if (useFallbackForDependencies)
            {
                repository = CreateFallbackRepository(repository);
            }
            RepositoryInfo info = GetRepositoryInfo();
            return new VsPackageManager(_solutionManager,
                                        repository,
                                        _fileSystemProvider,
                                        info.FileSystem,
                                        info.Repository,
                                        // We ensure DeleteOnRestartManager is initialized with a PhysicalFileSystem so the
                                        // .deleteme marker files that get created don't get checked into version control
                                        new DeleteOnRestartManager(() => new PhysicalFileSystem(info.FileSystem.Root)),
                                        _packageEvents);
        }

        /// <summary>
        /// Creates a FallbackRepository with an aggregate repository that also contains the primaryRepository.
        /// </summary>
        internal IPackageRepository CreateFallbackRepository(IPackageRepository primaryRepository)
        {
            if (IsAggregateRepository(primaryRepository))
            {
                // If we're using the aggregate repository, we don't need to create a fall back repo.
                return primaryRepository;
            }

            var aggregateRepository = _packageSourceProvider.GetAggregate(_repositoryFactory, ignoreFailingRepositories: true);
            aggregateRepository.ResolveDependenciesVertically = true;
            return new FallbackRepository(primaryRepository, aggregateRepository);
        }

        private static bool IsAggregateRepository(IPackageRepository repository)
        {
            if (repository is AggregateRepository)
            {
                // This test should be ok as long as any aggregate repository that we encounter here means the true Aggregate repository of all repositories in the package source
                // Since the repository created here comes from the UI, this holds true.
                return true;
            }
            var vsPackageSourceRepository = repository as VsPackageSourceRepository;
            if (vsPackageSourceRepository != null)
            {
                return IsAggregateRepository(vsPackageSourceRepository.GetActiveRepository());
            }
            return false;
        }

        private RepositoryInfo GetRepositoryInfo()
        {
            // Update the path if it needs updating
            string path = _repositorySettings.RepositoryPath;
            string configFolderPath = _repositorySettings.ConfigFolderPath;

            if (_repositoryInfo == null ||
                !_repositoryInfo.Path.Equals(path, StringComparison.OrdinalIgnoreCase) ||
                !_repositoryInfo.ConfigFolderPath.Equals(configFolderPath, StringComparison.OrdinalIgnoreCase) ||
                _solutionManager.IsSourceControlBound != _repositoryInfo.IsSourceControlBound)
            {
                IFileSystem fileSystem = _fileSystemProvider.GetFileSystem(path);
                IFileSystem configSettingsFileSystem = GetConfigSettingsFileSystem(configFolderPath);
                // this file system is used to access the repositories.config file. We want to use Source Control-bound
                // file system to access it even if the 'disableSourceControlIntegration' setting is set.
                IFileSystem storeFileSystem = _fileSystemProvider.GetFileSystem(path, ignoreSourceControlSetting: true);

                ISharedPackageRepository repository = new SharedPackageRepository(
                    new DefaultPackagePathResolver(fileSystem),
                    fileSystem,
                    storeFileSystem,
                    configSettingsFileSystem);

                _repositoryInfo = new RepositoryInfo(path, configFolderPath, fileSystem, repository);
            }

            return _repositoryInfo;
        }

        protected internal virtual IFileSystem GetConfigSettingsFileSystem(string configFolderPath)
        {
            return new SolutionFolderFileSystem(ServiceLocator.GetInstance<DTE>().Solution, VsConstants.NuGetSolutionSettingsFolder, configFolderPath);
        }

        private class RepositoryInfo
        {
            public RepositoryInfo(string path, string configFolderPath, IFileSystem fileSystem, ISharedPackageRepository repository)
            {
                Path = path;
                FileSystem = fileSystem;
                Repository = repository;
                ConfigFolderPath = configFolderPath;
            }

            public bool IsSourceControlBound
            {
                get
                {
                    return FileSystem is ISourceControlFileSystem;
                }
            }

            public IFileSystem FileSystem { get; private set; }
            public string Path { get; private set; }
            public string ConfigFolderPath { get; private set; }
            public ISharedPackageRepository Repository { get; private set; }
        }
    }
}


text:
package com.nihaskalam.progressbuttonlibrary;

interface OnAnimationEndListener {

    void onAnimationEnd();
}


text:
package me.codpoe.onlyweather.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import me.codpoe.onlyweather.model.entity.WeatherBean;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Codpoe on 2016/6/11.
 */
public class PrefsUtils {

    /**
     * 保存定位城市
     */
    public static void saveLocationCity(Context context, String cityName) {
        SharedPreferences.Editor editor = context.getSharedPreferences("location_city_prefs", Context.MODE_PRIVATE).edit();
        editor.putString("location_city", cityName).commit();
    }

    /**
     * 获取已保存的定位城市
     */
    public static String getLocationCity(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("location_city_prefs", Context.MODE_PRIVATE);
        return prefs.getString("location_city", "");
    }

    /**
     * 保存首页要展示的城市到 Prefs
     * @param cityName
     */
    public static void saveShowCityToPrefs(Context context, String cityName) {
        SharedPreferences.Editor editor = context.getSharedPreferences("show_city_prefs", Context.MODE_PRIVATE).edit();
        editor.putString("show_city", cityName);
        editor.commit();
    }

    /**
     * 获取已保存的首页展示的城市
     * @return
     */
    public static String getShowCityFromPrefs(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("show_city_prefs", Context.MODE_PRIVATE);
        return prefs.getString("show_city", "");
    }

    /**
     * 把 WeatherList 对象转换成 JSON 形式的字符串,并存进 SharedPreferences
     */
    public static void saveShowWeatherToPrefs(final Context context, WeatherBean weatherBean) {
        Observable.just(weatherBean)
                .map(new Func1<WeatherBean, Integer>() {
                    @Override
                    public Integer call(WeatherBean weatherBeans) {
                        SharedPreferences.Editor editor = context.getSharedPreferences("show_weather_prefs", Context.MODE_PRIVATE).edit();
                        String str = "";
                        Gson gson = new Gson();
                        str = gson.toJson(weatherBeans);
                        editor.putString("show_weather", str);
                        editor.commit();
                        return 0;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("PrefsUtils", e.getMessage());
                    }

                    @Override
                    public void onNext(Integer integer) {

                    }
                });

    }

    /**
     * 从 SharedPreferences 读取字符串,并把字符串解析成 WeatherList 对象
     */
    public static WeatherBean getShowWeatherFromPrefs(Context context) {
        WeatherBean weatherBean = null;
        SharedPreferences prefs = context.getSharedPreferences("show_weather_prefs", Context.MODE_PRIVATE);
        String str = prefs.getString("show_weather", "");
        if(str != null) {
            Gson gson = new Gson();
            weatherBean = gson.fromJson(str, new TypeToken<WeatherBean>(){}.getType());
        }
        return weatherBean;
    }
}


text:
{% extends "dashboard/base.html" %}
{% load url from future %}
{% load dashboard_extras %}
{% block page_title %}
{{ page_title }}
{% endblock %}

{% block site_brand %}
{{ globals.site_brand }}
{% endblock %}

{% block content %}

				 Events

			Description

			Time

		{% if events %}
		{% for event in events %}

				{% if event.level == 'info' %}

				{% elif event.level == 'error' %}

				{% elif event.level == 'warning' %}

				{% elif event.level == 'debug' %}

				{% elif event.level == 'alert' %}

				{% endif %}

				{{ event.description }}

				{{ event.entered_pretty }}

		{% endfor %}
		{% else %}

				No events yet

		{% endif %}

					 Balances

			{% for wallet in wallets %}

			    	{{ wallet.name }}

				  {{ wallet.balance }} {{ wallet.currency_code|upper }} /
	              0.00 USD

			{% endfor %}

					view all accounts »

					 Recent Transactions

						Account

						Date
						Amount

				{% for transaction in transactions %}

					{% if transaction.confirmations < 6 and transaction.category != 'move' %}

					{% else %}

					{% endif %}

						{% if transaction.category == 'receive'%}
						{{ transaction.currency_symbol }} {{ transaction.account|getaccountname }}
						{% elif transaction.category == 'send'%}
						{{ transaction.currency_symbol }} {{ transaction.account|getaccountname }}
						{% elif transaction.category == 'move'%}
						{{ transaction.currency_symbol }} {{ transaction.otheraccount|getaccountname }}
						{% endif %}

						{{ transaction.time_pretty }}
						{{ transaction.amount }} {{ transaction.currency|upper }}

				{% endfor %}

					view all transactions »

{% endblock %}


text:
package io.cortical.services;

import static io.cortical.rest.model.TestDataMother.createFingerprints;
import static io.cortical.rest.model.TestDataMother.createStrings;
import static io.cortical.rest.model.TestDataMother.createTexts;
import static io.cortical.services.ApiTestUtils.NOT_NULL_RETINA;
import io.cortical.rest.model.Fingerprint;
import io.cortical.rest.model.Text;
import io.cortical.services.Pagination;
import io.cortical.services.PosTag;
import io.cortical.services.TextRetinaApiImpl;
import io.cortical.services.api.client.ApiException;
import io.cortical.services.api.client.api.TextApi;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

/**
 *
 * {@link TextRetinaApiImpl} test class.
 */
public class TestTextRetinaApiImpl {
    /**
     *
     */
    private static final String[] KEYWORDS = { "KEY1", "KEY2", "KEY3" };
    private static final String TEXT = "test text";
    private static final String TEXT_2 = "test text 2";
    private static final String TEXT_3 = "test text 3";
    /**
     *
     */
    @Mock
    private TextApi textApi;
    private TextRetinaApiImpl textRetinaApiImpl;

    /**
     * initialization.
     */
    @Before
    public void before() {
        initMocks(this);
        textRetinaApiImpl = new TextRetinaApiImpl(textApi, NOT_NULL_RETINA);
    }

    /**
     * {@link TextRetinaApiImpl#getKeywords(String)} test method.
     *
     * @throws ApiException : should never be thrown
     */
    @Test
    public void getKeywordsForTextTest() throws ApiException {
        when(textApi.getKeywordsForText(eq(TEXT), eq(NOT_NULL_RETINA))).thenReturn(asList(KEYWORDS));
        textRetinaApiImpl.getKeywords(TEXT);
        verify(textApi, times(1)).getKeywordsForText(eq(TEXT), eq(NOT_NULL_RETINA));
    }

    /**
     * {@link TextRetinaApiImpl#getFingerprints(String)} test method.
     *
     * @throws ApiException : should never be thrown
     */
    @Test
    public void getRepresentationForTextTest() throws ApiException {
        int count = 4;
        when(textApi.getRepresentationForText(eq(TEXT), eq(NOT_NULL_RETINA))).thenReturn(
                createFingerprints(count));
        List<Fingerprint> fingerprints = textRetinaApiImpl.getFingerprints(TEXT);
        assertEquals(count, fingerprints.size());
        verify(textApi, times(1)).getRepresentationForText(eq(TEXT), eq(NOT_NULL_RETINA));
    }

    /**
     * {@link TextRetinaApiImpl#getFingerprints(String)} test method.
     *
     * @throws ApiException : should never be thrown
     * @throws JsonProcessingException
     */
    @Test
    public void getRepresentationsForBulkTextTest() throws ApiException, JsonProcessingException {
        double sparsity = 0.5;
        int count = 4;
        when(textApi.getRepresentationsForBulkText(any(String.class), eq(NOT_NULL_RETINA), eq(sparsity))).thenReturn(
                createFingerprints(count));
        List<Fingerprint> fingerprints =
                textRetinaApiImpl.getFingerprintBulk(sparsity, new Text(TEXT), new Text(TEXT_2), new Text(
                        TEXT_3));
        assertEquals(count, fingerprints.size());
        verify(textApi, times(1)).getRepresentationsForBulkText(any(String.class), eq(NOT_NULL_RETINA), eq(sparsity));
    }

    /**
     * {@link TextRetinaApiImpl#getSlices(String)} test method.
     *
     * @throws ApiException : should never be thrown
     * @throws JsonProcessingException
     */
    @Test
    public void getSlicesForTextTest() throws ApiException, JsonProcessingException {
        int count = 4;
        when(textApi.getSlicesForText(eq(TEXT), isNull(Boolean.class), eq(NOT_NULL_RETINA), isNull(Integer.class), isNull(Integer.class))).thenReturn(createTexts(count));
        List<Text> texts = textRetinaApiImpl.getSlices(TEXT);
        assertEquals(count, texts.size());
        verify(textApi, times(1)).getSlicesForText(eq(TEXT), isNull(Boolean.class), eq(NOT_NULL_RETINA), isNull(Integer.class), isNull(Integer.class));
    }

    /**
     * {@link TextRetinaApiImpl#getSlices(String, Boolean)} test method.
     *
     * @throws ApiException : should never be thrown
     * @throws JsonProcessingException
     */
    @Test
    public void getSlicesForTextTest_withFingerprints() throws ApiException, JsonProcessingException {
        int count = 4;
        boolean getFingerprint = false;
        when(textApi.getSlicesForText(eq(TEXT), eq(getFingerprint), eq(NOT_NULL_RETINA), isNull(Integer.class), isNull(Integer.class))).thenReturn(createTexts(count));
        List<Text> texts = textRetinaApiImpl.getSlices(TEXT, getFingerprint);
        assertEquals(count, texts.size());
        verify(textApi, times(1)).getSlicesForText(eq(TEXT), eq(getFingerprint), eq(NOT_NULL_RETINA), isNull(Integer.class), isNull(Integer.class));
    }

    /**
     * {@link TextRetinaApiImpl#getSlices(String, Pagination, Boolean)} test method.
     *
     * @throws ApiException : should never be thrown
     * @throws JsonProcessingException
     */
    @Test
    public void getSlicesForTextTest_withFingerprintsAndPegenation() throws ApiException, JsonProcessingException {
        int count = 4;
        boolean getFingerprint = false;
        int startIndex = 10;
        int maxResults = 10;
        Pagination pagination = new Pagination(startIndex, maxResults);
        when(textApi.getSlicesForText(eq(TEXT), eq(getFingerprint), eq(NOT_NULL_RETINA), eq(startIndex), eq(maxResults))).thenReturn(createTexts(count));
        List<Text> texts = textRetinaApiImpl.getSlices(TEXT, pagination, getFingerprint);
        assertEquals(count, texts.size());
        verify(textApi, times(1)).getSlicesForText(eq(TEXT), eq(getFingerprint), eq(NOT_NULL_RETINA), eq(startIndex), eq(maxResults));
    }

    /**
     * {@link TextRetinaApiImpl#getTokens(String, PosTag[])} test method.
     *
     * @throws ApiException : should never be thrown
     * @throws JsonProcessingException
     */
    @Test
    public void getTokensForTextTest() throws ApiException, JsonProcessingException {
        PosTag[] tags = {PosTag.DT, PosTag.JJS};
        int count = 4;
        String expectedPosTags =  PosTag.DT.getLabel() + "," +  PosTag.JJS.getLabel();
        when(textApi.getTokensForText(eq(TEXT), eq(expectedPosTags), eq(NOT_NULL_RETINA))).thenReturn(createStrings(count));
        List<String> tokens = textRetinaApiImpl.getTokens(TEXT, tags);
        assertEquals(count, tokens.size());
        verify(textApi, times(1)).getTokensForText(eq(TEXT), eq(expectedPosTags), eq(NOT_NULL_RETINA));
    }
}