text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class MagicDialog
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Me.btnCancel = New System.Windows.Forms.Button()
        Me.btnHigherAPI = New System.Windows.Forms.Button()
        Me.btnLowerAPI = New System.Windows.Forms.Button()
        Me.btnHigherApp = New System.Windows.Forms.Button()
        Me.btnLowerApp = New System.Windows.Forms.Button()
        Me.lblAppDuplicates = New System.Windows.Forms.Label()
        Me.pbDupAppIcon = New System.Windows.Forms.PictureBox()
        Me.lblDupAppName = New System.Windows.Forms.Label()
        Me.ListView1 = New System.Windows.Forms.ListView()
        Me.appIcon = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
        Me.appName = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
        Me.appVersion = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
        Me.apiVersion = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader)
        Me.ImageList1 = New System.Windows.Forms.ImageList(Me.components)
        CType(Me.pbDupAppIcon, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'btnCancel
        '
        Me.btnCancel.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.btnCancel.Location = New System.Drawing.Point(588, 310)
        Me.btnCancel.Name = "btnCancel"
        Me.btnCancel.Size = New System.Drawing.Size(140, 53)
        Me.btnCancel.TabIndex = 3
        Me.btnCancel.Text = "Cancel"
        '
        'btnHigherAPI
        '
        Me.btnHigherAPI.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.btnHigherAPI.Location = New System.Drawing.Point(442, 310)
        Me.btnHigherAPI.Name = "btnHigherAPI"
        Me.btnHigherAPI.Size = New System.Drawing.Size(140, 53)
        Me.btnHigherAPI.TabIndex = 3
        Me.btnHigherAPI.Text = "Remove higher API version(s)"
        '
        'btnLowerAPI
        '
        Me.btnLowerAPI.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.btnLowerAPI.Location = New System.Drawing.Point(296, 310)
        Me.btnLowerAPI.Name = "btnLowerAPI"
        Me.btnLowerAPI.Size = New System.Drawing.Size(140, 53)
        Me.btnLowerAPI.TabIndex = 3
        Me.btnLowerAPI.Text = "Remove lower API version(s)"
        '
        'btnHigherApp
        '
        Me.btnHigherApp.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.btnHigherApp.Location = New System.Drawing.Point(150, 310)
        Me.btnHigherApp.Name = "btnHigherApp"
        Me.btnHigherApp.Size = New System.Drawing.Size(140, 53)
        Me.btnHigherApp.TabIndex = 3
        Me.btnHigherApp.Text = "Remove higher app version(s)"
        '
        'btnLowerApp
        '
        Me.btnLowerApp.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.btnLowerApp.Location = New System.Drawing.Point(4, 310)
        Me.btnLowerApp.Name = "btnLowerApp"
        Me.btnLowerApp.Size = New System.Drawing.Size(140, 53)
        Me.btnLowerApp.TabIndex = 3
        Me.btnLowerApp.Text = "Remove lower app version(s)"
        '
        'lblAppDuplicates
        '
        Me.lblAppDuplicates.Location = New System.Drawing.Point(12, 12)
        Me.lblAppDuplicates.Name = "lblAppDuplicates"
        Me.lblAppDuplicates.Size = New System.Drawing.Size(166, 45)
        Me.lblAppDuplicates.TabIndex = 4
        Me.lblAppDuplicates.Text = "This app has {1} duplicate{s}:"
        Me.lblAppDuplicates.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
        '
        'pbDupAppIcon
        '
        Me.pbDupAppIcon.Location = New System.Drawing.Point(184, 12)
        Me.pbDupAppIcon.Name = "pbDupAppIcon"
        Me.pbDupAppIcon.Size = New System.Drawing.Size(45, 45)
        Me.pbDupAppIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom
        Me.pbDupAppIcon.TabIndex = 5
        Me.pbDupAppIcon.TabStop = False
        '
        'lblDupAppName
        '
        Me.lblDupAppName.Location = New System.Drawing.Point(235, 12)
        Me.lblDupAppName.Name = "lblDupAppName"
        Me.lblDupAppName.Size = New System.Drawing.Size(501, 45)
        Me.lblDupAppName.TabIndex = 4
        Me.lblDupAppName.Text = "UNKNOWN"
        Me.lblDupAppName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'ListView1
        '
        Me.ListView1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
            Or System.Windows.Forms.AnchorStyles.Left) _
            Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.ListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.appIcon, Me.appName, Me.appVersion, Me.apiVersion})
        Me.ListView1.FullRowSelect = True
        Me.ListView1.HideSelection = False
        Me.ListView1.LargeImageList = Me.ImageList1
        Me.ListView1.Location = New System.Drawing.Point(12, 63)
        Me.ListView1.Name = "ListView1"
        Me.ListView1.Size = New System.Drawing.Size(716, 241)
        Me.ListView1.SmallImageList = Me.ImageList1
        Me.ListView1.TabIndex = 6
        Me.ListView1.UseCompatibleStateImageBehavior = False
        Me.ListView1.View = System.Windows.Forms.View.Details
        '
        'appIcon
        '
        Me.appIcon.Text = "Icon"
        Me.appIcon.Width = 80
        '
        'appName
        '
        Me.appName.Text = "Name"
        Me.appName.Width = 372
        '
        'appVersion
        '
        Me.appVersion.Text = "Version"
        Me.appVersion.Width = 120
        '
        'apiVersion
        '
        Me.apiVersion.Text = "API Version"
        Me.apiVersion.Width = 120
        '
        'ImageList1
        '
        Me.ImageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit
        Me.ImageList1.ImageSize = New System.Drawing.Size(64, 64)
        Me.ImageList1.TransparentColor = System.Drawing.Color.Transparent
        '
        'MagicDialog
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(740, 375)
        Me.Controls.Add(Me.ListView1)
        Me.Controls.Add(Me.pbDupAppIcon)
        Me.Controls.Add(Me.lblDupAppName)
        Me.Controls.Add(Me.lblAppDuplicates)
        Me.Controls.Add(Me.btnLowerApp)
        Me.Controls.Add(Me.btnHigherApp)
        Me.Controls.Add(Me.btnLowerAPI)
        Me.Controls.Add(Me.btnHigherAPI)
        Me.Controls.Add(Me.btnCancel)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "MagicDialog"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
        Me.Text = "MagicDialog"
        CType(Me.pbDupAppIcon, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)

    End Sub
    Friend WithEvents btnCancel As System.Windows.Forms.Button
    Friend WithEvents btnHigherAPI As System.Windows.Forms.Button
    Friend WithEvents btnLowerAPI As System.Windows.Forms.Button
    Friend WithEvents btnHigherApp As System.Windows.Forms.Button
    Friend WithEvents btnLowerApp As System.Windows.Forms.Button
    Friend WithEvents lblAppDuplicates As System.Windows.Forms.Label
    Friend WithEvents pbDupAppIcon As System.Windows.Forms.PictureBox
    Friend WithEvents lblDupAppName As System.Windows.Forms.Label
    Friend WithEvents ListView1 As System.Windows.Forms.ListView
    Friend WithEvents appIcon As System.Windows.Forms.ColumnHeader
    Friend WithEvents appName As System.Windows.Forms.ColumnHeader
    Friend WithEvents appVersion As System.Windows.Forms.ColumnHeader
    Friend WithEvents apiVersion As System.Windows.Forms.ColumnHeader
    Friend WithEvents ImageList1 As System.Windows.Forms.ImageList

End Class


text:
@interface MSGaugeViewController : UIViewController
@property (nonatomic) NSArray *gauges;
@end

redpajama_set_name: RedPajamaGithub


text:
#if !defined(COLLECT_TOKEN_STATISTICS_VERSION_HPP)
#define COLLECT_TOKEN_STATISTICS_VERSION_HPP

#include <algorithm>
#include <map>

#include <boost/assert.hpp>
#include <boost/wave/token_ids.hpp>

///////////////////////////////////////////////////////////////////////////////
class collect_token_statistics
{
    enum {
        count = boost::wave::T_LAST_TOKEN - boost::wave::T_FIRST_TOKEN
    };

public:
    collect_token_statistics()
    {
        std::fill(&token_count[0], &token_count[count], 0);
    }

    // account for the given token type
    template <typename Token>
    void operator() (Token const& token)
    {
        using boost::wave::token_id;

        int id = token_id(token) - boost::wave::T_FIRST_TOKEN;
        BOOST_ASSERT(id < count);
        ++token_count[id];
    }

    // print out the token statistics in descending order
    void print() const
    {
        using namespace boost::wave;
        typedef std::multimap<int, token_id> ids_type;

        ids_type ids;
        for (unsigned int i = 0; i < count; ++i)
        {
            ids.insert(ids_type::value_type(
                token_count[i], token_id(i + T_FIRST_TOKEN)));
        }

        ids_type::reverse_iterator rend = ids.rend();
        for(ids_type::reverse_iterator rit = ids.rbegin(); rit != rend; ++rit)
        {
            std::cout << boost::wave::get_token_name((*rit).second) << ": "
                      << (*rit).first << std::endl;
        }
    }

private:
    int token_count[count];
};

#endif // !defined(COLLECT_TOKEN_STATISTICS_VERSION_HPP)


text:
void test01()
{
  using namespace std;
  bool test __attribute__((unused)) = true;

  typedef istringstream::pos_type pos_type;

  istringstream iss("Duos for Doris");
  ostringstream oss;

  VERIFY( iss.tellg() == pos_type(0) );

  iss >> oss.rdbuf();
  VERIFY( iss.rdstate() == iss.eofbit );
  VERIFY( iss.tellg() == pos_type(-1) );

  iss.clear();
  VERIFY( iss.tellg() == pos_type(14) );
}

int main()
{
  test01();
  return 0;
}


text:
.class public Landroid/webkit/HtmlComposerView$HCWHandler;
.super Landroid/os/Handler;
.source "HtmlComposerView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/webkit/HtmlComposerView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1
    name = "HCWHandler"
.end annotation

# instance fields
.field final synthetic this$0:Landroid/webkit/HtmlComposerView;

# direct methods
.method public constructor <init>(Landroid/webkit/HtmlComposerView;)V
    .locals 0
    .parameter

    .prologue
    .line 2292
    iput-object p1, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    invoke-direct {p0}, Landroid/os/Handler;-><init>()V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 5
    .parameter "msg"

    .prologue
    .line 2294
    iget v2, p1, Landroid/os/Message;->what:I

    packed-switch v2, :pswitch_data_0

    .line 2326
    :cond_0
    :goto_0
    return-void

    .line 2296
    :pswitch_0
    iget-object v2, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    sget v3, Landroid/webkit/HtmlComposerView;->operSel:I

    invoke-virtual {v2, v3}, Landroid/webkit/HtmlComposerView;->invokeTexttoSpeech(I)V

    goto :goto_0

    .line 2299
    :pswitch_1
    const-string v2, "HtmlComposerView"

    const-string v3, "HCWHandler UPDATE_RICHTEXT_TOOLBAR"

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 2300
    iget-object v2, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    const/4 v3, 0x0

    invoke-virtual {v2, v3}, Landroid/webkit/HtmlComposerView;->UpdateRichTextToolbar(Z)V

    goto :goto_0

    .line 2304
    :pswitch_2
    const-string v2, "HtmlComposerView"

    const-string v3, "HIT_INSERTED_IMAGE"

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 2305
    iget-object v0, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v0, Ljava/lang/String;

    .line 2306
    .local v0, imageUri:Ljava/lang/String;
    if-eqz v0, :cond_1

    .line 2307
    iget-object v2, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    iget-boolean v2, v2, Landroid/webkit/HtmlComposerView;->DEBUG:Z

    if-eqz v2, :cond_1

    const-string v2, "HtmlComposerView"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "HIT_INSERTED_IMAGE Selected imageUri = [ "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    const-string v4, " ] "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 2310
    :cond_1
    iget-object v2, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    iget-object v2, v2, Landroid/webkit/HtmlComposerView;->mInsertedImageHitListener:Landroid/webkit/HtmlComposerView$InsertedImageHitListener;

    if-eqz v2, :cond_0

    .line 2311
    iget-object v2, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    iget-object v2, v2, Landroid/webkit/HtmlComposerView;->mInsertedImageHitListener:Landroid/webkit/HtmlComposerView$InsertedImageHitListener;

    invoke-interface {v2, v0}, Landroid/webkit/HtmlComposerView$InsertedImageHitListener;->onHitResult(Ljava/lang/String;)V

    goto :goto_0

    .line 2316
    .end local v0           #imageUri:Ljava/lang/String;
    :pswitch_3
    const-string v2, "HtmlComposerView"

    const-string v3, "DELAYED_UPDATE_IMAGE_OUTLINE"

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 2318
    iget-object v2, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    invoke-virtual {v2}, Landroid/webkit/HtmlComposerView;->getSelectedImageRect()Landroid/graphics/Rect;

    move-result-object v1

    .line 2319
    .local v1, updateRect:Landroid/graphics/Rect;
    iget-object v2, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    iget-boolean v2, v2, Landroid/webkit/HtmlComposerView;->DEBUG:Z

    if-eqz v2, :cond_2

    const-string v2, "HtmlComposerView"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "DELAYED_UPDATE_IMAGE_OUTLINE result = ["

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget v4, v1, Landroid/graphics/Rect;->left:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    const-string v4, ", "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget v4, v1, Landroid/graphics/Rect;->top:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    const-string v4, ", "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget v4, v1, Landroid/graphics/Rect;->right:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    const-string v4, ", "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget v4, v1, Landroid/graphics/Rect;->bottom:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 2321
    :cond_2
    iget-object v2, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    iget-object v3, p0, Landroid/webkit/HtmlComposerView$HCWHandler;->this$0:Landroid/webkit/HtmlComposerView;

    #getter for: Landroid/webkit/HtmlComposerView;->mContext:Landroid/content/Context;
    invoke-static {v3}, Landroid/webkit/HtmlComposerView;->access$1000(Landroid/webkit/HtmlComposerView;)Landroid/content/Context;

    move-result-object v3

    invoke-virtual {v2, v3, v1}, Landroid/webkit/HtmlComposerView;->outlineDrawRect(Landroid/content/Context;Landroid/graphics/Rect;)V

    goto/16 :goto_0

    .line 2294
    nop

    :pswitch_data_0
    .packed-switch 0x500
        :pswitch_0
        :pswitch_1
        :pswitch_2
        :pswitch_3
    .end packed-switch
.end method


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

        <title>An Overview of RMI Applications (The Java™ Tutorials >
            RMI)
</title>

     <meta name="description" content="This RMI Java tutorial describes the Java RMI system. It walks through a complete client/server example" />
     <meta name="keywords" content="java programming, learn java, java sample code, java rmi, java client server" />

A browser with JavaScript enabled is required for this page to operate properly.

                            Download
                                the JDK

                            Search the
                                Tutorials

                            Hide the TOC

        Trail: RMI

An Overview of RMI Applications

Writing an RMI Server

Designing a Remote Interface

Implementing a Remote Interface

Creating a Client Program

Compiling and Running the Example

Compiling the Example Programs

Running the Example Programs

                Home Page
                >
                RMI

                « Previous • Trail • Next »

An Overview of RMI Applications

RMI applications often comprise two separate programs, a server
and a client. A typical server program creates some remote objects,
makes references to these objects accessible, and waits for clients to invoke
methods on these objects. A typical client program obtains a
remote reference to one or more remote objects on a server and then
invokes methods on them. RMI provides the mechanism by which the server
and the client communicate and pass information back and forth. Such an
application is sometimes referred to as a
distributed object application.

Distributed object applications need to do the following:

 Locate remote objects.
     Applications can use various mechanisms to obtain references to
     remote objects. For example, an application can register its remote objects
     with RMI's simple naming facility, the RMI registry.  Alternatively,
     an application can pass and return remote object references as
     part of other remote invocations.

 Communicate with remote objects.
     Details of communication between remote objects are handled by
     RMI.  To the programmer, remote communication looks similar to regular
     Java method invocations.

 Load class definitions for objects that are passed around.
     Because RMI enables objects to be passed back and forth, it
     provides mechanisms for loading an object's class definitions as
     well as for transmitting an object's data.

The following illustration depicts an RMI distributed application that
uses the RMI registry to obtain a reference to a remote object. The server
calls the registry to associate (or bind) a name with a remote object.
The client looks up the remote object by its name in the server's
registry and then invokes a method on it. The illustration also shows
that the RMI system uses an existing web server to load class
definitions, from server to client and from client to server, for objects
when needed.

Advantages of Dynamic Code Loading

One of the central and unique features of RMI is its ability to
download the definition of an object's class if the class is not
defined in the receiver's Java virtual machine. All of the types and behavior
of an object, previously available only in a single Java virtual machine,
can be transmitted to another, possibly remote, Java virtual machine. RMI
passes objects by their actual classes, so the behavior of the objects is
not changed when they are sent to another Java virtual machine. This capability enables
new types and behaviors to be introduced into a remote Java virtual machine, thus dynamically extending the behavior of an application. The compute
engine example in this trail uses this capability to introduce new
behavior to a distributed program.

Remote Interfaces, Objects, and Methods

Like any other Java application, a distributed application built by using Java
RMI is made up of interfaces and classes. The interfaces declare
methods.  The classes implement the methods declared in the
interfaces and, perhaps, declare additional methods as well. In a
distributed application, some implementations might reside in
some Java virtual machines but not others. Objects with methods that
can be invoked across Java virtual machines are called remote objects.

An object becomes remote by implementing a remote interface,
which has the following characteristics:

 A remote interface extends the interface java.rmi.Remote.

 Each method of the interface declares
     java.rmi.RemoteException in its throws
     clause, in addition to any application-specific exceptions.

RMI treats a remote object differently from a non-remote object when
the object is passed from one Java virtual machine to another Java virtual
machine. Rather than making a copy of the implementation object in the
receiving Java virtual machine, RMI passes a remote stub for a
remote object. The stub acts as the local representative, or proxy,
for the remote object and basically is, to the client, the remote
reference. The client invokes a method on the local stub, which is
responsible for carrying out the method invocation on the remote
object.

A stub for a remote object implements the same set of remote
interfaces that the remote object implements. This property enables a
stub to be cast to any of the interfaces that the remote object
implements. However, only those methods defined in a remote
interface are available to be called from the receiving Java virtual
machine.

Creating Distributed Applications by Using RMI

Using RMI to develop a distributed application involves these general
steps:

 Designing and implementing the components of your distributed application.

 Compiling sources.

 Making classes network accessible.

 Starting the application.

 Designing and Implementing the Application Components

First, determine your application architecture, including which
components are local objects and which components are remotely
accessible. This step includes:

 Defining the remote interfaces.
     A remote interface specifies the methods that can be invoked
     remotely by a client. Clients program to remote interfaces, not to
     the implementation classes of those interfaces. The design of such
     interfaces includes the determination of the types of objects that
     will be used as the parameters and return values for these methods.
     If any of these interfaces or classes do not yet exist, you need to
     define them as well.

 Implementing the remote objects.
     Remote objects must implement one or more remote interfaces. The
     remote object class may include implementations of other
     interfaces and methods that are
     available only locally. If any local classes are to be used for
     parameters or return values of any of these methods, they must be
     implemented as well.

 Implementing the clients.
     Clients that use remote objects can be implemented at any time
     after the remote interfaces are defined, including after the
     remote objects have been deployed.

Compiling Sources

As with any Java program, you use the
javac compiler to compile the source files. The source files contain
the declarations of the remote interfaces, their implementations, any other
server classes, and the client classes.

Note: With versions prior to Java Platform, Standard Edition 5.0,
an additional step was required to build stub classes, by using the
rmic compiler. However, this step is no longer necessary.

Making Classes Network Accessible

In this step, you make certain class definitions network accessible,
such as the definitions for the remote interfaces and their associated
types, and the definitions for classes that need to be downloaded to
the clients or servers.  Classes definitions are typically made
network accessible through a web server.

Starting the Application

Starting the application includes running the RMI remote object
registry, the server, and the client.

The rest of this section walks through the steps used to create a compute engine.

Building a Generic Compute Engine

This trail focuses on a simple, yet powerful, distributed application
called a compute engine. The compute engine is a remote object on the
server that takes tasks from clients, runs the tasks, and returns any results.
The tasks are run on the machine where the server is running. This type
of distributed application can enable a number of client machines to
make use of a particularly powerful machine or a machine that has specialized
hardware.

The novel aspect of the compute engine is that the tasks it runs do not
need to be defined when the compute engine is written or started. New kinds of
tasks can be created at any time and then given to the compute engine
to be run. The only requirement of a task is that its class implement a
particular interface. The code needed
to accomplish the task can be downloaded by the RMI system to the
compute engine. Then, the compute engine runs the task, using the resources
on the machine on which the compute engine is running.

The ability to perform arbitrary tasks is enabled by the dynamic nature
of the Java platform, which is extended to the network by RMI. RMI
dynamically loads the task code into the compute engine's Java virtual
machine and runs the task without prior knowledge of the class that
implements the task. Such an application, which has the ability to
download code dynamically, is often called a behavior-based
application. Such applications usually require full agent-enabled
infrastructures. With RMI, such applications are part of the basic
mechanisms for distributed computing on the Java platform.

            « Previous
            •
            Trail
            •
            Next »

Problems with the examples? Try Compiling and Running
        the Examples: FAQs.

    Complaints? Compliments? Suggestions? Give
    us your feedback.

Your use of this page and all the material on pages under "The Java Tutorials" banner,
and all the material on pages under "The Java Tutorials" banner is subject to the Java SE Tutorial Copyright
and License.
Additionally, any example code contained in any of these Java
Tutorials pages is licensed under the
Code
Sample License.

About Oracle | Oracle Technology Network | Terms of Service

Copyright © 1995, 2011 Oracle and/or its affiliates. All rights reserved.

        Previous page: Table of Contents

Next page: Writing an RMI Server

A browser with JavaScript enabled is required for this page to operate properly.


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: java.lang.reflect.InvocationHandler
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_LANG_REFLECT_INVOCATIONHANDLER_HPP_DECL
#define J2CPP_JAVA_LANG_REFLECT_INVOCATIONHANDLER_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { namespace reflect { class Method; } } } }

#include <java/lang/Object.hpp>
#include <java/lang/reflect/Method.hpp>

namespace j2cpp {

namespace java { namespace lang { namespace reflect {

	class InvocationHandler;
	class InvocationHandler
		: public object<InvocationHandler>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)

		explicit InvocationHandler(jobject jobj)
		: object<InvocationHandler>(jobj)
		{
		}

		operator local_ref<java::lang::Object>() const;

		local_ref< java::lang::Object > invoke(local_ref< java::lang::Object >  const&, local_ref< java::lang::reflect::Method >  const&, local_ref< array< local_ref< java::lang::Object >, 1> >  const&);
	}; //class InvocationHandler

} //namespace reflect
} //namespace lang
} //namespace java

} //namespace j2cpp

#endif //J2CPP_JAVA_LANG_REFLECT_INVOCATIONHANDLER_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_LANG_REFLECT_INVOCATIONHANDLER_HPP_IMPL
#define J2CPP_JAVA_LANG_REFLECT_INVOCATIONHANDLER_HPP_IMPL

namespace j2cpp {

java::lang::reflect::InvocationHandler::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

local_ref< java::lang::Object > java::lang::reflect::InvocationHandler::invoke(local_ref< java::lang::Object > const &a0, local_ref< java::lang::reflect::Method > const &a1, local_ref< array< local_ref< java::lang::Object >, 1> > const &a2)
{
	return call_method<
		java::lang::reflect::InvocationHandler::J2CPP_CLASS_NAME,
		java::lang::reflect::InvocationHandler::J2CPP_METHOD_NAME(0),
		java::lang::reflect::InvocationHandler::J2CPP_METHOD_SIGNATURE(0),
		local_ref< java::lang::Object >
	>(get_jobject(), a0, a1, a2);
}

J2CPP_DEFINE_CLASS(java::lang::reflect::InvocationHandler,"java/lang/reflect/InvocationHandler")
J2CPP_DEFINE_METHOD(java::lang::reflect::InvocationHandler,0,"invoke","(Ljava/lang/Object;Ljava/lang/reflect/Method;[java.lang.Object)Ljava/lang/Object;")

} //namespace j2cpp

#endif //J2CPP_JAVA_LANG_REFLECT_INVOCATIONHANDLER_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
require_relative "solo_runner"

module ChefSpec
  # As we start to migrate back to only SoloRunner, include this alias for now.
  #
  # @since 7.3
  Runner = SoloRunner
end


text:
---
title: Data in Gatsby
typora-copy-images-to: ./
---

Welcome to Part Four of the tutorial! Halfway through! Hope things are starting
to feel pretty comfortable 😀

## Recap of the first half of the tutorial

So far, you've been learning how to use React.js—how powerful it is to be able to
create your _own_ components to act as custom building blocks for websites.

You've also explored styling components using CSS Modules.

## What's in this tutorial?

In the next four parts of the tutorial (including this one), you'll be diving into the Gatsby data layer, which is a powerful feature of Gatsby that lets you easily build sites from Markdown, WordPress, headless CMSs, and other data sources of all flavors.

**NOTE:** Gatsby's data layer is powered by GraphQL. For an in-depth tutorial on
GraphQL, we recommend [How to GraphQL](https://www.howtographql.com/).

## Data in Gatsby

A website has four parts: HTML, CSS, JS, and data. The first half of the
tutorial focused on the first three. Now let's learn how to use data in Gatsby
sites.

**What is data?**

A very computer science-y answer would be: data is things like `"strings"`,
integers (`42`), objects (`{ pizza: true }`), etc.

For the purpose of working in Gatsby, however, a more useful answer is
"everything that lives outside a React component".

So far, you've been writing text and adding images _directly_ in components.
Which is an _excellent_ way to build many websites. But, often you want to store
data _outside_ components and then bring the data _into_ the component as
needed.

If you're building a site with WordPress (so other contributors
have a nice interface for adding & maintaining content) and Gatsby, the _data_
for the site (pages and posts) are in WordPress and you _pull_ that data, as
needed, into your components.

Data can also live in file types like Markdown, CSV, etc. as well as databases
and APIs of all sorts.

**Gatsby's data layer lets you pull data from these (and any other source)
directly into your components**—in the shape and form you want.

## Using Unstructured Data vs GraphQL

### Do I have to use GraphQL and source plugins to pull data into Gatsby sites?

Absolutely not! You can use the node `createPages` API to pull unstructured data into Gatsby pages directly, rather than through the GraphQL data layer. This is a great choice for small sites, while GraphQL and source plugins can help save time with more complex sites.

See the [Using Gatsby without GraphQL](/docs/using-gatsby-without-graphql/) guide to learn how to pull data into your Gatsby site using the node `createPages` API and to see an example site!

### When do I use unstructured data vs GraphQL?

If you're building a small site, one efficient way to build it is to pull in unstructured data as outlined in this guide, using `createPages` API, and then if the site becomes more complex later on, you move on to building more complex sites, or you'd like to transform your data, follow these steps:

1.  Check out the [Plugin Library](/plugins/) to see if the source plugins and/or transformer plugins you'd like to use already exist
2.  If they don't exist, read the [Plugin Authoring](/docs/creating-plugins/) guide and consider building your own!

### How Gatsby's data layer uses GraphQL to pull data into components

There are many options for loading data into React components. One of the most
popular and powerful of these is a technology called
[GraphQL](http://graphql.org/).

GraphQL was invented at Facebook to help product engineers _pull_ needed data into
components.

GraphQL is a **q**uery **l**anguage (the _QL_ part of its name). If you're
familiar with SQL, it works in a very similar way. Using a special syntax, you describe
the data you want in your component and then that data is given
to you.

Gatsby uses GraphQL to enable components to declare the data they need.

## Create a new example site

Create another new site for this part of the tutorial. You're going to build a Markdown blog called "Pandas Eating Lots". It's dedicated to showing off the best pictures and videos of pandas eating lots of food. Along the way, you'll be dipping your toes into GraphQL and Gatsby's Markdown support.

Open a new terminal window and run the following commands to create a new Gatsby site in a directory called `tutorial-part-four`. Then navigate to the new directory:

```shell
gatsby new tutorial-part-four https://github.com/gatsbyjs/gatsby-starter-hello-world
cd tutorial-part-four
```

Then install some other needed dependencies at the root of the project. You'll use the Typography theme
"Kirkham", and you'll try out a CSS-in-JS library, ["Emotion"](https://emotion.sh/):

```shell
npm install --save gatsby-plugin-typography typography react-typography typography-theme-kirkham gatsby-plugin-emotion @emotion/core
```

Set up a site similar to what you ended with in [Part Three](/tutorial/part-three). This site will have a layout component and two page components:

```jsx:title=src/components/layout.js
import React from "react"
import { css } from "@emotion/core"
import { Link } from "gatsby"

import { rhythm } from "../utils/typography"

export default ({ children }) => (
  <div
    css={css`
      margin: 0 auto;
      max-width: 700px;
      padding: ${rhythm(2)};
      padding-top: ${rhythm(1.5)};
    `}
  >
    <Link to={`/`}>
      <h3
        css={css`
          margin-bottom: ${rhythm(2)};
          display: inline-block;
          font-style: normal;
        `}
      >
        Pandas Eating Lots
      </h3>
    </Link>
    <Link
      to={`/about/`}
      css={css`
        float: right;
      `}
    >
      About
    </Link>
    {children}
  </div>
)
```

```jsx:title=src/pages/index.js
import React from "react"
import Layout from "../components/layout"

export default () => (
  <Layout>
    <h1>Amazing Pandas Eating Things</h1>
    <div>
      <img
        src="https://2.bp.blogspot.com/-BMP2l6Hwvp4/TiAxeGx4CTI/AAAAAAAAD_M/XlC_mY3SoEw/s1600/panda-group-eating-bamboo.jpg"
        alt="Group of pandas eating bamboo"
      />
    </div>
  </Layout>
)
```

```jsx:title=src/pages/about.js
import React from "react"
import Layout from "../components/layout"

export default () => (
  <Layout>
    <h1>About Pandas Eating Lots</h1>
    <p>
      We're the only site running on your computer dedicated to showing the best
      photos and videos of pandas eating lots of food.
    </p>
  </Layout>
)
```

```javascript:title=src/utils/typography.js
import Typography from "typography"
import kirkhamTheme from "typography-theme-kirkham"

const typography = new Typography(kirkhamTheme)

export default typography
export const rhythm = typography.rhythm
```

`gatsby-config.js` (must be in the root of your project, not under src)

```javascript:title=gatsby-config.js
module.exports = {
  plugins: [
    `gatsby-plugin-emotion`,
    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/utils/typography`,
      },
    },
  ],
}
```

Add the above files and then run `gatsby develop`, per usual, and you should see the following:

![start](start.png)

You have another small site with a layout and two pages.

Now you can start querying 😋

## Your first GraphQL query

When building sites, you'll probably want to reuse common bits of data -- like the _site title_ for example. Look at the `/about/` page. You'll notice that you have the site title (`Pandas Eating Lots`) in both the layout component (the site header) as well as in the `<h1 />` of the `about.js` page (the page header).

But what if you want to change the site title in the future? You'd have to search for the title across all your components and edit each instance. This is both cumbersome and error-prone, especially for larger, more complex sites. Instead, you can store the title in one location and reference that location from other files; Change the title in a single place, and Gatsby will _pull_ your updated title into files that reference it.

The place for these common bits of data is the `siteMetadata` object in the `gatsby-config.js` file. Add your site title to the `gatsby-config.js` file:

```javascript:title=gatsby-config.js
module.exports = {
  // highlight-start
  siteMetadata: {
    title: `Title from siteMetadata`,
  },
  // highlight-end
  plugins: [
    `gatsby-plugin-emotion`,
    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/utils/typography`,
      },
    },
  ],
}
```

Restart the development server.

### Use a page query

Now the site title is available to be queried; Add it to the `about.js` file using a [page query](/docs/page-query):

```jsx:title=src/pages/about.js
import React from "react"
import { graphql } from "gatsby" // highlight-line
import Layout from "../components/layout"

// highlight-next-line
export default ({ data }) => (
  <Layout>
    <h1>About {data.site.siteMetadata.title}</h1> {/* highlight-line */}
    <p>
      We're the only site running on your computer dedicated to showing the best
      photos and videos of pandas eating lots of food.
    </p>
  </Layout>
)

// highlight-start
export const query = graphql`
  query {
    site {
      siteMetadata {
        title
      }
    }
  }
`
// highlight-end
```

It worked! 🎉

![Page title pulling from siteMetadata](site-metadata-title.png)

The basic GraphQL query that retrieves the `title` in our `about.js` changes above is:

```graphql:title=src/pages/about.js
{
  site {
    siteMetadata {
      title
    }
  }
}
```

> 💡 In [part five](/tutorial/part-five/#introducing-graphiql), you'll meet a tool that lets us interactively explore the data available through GraphQL, and help formulate queries like the one above.

Page queries live outside of the component definition -- by convention at the end of a page component file -- and are only available on page components.

### Use a StaticQuery

[StaticQuery](/docs/static-query/) is a new API introduced in Gatsby v2 that allows non-page components (like our `layout.js` component), to retrieve data via GraphQL queries.
Let's use its newly introduced hook version — [`useStaticQuery`](/docs/use-static-query/)
Go ahead and make some changes to your `src/components/layout.js` file to use the `useStaticQuery` hook and a `{data.site.siteMetadata.title}` reference that uses this data. When you are done your file looks like this:

```jsx:title=src/components/layout.js
import React from "react"
import { css } from "@emotion/core"
// highlight-next-line
import { useStaticQuery, Link, graphql } from "gatsby"

import { rhythm } from "../utils/typography"
// highlight-start
export default ({ children }) => {
  const data = useStaticQuery(
    graphql`
      query {
        site {
          siteMetadata {
            title
          }
        }
      }
    `
  )
  return (
    // highlight-end
    <div
      css={css`
        margin: 0 auto;
        max-width: 700px;
        padding: ${rhythm(2)};
        padding-top: ${rhythm(1.5)};
      `}
    >
      <Link to={`/`}>
        <h3
          css={css`
            margin-bottom: ${rhythm(2)};
            display: inline-block;
            font-style: normal;
          `}
        >
          {data.site.siteMetadata.title} {/* highlight-line */}
        </h3>
      </Link>
      <Link
        to={`/about/`}
        css={css`
          float: right;
        `}
      >
        About
      </Link>
      {children}
    </div>
    // highlight-start
  )
}
// highlight-end
```

Another success! 🎉

![Page title and layout title both pulling from siteMetadata](site-metadata-two-titles.png)

Why use two different queries here? These examples were quick introductions to
the query types, how they are formatted, and where they can be used. For now,
keep in mind that only pages can make page queries. Non-page components, such as
Layout, can use StaticQuery. [Part 7](/tutorial/part-seven/) of the tutorial explains these in greater
depth.

But let's restore the real title.

One of the core principles of Gatsby is that _creators need an immediate connection to what they're creating_ ([hat tip to Bret Victor](http://blog.ezyang.com/2012/02/transcript-of-inventing-on-principle/)). In other words, when you make any change to code you should immediately see the effect of that change. You manipulate an input of Gatsby and you see the new output showing up on the screen.

So almost everywhere, changes you make will immediately take effect. Edit the `gatsby-config.js` file again, this time changing the `title` back to "Pandas Eating Lots". The change should show up very quickly in your site pages.

![Both titles say Pandas Eating Lots](pandas-eating-lots-titles.png)

## What's coming next?

Next, you'll be learning about how to pull data into your Gatsby site using
GraphQL with source plugins in [part five](/tutorial/part-five/) of the
tutorial.


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

namespace OpenTNF.Library.Model
{
    public class GpkgDataColumn
    {
        public string TableName { get; set; }
        public string ColumnName { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string MimeType { get; set; }
        public string ConstraintName { get; set; }

        public override bool Equals(object obj)
        {
            if (obj is GpkgDataColumn)
            {
                var v = obj as GpkgDataColumn;

                if (TableName == v.TableName &&
                    ColumnName == v.ColumnName &&
                    Name == v.Name &&
                    Title == v.Title &&
                    Description == v.Description &&
                    MimeType == v.MimeType &&
                    ConstraintName == v.ConstraintName)
                {
                    return true;
                }
            }

            return false;
        }

        public override int GetHashCode()
        {
            return Hashing.RsHash(
                TableName,
                ColumnName,
                Name,
                Title,
                Description,
                MimeType,
                ConstraintName);
        }

        public override string ToString()
        {
            return String.Format("GpkgDataColumn: TableName = {0}, ColumnName = {1}, Name = {2}, Title = {3}, " +
                                 "Description = {4}, MimeType = {5}, ConstraintName = {6}",
                TableName,
                ColumnName,
                Name,
                Title,
                Description,
                MimeType,
                ConstraintName);
        }
    }

    public class GpkgDataColumnsManager : TableManager
    {
        private const string PrimaryKey = "table_name, column_name";
        public static string GpkgDataColumnsTableName = "gpkg_data_columns";

        public GpkgDataColumnsManager(GeoPackageDatabase db) : base(db, GpkgDataColumnsTableName, GetColumnInfos(), PrimaryKey)
        {
        }

        protected override string[] Constraints()
        {
            return new[]
                {
                    String.Format("CONSTRAINT fk_gdc_tn FOREIGN KEY (table_name) REFERENCES {0}(table_name)", GpkgContentsManager.GpkgContentsTableName)
                };
        }

        private static ColumnInfo[] GetColumnInfos()
        {
            return new[]
            {
                new ColumnInfo
                {
                    Name = "table_name",
                    SqlType = "TEXT NOT NULL",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "column_name",
                    SqlType = "TEXT NOT NULL",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "name",
                    SqlType = "TEXT",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "title",
                    SqlType = "TEXT",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "description",
                    SqlType = "TEXT",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "mime_type",
                    SqlType = "TEXT",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "constraint_name",
                    SqlType = "TEXT",
                    DataType = Type.GetType("System.String")
                },
            };
        }

        public void Add(GpkgDataColumn gpkgDataColumn)
        {
            Add(new object[]
                {
                    gpkgDataColumn.TableName,
                    gpkgDataColumn.ColumnName,
                    gpkgDataColumn.Name,
                    gpkgDataColumn.Title,
                    gpkgDataColumn.Description,
                    gpkgDataColumn.MimeType,
                    gpkgDataColumn.ConstraintName
                });
        }

        public GpkgDataColumn Get(string tableName, string columnName)
        {
            return Get(ReadObject, new object[] { tableName, columnName });
        }

        public List<GpkgDataColumn> Get(int maxResults)
        {
            return Get(ReadObject, maxResults);
        }

        public int Update(GpkgDataColumn gpkgDataColumn)
        {
            return Update(new object[]
                {
                    gpkgDataColumn.TableName,
                    gpkgDataColumn.ColumnName,
                    gpkgDataColumn.Name,
                    gpkgDataColumn.Title,
                    gpkgDataColumn.Description,
                    gpkgDataColumn.MimeType,
                    gpkgDataColumn.ConstraintName
                });
        }

        public int Delete(string tableName, string columnName)
        {
            return Delete(new object[] { tableName, columnName });
        }

        private static GpkgDataColumn ReadObject(IDataRecord reader)
        {
            var gpkgDataColumn = new GpkgDataColumn();

            gpkgDataColumn.TableName = reader["table_name"].FromDbString();
            gpkgDataColumn.ColumnName = reader["column_name"].FromDbString();
            gpkgDataColumn.Name = reader["name"].FromDbString();
            gpkgDataColumn.Title = reader["title"].FromDbString();
            gpkgDataColumn.Description = reader["description"].FromDbString();
            gpkgDataColumn.MimeType = reader["mime_type"].FromDbString();
            gpkgDataColumn.ConstraintName = reader["constraint_name"].FromDbString();

            return gpkgDataColumn;
        }
    }
}


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

using Orleans.Runtime.Configuration;

namespace Orleankka
{
    using Core;
    using Utility;

    public interface IActorSystemConfigurator
    {}

    public abstract class ActorSystemConfigurator : MarshalByRefObject, IDisposable
    {
        readonly HashSet<Assembly> assemblies = new HashSet<Assembly>();

        Tuple<Type, object> serializer;
        Tuple<Type, object> activator;

        protected void RegisterSerializer<T>(object properties = null) where T : IMessageSerializer
        {
            if (serializer != null)
                throw new InvalidOperationException("Serializer has been already registered");

            serializer = Tuple.Create(typeof(T), properties);
        }

        protected void RegisterActivator<T>(object properties) where T : IActorActivator
        {
            if (activator != null)
                throw new InvalidOperationException("Activator has been already registered");

            activator = Tuple.Create(typeof(T), properties);
        }

        protected void RegisterAssemblies(params Assembly[] assemblies)
        {
            Requires.NotNull(assemblies, "assemblies");

            if (assemblies.Length == 0)
                throw new ArgumentException("Assemblies length should be greater than 0", "assemblies");

            foreach (var assembly in assemblies)
            {
                if (this.assemblies.Contains(assembly))
                    throw new ArgumentException(
                        string.Format("Assembly {0} has been already registered", assembly.FullName));

                this.assemblies.Add(assembly);
            }
        }

        protected internal void Configure(IDictionary<string, ProviderCategoryConfiguration> providerConfigurations)
        {
            if (providerConfigurations.ContainsKey("Stream"))
            {
                var providers = providerConfigurations["Stream"];
                StreamPath.Register(providers.Providers.Values);
            }

            if (serializer != null)
            {
                var instance = (IMessageSerializer) Activator.CreateInstance(serializer.Item1);
                instance.Init(assemblies.ToArray(), serializer.Item2 ?? new Dictionary<string, string>());

                MessageEnvelope.Serializer = instance;
            }

            if (activator != null)
            {
                var instance = (IActorActivator) Activator.CreateInstance(activator.Item1);
                instance.Init(activator.Item2);

                ActorEndpoint.Activator = instance;
            }

            ActorAssembly.Register(assemblies);
        }

        public void Dispose()
        {
            StreamPath.Reset();
            MessageEnvelope.Reset();
            ActorEndpoint.Reset();
            ActorAssembly.Reset();
        }

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}


text:
package water;

import water.fvec.Vec;
import water.network.SocketChannelFactory;

import java.io.IOException;
import java.nio.channels.ByteChannel;
import java.sql.Timestamp;

import static water.ExternalFrameHandler.*;

/**
 * Various utilities methods to help with external frame handling.
 */
public class ExternalFrameUtils {

    /**
     * Hints for expected types in order to improve performance network communication.
     * We make use of these to send and receive data we actually have.
     *
     * Each supported type for conversion has to be specified here
     */
    public static final byte EXPECTED_BOOL = 0;
    public static final byte EXPECTED_BYTE = 1;
    public static final byte EXPECTED_CHAR = 2;
    public static final byte EXPECTED_SHORT = 3;
    public static final byte EXPECTED_INT = 4;
    public static final byte EXPECTED_FLOAT = 5;
    public static final byte EXPECTED_LONG = 6;
    public static final byte EXPECTED_DOUBLE = 7;
    public static final byte EXPECTED_STRING = 8;
    public static final byte EXPECTED_TIMESTAMP = 9;
    public static final byte EXPECTED_VECTOR = 10;

    /* Helper empty int array */
    public static final int[] EMPTY_ARI = new int[0];

    /**
     * Meta Information used to specify whether we should expect sparse or dense vector
     */
    public static final boolean VECTOR_IS_SPARSE = true;
    public static final boolean VECTOR_IS_DENSE = false;

    /**
     * Get connection to a specific h2o node. The caller of this method is usually non-H2O node who wants to read H2O
     * frames or write to H2O frames from non-H2O environment, such as Spark executor.
     * This node usually does not have H2O running.
     */
    public static ByteChannel getConnection(String h2oNodeHostname, int h2oNodeApiPort, short nodeTimeStamp) throws IOException{
        SocketChannelFactory socketFactory = SocketChannelFactory.instance(H2OSecurityManager.instance());
        return H2ONode.openChan(TCPReceiverThread.TCP_EXTERNAL, socketFactory, h2oNodeHostname, h2oNodeApiPort +1, nodeTimeStamp);
    }

    public static ByteChannel getConnection(String ipPort, short nodeTimeStamp) throws IOException{
        String[] split = ipPort.split(":");
        return getConnection(split[0], Integer.parseInt(split[1]), nodeTimeStamp);
    }

    public static byte[] vecTypesFromExpectedTypes(byte[] expectedTypes, int[] vecElemSizes){
        assert vecElemSizes != null : "vecElemSizes should be not null!";
        int size = expectedTypes.length;
        size = size - vecElemSizes.length;
        // length is number of simple expected types
        // plus length of all vectors. the expected
        for(int vecSize: vecElemSizes){
            size += vecSize;
        }

        byte[] vecTypes = new byte[size];
        int vectorCount = 0;
        int currentVecIdx = 0;
        for (byte expectedType: expectedTypes) {
            switch (expectedType) {
                case EXPECTED_BOOL:
                    vecTypes[currentVecIdx] = Vec.T_NUM;
                    currentVecIdx++;
                    break;
                case EXPECTED_BYTE:
                    vecTypes[currentVecIdx] = Vec.T_NUM;
                    currentVecIdx++;
                    break;
                case EXPECTED_CHAR:
                    vecTypes[currentVecIdx] = Vec.T_NUM;
                    currentVecIdx++;
                    break;
                case EXPECTED_SHORT:
                    vecTypes[currentVecIdx] = Vec.T_NUM;
                    currentVecIdx++;
                    break;
                case EXPECTED_INT:
                    vecTypes[currentVecIdx] = Vec.T_NUM;
                    currentVecIdx++;
                    break;
                case EXPECTED_LONG:
                    vecTypes[currentVecIdx] = Vec.T_NUM;
                    currentVecIdx++;
                    break;
                case EXPECTED_FLOAT:
                    vecTypes[currentVecIdx] = Vec.T_NUM;
                    currentVecIdx++;
                    break;
                case EXPECTED_DOUBLE:
                    vecTypes[currentVecIdx] = Vec.T_NUM;
                    currentVecIdx++;
                    break;
                case EXPECTED_STRING:
                    vecTypes[currentVecIdx] = Vec.T_STR;
                    currentVecIdx++;
                    break;
                case EXPECTED_TIMESTAMP:
                    vecTypes[currentVecIdx] = Vec.T_TIME;
                    currentVecIdx++;
                    break;
                case EXPECTED_VECTOR:
                    for (int j = 0; j < vecElemSizes[vectorCount]; j++) {
                        vecTypes[currentVecIdx] = Vec.T_NUM;
                        currentVecIdx++;
                    }
                    // We need to move pointer to the next vector
                    vectorCount++;
                    break;
                default:
                    throw new IllegalArgumentException("Unknown expected type: " + expectedType);
            }
        }
        assert vecElemSizes.length == vectorCount : "Inconsistency in passed parameters:"
                                                 + " vectors lenght specified, but no vector found";
        return vecTypes;
    }

    static void sendIntArray(AutoBuffer ab, ByteChannel channel, int[] data) throws IOException{
        ab.putA4(data);
        writeToChannel(ab, channel);
    }

    static void sendDoubleArray(AutoBuffer ab, ByteChannel channel, double[] data) throws IOException{
        ab.putA8d(data);
        writeToChannel(ab, channel);
    }

    static void sendBoolean(AutoBuffer ab, ByteChannel channel, boolean data) throws IOException{
        sendBoolean(ab, channel, data ? (byte)1 : (byte)0);
    }

    static void sendBoolean(AutoBuffer ab, ByteChannel channel, byte boolData) throws IOException{
        ab.put1(boolData);
        putMarkerAndSend(ab, channel, boolData);
    }

    static void sendByte(AutoBuffer ab, ByteChannel channel, byte data) throws IOException{
        ab.put1(data);
        putMarkerAndSend(ab, channel, data);
    }

    static void sendChar(AutoBuffer ab, ByteChannel channel, char data) throws IOException{
        ab.put2(data);
        putMarkerAndSend(ab, channel, data);
    }

    static void sendShort(AutoBuffer ab, ByteChannel channel, short data) throws IOException{
        ab.put2s(data);
        putMarkerAndSend(ab, channel, data);
    }

    static void sendInt(AutoBuffer ab, ByteChannel channel, int data) throws IOException{
        ab.putInt(data);
        putMarkerAndSend(ab, channel, data);
    }

    static void sendLong(AutoBuffer ab, ByteChannel channel, long data) throws IOException{
        ab.put8(data);
        putMarkerAndSend(ab, channel, data);
    }

    static void sendFloat(AutoBuffer ab, ByteChannel channel, float data) throws IOException{
        ab.put4f(data);
        writeToChannel(ab, channel);
    }

    static void sendDouble(AutoBuffer ab, ByteChannel channel, double data) throws IOException{
        ab.put8d(data);
        writeToChannel(ab, channel);
    }

    static void sendString(AutoBuffer ab, ByteChannel channel, String data) throws IOException{
        ab.putStr(data);
        if(data != null && data.equals(STR_MARKER_NEXT_BYTE_FOLLOWS)){
            ab.put1(MARKER_ORIGINAL_VALUE);
        }
        writeToChannel(ab, channel);
    }

    static void sendTimestamp(AutoBuffer ab, ByteChannel channel, long time) throws IOException{
        sendLong(ab, channel, time);
    }

    static void sendTimestamp(AutoBuffer ab, ByteChannel channel, Timestamp data) throws IOException{
        sendLong(ab, channel, data.getTime());
    }

    static void sendNA(AutoBuffer ab, ByteChannel channel, byte expectedType) throws IOException{
        switch (expectedType){
            case EXPECTED_BOOL: // // fall through to byte since BOOL is internally stored in frame as number (byte)
            case EXPECTED_BYTE:
                ab.put1(NUM_MARKER_NEXT_BYTE_FOLLOWS);
                ab.put1(MARKER_NA);
                writeToChannel(ab, channel);
                break;
            case EXPECTED_CHAR:
                ab.put2(NUM_MARKER_NEXT_BYTE_FOLLOWS);
                ab.put1(MARKER_NA);
                writeToChannel(ab, channel);
                break;
            case EXPECTED_SHORT:
                ab.put2s(NUM_MARKER_NEXT_BYTE_FOLLOWS);
                ab.put1(MARKER_NA);
                writeToChannel(ab, channel);
                break;
            case EXPECTED_INT:
                ab.putInt(NUM_MARKER_NEXT_BYTE_FOLLOWS);
                ab.put1(MARKER_NA);
                writeToChannel(ab, channel);
                break;
            case EXPECTED_TIMESTAMP: // fall through to long since TIMESTAMP is internally stored in frame as long
            case EXPECTED_LONG:
                ab.put8(NUM_MARKER_NEXT_BYTE_FOLLOWS);
                ab.put1(MARKER_NA);
                writeToChannel(ab, channel);
                break;
            case EXPECTED_FLOAT:
                ab.put4f(Float.NaN);
                writeToChannel(ab, channel);
                break;
            case EXPECTED_DOUBLE:
                ab.put8d(Double.NaN);
                writeToChannel(ab, channel);
                break;
            case EXPECTED_STRING:
                ab.putStr(STR_MARKER_NEXT_BYTE_FOLLOWS);
                ab.put1(MARKER_NA);
                writeToChannel(ab, channel);
                break;
            default:
                throw new IllegalArgumentException("Unknown expected type " + expectedType);
        }
    }

    public static boolean isNA(AutoBuffer ab, boolean data){
        return isNA(ab, data ? (long) 1: 0);
    }

    public static boolean isNA(AutoBuffer ab, long data){
        return data == NUM_MARKER_NEXT_BYTE_FOLLOWS && ab.get1() == MARKER_NA;
    }

    public static boolean isNA(double data){
        return Double.isNaN(data);
    }

    public static boolean isNA(AutoBuffer ab, Timestamp data){
        return isNA(ab, data.getTime());
    }

    public static boolean isNA(AutoBuffer ab, String data){
        return data != null && data.equals(STR_MARKER_NEXT_BYTE_FOLLOWS) && ab.get1() == MARKER_NA;
    }

    static int[] getStartPositions(int[] elemSizes){
        int[] startPos = new int[elemSizes.length];
        for(int i = 1; i<elemSizes.length; i++){
            startPos[i] = startPos[ i - 1] + elemSizes[i - 1];
        }
        return startPos;
    }

    static int[] getElemSizes(byte[] expectedTypes, int[] vecElemSizes){
        assert vecElemSizes != null : "vecElemSizes should be not null!";
        int vecCount = 0;
        int[] elemSizes = new int[expectedTypes.length];
        for(int i = 0; i<expectedTypes.length; i++){
            switch (expectedTypes[i]){
                case EXPECTED_BOOL:
                case EXPECTED_BYTE:
                case EXPECTED_CHAR:
                case EXPECTED_SHORT:
                case EXPECTED_INT:
                case EXPECTED_LONG:
                case EXPECTED_FLOAT:
                case EXPECTED_DOUBLE:
                case EXPECTED_STRING:
                case EXPECTED_TIMESTAMP: elemSizes[i] = 1; break;
                case EXPECTED_VECTOR: elemSizes[i] = vecElemSizes[vecCount++]; break;
            }
        }
        assert vecElemSizes.length == vecCount : "Inconsistency in passed parameters:"
                                                 + " vectors lenght specified, but no vector found";
        return elemSizes;
    }

    /**
     * Sends another byte as a marker if it's needed and send the data
     */
    private static void putMarkerAndSend(AutoBuffer ab, ByteChannel channel, long data) throws IOException{
        if(data == NUM_MARKER_NEXT_BYTE_FOLLOWS){
            // we need to send another byte because zero is represented as 00 ( 2 bytes )
            ab.put1(MARKER_ORIGINAL_VALUE);
        }
        writeToChannel(ab, channel);
    }

    public static void writeToChannel(AutoBuffer ab, ByteChannel channel) throws IOException {
        ab.flipForReading();
        channel.write(ab._bb);
        ab.clearForWriting(H2O.MAX_PRIORITY);
    }
}


text:
use std::os::raw::c_ushort;

use cocoa::{
    appkit::{NSEvent, NSEventModifierFlags},
    base::id,
};

use crate::{
    dpi::LogicalSize,
    event::{ElementState, Event, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent},
    platform_impl::platform::{
        util::{IdRef, Never},
        DEVICE_ID,
    },
};

#[derive(Debug)]
pub enum EventWrapper {
    StaticEvent(Event<'static, Never>),
    EventProxy(EventProxy),
}

#[derive(Debug, PartialEq)]
pub enum EventProxy {
    DpiChangedProxy {
        ns_window: IdRef,
        suggested_size: LogicalSize<f64>,
        scale_factor: f64,
    },
}

pub fn char_to_keycode(c: char) -> Option<VirtualKeyCode> {
    // We only translate keys that are affected by keyboard layout.
    //
    // Note that since keys are translated in a somewhat "dumb" way (reading character)
    // there is a concern that some combination, i.e. Cmd+char, causes the wrong
    // letter to be received, and so we receive the wrong key.
    //
    // Implementation reference: https://github.com/WebKit/webkit/blob/82bae82cf0f329dbe21059ef0986c4e92fea4ba6/Source/WebCore/platform/cocoa/KeyEventCocoa.mm#L626
    Some(match c {
        'a' | 'A' => VirtualKeyCode::A,
        'b' | 'B' => VirtualKeyCode::B,
        'c' | 'C' => VirtualKeyCode::C,
        'd' | 'D' => VirtualKeyCode::D,
        'e' | 'E' => VirtualKeyCode::E,
        'f' | 'F' => VirtualKeyCode::F,
        'g' | 'G' => VirtualKeyCode::G,
        'h' | 'H' => VirtualKeyCode::H,
        'i' | 'I' => VirtualKeyCode::I,
        'j' | 'J' => VirtualKeyCode::J,
        'k' | 'K' => VirtualKeyCode::K,
        'l' | 'L' => VirtualKeyCode::L,
        'm' | 'M' => VirtualKeyCode::M,
        'n' | 'N' => VirtualKeyCode::N,
        'o' | 'O' => VirtualKeyCode::O,
        'p' | 'P' => VirtualKeyCode::P,
        'q' | 'Q' => VirtualKeyCode::Q,
        'r' | 'R' => VirtualKeyCode::R,
        's' | 'S' => VirtualKeyCode::S,
        't' | 'T' => VirtualKeyCode::T,
        'u' | 'U' => VirtualKeyCode::U,
        'v' | 'V' => VirtualKeyCode::V,
        'w' | 'W' => VirtualKeyCode::W,
        'x' | 'X' => VirtualKeyCode::X,
        'y' | 'Y' => VirtualKeyCode::Y,
        'z' | 'Z' => VirtualKeyCode::Z,
        '1' | '!' => VirtualKeyCode::Key1,
        '2' | '@' => VirtualKeyCode::Key2,
        '3' | '#' => VirtualKeyCode::Key3,
        '4' | '$' => VirtualKeyCode::Key4,
        '5' | '%' => VirtualKeyCode::Key5,
        '6' | '^' => VirtualKeyCode::Key6,
        '7' | '&' => VirtualKeyCode::Key7,
        '8' | '*' => VirtualKeyCode::Key8,
        '9' | '(' => VirtualKeyCode::Key9,
        '0' | ')' => VirtualKeyCode::Key0,
        '=' | '+' => VirtualKeyCode::Equals,
        '-' | '_' => VirtualKeyCode::Minus,
        ']' | '}' => VirtualKeyCode::RBracket,
        '[' | '{' => VirtualKeyCode::LBracket,
        '\'' | '"' => VirtualKeyCode::Apostrophe,
        ';' | ':' => VirtualKeyCode::Semicolon,
        '\\' | '|' => VirtualKeyCode::Backslash,
        ',' | '<' => VirtualKeyCode::Comma,
        '/' | '?' => VirtualKeyCode::Slash,
        '.' | '>' => VirtualKeyCode::Period,
        '`' | '~' => VirtualKeyCode::Grave,
        _ => return None,
    })
}

pub fn scancode_to_keycode(scancode: c_ushort) -> Option<VirtualKeyCode> {
    Some(match scancode {
        0x00 => VirtualKeyCode::A,
        0x01 => VirtualKeyCode::S,
        0x02 => VirtualKeyCode::D,
        0x03 => VirtualKeyCode::F,
        0x04 => VirtualKeyCode::H,
        0x05 => VirtualKeyCode::G,
        0x06 => VirtualKeyCode::Z,
        0x07 => VirtualKeyCode::X,
        0x08 => VirtualKeyCode::C,
        0x09 => VirtualKeyCode::V,
        //0x0a => World 1,
        0x0b => VirtualKeyCode::B,
        0x0c => VirtualKeyCode::Q,
        0x0d => VirtualKeyCode::W,
        0x0e => VirtualKeyCode::E,
        0x0f => VirtualKeyCode::R,
        0x10 => VirtualKeyCode::Y,
        0x11 => VirtualKeyCode::T,
        0x12 => VirtualKeyCode::Key1,
        0x13 => VirtualKeyCode::Key2,
        0x14 => VirtualKeyCode::Key3,
        0x15 => VirtualKeyCode::Key4,
        0x16 => VirtualKeyCode::Key6,
        0x17 => VirtualKeyCode::Key5,
        0x18 => VirtualKeyCode::Equals,
        0x19 => VirtualKeyCode::Key9,
        0x1a => VirtualKeyCode::Key7,
        0x1b => VirtualKeyCode::Minus,
        0x1c => VirtualKeyCode::Key8,
        0x1d => VirtualKeyCode::Key0,
        0x1e => VirtualKeyCode::RBracket,
        0x1f => VirtualKeyCode::O,
        0x20 => VirtualKeyCode::U,
        0x21 => VirtualKeyCode::LBracket,
        0x22 => VirtualKeyCode::I,
        0x23 => VirtualKeyCode::P,
        0x24 => VirtualKeyCode::Return,
        0x25 => VirtualKeyCode::L,
        0x26 => VirtualKeyCode::J,
        0x27 => VirtualKeyCode::Apostrophe,
        0x28 => VirtualKeyCode::K,
        0x29 => VirtualKeyCode::Semicolon,
        0x2a => VirtualKeyCode::Backslash,
        0x2b => VirtualKeyCode::Comma,
        0x2c => VirtualKeyCode::Slash,
        0x2d => VirtualKeyCode::N,
        0x2e => VirtualKeyCode::M,
        0x2f => VirtualKeyCode::Period,
        0x30 => VirtualKeyCode::Tab,
        0x31 => VirtualKeyCode::Space,
        0x32 => VirtualKeyCode::Grave,
        0x33 => VirtualKeyCode::Back,
        //0x34 => unkown,
        0x35 => VirtualKeyCode::Escape,
        0x36 => VirtualKeyCode::RWin,
        0x37 => VirtualKeyCode::LWin,
        0x38 => VirtualKeyCode::LShift,
        //0x39 => Caps lock,
        0x3a => VirtualKeyCode::LAlt,
        0x3b => VirtualKeyCode::LControl,
        0x3c => VirtualKeyCode::RShift,
        0x3d => VirtualKeyCode::RAlt,
        0x3e => VirtualKeyCode::RControl,
        //0x3f => Fn key,
        0x40 => VirtualKeyCode::F17,
        0x41 => VirtualKeyCode::NumpadDecimal,
        //0x42 -> unkown,
        0x43 => VirtualKeyCode::NumpadMultiply,
        //0x44 => unkown,
        0x45 => VirtualKeyCode::NumpadAdd,
        //0x46 => unkown,
        0x47 => VirtualKeyCode::Numlock,
        //0x48 => KeypadClear,
        0x49 => VirtualKeyCode::VolumeUp,
        0x4a => VirtualKeyCode::VolumeDown,
        0x4b => VirtualKeyCode::NumpadDivide,
        0x4c => VirtualKeyCode::NumpadEnter,
        //0x4d => unkown,
        0x4e => VirtualKeyCode::NumpadSubtract,
        0x4f => VirtualKeyCode::F18,
        0x50 => VirtualKeyCode::F19,
        0x51 => VirtualKeyCode::NumpadEquals,
        0x52 => VirtualKeyCode::Numpad0,
        0x53 => VirtualKeyCode::Numpad1,
        0x54 => VirtualKeyCode::Numpad2,
        0x55 => VirtualKeyCode::Numpad3,
        0x56 => VirtualKeyCode::Numpad4,
        0x57 => VirtualKeyCode::Numpad5,
        0x58 => VirtualKeyCode::Numpad6,
        0x59 => VirtualKeyCode::Numpad7,
        0x5a => VirtualKeyCode::F20,
        0x5b => VirtualKeyCode::Numpad8,
        0x5c => VirtualKeyCode::Numpad9,
        0x5d => VirtualKeyCode::Yen,
        //0x5e => JIS Ro,
        //0x5f => unkown,
        0x60 => VirtualKeyCode::F5,
        0x61 => VirtualKeyCode::F6,
        0x62 => VirtualKeyCode::F7,
        0x63 => VirtualKeyCode::F3,
        0x64 => VirtualKeyCode::F8,
        0x65 => VirtualKeyCode::F9,
        //0x66 => JIS Eisuu (macOS),
        0x67 => VirtualKeyCode::F11,
        //0x68 => JIS Kanna (macOS),
        0x69 => VirtualKeyCode::F13,
        0x6a => VirtualKeyCode::F16,
        0x6b => VirtualKeyCode::F14,
        //0x6c => unkown,
        0x6d => VirtualKeyCode::F10,
        //0x6e => unkown,
        0x6f => VirtualKeyCode::F12,
        //0x70 => unkown,
        0x71 => VirtualKeyCode::F15,
        0x72 => VirtualKeyCode::Insert,
        0x73 => VirtualKeyCode::Home,
        0x74 => VirtualKeyCode::PageUp,
        0x75 => VirtualKeyCode::Delete,
        0x76 => VirtualKeyCode::F4,
        0x77 => VirtualKeyCode::End,
        0x78 => VirtualKeyCode::F2,
        0x79 => VirtualKeyCode::PageDown,
        0x7a => VirtualKeyCode::F1,
        0x7b => VirtualKeyCode::Left,
        0x7c => VirtualKeyCode::Right,
        0x7d => VirtualKeyCode::Down,
        0x7e => VirtualKeyCode::Up,
        //0x7f =>  unkown,
        0xa => VirtualKeyCode::Caret,
        _ => return None,
    })
}

// While F1-F20 have scancodes we can match on, we have to check against UTF-16
// constants for the rest.
// https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?preferredLanguage=occ
pub fn check_function_keys(string: &str) -> Option<VirtualKeyCode> {
    if let Some(ch) = string.encode_utf16().next() {
        return Some(match ch {
            0xf718 => VirtualKeyCode::F21,
            0xf719 => VirtualKeyCode::F22,
            0xf71a => VirtualKeyCode::F23,
            0xf71b => VirtualKeyCode::F24,
            _ => return None,
        });
    }

    None
}

pub fn event_mods(event: id) -> ModifiersState {
    let flags = unsafe { NSEvent::modifierFlags(event) };
    let mut m = ModifiersState::empty();
    m.set(
        ModifiersState::SHIFT,
        flags.contains(NSEventModifierFlags::NSShiftKeyMask),
    );
    m.set(
        ModifiersState::CTRL,
        flags.contains(NSEventModifierFlags::NSControlKeyMask),
    );
    m.set(
        ModifiersState::ALT,
        flags.contains(NSEventModifierFlags::NSAlternateKeyMask),
    );
    m.set(
        ModifiersState::LOGO,
        flags.contains(NSEventModifierFlags::NSCommandKeyMask),
    );
    m
}

pub fn get_scancode(event: cocoa::base::id) -> c_ushort {
    // In AppKit, `keyCode` refers to the position (scancode) of a key rather than its character,
    // and there is no easy way to navtively retrieve the layout-dependent character.
    // In winit, we use keycode to refer to the key's character, and so this function aligns
    // AppKit's terminology with ours.
    unsafe { msg_send![event, keyCode] }
}

pub unsafe fn modifier_event(
    ns_event: id,
    keymask: NSEventModifierFlags,
    was_key_pressed: bool,
) -> Option<WindowEvent<'static>> {
    if !was_key_pressed && NSEvent::modifierFlags(ns_event).contains(keymask)
        || was_key_pressed && !NSEvent::modifierFlags(ns_event).contains(keymask)
    {
        let state = if was_key_pressed {
            ElementState::Released
        } else {
            ElementState::Pressed
        };

        let scancode = get_scancode(ns_event);
        let virtual_keycode = scancode_to_keycode(scancode);
        #[allow(deprecated)]
        Some(WindowEvent::KeyboardInput {
            device_id: DEVICE_ID,
            input: KeyboardInput {
                state,
                scancode: scancode as _,
                virtual_keycode,
                modifiers: event_mods(ns_event),
            },
            is_synthetic: false,
        })
    } else {
        None
    }
}


text:
#ifndef vnsw_agent_proto_handler_hpp
#define vnsw_agent_proto_handler_hpp

#include "pkt_handler.h"

// Pseudo header for UDP checksum
struct PseudoUdpHdr {
    in_addr_t src;
    in_addr_t dest;
    uint8_t   res;
    uint8_t   prot;
    uint16_t  len;
    PseudoUdpHdr(in_addr_t s, in_addr_t d, uint8_t p, uint16_t l) :
        src(s), dest(d), res(0), prot(p), len(l) { }
};

// Protocol handler, to process an incoming packet
// Each protocol has a handler derived from this
class ProtoHandler {
public:
    ProtoHandler(Agent *agent, boost::shared_ptr<PktInfo> info,
                 boost::asio::io_service &io);
    virtual ~ProtoHandler();

    virtual bool Run() = 0;

    void Send(uint16_t, uint16_t, uint16_t, uint16_t, PktHandler::PktModuleName);

    void EthHdr(const unsigned char *, const unsigned char *, const uint16_t);
    void IpHdr(uint16_t, in_addr_t, in_addr_t, uint8_t);
    void UdpHdr(uint16_t, in_addr_t, uint16_t, in_addr_t, uint16_t);

    uint32_t Sum(uint16_t *, std::size_t, uint32_t);
    uint16_t Csum(uint16_t *, std::size_t, uint32_t);
    uint16_t UdpCsum(in_addr_t, in_addr_t, std::size_t, udphdr *);

    Agent *agent() { return agent_; }
    uint32_t GetVrfIndex() const { return pkt_info_->GetAgentHdr().vrf; }
    uint16_t GetInterfaceIndex() const {
        return pkt_info_->GetAgentHdr().ifindex;
    }
    uint16_t GetLength() const { return pkt_info_->len; }
    uint32_t GetCmdParam() const { return pkt_info_->GetAgentHdr().cmd_param; }

protected:
    Agent   *agent_;
    boost::shared_ptr<PktInfo> pkt_info_;
    boost::asio::io_service &io_;

private:
    DISALLOW_COPY_AND_ASSIGN(ProtoHandler);
};

#endif // vnsw_agent_proto_handler_hpp


text:
Laboratório de Computação I

Projeto de Gabriel Augusto Lourenço da Conceição, para a disciplina, Laboratório, de Computação I, pela Universidade Federal Rural do Rio de Janeiro.

O presente documento foi elaborado em linguagem C e a biblioteca SDL, em 2D.

Para jogar, testar, o usuário precisa ter instalado o compilador gcc, para a linguagem C ou o compilador g++, que podem vir juntos com pacote buil-essential (para usuários do Ubuntu), mas podem ser encontrados separadamente. Também precisa ter instalada a biblioteca SDL com todas as suas extensões.

A forma proposta para compilação pode ser, dentre muitas, a que se encontra abaixo:

g++ tentar.cpp -o tentar -lSDL -lSDL_image -lSDL_mixer -lSDL_ttf


text:
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use App\User;
use Image;
use Storage;

class UploadController extends Controller
{

    public function store(Request $request)
    {
       // $this->validate($request, [
       //      'image' => 'image',
       //  ]);

       $img = substr($request->image, strpos($request->image, ",")+1);
       $image = base64_decode($img);

       Storage::disk('local')->put('/dist/images/avatars/'.auth()->user()->usn.'.jpg', $image);

       $path = asset('/dist/images/avatars/'.auth()->user()->usn.'.jpg');

       return $path;
    }

}


text:
      Lanes:
      <button (click)="removeLine(gridster)">-</button>
      {{ gridsterOptions.lanes }}
      <button (click)="addLine(gridster)">+</button>

      <button (click)="addWidgetWithoutData()">
          Add widget without data
      </button>

      <button (click)="removeAllWidgets()">
          Remove all widgets
      </button>

      <button (click)="resetWidgets()">
          Reset widgets
      </button>

      Ratio<input type="number" id="ratio" [(ngModel)]="gridsterOptions.widthHeightRatio" min="0.1"
                                             (change)="gridster.setOption('widthHeightRatio', gridsterOptions.widthHeightRatio).reload()">

      <input id="draggable" type="checkbox" [(ngModel)]="gridsterOptions.dragAndDrop" value="true"
             (change)="gridster.setOption('dragAndDrop', gridsterOptions.dragAndDrop)">Draggable

      <input type="checkbox" [(ngModel)]="gridsterOptions.resizable" value="true" id="resizable"
             (change)="gridster.setOption('resizable', gridsterOptions.resizable)">Resizable

      <input type="checkbox" [(ngModel)]="gridsterOptions.floating" value="true" id="floating"
             (change)="gridster.setOption('floating', gridsterOptions.floating)">Floating (gravity)

      Direction

          <input type="radio" [(ngModel)]="gridsterOptions.direction" value="none"
                 (change)="gridster.setOption('direction', 'none').reload()">None

          <input type="radio" [(ngModel)]="gridsterOptions.direction" value="horizontal"
                 (change)="gridster.setOption('direction', 'horizontal').reload()">Horizontal

          <input type="radio" [(ngModel)]="gridsterOptions.direction" value="vertical"
                 (change)="gridster.setOption('direction', 'vertical').reload()">Vertical

      Max item size: {{itemOptions.maxWidth}} x {{itemOptions.maxHeight}}

          Drag me (clone)

          1x1

New widget

          Drag me (clone)

          1x2

New widget

          Drag me

          2x1

New widget

  <ngx-gridster [options]="gridsterOptions" [draggableOptions]="gridsterDraggableOptions" (reflow)="onReflow($event)"
            (optionsChange)="optionsChange($event)" #gridster1 class="dashboard">

      <ngx-gridster-item *ngFor="let widget of widgets; let indx = index" #itemComp
                     [options]="itemOptions"
                     [dragAndDrop]="widget.dragAndDrop" [resizable]="widget.resizable"
                     [(x)]="widget.x" [(y)]="widget.y"
                     [(xSm)]="widget.xSm" [(ySm)]="widget.ySm"
                     [(xMd)]="widget.xMd" [(yMd)]="widget.yMd"
                     [(xLg)]="widget.xLg" [(yLg)]="widget.yLg"
                     [(xXl)]="widget.xXl" [(yXl)]="widget.yXl"
                     [(w)]="widget.w" [(h)]="widget.h"
                     [(wSm)]="widget.wSm" [(hSm)]="widget.hSm"
                     [(wMd)]="widget.wMd" [(hMd)]="widget.hMd"
                     [(wLg)]="widget.wLg" [(hLg)]="widget.hLg"
                     [(wXl)]="widget.wXl" [(hXl)]="widget.hXl"
                     (change)="itemChange($event, gridster1)">

{{ widget.title }}

                Position: {{itemComp?.item?.x}} x {{itemComp?.item?.y}}

                Size: {{itemComp?.item?.w}} x {{itemComp?.item?.h}}

                      <input type="checkbox" [(ngModel)]="widget.dragAndDrop" value="true"> Draggable

                      <input type="checkbox" [(ngModel)]="widget.resizable" value="true"> Resizable

                  <button (click)="setWidth(widget, 1, $event, gridster1)">width +</button>
                  <button (click)="setWidth(widget, -1, $event, gridster1)">width -</button>
                  <button (click)="setHeight(widget, 1, $event, gridster1)">height +</button>
                  <button (click)="setHeight(widget, -1, $event, gridster1)">height -</button>

                  <button (click)="remove($event, indx,gridster1)">remove</button>

{{ widget | json }}

      </ngx-gridster-item>

  </ngx-gridster>


text:
package com.esri.geoevent.transport.instagram;

import com.esri.ges.core.component.ComponentException;
import com.esri.ges.transport.Transport;
import com.esri.ges.transport.http.HttpInboundTransportService;
import com.esri.ges.transport.util.XmlTransportDefinition;

public class InstagramInboundTransportService extends HttpInboundTransportService
{
	public InstagramInboundTransportService()
	{
		super();
		definition = new XmlTransportDefinition(getResourceAsStream("instagram-inboundtransport-definition.xml"), super.definition);
	}

	public Transport createTransport() throws ComponentException
	{
		return new InstagramInboundTransport(definition);
	}
}


text:
<?php

namespace Somnambulist\Tenancy\Tests\Stubs\Entities;

use Somnambulist\Tenancy\Contracts\DomainAwareTenantParticipantRepository;

/**
 * Class SiteRepository
 *
 * @package    Somnambulist\Tenancy\Tests\Stubs\Entities
 * @subpackage Somnambulist\Tenancy\Tests\Stubs\Entities\SiteRepository
 * @author     Dave Redfern
 */
class SiteRepository implements DomainAwareTenantParticipantRepository
{
    public function findOneByDomain($domain)
    {
        switch ($domain)
        {
            case 'example.dev': return new Site(1, 'example.dev', 'example'); break;
            case 'testme.com': return new Site(2, 'testme.com', 'Test Site'); break;
            default:
                return null;
        }
    }

    public function find($id)
    {
        return null;
    }

    public function findAll()
    {
        return null;
    }

    public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        return null;
    }

    public function findOneBy(array $criteria, array $orderBy = null)
    {
        return null;
    }

    public function getClassName()
    {
        return Site::class;
    }
}


text:
/*
 * This is a .NET port of the original Java version, which was written by
 * Gil Tene as described in
 * https://github.com/HdrHistogram/HdrHistogram
 * and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

using System.Collections;
using System.Collections.Generic;

namespace Cassandra.AppMetrics.HdrHistogram.Iteration
{
    /// <summary>
    /// An enumerator of <see cref="HistogramIterationValue"/> through the histogram using a <see cref="PercentileEnumerator"/>
    /// </summary>
    internal sealed class PercentileEnumerable : IEnumerable<HistogramIterationValue>
    {
        private readonly HistogramBase _histogram;
        private readonly int _percentileTicksPerHalfDistance;

        public PercentileEnumerable(HistogramBase histogram, int percentileTicksPerHalfDistance)
        {
            _histogram = histogram;
            _percentileTicksPerHalfDistance = percentileTicksPerHalfDistance;
        }

        public IEnumerator<HistogramIterationValue> GetEnumerator()
        {
            return new PercentileEnumerator(_histogram, _percentileTicksPerHalfDistance);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


text:
<?php

class XWrap extends stdClass {
	private $__item;
	private $__name;
	public function __construct(XMeta $m,XItem $item,$name){
		$this->__item = $item;
		$this->__name = $name;
		for ($mm = $m; !is_null($mm); $mm = $mm->GetParent()){
			foreach ($mm as $key=>$value){
				if ($value instanceof XMetaField){
					$this->$key = new XWrapField($this,$value);
				}
				elseif ($value instanceof XMetaSlave){
					$this->$key = new XWrapSlave($this,$value);
				}
			}
		}
	}

	public function GetItem(){ return $this->__item; }
	public function GetName(){ return $this->__name; }

	public function Read(Http $http, $control_classname=null){
		if (is_null($control_classname)){
			/** @var $f XWrapField */
			foreach ($this->GetFields() as $f){
				$n = $f->GetName();
				if (isset($http[$n])) {
					$f->SetValue( $http[$n]->CastTo($f->GetType()) );
				}
			}
		}
		else {
			/** @var $c XWrapControl */
			$c = new $control_classname($this);
			$c->Read($http);
		}
	}

	public function GetFields(){
		$r = array();
		foreach ($this as $key=>$value) {
			if ($value instanceof XWrapField) {
				$r[$key] = $value;
			}
		}
		return $r;
	}
	public function GetSlaves(){
		$r = array();
		foreach ($this as $key=>$value) {
			if ($value instanceof XWrapSlave) {
				$r[$key] = $value;
			}
		}
		return $r;
	}
}


text:
package io.kimo.faker.ui.fragment;

import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import io.kimo.faker.R;
import io.kimo.faker.mvp.BaseView;
import io.kimo.faker.mvp.presenter.LoremPresenter;
import io.kimo.faker.mvp.view.LoremView;

public class LoremFragment extends BaseView implements LoremView {

    private View mainView, loadingView;
    private TextView character, characters, word, words, sentence, sentences, paragraph, paragraphs;

    private LoremPresenter presenter;

    public static LoremFragment newInstance() {
        return new LoremFragment();
    }

    @Override
    public int getLayoutResource() {
        return R.layout.fragment_lorem;
    }

    @Override
    public void mapGUI(View view) {

        mainView = view.findViewById(R.id.main_container);
        loadingView = view.findViewById(R.id.view_loading);

        character = (TextView) view.findViewById(R.id.lorem_character);
        characters = (TextView) view.findViewById(R.id.lorem_characters);

        word = (TextView) view.findViewById(R.id.lorem_word);
        words = (TextView) view.findViewById(R.id.lorem_words);

        sentence = (TextView) view.findViewById(R.id.lorem_sentence);
        sentences = (TextView) view.findViewById(R.id.lorem_sentences);

        paragraph = (TextView) view.findViewById(R.id.lorem_paragraph);
        paragraphs = (TextView) view.findViewById(R.id.lorem_paragraphs);
    }

    @Override
    public void configureGUI() {
        getActivity().setTitle("Lorem");
    }

    @Override
    public void startPresenter() {
        presenter = new LoremPresenter(this, getActivity());
        presenter.createView();
    }

    @Override
    public void stopPresenter() {
        presenter.destroyView();
    }

    @Override
    public void updateCharacterExample(String value) {
        character.setText(value);
    }

    @Override
    public void updateCharactersExample(String value) {
        characters.setText(value);
    }

    @Override
    public void updateWordExample(String value) {
        word.setText(value);
    }

    @Override
    public void updateWordsExample(String value) {
        words.setText(value);
    }

    @Override
    public void updateSentenceExample(String value) {
        sentence.setText(value);
    }

    @Override
    public void updateSentencesExample(String value) {
        sentences.setText(value);
    }

    @Override
    public void updateParagraphExample(String value) {
        paragraph.setText(value);
    }

    @Override
    public void updateParagraphsExample(String value) {
        paragraphs.setText(value);
    }

    @Override
    public void showFeedback(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showView() {
        mainView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideView() {
        mainView.setVisibility(View.GONE);
    }

    @Override
    public void showLoading() {
        loadingView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        loadingView.setVisibility(View.GONE);
    }
}


text:
Open working/hlall.html and use it. C-like languages use `clang`.
# jQuery.Syntax [release-3.0] #

jQuery.Syntax is a light-weight client-side syntax highlighter, which dynamically loads external dependencies (JavaScript & CSS) when required. It uses jQuery to make it cross-browser compatible and to simplify integration.

To use jQuery.Syntax with minimal work, simply review the examples and use the files in the public sub-directory.

For more advanced usage and customisation, you will need to install the following dependencies to use jQuery.Syntax:
	$ sudo gem install rake haml

To install jQuery.Syntax into the standard 'public' directory
	$ rake install

To customise the install process, including destination directory and theme, edit <tt>install.yaml</tt>.

jQuery.Syntax depends on jQuery 1.4.1+.

For downloads, documentation, compatibility, please visit <http://www.oriontransfer.co.nz/software/jquery-syntax/>.

There are several plugins available (source code - for stable releases see the main project page above):

 - DokuWiki: <http://github.com/ioquatix/jquery-syntax-dokuwiki>
 - WordPress: <http://github.com/ioquatix/jquery-syntax-wordpress>

## License ##

Copyright (c) 2011 Samuel G. D. Williams. <http://www.oriontransfer.co.nz>

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

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

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

## Change Log ##

### release-3.0 ###
 - Changed license from AGPL to MIT.
 - Improvements to the following brushes: C#, Objective-C, Java, Ruby, PHP, HTML, SQL, Assembly, Bash
 - Added support for perl style regular expressions.
 - Improved bash brush formatting and command matching.
 - Fixed some issues when highlighting ruby code with scope operator '::' and symbols.
 - Bug fixes to rakefile - new environment variable PREFIX determines install location.
 - Improvements to XML brush including supporting CDATA tags.
 - Bug fixes to several brushes including:
    - Objective-C methods (incorrect highlighting of last argument).
    - Diff insertion and deletion how highlight the background row colour.
    - Camel case type now expects a capital letter in the first non-underscore position.
    - Improved the style of XML entities, percent-escapes.
 - Several examples now included in examples sub-directory.
 - Default install now included in public sub-directory.
 - Fixed minor issue in path detection regular expression.
 - Installation now staged directly into destination directory.
 - Installation now supports configuration files.
 - Minor fixes to brushes.
 - Support for marked up content.
 - Support for several new languages (Kai, io).
 - Installation process (now the recommended process).
 - Enhanced support for themes.
 - Support for derived brushes.

### release-2.2.2 ###
 - Major Internet Exploder bugfix.

### release-2.2 ###
 - Added support for Lua, C#
 - Added new fixed and list layouts.
 - Improvements to whitespace handling.
 - Several bug fixes and enhancements.

### release-1.9.1 ###
 - Added several new languages.
 - Minor bug fixes and enhancements.

### release-1.8 ###
 - Improved the simple function usability.
 - Improved shorthand notation so it is now more flexible.
   - You can now specify a combination of classes, in any order.

### release-1.7 ###
 - Added support for YAML.
 - Fixed a bug in the bisection algorithm.
 - Added support for highlighting inline code tags.
 - Added shorthand notation
 - Improved simple function to improve consistency.

Shorthand notation depends on the classes being in a specific order, i.e. <tt>"syntax {language}"</tt>. e.g.

Previously, this would have been written as (and is still acceptable):

### release-1.6 ###
 - Fixed a compatibility issue with jQuery 1.4.2.

### release-1.5 ###
 - Added support for [Visual] Basic, SQL and Lisp.
 - Enabled a small optimization in the bisection algorithm.
 - Fixed a bug with alias names (they weren't working).
 - Minor updates to several other brushes.