text:
<!doctype html>

<meta charset="utf-8">
<title>Recent Posts</title>
<meta name="description" content="Recent posts in Alex Salguero's blog">
<meta name="keywords" content="posts, software, blog, alex salguero, hasumedic">

<meta property="og:locale" content="en_US">
<meta property="og:title" content="Recent Posts">
<meta property="og:description" content="Recent posts in Alex Salguero's blog">
<meta property="og:url" content="/index.html">
<meta property="og:site_name" content="Alex Salguero">

<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Alex Salguero Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Crimson+Text:400,400italic,700,700italic" rel='stylesheet' type='text/css' />
<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="/assets/css/entypo.css" media="all">
<link rel="stylesheet" href="/assets/css/highlight.css" media="all">

<link rel="stylesheet" href="/assets/css/i.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/favicon.ico">

        <hgroup>

Alex Salguero

        </hgroup>
        ☰

              Home

About

Posts

                 <lh>
Recent Posts
</lh>

Scala case classes

<time datetime="2016-06-21T00:00:00+01:00" itemprop="datePublished">June 21, 2016</time>

In my previous post I made an overview to the relationship between classes and objects in Scala. In this post I'd lik...

Scala classes and objects

<time datetime="2016-02-23T00:00:00+00:00" itemprop="datePublished">February 23, 2016</time>

When learning Scala, you often find yourself reading stuff from lots of sources with tons of information about differ...

Scala eXchange 2015

<time datetime="2015-12-16T00:00:00+00:00" itemprop="datePublished">December 16, 2015</time>

So last week I attended my first Scala conference, that being the Scala eXchange 2015 in London.For me personally, it...

Sliding through collections

<time datetime="2015-11-22T00:00:00+00:00" itemprop="datePublished">November 22, 2015</time>

The other day I found myself trying to solve one of those math puzzles which had to do with doing computations on sub...

Book review: "The Software Craftsman"

<time datetime="2015-08-31T00:00:00+01:00" itemprop="datePublished">August 31, 2015</time>

I've been intrigued for a while to find out what exactly this concept of Software Craftsmanship is.It all started one...

Recent Posts

              Scala case classes
              Jun 21, 2016

              Scala classes and objects
              Feb 23, 2016

              Scala eXchange 2015
              Dec 16, 2015

                         Contact Me

                 @hasumedic

                 Github

    © 2016 Alex Salguero. Powered by Jekyll using the Balzac theme.


text:
<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <Edge_ProductRestrictShipping>
            <version>1.0.0</version>
        </Edge_ProductRestrictShipping>
    </modules>
    <global>
        <models>
            <productrestrictshipping>
                <class>Edge_ProductRestrictShipping_Model</class>
                <resourceModel>productrestrictshipping_resource</resourceModel>
            </productrestrictshipping>
            <productrestrictshipping_resource>
                <class>Edge_ProductRestrictShipping_Model_Resource</class>
                <entities>
                    <productRestrictShipping>

productrestrictshipping

                    </productRestrictShipping>
                </entities>
            </productrestrictshipping_resource>
        </models>
        <resources>
            <productrestrictshipping_setup>
                <setup>
                    <module>Edge_ProductRestrictShipping</module>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </productrestrictshipping_setup>
            <productrestrictshipping_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </productrestrictshipping_read>
            <productrestrictshipping_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </productrestrictshipping_write>
        </resources>
        <helpers>
            <productrestrictshipping>
                <class>Edge_ProductRestrictShipping_Helper</class>
            </productrestrictshipping>
        </helpers>
        <blocks>
            <productrestrictshipping>
                <class>Edge_ProductRestrictShipping_Block</class>
            </productrestrictshipping>
        </blocks>
    </global>
    <frontend>
        <events>
            <controller_action_predispatch>
                <observers>
                    <edge_product_restrict_shipping_verify>
                        <type>singleton</type>
                        <class>Edge_ProductRestrictShipping_Model_Observer</class>
                        <method>saveShippingActionPredispatch</method>
                    </edge_product_restrict_shipping_verify>
                </observers>
            </controller_action_predispatch>
        </events>
    </frontend>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <productrestrictshipping before="Mage_Adminhtml">Edge_ProductRestrictShipping_Adminhtml</productrestrictshipping>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
</config>

redpajama_set_name: RedPajamaGithub


text:
class InvitationCodesController < ApplicationController
  before_action :ensure_valid_invite_code

  rescue_from ActiveRecord::RecordNotFound do
    redirect_to root_url, :notice => "That invite code is no longer valid"
  end

  def show
    sign_out(current_user) if user_signed_in?
    redirect_to new_user_registration_path(:invite => {:token => params[:id]})
  end

  private

  def ensure_valid_invite_code
    InvitationCode.find_by_token!(params[:id])
  end
end


text:
var adminSettingsModal = jQuery('.admin-settings-modal');

jQuery('._js_admin-settings').on('click', function(e){
    e.preventDefault();

    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'api/settings/get_admin', true);
    xhr.send();

    xhr.onloadend = function() {
        if(xhr.status == 200) {
            var resp = JSON.parse(xhr.response);

            jQuery('#adminName').val(resp["name"]);
            jQuery('#adminEmail').val(resp["email"]);
        }
        adminSettingsModal.modal('show');
    }
});

jQuery('._js_admin-settings-form').on('submit', function(e){
    e.preventDefault();

    var flag = false;
    jQuery(this).find('input').each(function(i){
        if(jQuery(this) && jQuery(this).val()) return true;
        else {
            flag = true;
            return false;
        }
    });

    if(flag) {
        alert('All inputs need to be filled out.');
        return;
    }

    var requestData = {};
    requestData["name"] = jQuery(this).find('#adminName').val();
    requestData["email"] = jQuery(this).find('#adminEmail').val();

    var xhr = new XMLHttpRequest();
    xhr.open(jQuery(this).attr('method'), jQuery(this).attr('action'), true);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    xhr.send(JSON.stringify(requestData));

    xhr.onloadend = function() {
        if(xhr.status == 204) {
            alert('Administrator settings successfully set.');
        }
        else {
            if(xhr.response != undefined && xhr.response.length != 0) {
                alert('Error: ' + xhr.response);
            }
            else {
                alert('An error has occurred, refresh and try again. If problem persists please contact your administrator.');
            }
        }
    }
});


text:
var path = require('path');
var fs   = require('fs');
var ytdl = require('youtube-dl');

// Ezarri hemen non nahi duzun bideoak gordetzea
var dest = "/Users/ikerib/Downloads/JETXI";

var myArgs = process.argv.slice(2);
if (myArgs.length == 0) {
  console.log("Youtube helbidea zehaztea ahaztu zaizu.");
  return;
}
var url = myArgs[0];
console.log("URL:" + url);

var video = ytdl(url,
  // Optional arguments passed to youtube-dl.
  ['--max-quality=22']);

if (!fs.existsSync(dest)){
    fs.mkdirSync(dest);
}

var size = 0;
video.on('info', function(info) {
  size = info.size;
  console.log('Bideoa topatu da.');
  console.log(info.filename + ' gordetzen...');
  var output = path.join(dest, info.filename);
  video.pipe(fs.createWriteStream(output));
});

var pos = 0;
video.on('data', function(data) {
  pos += data.length;
  // `size` should not be 0 here.
  if (size) {
    var percent = (pos / size * 100).toFixed(2);
    process.stdout.cursorTo(0);
    process.stdout.clearLine(1);
    process.stdout.write(percent + '%');
  }
});

video.on('Amaitu dut.', function() {
  console.log();
});


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="portfolio">
  <meta name="author" content="king pra">

  <title>King Pra</title>
  <link rel="shortcut icon" href="./favicon.ico">

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

  <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
  <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

  <link href="css/agency.min.css" rel="stylesheet">

      King Pra
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive"
        aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        Menu

      </button>

            Portfolio

            About

            Contact

Front End Developer

King Pra

Portfolio

CKP Tuning

visit site

Movie Emporeum

visit site

CSS Bear

visit site

CSS Variables

visit site

Codepen.io

visit site

About

KING PRA | FRONT END DEVELOPMENT

I AM KING!

 No really, that's my name. I am a Front End Developer striving to build awesome
                    and responsive web applications. I am very adaptable, enjoy learning new skills and tools and am passionate
                    about web development.

When I'm not coding

you can find me enjoying the outdoors on a mountain bike or a snowboard during the
                    snow season. I'm also a gearhead. My latest project is a 2015 Jeep Wrangler Unlimited😢.

          Copyright © www.KingPra.com 2017-2018

CKP Tuning

This site is designed to help CKP Tuning bring a web presence and outline some of the services that are
                  offered by the company

Date: March 2017 - Current

Client: CKP Tuning

Category: HTML5 | CSS3 |Bootstrap

                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

Movie Emporeum

This is one of my assignments while attending The Iron Yard Coding Bootcamp. This web app is built using
                  AngularJS for the framework and using Moviedb.org for it's API.

Date: January 2017

Category: HTML5 | CSS3 | AngularJS

                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

CSS Bear

This is a project I completed to get more familiar with CSS. This is coded in purely css.

Date: May 2017

Category: HTML5 | CSS3 | JS

                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

CSS Variables

This is a project that I completed to learn the strengths of CSS variables vs pre-compiled variables.

Date: May 2017

Category: HTML5 | CSS3 | JS

                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>

Codepen.io

Codepen.io is a Front End Dev's playground. It's a social development environment that allows you to write
                  code in the browser.

Date: 2016 to Current

Category: HTML5 | CSS3 | JS

                <button class="btn btn-primary" data-dismiss="modal" type="button"> Close Project</button>


text:
<?php namespace Illuminate\Auth;

use Illuminate\Hashing\HasherInterface;

class EloquentUserProvider implements UserProviderInterface {

	/**
	 * The hasher implementation.
	 *
	 * @var \Illuminate\Hashing\HasherInterface
	 */
	protected $hasher;

	/**
	 * The Eloquent user model.
	 *
	 * @var string
	 */
	protected $model;

	/**
	 * Create a new database user provider.
	 *
	 * @param  \Illuminate\Hashing\HasherInterface  $hasher
	 * @param  string  $model
	 * @return void
	 */
	public function __construct(HasherInterface $hasher, $model)
	{
		$this->model = $model;
		$this->hasher = $hasher;
	}

	/**
	 * Retrieve a user by their unique identifier.
	 *
	 * @param  mixed  $identifier
	 * @return \Illuminate\Auth\UserInterface|null
	 */
	public function retrieveById($identifier)
	{
		return $this->createModel()->newQuery()->find($identifier);
	}

	/**
	 * Retrieve a user by by their unique identifier and "remember me" token.
	 *
	 * @param  mixed  $identifier
	 * @param  string  $token
	 * @return \Illuminate\Auth\UserInterface|null
	 */
	public function retrieveByToken($identifier, $token)
	{
		$model = $this->createModel();

		return $model->newQuery()
                        ->where($model->getKeyName(), $identifier)
                        ->where($model->getRememberTokenName(), $token)
                        ->first();
	}

	/**
	 * Update the "remember me" token for the given user in storage.
	 *
	 * @param  \Illuminate\Auth\UserInterface  $user
	 * @param  string  $token
	 * @return void
	 */
	public function updateRememberToken(UserInterface $user, $token)
	{
		$user->setAttribute($user->getRememberTokenName(), $token);

		$user->save();
	}

	/**
	 * Retrieve a user by the given credentials.
	 *
	 * @param  array  $credentials
	 * @return \Illuminate\Auth\UserInterface|null
	 */
	public function retrieveByCredentials(array $credentials)
	{
		// First we will add each credential element to the query as a where clause.
		// Then we can execute the query and, if we found a user, return it in a
		// Eloquent User "model" that will be utilized by the Guard instances.
		$query = $this->createModel()->newQuery();

		foreach ($credentials as $key => $value)
		{
			if ( ! str_contains($key, 'password')) $query->where($key, $value);
		}

		return $query->first();
	}

	/**
	 * Validate a user against the given credentials.
	 *
	 * @param  \Illuminate\Auth\UserInterface  $user
	 * @param  array  $credentials
	 * @return bool
	 */
	public function validateCredentials(UserInterface $user, array $credentials)
	{
		$plain = $credentials['password'];

		return $this->hasher->check($plain, $user->getAuthPassword());
	}

	/**
	 * Create a new instance of the model.
	 *
	 * @return \Illuminate\Database\Eloquent\Model
	 */
	public function createModel()
	{
		$class = '\\'.ltrim($this->model, '\\');

		return new $class;
	}

}


text:
require_relative 'validate'

module AutomationObject
  module BluePrint
    module HashAdapter
      module Validators
        # Validates tests the a key exists on a composite hash
        class ValidatePresenceOf < Validate
          # @param args [Hash] arguments for the validation class
          def initialize(args)
            @key = args.fetch :key

            options = args.fetch :args, {}
            options = options.is_a?(Hash) ? options : {}
            @unless_presence_of = options.fetch :unless_presence_of, nil
          end

          # Validates the composite object and throws errors on failure
          # @param composite_object [Object] Composite object to be tested.
          # @return [nil] no return on exceptions on failure
          def validate(composite_object)
            # Get the hash value from the composite object
            return if composite_object.hash.key?(@key)

            # Do unless_presence_of check
            if @unless_presence_of
              return if composite_object.hash.key?(@unless_presence_of)
            end

            error_messages.push("Required Key Missing: #{@key}, at: #{composite_object.location}.")
          end
        end
      end
    end
  end
end


text:
//  ----------------------------------------------------------------------------------
//  Copyright Microsoft Corporation
//  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.
//  ----------------------------------------------------------------------------------

namespace DurableTask.Core.Tracking
{
    using System;
    using System.IO;
    using System.Threading.Tasks;

    /// <summary>
    /// Interface to allow save and load large blobs, such as message and session, as a stream using a storage store.
    /// The blob is saved in the store using an access key (e.g., a path to the blob),
    /// which can be used to uniquely load the blob back.
    /// </summary>
    public interface IOrchestrationServiceBlobStore
    {
        /// <summary>
        /// Create a blob storage access key based on the orchestrationInstance.
        /// This key will be used to save and load the stream message in external storage when it is too large.
        /// </summary>
        /// <param name="orchestrationInstance">The orchestration instance.</param>
        /// <param name="messageFireTime">The message fire time. Could be DateTime.MinValue.</param>
        /// <returns>A message blob key.</returns>
        string BuildMessageBlobKey(OrchestrationInstance orchestrationInstance, DateTime messageFireTime);

        /// <summary>
        /// Create a blob storage access key based on message session.
        /// This key will be used to save and load the stream in external storage when it is too large.
        /// </summary>
        /// <param name="sessionId">The message session Id.</param>
        /// <returns>A blob key.</returns>
        string BuildSessionBlobKey(string sessionId);

        /// <summary>
        /// Save the stream of the message or seesion using key.
        /// </summary>
        /// <param name="blobKey">The blob key.</param>
        /// <param name="stream">The stream of the message or session.</param>
        /// <returns></returns>
        Task SaveStreamAsync(string blobKey, Stream stream);

        /// <summary>
        /// Load the stream of message or seesion from storage using key.
        /// </summary>
        /// <param name="blobKey">The blob key.</param>
        /// <returns>The saved stream message or session.</returns>
        Task<Stream> LoadStreamAsync(string blobKey);

        /// <summary>
        /// Deletes the blob store
        /// </summary>
        Task DeleteStoreAsync();

        /// <summary>
        /// Purges expired containers from storage for given time threshold
        /// </summary>
        /// <param name="thresholdDateTimeUtc">The datetime in UTC to use as the threshold for purging containers</param>
        Task PurgeExpiredBlobsAsync(DateTime thresholdDateTimeUtc);
    }
}


text: export * from './angular2-spotify';


text:
using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;

class RPCServer
{
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using( var connection = factory.CreateConnection() )
        using( var channel = connection.CreateModel() )
        {
            channel.QueueDeclare( queue: "rpc_queue", durable: false, exclusive: false, autoDelete: false, arguments: null );
            channel.BasicQos( 0, 1, false );
            var consumer = new QueueingBasicConsumer( channel );
            channel.BasicConsume( queue: "rpc_queue", noAck: false, consumer: consumer );
            Console.WriteLine( " [x] Awaiting RPC requests" );

            while( true )
            {
                string response = null;
                var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

                var body = ea.Body;
                var props = ea.BasicProperties;
                var replyProps = channel.CreateBasicProperties();
                replyProps.CorrelationId = props.CorrelationId;

                try
                {
                    var message = Encoding.UTF8.GetString( body );
                    int n = int.Parse( message );
                    Console.WriteLine( " [.] fib({0})", message );
                    response = fib( n ).ToString();
                }
                catch( Exception e )
                {
                    Console.WriteLine( " [.] " + e.Message );
                    response = "";
                }
                finally
                {
                    var responseBytes = Encoding.UTF8.GetBytes( response );
                    channel.BasicPublish( exchange: "", routingKey: props.ReplyTo, basicProperties: replyProps, body: responseBytes );
                    channel.BasicAck( deliveryTag: ea.DeliveryTag, multiple: false );
                }
            }
        }
    }

    /// <summary>
    /// Assumes only valid positive integer input.
    /// Don't expect this one to work for big numbers, and it's probably the slowest recursive implementation possible.
    /// </summary>
    private static int fib( int n )
    {
        if( n == 0 || n == 1 )
        {
            return n;
        }

        return fib( n - 1 ) + fib( n - 2 );
    }
}


text:
namespace RCF {

    bool serializeOverride(SerializationProtocolOut &out, ByteBuffer & u)
    {
        int runtimeVersion = out.getRuntimeVersion();

        if (runtimeVersion <= 3)
        {
            // Legacy behavior - no metadata for ByteBuffer.
            int len = static_cast<int>(u.getLength());
            serialize(out, len);
            out.insert(u);
            return true;
        }
        else
        {
            return false;
        }
    }

    bool serializeOverride(SerializationProtocolOut &out, ByteBuffer * pu)
    {
        RCF_ASSERT(pu);
        return serializeOverride(out, *pu);
    }

    bool deserializeOverride(SerializationProtocolIn &in, ByteBuffer & u)
    {
        int runtimeVersion = in.getRuntimeVersion();

        if (runtimeVersion <= 3)
        {
            // Legacy behavior - no metadata for ByteBuffer.
            int len = 0;
            deserialize(in, len);
            in.extractSlice(u, len);
            return true;
        }
        else
        {
            return false;
        }
    }

    Mutex * gpCandidatesMutex = NULL;
    Candidates * gpCandidates = NULL;

    void initAmi()
    {
        gpCandidatesMutex = new Mutex;
        gpCandidates = new Candidates;
    }

    void deinitAmi()
    {
        delete gpCandidatesMutex;
        gpCandidatesMutex = NULL;
        delete gpCandidates;
        gpCandidates = NULL;
    }

    Mutex & gCandidatesMutex()
    {
        return *gpCandidatesMutex;
    }

    Candidates & gCandidates()
    {
        return *gpCandidates;
    }

    void ClientStub::enrol(I_Future *pFuture)
    {
        mFutures.push_back(pFuture);
        pFuture->setClientStub(this);
    }

    void ClientStub::init(
        const std::string & interfaceName,
        int fnId,
        RCF::RemoteCallSemantics rcs)
    {
        mRequest.init(
            getTargetToken(),
            getTargetName(),
            interfaceName,
            fnId,
            getSerializationProtocol(),
            mMarshalingProtocol,
            (rcs == RCF::Oneway),
            false,
            getRuntimeVersion(),
            false,
            mPingBackIntervalMs,
            mArchiveVersion,
            mUseNativeWstringSerialization,
            mEnableSfPointerTracking);

        ::RCF::CurrentClientStubSentry sentry(*this);

        mOut.reset(
            getSerializationProtocol(),
            32,
            mRequest.encodeRequestHeader(),
            mRuntimeVersion,
            mArchiveVersion,
            mEnableSfPointerTracking);

        bool asyncParameters = false;
        mpParameters->write(mOut);
        mFutures.clear();
        asyncParameters = mpParameters->enrolFutures(this);

        if (asyncParameters)
        {
            setAsync(true);
        }
    }

    void ClientStub::connect()
    {
        CurrentClientStubSentry sentry(*this);
        instantiateTransport();

        // Do we need to reconnect?

        bool shouldReconnect = false;

        if (!mConnected)
        {
            // Not connected.
            shouldReconnect = true;
        }
        else if (       mConnected
                    &&  mAutoReconnect
                    &&  mRcs == Twoway
                    &&  !mTransport->isConnected())
        {
            // Auto reconnect.
            shouldReconnect = true;
        }

        if (shouldReconnect)
        {
            std::string endpoint;
            if (mEndpoint.get())
            {
                endpoint = mEndpoint->asString();
            }

            RCF_LOG_2()(this)(endpoint)(mConnectTimeoutMs)
                << "RcfClient - connect to server.";

            if ( getTransportType() == Tt_Http || getTransportType() == Tt_Https )
            {
                if ( getHttpProxy().size() > 0 )
                {
                    RCF_LOG_2()(this) << "RcfClient - HTTP proxy: " << getHttpProxy() << ":" << getHttpProxyPort();
                }
                else
                {
                    RCF_LOG_2()(this) << "RcfClient - HTTP proxy: <None configured>";
                }
            }

            unsigned int connectTimeoutMs = mConnectTimeoutMs;
            if (connectTimeoutMs == 0)
            {
                connectTimeoutMs = MaxTimeoutMs;
            }
            mTransport->disconnect(connectTimeoutMs);

            mAsyncOpType = Connect;

            mTransport->connect(*this, connectTimeoutMs);
        }
        else
        {
            onConnectCompleted(true);
        }
    }

    void ClientStub::connectAsync(boost::function0<void> onCompletion)
    {
        setAsync(true);
        instantiateTransport();
        mTransport->setAsync(mAsync);
        setAsyncCallback(onCompletion);
        connect();

        // In case the connect completes on this thread (as it would for a named pipe).
        getTlsAmiNotification().run();
    }

    void ClientStub::wait(
        boost::function0<void> onCompletion,
        boost::uint32_t timeoutMs)
    {
        setAsync(true);
        instantiateTransport();
        mTransport->setAsync(mAsync);
        setAsyncCallback(onCompletion);

        mAsyncOpType = Wait;
        mTransport->setTimer(timeoutMs, this);
    }

    void ClientStub::doBatching()
    {
        RCF_ASSERT_EQ(mRcs , Oneway);
        RCF_ASSERT(!mAsync);
        RCF_ASSERT(mBatchBufferPtr);

        // Accumulate in the batch buffer.
        std::size_t appendLen = lengthByteBuffers(mEncodedByteBuffers);
        std::size_t currentSize = mBatchBufferPtr->size();

        bool usingTempBuffer = false;

        // If this message will cause us to exceed the limit, then flush first.
        if (    mBatchMaxMessageLength
            &&  currentSize + appendLen > mBatchMaxMessageLength)
        {
            mBatchBufferTemp.resize(appendLen);
            copyByteBuffers(mEncodedByteBuffers, & mBatchBufferTemp[0] );
            usingTempBuffer = true;

            unsigned int timeoutMs = generateTimeoutMs(mEndTimeMs);
            flushBatch(timeoutMs);
            currentSize = mBatchBufferPtr->size();
        }

        mBatchBufferPtr->resize( currentSize + appendLen);

        if (usingTempBuffer)
        {
            memcpy(
                & (*mBatchBufferPtr)[currentSize],
                &mBatchBufferTemp[0],
                mBatchBufferTemp.size());
        }
        else
        {
            copyByteBuffers(
                mEncodedByteBuffers,
                & (*mBatchBufferPtr)[currentSize] );
        }

        ++mBatchMessageCount;
    }

    void ClientStub::onRequestTransportFiltersCompleted()
    {
        if (mAsync && hasAsyncException())
        {
            scheduleAmiNotification();
            getTlsAmiNotification().run();
            return;
        }

        try
        {
            mSetTransportProtocol = false;
            mConnected = true;

            // Progress notification when connection is established.
            if (
                mClientProgressPtr.get() &&
                (mClientProgressPtr->mTriggerMask & ClientProgress::Event))
            {
                ClientProgress::Action action = ClientProgress::Continue;

                mClientProgressPtr->mProgressCallback(
                    0,
                    0,
                    ClientProgress::Event,
                    ClientProgress::Connect,
                    action);

                RCF_VERIFY(
                    action != ClientProgress::Cancel,
                    Exception(_RcfError_ClientCancel()));
            }

            // If we're only connecting, mEncodedByteBuffers will be empty.
            if (!mEncodedByteBuffers.empty())
            {
                beginSend();
            }
            else
            {
                if (mAsync)
                {
                    scheduleAmiNotification();
                }
            }
        }
        catch(const RCF::Exception & e)
        {
            if (mAsync)
            {
                std::auto_ptr<Exception> ePtr(e.clone());
                setAsyncException(ePtr);
                scheduleAmiNotification();
                getTlsAmiNotification().run();
            }
            else
            {
                throw;
            }
        }
    }

    void ClientStub::beginSend()
    {
        RCF_ASSERT( !mEncodedByteBuffers.empty() );

        unsigned int timeoutMs = generateTimeoutMs(mEndTimeMs);

        if (mAsync)
        {
            mAsyncOpType = Write;
        }

        // Add framing (4 byte length prefix).
        int messageSize =
            static_cast<int>(RCF::lengthByteBuffers(mEncodedByteBuffers));

        ByteBuffer &byteBuffer = mEncodedByteBuffers.front();

        RCF_ASSERT_GTEQ(byteBuffer.getLeftMargin() , 4);
        byteBuffer.expandIntoLeftMargin(4);
        memcpy(byteBuffer.getPtr(), &messageSize, 4);
        RCF::machineToNetworkOrder(byteBuffer.getPtr(), 4, 1);

        if (mBatchMode)
        {
            doBatching();
        }
        else
        {
            int err = getTransport().send(*this, mEncodedByteBuffers, timeoutMs);
            RCF_UNUSED_VARIABLE(err);
        }
    }

    void ClientStub::onConnectCompleted(bool alreadyConnected)
    {
        CurrentClientStubSentry sentry(*this);

        if (alreadyConnected && !mSetTransportProtocol)
        {
            if (mEncodedByteBuffers.size() > 0)
            {
                beginSend();
            }
        }
        else
        {
            if (mAsync)
            {
                mAsyncOpType = None;
            }

            std::vector<FilterPtr> filters;
            mTransport->getTransportFilters(filters);
            if (
                    mTransportProtocol == Tp_Clear
                &&  !mEnableCompression
                &&  filters.size() > 0)
            {
                // Custom filter sequence. Setup transport filters again for a
                // new connection.
                std::vector<FilterPtr> filterVec;
                mTransport->getTransportFilters(filterVec);

                for ( std::size_t i = 0; i<filterVec.size(); ++i )
                {
                    filterVec[i]->resetState();
                }

                mTransport->setTransportFilters(std::vector<FilterPtr>());
                if ( !filterVec.empty() )
                {
                    requestTransportFilters(filterVec);
                }
                onRequestTransportFiltersCompleted();
            }
            else
            {
                if (!mTransport->supportsTransportFilters())
                {
                    onRequestTransportFiltersCompleted();
                }
                else
                {
                    mTransport->setTransportFilters(std::vector<FilterPtr>());
                    if (mTransportProtocol == Tp_Clear && !mEnableCompression)
                    {
                        onRequestTransportFiltersCompleted();
                    }
                    else
                    {
                        std::vector<FilterPtr> filterVec;
                        createFilterSequence(filterVec);

                        if (mAsync)
                        {
                            requestTransportFiltersAsync(
                                filterVec,
                                boost::bind(&ClientStub::onRequestTransportFiltersCompleted, this));
                        }
                        else
                        {
                            requestTransportFilters(filterVec);
                            onRequestTransportFiltersCompleted();
                        }
                    }
                }
            }
        }
    }

    void ClientStub::beginCall()
    {
        CurrentClientStubSentry sentry(*this);

        unsigned int totalTimeoutMs = getRemoteCallTimeoutMs();
        unsigned int startTimeMs = getCurrentTimeMs();
        if (totalTimeoutMs)
        {
            mEndTimeMs = startTimeMs + totalTimeoutMs;
        }
        else
        {
            // Disable timeout.
            static const unsigned int maxTimeoutMs = (((unsigned int)-1)/10)*9;
            mEndTimeMs = startTimeMs + maxTimeoutMs;
        }

        ThreadLocalCached< std::vector<ByteBuffer> > tlcByteBuffers;
        std::vector<ByteBuffer> &byteBuffers = tlcByteBuffers.get();

        mOut.extractByteBuffers(byteBuffers);
        int protocol = mOut.getSerializationProtocol();
        RCF_UNUSED_VARIABLE(protocol);

        mEncodedByteBuffers.resize(0);

        mRequest.encodeRequest(
            byteBuffers,
            mEncodedByteBuffers,
            getMessageFilters());

        instantiateTransport();

        mTransport->setAsync(mAsync);

        WithProgressCallback *pWithCallbackProgress =
            dynamic_cast<WithProgressCallback *>(&getTransport());

        if (pWithCallbackProgress)
        {
            pWithCallbackProgress->setClientProgressPtr(
                getClientProgressPtr());
        }

        // TODO: make sure timeouts behave as expected, esp. when connect() is
        // doing round trip filter setup calls
        connect();

    }

    void ClientStub::onSendCompleted()
    {
        if (mRcs == RCF::Oneway)
        {
            mEncodedByteBuffers.resize(0);

            // TODO: Refactor. This code is identical to what happens when a
            // receive completes, in a twoway call.

            if (mAsync)
            {
                mAsyncOpType = None;
                scheduleAmiNotification();
            }
        }
        else
        {
            mEncodedByteBuffers.resize(0);
            beginReceive();
        }
    }

    void ClientStub::beginReceive()
    {
        if (mPingBackIntervalMs && mRuntimeVersion >= 5)
        {
            mPingBackCheckIntervalMs = 3 * mPingBackIntervalMs;

            mNextPingBackCheckMs =
                RCF::getCurrentTimeMs() + mPingBackCheckIntervalMs;

            // So we avoid the special value 0.
            mNextPingBackCheckMs |= 1;
        }

        if (mAsync)
        {
            mAsyncOpType = Read;
        }

        unsigned int timeoutMs = generateTimeoutMs(mEndTimeMs);

        mEncodedByteBuffer.clear();
        int err = getTransport().receive(*this, mEncodedByteBuffer, timeoutMs);
        RCF_UNUSED_VARIABLE(err);
    }

    void ClientStub::onException(const Exception & e)
    {
        if (mAsync)
        {
            onError(e);
        }
        else
        {
            e.throwSelf();
        }
    }

    void ClientStub::onReceiveCompleted()
    {
        if (mAsync)
        {
            mAsyncOpType = None;
        }

        ByteBuffer unfilteredByteBuffer;

        MethodInvocationResponse response;

        mRequest.decodeResponse(
            mEncodedByteBuffer,
            unfilteredByteBuffer,
            response,
            getMessageFilters());

        mEncodedByteBuffer.clear();

        mIn.reset(
            unfilteredByteBuffer,
            mOut.getSerializationProtocol(),
            mRuntimeVersion,
            mArchiveVersion,
            response.getEnableSfPointerTracking());

        RCF_LOG_3()(this)(response) << "RcfClient - received response.";

        if (response.isException())
        {
            std::auto_ptr<RemoteException> remoteExceptionAutoPtr(
                response.getExceptionPtr());

            if (!remoteExceptionAutoPtr.get())
            {
                int runtimeVersion = mRequest.mRuntimeVersion;
                if (runtimeVersion < 8)
                {
                    deserialize(mIn, remoteExceptionAutoPtr);
                }
                else
                {
                    RemoteException * pRe = NULL;
                    deserialize(mIn, pRe);
                    remoteExceptionAutoPtr.reset(pRe);
                }
            }

            onException(*remoteExceptionAutoPtr);
        }
        else if (response.isError())
        {
            int err = response.getError();
            if (err == RcfError_VersionMismatch)
            {
                int serverRuntimeVersion = response.getArg0();
                int serverArchiveVersion = response.getArg1();

                int clientRuntimeVersion = getRuntimeVersion();
                int clientArchiveVersion = getArchiveVersion();

                // We get this response from the server, if either the
                // client runtime version or client archive version, is
                // greater than what the server supports.

                if (getAutoVersioning() && getTries() == 0)
                {
                    int adjustedRuntimeVersion = RCF_MIN(serverRuntimeVersion, clientRuntimeVersion);
                    setRuntimeVersion(adjustedRuntimeVersion);

                    if (serverArchiveVersion)
                    {
                        int adjustedArchiveVersion = RCF_MIN(serverArchiveVersion, clientArchiveVersion);
                        setArchiveVersion(adjustedArchiveVersion);
                    }
                    setTries(1);

                    init(mRequest.getSubInterface(), mRequest.getFnId(), mRcs);
                    beginCall();
                }
                else
                {
                    onException( VersioningException(
                        serverRuntimeVersion,
                        serverArchiveVersion));
                }
            }
            else if (err == RcfError_PingBack)
            {
                // A ping back message carries a parameter specifying
                // the ping back interval in ms. The client can use that
                // to make informed decisions about whether the connection
                // has died or not.

                mPingBackIntervalMs = response.getArg0();

                // Record a timestamp and go back to receiving.

                ++mPingBackCount;
                mPingBackTimeStamp = RCF::getCurrentTimeMs();

                applyRecursionLimiter(
                    mRecursionState,
                    &ClientStub::beginReceive,
                    *this);
            }
            else
            {
                onException(RemoteException( Error(response.getError()) ));
            }
        }
        else
        {
            RCF::CurrentClientStubSentry sentry(*this);
            mpParameters->read(mIn);
            mIn.clearByteBuffer();

#if RCF_FEATURE_FILETRANSFER==1

            // Check for any file downloads.
            {
                if (!mDownloadStreams.empty())
                {
                    std::vector<FileDownload> downloadStreams;
                    downloadStreams.swap(mDownloadStreams);
                    for (std::size_t i=0; i<downloadStreams.size(); ++i)
                    {
                        downloadStreams[i].download(*this);
                    }
                }
            }

#endif

            if (mAsync)
            {
                scheduleAmiNotification();
            }
        }
    }

    void ClientStub::scheduleAmiNotification()
    {
        if (!mCurrentCallDesc.empty())
        {
            RCF_LOG_2() << "RcfClient - end remote call. " << mCurrentCallDesc;
        }

        if (mSignalledLockPtr)
        {
            RCF_ASSERT( !mSignalledLockPtr->locked() );
            mSignalledLockPtr->lock();
        }
        else
        {
            mSignalledLockPtr.reset( new Lock(*mSignalledMutexPtr) );
        }

        mCallInProgress = false;
        mSignalled = true;
        mSignalledConditionPtr->notify_all(*mSignalledLockPtr);

        boost::function0<void> cb;
        if (mAsyncCallback)
        {
            cb = mAsyncCallback;
            mAsyncCallback = boost::function0<void>();
        }

        getTlsAmiNotification().set(cb, mSignalledLockPtr, mSignalledMutexPtr);
    }

    bool ClientStub::ready()
    {
        Lock lock(*mSignalledMutexPtr);
        return mSignalled;
    }

    void ClientStub::waitForReady(boost::uint32_t timeoutMs)
    {
        Lock lock(*mSignalledMutexPtr);
        if (!mSignalled)
        {
            if (timeoutMs)
            {
                mSignalledConditionPtr->timed_wait(lock, timeoutMs);
            }
            else
            {
                mSignalledConditionPtr->wait(lock);
            }
        }
    }

    void ClientStub::cancel()
    {
        if (mTransport.get())
        {
            mTransport->cancel();
        }
        getTlsAmiNotification().run();
    }

    void ClientStub::setSubRcfClientPtr(RcfClientPtr clientStubPtr)
    {
        Lock lock(mSubRcfClientMutex);
        mSubRcfClientPtr = clientStubPtr;
    }

    RcfClientPtr ClientStub::getSubRcfClientPtr()
    {
        Lock lock(mSubRcfClientMutex);
        return mSubRcfClientPtr;
    }

    void ClientStub::call(
        RCF::RemoteCallSemantics rcs)
    {

        if (    rcs == RCF::Oneway
            &&  (getTransportType() == RCF::Tt_Http || getTransportType() == RCF::Tt_Https) )
        {
            // Oneway is not possible over HTTP/HTTPS.
            throw RCF::Exception(_RcfError_OnewayHttp());
        }

        mRetry = false;
        mRcs = rcs;
        mPingBackTimeStamp = 0;
        mPingBackCount = 0;

        // Set the progress timer timeouts.
        mTimerIntervalMs = 0;
        mNextTimerCallbackMs = 0;

        if (    mClientProgressPtr.get()
            &&  mClientProgressPtr->mTriggerMask & ClientProgress::Timer)
        {
            mTimerIntervalMs = mClientProgressPtr->mTimerIntervalMs;

            mNextTimerCallbackMs =
                RCF::getCurrentTimeMs() + mTimerIntervalMs;

            // So we avoid the special value 0.
            mNextTimerCallbackMs |= 1;
        }

        // We don't set ping back timeouts until we are about to receive.
        mPingBackCheckIntervalMs = 0;
        mNextPingBackCheckMs = 0;

        mSignalled = false;

        beginCall();
    }

    void ClientStub::setAsync(bool async)
    {
        mAsync = async;

        if (mAsync && !mSignalledMutexPtr)
        {
            mSignalledMutexPtr.reset( new Mutex() );
            mSignalledConditionPtr.reset( new Condition() );
        }
    }

    bool ClientStub::getAsync()
    {
        return mAsync;
    }

    void ClientStub::setAsyncCallback(boost::function0<void> callback)
    {
        mAsyncCallback = callback;
    }

    std::auto_ptr<Exception> ClientStub::getAsyncException()
    {
        Lock lock(*mSignalledMutexPtr);
        return mAsyncException;
    }

    void ClientStub::setAsyncException(std::auto_ptr<Exception> asyncException)
    {
        Lock lock(*mSignalledMutexPtr);
        mAsyncException = asyncException;
    }

    bool ClientStub::hasAsyncException()
    {
        Lock lock(*mSignalledMutexPtr);
        return mAsyncException.get() != NULL;
    }

    typedef boost::shared_ptr< ClientTransportAutoPtr > ClientTransportAutoPtrPtr;

    void vc6_helper(
        boost::function2<void, RcfSessionPtr, ClientTransportAutoPtr> func,
        RcfSessionPtr sessionPtr,
        ClientTransportAutoPtrPtr clientTransportAutoPtrPtr)
    {
        func(sessionPtr, *clientTransportAutoPtrPtr);
    }

    void convertRcfSessionToRcfClient(
        OnCallbackConnectionCreated func,
        RemoteCallSemantics rcs)
    {
        RcfSessionPtr sessionPtr = getCurrentRcfSessionPtr()->shared_from_this();
        RcfSession & rcfSession = *sessionPtr;

        ServerTransportEx & serverTransport =
            dynamic_cast<ServerTransportEx &>(
                rcfSession.getNetworkSession().getServerTransport());

        ClientTransportAutoPtrPtr clientTransportAutoPtrPtr(
            new ClientTransportAutoPtr(
                serverTransport.createClientTransport(rcfSession.shared_from_this())));

        rcfSession.addOnWriteCompletedCallback(
            boost::bind(
                vc6_helper,
                func,
                sessionPtr,
                clientTransportAutoPtrPtr) );

        bool closeSession = (rcs == RCF::Twoway);

        rcfSession.setCloseSessionAfterWrite(closeSession);
    }

    RcfSessionPtr convertRcfClientToRcfSession(
        ClientStub & clientStub,
        ServerTransport & serverTransport,
        bool keepClientConnection)
    {
        ServerTransportEx &serverTransportEx =
            dynamic_cast<RCF::ServerTransportEx &>(serverTransport);

        ClientTransportAutoPtr clientTransportAutoPtr(
            clientStub.releaseTransport());

        SessionPtr sessionPtr = serverTransportEx.createServerSession(
            clientTransportAutoPtr,
            StubEntryPtr(),
            keepClientConnection);

        clientStub.setTransport(clientTransportAutoPtr);

        return sessionPtr;
    }

    RcfSessionPtr convertRcfClientToRcfSession(
        ClientStub & clientStub,
        RcfServer & server,
        bool keepClientConnection)
    {
        return convertRcfClientToRcfSession(
            clientStub,
            server.getServerTransport(),
            keepClientConnection);
    }

    void createCallbackConnectionImpl(
        ClientStub & clientStubOrig,
        ServerTransport & callbackServer)
    {
        if (clientStubOrig.getRuntimeVersion() <= 11)
        {
            createCallbackConnectionImpl_Legacy(clientStubOrig, callbackServer);
        }
        else
        {
            I_RcfClient client("", clientStubOrig);
            ClientStub & stub = client.getClientStub();
            stub.setTransport( clientStubOrig.releaseTransport() );

            OobCreateCallbackConnection msg(clientStubOrig.getRuntimeVersion());
            ByteBuffer controlRequest;
            msg.encodeRequest(controlRequest);
            stub.setOutofBandRequest(controlRequest);

            stub.ping(RCF::Twoway);

            // Get OOB response.
            ByteBuffer controlResponse = stub.getOutOfBandResponse();
            stub.setOutofBandRequest(ByteBuffer());
            stub.setOutofBandResponse(ByteBuffer());
            msg.decodeResponse(controlResponse);

            int ret = msg.mResponseError;
            RCF_VERIFY(ret == RcfError_Ok, RemoteException( Error(ret) ));

            convertRcfClientToRcfSession(client.getClientStub(), callbackServer);
        }
    }

    void createCallbackConnectionImpl(
        ClientStub & clientStub,
        RcfServer & callbackServer)
    {
        createCallbackConnectionImpl(clientStub, callbackServer.getServerTransport());
    }

    void setCurrentCallDesc(
        std::string& desc,
        RCF::MethodInvocationRequest& request,
        const char * szFunc,
        const char * szArity)
    {
        desc.clear();
        if (LogManager::instance().isEnabled(LogNameRcf, LogLevel_2))
        {
            const std::string & subInterface = request.getSubInterface();
            const std::string & target = request.getService();

            if (subInterface == target)
            {
                desc = request.getSubInterface();
                desc += "::";
                desc += szFunc;
                desc += "().";
            }
            else
            {
                desc = request.getSubInterface();
                desc += "::";
                desc += szFunc;
                if (request.getService().empty())
                {
                    desc += "().";
                }
                else
                {
                    desc += "() on ";
                    desc += request.getService();
                    desc += ".";
                }
            }

            char szFnid[10] = {0};

#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4995) // 'sprintf': name was marked as #pragma deprecated
#pragma warning(disable: 4996) // 'sprintf'/'localtime': This function or variable may be unsafe.
#endif

            sprintf(szFnid, "%d", request.getFnId());

#if defined(_MSC_VER)
#pragma warning(pop)
#endif

            desc += " Fnid: ";
            desc += szFnid;
            desc += ". Type: ";
            desc += szArity;
        }
    }

} // namespace RCF


text:
from __future__ import with_statement

import flask
import logging

from wt.util import WTException
from wt.admin import AdministrativeDomainHelper

from nexiles.tools.utils import OBJ, OID
from nexiles.tools.rest.api import ApiBase

from nexiles.tools.rest import APIError
from nexiles.tools.rest import handle_api_error
from nexiles.tools.rest import returns_json
from nexiles.tools.rest import inject_runtime

from nexiles.tools.utils import get_info_page_url

from .blueprint import blueprint

# This module implements the "business logic"
from .example import example_query

logger = logging.getLogger("nexiles.gateway.example")

if 0:
    logger.setLevel(logging.DEBUG)

def format_object(obj):
    """format_object(obj) -> mapping

    This function maps Windchill Object Attributes to JSON.
    """
    d = {}

    # Add the OID and teh name of this object.
    d["OID"] = OID(obj)
    d["name"] = obj.getName()

    # The URL will point to the nexiles.gateway URL for this object
    d["url"] = ApiBase.url(d["oid"])

    # This will be the Windchill Details Page for that object
    d["details"] = get_info_page_url(obj)

    return d

######################################################################
# API routes

@blueprint.route("/1.0/example", endpoint="example_post", methods=["POST"])
@handle_api_error
@returns_json
@inject_runtime
def example():
    logger.debug("example_post")

    logger.debug("JSON Body: %r", flask.request.json)
    json_body = flask.request.json
    if not json_body:
        raise APIError(400, "illegal request", "need a json body.")

    # This example does nothing but echo the JSON body back to the
    # client.

    return {
        "body": json_body
    }

@blueprint.route("/1.0/example", endpoint="example_get", methods=["GET"])
@handle_api_error
@returns_json
@inject_runtime
def example_get_page():
    limit = flask.request.args.get("limit", 25, type=int)
    logger.debug("example_get: limit=%d", limit)

    # Call the example code form the business logic.  This is a hypothetic
    # query with some limit.  The query returns Windchill Objects.
    results = example_query(limit=limit)

    # Format the Windchill Objects to suitable JSON.
    items = []
    for obj in results:
        items.append(format_object(obj))

    return {
        "count": len(items),
        "items": items
    }

# vim: set ft=python ts=4 sw=4 expandtab :


text:
using System;
using System.Collections.Generic;
using System.Reflection;

namespace Aspects.Universal.Events
{
    public class AspectEventArgs : EventArgs
    {
        public object Instance { get; internal set; }
        public Type Type { get; internal set; }
        public MethodBase Method { get; internal set; }
        public string Name { get; internal set; }
        public IReadOnlyList<object> Args { get; internal set; }
        public Type ReturnType { get; internal set; }
        public Attribute[] Triggers { get; internal set; }
    }
}