text:
import { Component } from '@angular/core';
import { NavParams, ViewController } from 'ionic-angular';
import { Logger } from '../../../../../../providers/logger/logger';

// native
import { SocialSharing } from '@ionic-native/social-sharing';

// providers
import { AppProvider } from '../../../../../../providers/app/app';
import { OnGoingProcessProvider } from '../../../../../../providers/on-going-process/on-going-process';
import { PlatformProvider } from '../../../../../../providers/platform/platform';

@Component({
  selector: 'page-all-addresses',
  templateUrl: 'all-addresses.html'
})
export class AllAddressesPage {
  public noBalance;
  public withBalance;
  public coin: string;
  public isCordova: boolean;
  public allAddresses;

  private walletName: string;

  constructor(
    private navParams: NavParams,
    private viewCtrl: ViewController,
    private onGoingProcessProvider: OnGoingProcessProvider,
    private socialSharing: SocialSharing,
    private appProvider: AppProvider,
    private logger: Logger,
    private platformProvider: PlatformProvider
  ) {
    this.walletName = this.navParams.data.walletName;
    this.noBalance = this.navParams.data.noBalance;
    this.withBalance = this.navParams.data.withBalance;
    this.coin = this.navParams.data.coin;
    this.allAddresses = this.noBalance.concat(this.withBalance);
    this.isCordova = this.platformProvider.isCordova;
  }

  dismiss() {
    this.viewCtrl.dismiss();
  }

  private formatDate(ts: number) {
    const dateObj = new Date(ts * 1000);
    if (!dateObj) {
      this.logger.warn('Error formating a date');
      return 'DateError';
    }
    if (!dateObj.toJSON()) {
      return '';
    }
    return dateObj.toJSON();
  }

  public sendByEmail() {
    this.onGoingProcessProvider.set('sendingByEmail');
    setTimeout(() => {
      this.onGoingProcessProvider.clear();
      const appName = this.appProvider.info.nameCase;

      let body: string =
        appName +
        ' Wallet "' +
        this.walletName +
        '" Addresses\n  Only Main Addresses are  shown.\n\n';
      body += '\n';
      body += this.allAddresses
        .map(v => {
          return (
            '* ' +
            v.address +
            ' xpub' +
            v.path.substring(1) +
            ' ' +
            this.formatDate(v.createdOn)
          );
        })
        .join('\n');

      const subject = appName + ' Addresses';

      // Check if sharing via email is supported
      this.socialSharing
        .canShareViaEmail()
        .then(() => {
          this.logger.info('sharing via email is possible');
          this.socialSharing
            .shareViaEmail(
              body,
              subject,
              null, // TO: must be null or an array
              null, // CC: must be null or an array
              null, // BCC: must be null or an array
              null // FILES: can be null, a string, or an array
            )
            .then(data => {
              this.logger.info('Email created successfully: ', data);
            })
            .catch(err => {
              this.logger.error('socialSharing Error: ', err);
            });
        })
        .catch(() => {
          this.logger.warn('sharing via email is not possible');
          this.socialSharing.share(body, subject).catch(err => {
            this.logger.error('socialSharing Error: ', err);
          });
        });
    });
  }
}


text:
@(resource: Resource)

@resource.getHeader()

redpajama_set_name: RedPajamaGithub


text:
[IOTDB](https://github.com/dpjanes/node-iotdb) Bridge for CoAP data sources

<img src="https://raw.githubusercontent.com/dpjanes/iotdb-homestar/master/docs/HomeStar.png" align="right" />

THIS IS JUST A STUB - needs to do the actual work still

# Installation

* [Read this first](https://github.com/dpjanes/node-iotdb/blob/master/docs/install.md)

Then:

    $ npm install homestar-coap


text:
import uuid from 'uuid';
import { ValidationError } from 'objection';
import getPubSubClient from '../services/pubsub';
import models from '../models';
import dataloaders from './loaders/index';

class Context {
  constructor({ user = null }) {
    // Generate a new context id for the request.
    this.id = uuid.v4();

    // Load the current logged in user to `user`, otherwise this'll be null.
    if (user) {
      this.user = user;
    }
    this.ValidationError = ValidationError;
    this.models = models;
    // Create the loaders.
    this.loaders = dataloaders(this);

    // Bind the publish/subscribe to the context.
    this.pubsub = getPubSubClient();
  }
}
export default Context;


text:
namespace Aspose.CreateProjectWizard
{
  partial class InstallerForm
  {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
      if (disposing && (components != null))
      {
        components.Dispose();
      }
      base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InstallerForm));
            this.contentPanel = new System.Windows.Forms.Panel();
            this.buttonPanel = new System.Windows.Forms.TableLayoutPanel();
            this.cancelButton = new System.Windows.Forms.Button();
            this.prevButton = new System.Windows.Forms.Button();
            this.nextButton = new System.Windows.Forms.Button();
            this.topSeparatorPanel = new System.Windows.Forms.Panel();
            this.bottomSeparatorPanel = new System.Windows.Forms.Panel();
            this.titlePanel = new System.Windows.Forms.Panel();
            this.logoPicture = new System.Windows.Forms.PictureBox();
            this.subTitleLabel = new System.Windows.Forms.Label();
            this.titleLabel = new System.Windows.Forms.Label();
            this.buttonPanel.SuspendLayout();
            this.titlePanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.logoPicture)).BeginInit();
            this.SuspendLayout();
            //
            // contentPanel
            //
            this.contentPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            this.contentPanel.Location = new System.Drawing.Point(0, 70);
            this.contentPanel.Name = "contentPanel";
            this.contentPanel.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
            this.contentPanel.Size = new System.Drawing.Size(542, 292);
            this.contentPanel.TabIndex = 2;
            //
            // buttonPanel
            //
            this.buttonPanel.ColumnCount = 4;
            this.buttonPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.buttonPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.buttonPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.buttonPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.buttonPanel.Controls.Add(this.cancelButton, 3, 0);
            this.buttonPanel.Controls.Add(this.prevButton, 1, 0);
            this.buttonPanel.Controls.Add(this.nextButton, 2, 0);
            this.buttonPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.buttonPanel.Location = new System.Drawing.Point(0, 362);
            this.buttonPanel.Name = "buttonPanel";
            this.buttonPanel.RowCount = 1;
            this.buttonPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.buttonPanel.Size = new System.Drawing.Size(542, 44);
            this.buttonPanel.TabIndex = 0;
            //
            // cancelButton
            //
            this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.cancelButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.cancelButton.Location = new System.Drawing.Point(465, 10);
            this.cancelButton.Margin = new System.Windows.Forms.Padding(10, 10, 10, 3);
            this.cancelButton.Name = "cancelButton";
            this.cancelButton.Size = new System.Drawing.Size(67, 23);
            this.cancelButton.TabIndex = 0;
            this.cancelButton.Text = "&Abort";
            this.cancelButton.UseVisualStyleBackColor = true;
            this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
            //
            // prevButton
            //
            this.prevButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.prevButton.Location = new System.Drawing.Point(297, 10);
            this.prevButton.Margin = new System.Windows.Forms.Padding(3, 10, 3, 3);
            this.prevButton.Name = "prevButton";
            this.prevButton.Size = new System.Drawing.Size(74, 23);
            this.prevButton.TabIndex = 2;
            this.prevButton.Text = "&Previous";
            this.prevButton.UseVisualStyleBackColor = true;
            this.prevButton.Click += new System.EventHandler(this.prevButton_Click);
            //
            // nextButton
            //
            this.nextButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.nextButton.Location = new System.Drawing.Point(377, 10);
            this.nextButton.Margin = new System.Windows.Forms.Padding(3, 10, 3, 3);
            this.nextButton.Name = "nextButton";
            this.nextButton.Size = new System.Drawing.Size(75, 23);
            this.nextButton.TabIndex = 1;
            this.nextButton.Text = "&Next";
            this.nextButton.UseVisualStyleBackColor = true;
            this.nextButton.Click += new System.EventHandler(this.nextButton_Click);
            //
            // topSeparatorPanel
            //
            this.topSeparatorPanel.BackColor = System.Drawing.SystemColors.ControlDark;
            this.topSeparatorPanel.Dock = System.Windows.Forms.DockStyle.Top;
            this.topSeparatorPanel.Location = new System.Drawing.Point(0, 70);
            this.topSeparatorPanel.Name = "topSeparatorPanel";
            this.topSeparatorPanel.Size = new System.Drawing.Size(542, 1);
            this.topSeparatorPanel.TabIndex = 0;
            //
            // bottomSeparatorPanel
            //
            this.bottomSeparatorPanel.BackColor = System.Drawing.SystemColors.ControlDark;
            this.bottomSeparatorPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.bottomSeparatorPanel.Location = new System.Drawing.Point(0, 361);
            this.bottomSeparatorPanel.Name = "bottomSeparatorPanel";
            this.bottomSeparatorPanel.Size = new System.Drawing.Size(542, 1);
            this.bottomSeparatorPanel.TabIndex = 1;
            //
            // titlePanel
            //
            this.titlePanel.BackColor = System.Drawing.Color.White;
            this.titlePanel.Controls.Add(this.logoPicture);
            this.titlePanel.Controls.Add(this.subTitleLabel);
            this.titlePanel.Controls.Add(this.titleLabel);
            this.titlePanel.Cursor = System.Windows.Forms.Cursors.Hand;
            this.titlePanel.Dock = System.Windows.Forms.DockStyle.Top;
            this.titlePanel.Location = new System.Drawing.Point(0, 0);
            this.titlePanel.Name = "titlePanel";
            this.titlePanel.Size = new System.Drawing.Size(542, 70);
            this.titlePanel.TabIndex = 1;
            this.titlePanel.Click += new System.EventHandler(this.titlePanel_Click);
            //
            // logoPicture
            //
            this.logoPicture.Anchor = System.Windows.Forms.AnchorStyles.Right;
            this.logoPicture.BackColor = System.Drawing.Color.Transparent;
            this.logoPicture.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            this.logoPicture.Cursor = System.Windows.Forms.Cursors.Hand;
            this.logoPicture.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.logoPicture.Location = new System.Drawing.Point(470, 0);
            this.logoPicture.Name = "logoPicture";
            this.logoPicture.Size = new System.Drawing.Size(70, 70);
            this.logoPicture.TabIndex = 2;
            this.logoPicture.TabStop = false;
            this.logoPicture.Click += new System.EventHandler(this.logoPicture_Click);
            //
            // subTitleLabel
            //
            this.subTitleLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            this.subTitleLabel.BackColor = System.Drawing.Color.Transparent;
            this.subTitleLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F);
            this.subTitleLabel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.subTitleLabel.Location = new System.Drawing.Point(8, 40);
            this.subTitleLabel.Name = "subTitleLabel";
            this.subTitleLabel.Size = new System.Drawing.Size(456, 38);
            this.subTitleLabel.TabIndex = 1;
            this.subTitleLabel.Text = "[Sub Title]";
            this.subTitleLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.subTitleLabel.Click += new System.EventHandler(this.subTitleLabel_Click);
            //
            // titleLabel
            //
            this.titleLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            this.titleLabel.BackColor = System.Drawing.Color.Transparent;
            this.titleLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold);
            this.titleLabel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
            this.titleLabel.Location = new System.Drawing.Point(8, 15);
            this.titleLabel.Name = "titleLabel";
            this.titleLabel.Size = new System.Drawing.Size(456, 23);
            this.titleLabel.TabIndex = 0;
            this.titleLabel.Text = "[Title]";
            this.titleLabel.Click += new System.EventHandler(this.titleLabel_Click);
            //
            // InstallerForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.cancelButton;
            this.ClientSize = new System.Drawing.Size(542, 406);
            this.ControlBox = false;
            this.Controls.Add(this.topSeparatorPanel);
            this.Controls.Add(this.bottomSeparatorPanel);
            this.Controls.Add(this.contentPanel);
            this.Controls.Add(this.titlePanel);
            this.Controls.Add(this.buttonPanel);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "InstallerForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "[FormTitle]";
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.InstallerForm_FormClosing);
            this.buttonPanel.ResumeLayout(false);
            this.titlePanel.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.logoPicture)).EndInit();
            this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Panel titlePanel;
    private System.Windows.Forms.Panel contentPanel;
    private System.Windows.Forms.Panel topSeparatorPanel;
    private System.Windows.Forms.Panel bottomSeparatorPanel;
    private System.Windows.Forms.Button nextButton;
    private System.Windows.Forms.Button cancelButton;
    private System.Windows.Forms.Button prevButton;
    private System.Windows.Forms.Label titleLabel;
    private System.Windows.Forms.Label subTitleLabel;
    private System.Windows.Forms.TableLayoutPanel buttonPanel;
    private System.Windows.Forms.PictureBox logoPicture;
  }
}


text:
<link rel="stylesheet" href="/assets/css/marketing.css">

  <title>Sales Force Automation</title>
  <link rel="import" href="/assets/head-bootstrap.html">

Sales Force Automation

    Help Desk Tickets
    Orders
    Sales People
    Leads
    New Order
    New Lead

Outstanding Tickets

Orders

Sales People

Leads

New Order

          Customer ID: <input class="user_id" />

          Product ID: <input class="product_id"/>

          Quantity: <input class="quantity" />

          Shipping Address: <input class="shipaddr" id="shipaddr" />

    <button onclick="newOrderForm();">Submit</button>

New Lead

          Name <input class="name"/>

          Phone Number: <input class="phone_number" />

          Description: <textarea class="description"></textarea>

    <button onclick="newLeadForm();">Submit</button>


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3/agent.proto

package com.google.cloud.dialogflow.cx.v3;

public interface RestoreAgentRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.cx.v3.RestoreAgentRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The name of the agent to restore into.
   * Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>`.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Required. The name of the agent to restore into.
   * Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>`.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * The [Google Cloud Storage](https://cloud.google.com/storage/docs/) URI
   * to restore agent from. The format of this URI must be
   * `gs://<bucket-name>/<object-name>`.
   * Dialogflow performs a read operation for the Cloud Storage object
   * on the caller's behalf, so your request authentication must
   * have read permissions for the object. For more information, see
   * [Dialogflow access
   * control](https://cloud.google.com/dialogflow/cx/docs/concept/access-control#storage).
   *

   *
   * string agent_uri = 2;
   *
   * @return Whether the agentUri field is set.
   */
  boolean hasAgentUri();
  /**
   *
   *
   *

   * The [Google Cloud Storage](https://cloud.google.com/storage/docs/) URI
   * to restore agent from. The format of this URI must be
   * `gs://<bucket-name>/<object-name>`.
   * Dialogflow performs a read operation for the Cloud Storage object
   * on the caller's behalf, so your request authentication must
   * have read permissions for the object. For more information, see
   * [Dialogflow access
   * control](https://cloud.google.com/dialogflow/cx/docs/concept/access-control#storage).
   *

   *
   * string agent_uri = 2;
   *
   * @return The agentUri.
   */
  java.lang.String getAgentUri();
  /**
   *
   *
   *

   * The [Google Cloud Storage](https://cloud.google.com/storage/docs/) URI
   * to restore agent from. The format of this URI must be
   * `gs://<bucket-name>/<object-name>`.
   * Dialogflow performs a read operation for the Cloud Storage object
   * on the caller's behalf, so your request authentication must
   * have read permissions for the object. For more information, see
   * [Dialogflow access
   * control](https://cloud.google.com/dialogflow/cx/docs/concept/access-control#storage).
   *

   *
   * string agent_uri = 2;
   *
   * @return The bytes for agentUri.
   */
  com.google.protobuf.ByteString getAgentUriBytes();

  /**
   *
   *
   *

   * Uncompressed raw byte content for agent.
   *

   *
   * bytes agent_content = 3;
   *
   * @return Whether the agentContent field is set.
   */
  boolean hasAgentContent();
  /**
   *
   *
   *

   * Uncompressed raw byte content for agent.
   *

   *
   * bytes agent_content = 3;
   *
   * @return The agentContent.
   */
  com.google.protobuf.ByteString getAgentContent();

  /**
   *
   *
   *

   * Agent restore mode. If not specified, `KEEP` is assumed.
   *

   *
   * .google.cloud.dialogflow.cx.v3.RestoreAgentRequest.RestoreOption restore_option = 5;
   *
   *
   * @return The enum numeric value on the wire for restoreOption.
   */
  int getRestoreOptionValue();
  /**
   *
   *
   *

   * Agent restore mode. If not specified, `KEEP` is assumed.
   *

   *
   * .google.cloud.dialogflow.cx.v3.RestoreAgentRequest.RestoreOption restore_option = 5;
   *
   *
   * @return The restoreOption.
   */
  com.google.cloud.dialogflow.cx.v3.RestoreAgentRequest.RestoreOption getRestoreOption();

  public com.google.cloud.dialogflow.cx.v3.RestoreAgentRequest.AgentCase getAgentCase();
}


text:
import Earth from './assets/earth.svg?sprite';
import Map from './assets/map.svg?sprite';
import People from './assets/people.svg?sprite';

export const sgfBenefits = [
  'Grant awards between $10K - $40K.',
  'Individualized training and support.',
  'Form part of the GFW partnership.',
];

export const fellowshipBenefits = [
  'A monthly stipend, and access to additional discretionary funds for feld visits, equipment purchases, professional development, or workshop costs.',
  'All expenses paid (airfare, visa costs, meals and accommodation) to participate in tech camp and the GFW User Summit in Washington, DC.',
  'Training by experts in forest monitoring, land use planning, advocacy and enforcement, and project design and implementation.',
  'Participation in the GFW partnership and SGF/Fellowship alumni community.',
  'Communications coverage in WRI's newsletters, blogs and social media.',
];

export const results = [
  {
    icon: Earth,
    label: '44 projects from 30 countries',
  },
  {
    icon: Map,
    label: 'Over 1.8 billion hectares of forests monitored using GFW',
  },
  {
    icon: People,
    label: 'Over 1,800 people trained in using GFW',
  },
];


text:
import unittest

from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable

on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
disposed = ReactiveTest.disposed
created = ReactiveTest.created

class TestFind(unittest.TestCase):

    def test_find_never(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(
            on_next(150, 1)
        )

        def create():
            return xs.find(lambda x,i,s: True)

        res = scheduler.start(create)

        res.messages.assert_equal(
        )

    def test_find_empty(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(
            on_next(150, 1),
            on_completed(210)
        )

        def create():
            return xs.find(lambda x,i,s: True)

        res = scheduler.start(create)

        res.messages.assert_equal(
            on_next(210, None),
            on_completed(210)
        )

    def test_find_single(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(
            on_next(150, 1),
            on_next(210, 2),
            on_completed(220)
        )

        def create():
            return xs.find(lambda x,i,s: x==2)
        res = scheduler.start(create)

        res.messages.assert_equal(
            on_next(210, 2),
            on_completed(210)
        )

    def test_find_notfound(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(
            on_next(150, 1),
            on_next(210, 2),
            on_completed(220)
        )

        def create():
            return xs.find(lambda x,i,s: x==3)
        res = scheduler.start(create)

        res.messages.assert_equal(
            on_next(220, None),
            on_completed(220)
        )

    def test_find_Error(self):
        ex = Exception('error')
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(
            on_next(150, 1),
            on_next(210, 2),
            on_error(220, ex)
        )

        def create():
            return xs.find(lambda x,i,s: x==3)
        res = scheduler.start(create)

        res.messages.assert_equal(
            on_error(220, ex)
        )

    def test_find_throws(self):
        ex = 'error'
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(
            on_next(150, 1),
            on_next(210, 2),
            on_completed(220)
        )

        def create():
            def predicate(x, i, source):
                raise Exception(ex)
            return xs.find(predicate)
        res = scheduler.start(create)

        res.messages.assert_equal(
            on_error(210, ex)
        )


text:
require 'bundler/setup'
Bundler.setup

require 'uniq_number_id'
require_relative 'models/user'
require_relative 'models/course'

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end


text:
NOAA Tide Prediction Scraper
============================

A scraper I wrote to get the tide prediction information from NOAA. For reasons.

Workflow:
* scrape the [NOAA prediction pages](http://tidesandcurrents.noaa.gov/tide_predictions.html) for URLs to all the stations
    * builds a nicely formatted XML tree of the stations and their locations...
      this is a byproduct of needing to have this file for something I was
      working on.
    * stored in stations.xml
* go to each station's page and download the yearly prediction files
    * downloaded to xml/* for each station.

Outputting the station info to XML is mainly to provide a proof-of-concept.
I kept it simple since database abstraction is out of the scope of what I was
trying to provide.

Check out the examples directory for example output.

NOAA Tide Predictions: http://tidesandcurrents.noaa.gov/tide_predictions.html


text:
<!doctype html>
<html <?php language_attributes(); ?> class="no-js">

		<meta charset="<?php bloginfo('charset'); ?>">
		<title><?php wp_title(''); ?><?php if(wp_title('', false)) { echo ' :'; } ?> <?php bloginfo('name'); ?></title>

		<link href="//www.google-analytics.com" rel="dns-prefetch">
                <link href="<?php echo get_template_directory_uri(); ?>/img/icons/favicon.ico" rel="shortcut icon">
                <link href="<?php echo get_template_directory_uri(); ?>/img/icons/touch.png" rel="apple-touch-icon-precomposed">

                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="description" content="<?php bloginfo('description'); ?>">

		<?php wp_head(); ?>

	<body <?php body_class(); ?>>

						<a href="<?php echo home_url(); ?>">

							<img src="<?php echo get_template_directory_uri(); ?>/img/logo.svg" alt="Logo" class="logo-img">

                                          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                                            Toggle navigation

                                          </button>

						<?php html5blank_nav(); ?>


text:
import angular from 'angular-fix'
import utils from '../other/utils'

export default formlyConfig

// @ngInject
function formlyConfig(formlyUsabilityProvider, formlyErrorAndWarningsUrlPrefix, formlyApiCheck) {

  const typeMap = {}
  const templateWrappersMap = {}
  const defaultWrapperName = 'default'
  const _this = this
  const getError = formlyUsabilityProvider.getFormlyError

  angular.extend(this, {
    setType,
    getType,
    getTypes,
    getTypeHeritage,
    setWrapper,
    getWrapper,
    getWrapperByType,
    removeWrapperByName,
    removeWrappersForType,
    disableWarnings: false,
    extras: {
      disableNgModelAttrsManipulator: false,
      fieldTransform: [],
      ngModelAttrsManipulatorPreferUnbound: false,
      removeChromeAutoComplete: false,
      defaultHideDirective: 'ng-if',
      getFieldId: null,
    },
    templateManipulators: {
      preWrapper: [],
      postWrapper: [],
    },
    $get: () => this,
  })

  function setType(options) {
    if (angular.isArray(options)) {
      const allTypes = []
      angular.forEach(options, item => {
        allTypes.push(setType(item))
      })
      return allTypes
    } else if (angular.isObject(options)) {
      checkType(options)
      if (options.extends) {
        extendTypeOptions(options)
      }
      typeMap[options.name] = options
      return typeMap[options.name]
    } else {
      throw getError(`You must provide an object or array for setType. You provided: ${JSON.stringify(arguments)}`)
    }
  }

  function checkType(options) {
    formlyApiCheck.throw(formlyApiCheck.formlyTypeOptions, options, {
      prefix: 'formlyConfig.setType',
      url: 'settype-validation-failed',
    })
    if (!options.overwriteOk) {
      checkOverwrite(options.name, typeMap, options, 'types')
    } else {
      options.overwriteOk = undefined
    }
  }

  function extendTypeOptions(options) {
    const extendsType = getType(options.extends, true, options)
    extendTypeControllerFunction(options, extendsType)
    extendTypeLinkFunction(options, extendsType)
    extendTypeDefaultOptions(options, extendsType)
    utils.reverseDeepMerge(options, extendsType)
    extendTemplate(options, extendsType)
  }

  function extendTemplate(options, extendsType) {
    if (options.template && extendsType.templateUrl) {
      delete options.templateUrl
    } else if (options.templateUrl && extendsType.template) {
      delete options.template
    }
  }

  function extendTypeControllerFunction(options, extendsType) {
    const extendsCtrl = extendsType.controller
    if (!angular.isDefined(extendsCtrl)) {
      return
    }
    const optionsCtrl = options.controller
    if (angular.isDefined(optionsCtrl)) {
      options.controller = function($scope, $controller) {
        $controller(extendsCtrl, {$scope})
        $controller(optionsCtrl, {$scope})
      }
      options.controller.$inject = ['$scope', '$controller']
    } else {
      options.controller = extendsCtrl
    }
  }

  function extendTypeLinkFunction(options, extendsType) {
    const extendsFn = extendsType.link
    if (!angular.isDefined(extendsFn)) {
      return
    }
    const optionsFn = options.link
    if (angular.isDefined(optionsFn)) {
      options.link = function() {
        extendsFn(...arguments)
        optionsFn(...arguments)
      }
    } else {
      options.link = extendsFn
    }
  }

  function extendTypeDefaultOptions(options, extendsType) {
    const extendsDO = extendsType.defaultOptions
    if (!angular.isDefined(extendsDO)) {
      return
    }
    const optionsDO = options.defaultOptions || {}
    const optionsDOIsFn = angular.isFunction(optionsDO)
    const extendsDOIsFn = angular.isFunction(extendsDO)
    if (extendsDOIsFn) {
      options.defaultOptions = function defaultOptions(opts, scope) {
        const extendsDefaultOptions = extendsDO(opts, scope)
        const mergedDefaultOptions = {}
        utils.reverseDeepMerge(mergedDefaultOptions, opts, extendsDefaultOptions)
        let extenderOptionsDefaultOptions = optionsDO
        if (optionsDOIsFn) {
          extenderOptionsDefaultOptions = extenderOptionsDefaultOptions(mergedDefaultOptions, scope)
        }
        utils.reverseDeepMerge(extenderOptionsDefaultOptions, extendsDefaultOptions)
        return extenderOptionsDefaultOptions
      }
    } else if (optionsDOIsFn) {
      options.defaultOptions = function defaultOptions(opts, scope) {
        const newDefaultOptions = {}
        utils.reverseDeepMerge(newDefaultOptions, opts, extendsDO)
        return optionsDO(newDefaultOptions, scope)
      }
    }
  }

  function getType(name, throwError, errorContext) {
    if (!name) {
      return undefined
    }
    const type = typeMap[name]
    if (!type && throwError === true) {
      throw getError(
        `There is no type by the name of "${name}": ${JSON.stringify(errorContext)}`
      )
    } else {
      return type
    }
  }

  function getTypes() {
    return typeMap
  }

  function getTypeHeritage(parent) {
    const heritage = []
    let type = parent
    if (angular.isString(type)) {
      type = getType(parent)
    }
    parent = type.extends
    while (parent) {
      type = getType(parent)
      heritage.push(type)
      parent = type.extends
    }
    return heritage
  }

  function setWrapper(options, name) {
    if (angular.isArray(options)) {
      return options.map(wrapperOptions => setWrapper(wrapperOptions))
    } else if (angular.isObject(options)) {
      options.types = getOptionsTypes(options)
      options.name = getOptionsName(options, name)
      checkWrapperAPI(options)
      templateWrappersMap[options.name] = options
      return options
    } else if (angular.isString(options)) {
      return setWrapper({
        template: options,
        name,
      })
    }
  }

  function getOptionsTypes(options) {
    if (angular.isString(options.types)) {
      return [options.types]
    }
    if (!angular.isDefined(options.types)) {
      return []
    } else {
      return options.types
    }
  }

  function getOptionsName(options, name) {
    return options.name || name || options.types.join(' ') || defaultWrapperName
  }

  function checkWrapperAPI(options) {
    formlyUsabilityProvider.checkWrapper(options)
    if (options.template) {
      formlyUsabilityProvider.checkWrapperTemplate(options.template, options)
    }
    if (!options.overwriteOk) {
      checkOverwrite(options.name, templateWrappersMap, options, 'templateWrappers')
    } else {
      delete options.overwriteOk
    }
    checkWrapperTypes(options)
  }

  function checkWrapperTypes(options) {
    const shouldThrow = !angular.isArray(options.types) || !options.types.every(angular.isString)
    if (shouldThrow) {
      throw getError(`Attempted to create a template wrapper with types that is not a string or an array of strings`)
    }
  }

  function checkOverwrite(property, object, newValue, objectName) {
    if (object.hasOwnProperty(property)) {
      warn('overwriting-types-or-wrappers', [
        `Attempting to overwrite ${property} on ${objectName} which is currently`,
        `${JSON.stringify(object[property])} with ${JSON.stringify(newValue)}`,
        `To supress this warning, specify the property "overwriteOk: true"`,
      ].join(' '))
    }
  }

  function getWrapper(name) {
    return templateWrappersMap[name || defaultWrapperName]
  }

  function getWrapperByType(type) {
    /* eslint prefer-const:0 */
    const wrappers = []
    for (let name in templateWrappersMap) {
      if (templateWrappersMap.hasOwnProperty(name)) {
        if (templateWrappersMap[name].types && templateWrappersMap[name].types.indexOf(type) !== -1) {
          wrappers.push(templateWrappersMap[name])
        }
      }
    }
    return wrappers
  }

  function removeWrapperByName(name) {
    const wrapper = templateWrappersMap[name]
    delete templateWrappersMap[name]
    return wrapper
  }

  function removeWrappersForType(type) {
    const wrappers = getWrapperByType(type)
    if (!wrappers) {
      return undefined
    }
    if (!angular.isArray(wrappers)) {
      return removeWrapperByName(wrappers.name)
    } else {
      wrappers.forEach((wrapper) => removeWrapperByName(wrapper.name))
      return wrappers
    }
  }

  function warn() {
    if (!_this.disableWarnings && console.warn) {
      /* eslint no-console:0 */
      const args = Array.prototype.slice.call(arguments)
      const warnInfoSlug = args.shift()
      args.unshift('Formly Warning:')
      args.push(`${formlyErrorAndWarningsUrlPrefix}${warnInfoSlug}`)
      console.warn(...args)
    }
  }
}


text:
maddux.objects package
======================

Submodules
----------

maddux.objects.ball module
--------------------------

.. automodule:: maddux.objects.ball
    :members:
    :undoc-members:
    :show-inheritance:

maddux.objects.dynamic module
-----------------------------

.. automodule:: maddux.objects.dynamic
    :members:
    :undoc-members:
    :show-inheritance:

maddux.objects.obstacle module
------------------------------

.. automodule:: maddux.objects.obstacle
    :members:
    :undoc-members:
    :show-inheritance:

maddux.objects.static module
----------------------------

.. automodule:: maddux.objects.static
    :members:
    :undoc-members:
    :show-inheritance:

maddux.objects.target module
----------------------------

.. automodule:: maddux.objects.target
    :members:
    :undoc-members:
    :show-inheritance:

maddux.objects.throwable module
-------------------------------

.. automodule:: maddux.objects.throwable
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: maddux.objects
    :members:
    :undoc-members:
    :show-inheritance:


text:
package com.orientechnologies.orient.core.security;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

/** Created by frank on 19/11/2015. */
public class OSecurityManagerTest {

  @Test
  public void shouldCheckPlainPasswordAgainstHash() throws Exception {

    String hash = OSecurityManager.createHash("password", OSecurityManager.HASH_ALGORITHM, true);

    assertThat(OSecurityManager.checkPassword("password", hash)).isTrue();

    hash = OSecurityManager.createHash("password", OSecurityManager.PBKDF2_ALGORITHM, true);

    assertThat(OSecurityManager.checkPassword("password", hash)).isTrue();
  }

  @Test
  public void shouldCheckHashedPasswordAgainstHash() throws Exception {

    String hash = OSecurityManager.createHash("password", OSecurityManager.HASH_ALGORITHM, true);
    assertThat(OSecurityManager.checkPassword(hash, hash)).isFalse();

    hash = OSecurityManager.createHash("password", OSecurityManager.PBKDF2_ALGORITHM, true);

    assertThat(OSecurityManager.checkPassword(hash, hash)).isFalse();
  }

  @Test
  public void shouldCheckPlainPasswordAgainstHashWithSalt() throws Exception {

    String hash = OSecurityManager.createHashWithSalt("password");

    assertThat(OSecurityManager.checkPasswordWithSalt("password", hash)).isTrue();
  }

  @Test
  public void shouldCheckHashedWithSalPasswordAgainstHashWithSalt() throws Exception {

    String hash = OSecurityManager.createHashWithSalt("password");
    assertThat(OSecurityManager.checkPasswordWithSalt(hash, hash)).isFalse();
  }
}


text:
LAUNCH_DIR=${PWD}

cd plugins/api
rm -rf node_modules
npm i
npm link
cd $LAUNCH_DIR

cd plugins/client
rm -rf node_modules
npm i
npm link
cd $LAUNCH_DIR

cd plugins/cors
rm -rf node_modules
npm i
npm link
cd $LAUNCH_DIR

cd plugins/logging
rm -rf node_modules
npm i
npm link
cd $LAUNCH_DIR

cd plugins/security
rm -rf node_modules
npm i
npm link
cd $LAUNCH_DIR

cd plugins/socketio
rm -rf node_modules
npm i
npm link
cd $LAUNCH_DIR

cd server-hapi
rm -rf node_modules
npm i
npm link server-hapi-api
npm link server-hapi-client
npm link server-hapi-cors
npm link server-hapi-logging
npm link server-hapi-socketio
cd $LAUNCH_DIR

cd plugins/api/node_modules
npm link server-hapi-security


text:
package com.linkedin.drelephant.exceptions;

import com.linkedin.drelephant.configurations.scheduler.SchedulerConfigurationData;
import com.linkedin.drelephant.security.HadoopSecurity;
import com.linkedin.drelephant.util.InfoExtractor;
import java.io.File;
import java.io.IOException;
import java.security.PrivilegedAction;
import javax.naming.AuthenticationException;
import org.apache.log4j.Logger;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * ExceptionFinder class finds the exception along with the level of the exception. It takes the scheduler and the url of the workflow as
 * parameters.
 */
public class ExceptionFinder {
  private final Logger logger = Logger.getLogger(ExceptionFinder.class);
  private HadoopException _exception;
  private WorkflowClient _workflowClient;
  private MRClient _mrClient;

  private static String USERNAME = "username";
  private static String PRIVATE_KEY  = "private_key";
  private static String PASSWORD = "password";
  private static int SAMPLE_SIZE = 3;

  /**
   * Constructor for ExceptionFinder class
   * @param url The url of the workflow to analyze
   * @param scheduler The scheduler where the workflow was run.
   * @throws URISyntaxException
   * @throws MalformedURLException
   */
  public ExceptionFinder(String url, String scheduler)
      throws URISyntaxException, MalformedURLException, AuthenticationException, IOException {

    // create a new MRClient
    _mrClient = new MRClient();

    // create a new workflow client
    _workflowClient = InfoExtractor.getWorkflowClientInstance(scheduler, url);

    // get the schedulerData
    SchedulerConfigurationData schedulerData = InfoExtractor.getSchedulerData(scheduler);

    if(schedulerData==null) {
      throw new RuntimeException(String.format("Cannot find scheduler %s", scheduler));
    }

    if(!schedulerData.getParamMap().containsKey(USERNAME)) {
      throw new RuntimeException(String.format("Cannot find username for login"));
    }

    String username = schedulerData.getParamMap().get(USERNAME);

    if(schedulerData.getParamMap().containsKey(PRIVATE_KEY)) {
      _workflowClient.login(username, new File(schedulerData.getParamMap().get(PRIVATE_KEY)));
    } else if (schedulerData.getParamMap().containsKey(PASSWORD)) {
      _workflowClient.login(username, schedulerData.getParamMap().get(PASSWORD));
    } else {
      throw new RuntimeException("Neither private key nor password was specified");
    }
    _exception = analyzeFlow(url);
  }

  /**
   * Analyzes a Flow and returns a HadoopException object which captures all the exception in the flow.
   * @param execUrl the execution URL of the flow
   * @return HadoopException object which captures all the exceptions in the given Flow
   */
  private HadoopException analyzeFlow(final String execUrl) throws AuthenticationException, IOException {
    HadoopSecurity _hadoopSecurity = HadoopSecurity.getInstance();

    return _hadoopSecurity.doAs(new PrivilegedAction<HadoopException>() {
      @Override
      public HadoopException run() {
        HadoopException flowLevelException = new HadoopException();
        List<HadoopException> childExceptions = new ArrayList<HadoopException>();
        Map<String, String> jobIdStatus = _workflowClient.getJobsFromFlow();

        // Find exceptions in all the unsuccessful jobs of the workflow
        for (String unsuccessfulJobId : jobIdStatus.keySet()) {
          if (jobIdStatus.get(unsuccessfulJobId).toLowerCase().equals("failed")) {
            HadoopException jobLevelException = analyzeJob(unsuccessfulJobId);
            childExceptions.add(jobLevelException);
          }
        }

        flowLevelException.setType(HadoopException.HadoopExceptionType.FLOW);
        flowLevelException.setId(execUrl);
        flowLevelException.setLoggingEvent(null); // No flow level exception
        flowLevelException.setChildExceptions(childExceptions);
        return flowLevelException;
      }
    });
 }

  /**
   * Given a failed Job, this method analyzes the job and returns a HadoopException object which captures all the exception in the given job.
   * @param jobId The job execution id/url, specific to the scheduler
   * @return HadoopException object which captures all the exceptions in the given job
   */
  private HadoopException analyzeJob(String jobId) {
    HadoopException jobLevelException = new HadoopException();
    List<HadoopException> childExceptions = new ArrayList<HadoopException>();

    _workflowClient.analyzeJob(jobId);

    // get the set of all the yarn jobs from workflowClient
    Set<String> yarnJobIds = _workflowClient.getYarnApplicationsFromJob(jobId);

    for (String mrJobId : yarnJobIds) {
      //To do: Check if mr job logs are there or not in job history server
      String rawMRJobLog = _mrClient.getMRJobLog(mrJobId);
      if (rawMRJobLog != null && !rawMRJobLog.isEmpty()) { // null for log not found and empty for successful mr jobs
        //To do: rawMRJob is empty for successful mr jobs but this is not a good way to figure out whether a job failed
        // or succeeded, do this using the state field in rest api
        HadoopException mrJobLevelException = analyzeMRJob(mrJobId, rawMRJobLog);
        childExceptions.add(mrJobLevelException);
      }
    }

    if (_workflowClient.getJobState(jobId) == JobState.MRFAIL) {
      jobLevelException.setType(HadoopException.HadoopExceptionType.MR);
      jobLevelException.setLoggingEvent(_workflowClient.getJobException(jobId));
      //LoggingEvent is set only for the case if mr logs could not be found in job history server and childException is
      // empty
      jobLevelException.setChildExceptions(childExceptions);
    } else if (_workflowClient.getJobState(jobId) == JobState.SCHEDULERFAIL) {
      jobLevelException.setType(HadoopException.HadoopExceptionType.SCHEDULER);
      jobLevelException.setLoggingEvent(_workflowClient.getJobException(jobId));
      jobLevelException.setChildExceptions(null);
    } else if (_workflowClient.getJobState(jobId) == JobState.SCRIPTFAIL) {
      jobLevelException.setType(HadoopException.HadoopExceptionType.SCRIPT);
      jobLevelException.setLoggingEvent(_workflowClient.getJobException(jobId));
      jobLevelException.setChildExceptions(null);
    } else if (_workflowClient.getJobState(jobId) == JobState.KILLED) {
      jobLevelException.setType(HadoopException.HadoopExceptionType.KILL);
      jobLevelException.setLoggingEvent(null);
      jobLevelException.setChildExceptions(null);
    }
    jobLevelException.setId(jobId);
    return jobLevelException;
  }

  /**
   * Given a failed MR Job id and diagnostics of the job, this method analyzes it and returns a HadoopException object which captures all the exception in the given MR Job.
   * @param mrJobId Mapreduce job id
   * @param rawMRJoblog Diagnostics of the mapreduce job in a string
   * @return HadoopException object which captures all the exceptions in the given Mapreduce job
   */
  private HadoopException analyzeMRJob(String mrJobId, String rawMRJoblog) {
    // This method is called only for unsuccessful MR jobs
    HadoopException mrJobLevelException = new HadoopException();
    List<HadoopException> childExceptions = new ArrayList<HadoopException>();
    MRJobLogAnalyzer analyzedLog = new MRJobLogAnalyzer(rawMRJoblog);
    Set<String> failedMRTaskIds = analyzedLog.getFailedSubEvents();

    // sampling of tasks
    int samplingSize = SAMPLE_SIZE;
    for (String failedMRTaskId : failedMRTaskIds) {
      if(samplingSize<=0) {
        break;
      }
      String rawMRTaskLog = _mrClient.getMRTaskLog(mrJobId, failedMRTaskId);
      HadoopException mrTaskLevelException = analyzeMRTask(failedMRTaskId, rawMRTaskLog);
      childExceptions.add(mrTaskLevelException);

      samplingSize--;
    }

    mrJobLevelException.setChildExceptions(childExceptions);
    mrJobLevelException.setLoggingEvent(analyzedLog.getException());
    mrJobLevelException.setType(HadoopException.HadoopExceptionType.MRJOB);
    mrJobLevelException.setId(mrJobId);
    return mrJobLevelException;
  }

  /**
   * Given a failed MR Task id and diagnostics of the task, this method analyzes it and returns a HadoopException object which captures all the exception in the given MR task.
   * @param mrTaskId The task id of the map reduce job
   * @param rawMRTaskLog Raw map-reduce log
   * @return HadoopException object which captures all the exceptions in the given Mapreduce task
   */
  private HadoopException analyzeMRTask(String mrTaskId, String rawMRTaskLog) {
    HadoopException mrTaskLevelException = new HadoopException();
    MRTaskLogAnalyzer analyzedLog = new MRTaskLogAnalyzer(rawMRTaskLog);
    mrTaskLevelException.setLoggingEvent(analyzedLog.getException());
    mrTaskLevelException.setType(HadoopException.HadoopExceptionType.MRTASK);
    mrTaskLevelException.setId(mrTaskId);
    mrTaskLevelException.setChildExceptions(null);
    return mrTaskLevelException;
  }

  /**
   * Returns the Hadoop Exception object
   * @return Returns the Hadoop Exception object
   */
  public HadoopException getExceptions() {
    return this._exception;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using DirectCanvas;
using DirectCanvas.Brushes;
using DirectCanvas.Imaging;
using DirectCanvas.Misc;
using DirectCanvas.Shapes;
using DirectCanvas.Transforms;
using DirectCanvas.Scenes;

namespace WindowsFormsTest.Demos.GeometryDemo
{
    class GeometryScene : Scene
    {
        private readonly Presenter m_presenter;
        private PathGeometry m_pathGeometry;
        private SolidColorBrush m_solidColorBrush;
        private bool m_mousedown;
        private PointF m_mousePosition;

        private const int SCENE_WIDTH = 1200;
        private const int SCENE_HEIGHT = 1000;

        private LinearGradientBrush m_gradientBrush;
        private DrawingLayer m_bitmap;
        private DrawingLayerBrush m_bitmapBrush;
        private RadialGradientBrush m_radialBrush;
        private RotateTransform m_rotateTransform = new RotateTransform();

        public GeometryScene(Presenter presenter)
        {
            m_presenter = presenter;
            Initialize();
        }

        public override void SetInputState(int inputId, InputStatus status, PointF position)
        {
            m_mousedown = status == InputStatus.Down;
            m_mousePosition = position;
        }

        public override void Render()
        {
            m_rotateTransform.Angle++;

            m_radialBrush.Alignment = BrushAlignment.GeometryRelative;
            m_gradientBrush.Alignment = BrushAlignment.GeometryRelative;

            m_presenter.Clear();
            m_presenter.BeginDraw();

            var brush = m_bitmapBrush;

            brush.Alignment = BrushAlignment.DrawingLayerAbsolute;
            brush.Opacity = 0.2f;
            m_presenter.FillRectangle(brush, new RectangleF(0, 0, m_bitmap.Width, m_bitmap.Height));

            brush.Opacity = 1f;

            brush.Alignment = BrushAlignment.GeometryRelative;
            RenderElement(brush, 100, 100, 50, 100);

            brush.Alignment = BrushAlignment.GeometryAbsolute;
            RenderElement(brush, 280, 100, 130, 130);

            brush.Alignment = BrushAlignment.DrawingLayerAbsolute;
            RenderElement(brush, 100, 300, 50, 100);

            brush.Alignment = BrushAlignment.DrawingLayerRelative;
            RenderElement(brush, 280, 300, 50, 100);

            brush.Alignment = BrushAlignment.DrawingLayerAbsolute;
            m_pathGeometry.Transform = new TranslateTransform() {X = m_mousePosition.X, Y = m_mousePosition.Y};
            m_presenter.FillGeometry(brush, m_pathGeometry);

            m_presenter.EndDraw();
        }

        private void RenderElement(Brush brush, float x, float y, float width, float height)
        {
            var ellipse = new Ellipse(new PointF(x + (width/2), y+ (height/2)), width, height);
            m_rotateTransform.CenterX = ellipse.Center.X;
            m_rotateTransform.CenterY = ellipse.Center.Y;
            m_presenter.FillEllipse(brush, ellipse, m_rotateTransform);
            m_presenter.DrawText(m_solidColorBrush, brush.Alignment.ToString(), x - width / 2, y - height / 2);
        }

        private void Initialize()
        {
            SetupGeometry();

            m_solidColorBrush = m_presenter.Factory.CreateSolidColorBrush(new Color4(1, 1, 1, 1));
            m_bitmap = m_presenter.Factory.CreateDrawingLayerFromFile(@".\Assets\Nature Mountains photo.jpg");
            m_bitmapBrush = m_presenter.Factory.CreateDrawingLayerBrush(m_bitmap);

            GradientStop[] stops = new GradientStop[3];

            stops[0].Position = 0;
            stops[0].Color = new Color4(1f, 1, 0, 0);

            stops[1].Position = 0.5f;
            stops[1].Color = new Color4(1f, 0, 1, 0);

            stops[2].Position = 1f;
            stops[2].Color = new Color4(.1f, 0, 0, 1);

            m_gradientBrush = m_presenter.Factory.CreateLinearGradientBrush(stops, ExtendMode.Clamp, new PointF(0, 0), new PointF(SCENE_WIDTH, 0));
            m_gradientBrush.Transform = new RotateTransform();

            m_radialBrush = m_presenter.Factory.CreateRadialGradientBrush(stops,
                                                                                ExtendMode.Clamp,
                                                                                new PointF(500, 500),
                                                                                new PointF(0, 0),
                                                                                new SizeF(500, 500));
        }

        private void SetupGeometry()
        {
            XDocument xml = XDocument.Load(@".\Assets\svg.txt");

            var query = from p in xml.Descendants()
                        select p;

            m_pathGeometry = m_presenter.Factory.CreatePathGeometry();
            m_pathGeometry.BeginModify(FillMode.Winding);

            foreach (var xElement in query)
            {
                if(xElement.Name.LocalName == "polygon")
                {
                    var dataAttrib = xElement.Attribute("points").Value;
                    var points = GetLinePoints(dataAttrib);

                    m_pathGeometry.BeginFigure(FigureBegin.Filled, points[0]);

                    foreach (var pointF in points)
                    {
                        m_pathGeometry.AddLine(pointF);
                    }

                    m_pathGeometry.EndFigure(FigureEnd.Closed);
                }
            }

            m_pathGeometry.EndModify();

            return;
        }

        private static PointF[] GetLinePoints(string data)
        {
            var points = new List<PointF>();

            data = data.Replace("\r\n", " ");

            string[] dataArray = data.Split(' ');

            foreach (var s in dataArray)
            {
                if(!string.IsNullOrEmpty(s))
                {
                    var dataItems = s.Split(',');

                    points.Add(new PointF(Int32.Parse(dataItems[0]), Int32.Parse(dataItems[1])));
                }
            }

            return points.ToArray();
        }
    }
}


text:
- Rewrite without dependencies
  - It now properly streams data. Before, all stdin data was buffered in memory.
- Add prettier and editorconfig files
- Update documentation
- Add CHANGELOG file

## v1.2.0 - 2019-03-26

- Upgrade dependencies to mitigate CVE-2016-10538
- Add lock files to .gitignore
- Fix test script
- Fix typo on README

## v1.1.4 - 2015-06-21
## v1.1.3 - 2015-06-21
## v1.1.2 - 2015-06-21
## v1.1.1 - 2015-06-21
## v1.1.0 - 2015-06-21

- Fix binary not showing right version
- Improve documentation
- Add -i/--ignore-interrupts option to make ntee more compliant with UNIX tee

## v1.0.0 - 2015-06-17

- Initial release


text:
namespace content {
class RenderFrameHost;
class NavigationHandle;
}

// Per-tab class to manage tab closures and navigations, so that data usage per
// tab can be properly recorded..
class DataUseTabHelper : public content::WebContentsObserver,
                         public content::WebContentsUserData<DataUseTabHelper> {
 public:
  ~DataUseTabHelper() override;

 private:
  friend class content::WebContentsUserData<DataUseTabHelper>;

  explicit DataUseTabHelper(content::WebContents* web_contents);

  // Overridden from content::WebContentsObserver:
  void ReadyToCommitNavigation(
      content::NavigationHandle* navigation_handle) override;
  void FrameDeleted(content::RenderFrameHost* render_frame_host) override;

  DISALLOW_COPY_AND_ASSIGN(DataUseTabHelper);
};

#endif  // CHROME_BROWSER_ANDROID_DATA_USAGE_DATA_USE_TAB_HELPER_H_


text:
Configuration files for git, [prezto](https://github.com/sorin-ionescu/prezto),
tmux, vim/neovim, and zsh.

## Requirements
### Set zsh as login shell

```
chsh -s $(which zsh) $(whoami)
```

## Install
### Clone the repository
```
git clone https://github.com/janclarin/dotfiles.git ~/.dotfiles
cd ~/.dotfiles
```

### Run installation scripts
```
./install.sh
./install-vim.sh [--nvim] [--ideavim]
./install-tmux.sh
```

- Specify the `--nvim` flag to install [Neovim](https://github.com/neovim/neovim).
- Specify the `--ideavim` flag to install vimrc for [IdeaVim](https://github.com/JetBrains/ideavim).
- Use the `vi` alias to open Neovim if it's installed. This defaults to vim.

#### Installation info
- `./install.sh` installs dotfiles, prezto, vimrc & plugins, Homebrew on macOS
- `./install-vim.sh` installs vimrc & vim plugins. Neovim is an optional flag
- `./install-tmux.sh` installs tmux.conf and
    [tpm](https://github.com/tmux-plugins/tpm)

## Customizations
### Git
Since `~/.gitconfig` is replaced, store your custom git configurations, e.g.
user info, in a `~/.gitconfig.local` file.

Sample `~/.gitconfig.local`

```
[user]
    name = Jan Clarin
    email = hi@janclarin.com
```

### Vim
Sample `~/.vimrc.local` is for customized vim configs.

```
" neovim local configuration
let g:python_host_prog = '/usr/local/bin/python'
let g:python3_host_prog = '/usr/local/bin/python3'
```

Sample `~/.vimrc.plugins.local` for customized or secret plugins.
Loaded with [vim-plug](https://github.com/junegunn/vim-plug).

```
" my vim plugins loaded with vim-plug
Plug 'vim-syntastic/syntastic'
```

### Other *.local files
Currently supports the following local versions of source files that are loaded
after the dotfiles version.

- `path.local`
- `exports.local`
- `aliases.local`

## Update
### Prezto
```
git smu
```

Then commit `prezto/`


text:
template <int> int f(int);  // expected-note {{candidate function}}
#if __cplusplus <= 199711L
// expected-note@-2 {{candidate function}}
#endif

template <signed char> int f(int); // expected-note {{candidate function}}
#if __cplusplus <= 199711L
// expected-note@-2 {{candidate function}}
#endif

int i1 = f<1>(0); // expected-error{{call to 'f' is ambiguous}}
int i2 = f<1000>(0);
#if __cplusplus <= 199711L
// expected-error@-2{{call to 'f' is ambiguous}}
#endif

namespace PR6707 {
  template<typename T, T Value>
  struct X { };

  template<typename T, T Value>
  void f(X<T, Value>);

  void g(X<int, 10> x) {
    f(x);
  }

  static const unsigned char ten = 10;
  template<typename T, T Value, typename U>
  void f2(X<T, Value>, X<U, Value>);
  // expected-note@-1 {{candidate template ignored: deduced values of conflicting types for parameter 'Value' (10 of type 'int' vs. 10 of type 'char')}}
  // expected-note@-2 {{candidate template ignored: deduced values of conflicting types for parameter 'Value' (10 of type 'char' vs. 10 of type 'int')}}

  void g2() {
    f2(X<int, 10>(), X<char, ten>()); // expected-error {{no matching}}
    f2(X<char, 10>(), X<int, ten>()); // expected-error {{no matching}}
  }
}


text:
<?php
class BaseDatabase {
    private static $_instance = false;

    public static function instance() {
        if(self::$_instance === false) {
            // create instance
            self::$_instance = true;
        }

        return self::$_instance;
    }
}

class BaseUser {
    static $db = null;

    function __construct($username, $password, $user_id, $ip, $last_login) {
    }

    public static function authenticate($username, $password) {
    }

    public static function get($user) {
    }

    public static function find($username) {
    }

    public function status($s=null, $message=null) {
    }

    public function ip($ip=null) {
    }

    public function lastLogin($ll=null) {
    }

    public function save($id=null) {
    }
}

class BaseStatus {
    const Offline = 0;
    const Available = 1;
    const Away = 2;
    const Invisible = 3;

    static $db = null;

    function __construct($user_id, $s=null, $message='') {
    }

    public static function of($user) {
    }

    public function is($s, $message='') {
    }
}

class BaseMessage {
    static $db = null;

    function __construct($from='', $to='', $message='', $type='') {
    }

    public static function send($from, $to, $message) {
    }

    public static function get($id) {
    }

    public static function getMany($from_or_to, $user) {
    }

    public function sent($ts=null) {
    }

    public function from($from=null) {
    }

    public function to($to=null) {
    }

    public function message($message=null) {
    }

    public function save($id=null) {
    }
}

class BaseFriend {
    static $db = null;

    function __construct($user=null, $friend=null, $group=null) {
    }

    public static function get($id) {
    }

    public static function find($friend, $user=0) {
    }

    public function group($group=null) {
    }

    public function save() {
    }

    public function remove() {
    }
}

class BaseFriendGroup {
    static $db = null;

    function __construct($user, $group) {
    }

    public static function get($id) {
    }

    public static function find($group) {
    }

    public function addFriend($friend) {
    }

    public function friends() {
    }

    public function save() {
    }

    public function remove() {
    }
}

/* End of libraries/db/base.php */


text:
namespace media {
namespace test {

// A helper class to write each frame to disk.
class BitstreamFileWriter::FrameFileWriter {
 public:
  FrameFileWriter(std::unique_ptr<IvfWriter> ivf_writer)
      : ivf_writer_(std::move(ivf_writer)) {}
  FrameFileWriter(base::File output_file)
      : output_file_(std::move(output_file)) {}

  bool WriteFrame(uint32_t data_size, uint64_t timestamp, const uint8_t* data) {
    if (ivf_writer_) {
      return ivf_writer_->WriteFrame(data_size, timestamp, data);
    }
    // For H.264.
    LOG_ASSERT(output_file_.IsValid());
    return output_file_.WriteAtCurrentPos(reinterpret_cast<const char*>(data),
                                          data_size) ==
           static_cast<int>(data_size);
  }

 private:
  const std::unique_ptr<IvfWriter> ivf_writer_;
  base::File output_file_;
};

BitstreamFileWriter::BitstreamFileWriter(
    std::unique_ptr<FrameFileWriter> frame_file_writer,
    absl::optional<size_t> spatial_layer_index_to_write,
    absl::optional<size_t> temporal_layer_index_to_write,
    const std::vector<gfx::Size>& spatial_layer_resolutions)
    : frame_file_writer_(std::move(frame_file_writer)),
      spatial_layer_index_to_write_(spatial_layer_index_to_write),
      temporal_layer_index_to_write_(temporal_layer_index_to_write),
      spatial_layer_resolutions_(spatial_layer_resolutions),
      num_buffers_writing_(0),
      num_errors_(0),
      writer_thread_("BitstreamFileWriterThread"),
      writer_cv_(&writer_lock_) {
  DETACH_FROM_SEQUENCE(writer_thread_sequence_checker_);
}

BitstreamFileWriter::~BitstreamFileWriter() {
  base::AutoLock auto_lock(writer_lock_);
  DCHECK_EQ(0u, num_buffers_writing_);

  writer_thread_.Stop();
}

// static
std::unique_ptr<BitstreamFileWriter> BitstreamFileWriter::Create(
    const base::FilePath& output_filepath,
    VideoCodec codec,
    const gfx::Size& resolution,
    uint32_t frame_rate,
    uint32_t num_frames,
    absl::optional<size_t> spatial_layer_index_to_write,
    absl::optional<size_t> temporal_layer_index_to_write,
    const std::vector<gfx::Size>& spatial_layer_resolutions) {
  std::unique_ptr<FrameFileWriter> frame_file_writer;
  if (!base::DirectoryExists(output_filepath.DirName()))
    base::CreateDirectory(output_filepath.DirName());

  if (codec == VideoCodec::kH264) {
    base::File output_file(output_filepath, base::File::FLAG_CREATE_ALWAYS |
                                                base::File::FLAG_WRITE);
    LOG_ASSERT(output_file.IsValid());
    frame_file_writer =
        std::make_unique<FrameFileWriter>(std::move(output_file));
  } else {
    auto ivf_writer = std::make_unique<IvfWriter>(output_filepath);
    if (!ivf_writer->WriteFileHeader(codec, resolution, frame_rate,
                                     num_frames)) {
      LOG(ERROR) << "Failed writing ivf header";
      return nullptr;
    }

    frame_file_writer =
        std::make_unique<FrameFileWriter>(std::move(ivf_writer));
  }

  auto bitstream_file_writer = base::WrapUnique(new BitstreamFileWriter(
      std::move(frame_file_writer), spatial_layer_index_to_write,
      temporal_layer_index_to_write, spatial_layer_resolutions));
  if (!bitstream_file_writer->writer_thread_.Start()) {
    LOG(ERROR) << "Failed to start file writer thread";
    return nullptr;
  }

  return bitstream_file_writer;
}

void BitstreamFileWriter::ConstructSpatialIndices(
    const std::vector<gfx::Size>& spatial_layer_resolutions) {
  SEQUENCE_CHECKER(validator_thread_sequence_checker_);
  CHECK(!spatial_layer_resolutions.empty());
  CHECK_LE(spatial_layer_resolutions.size(), spatial_layer_resolutions_.size());

  original_spatial_indices_.resize(spatial_layer_resolutions.size());
  auto begin = std::find(spatial_layer_resolutions_.begin(),
                         spatial_layer_resolutions_.end(),
                         spatial_layer_resolutions.front());
  CHECK(begin != spatial_layer_resolutions_.end());
  uint8_t sid_offset = begin - spatial_layer_resolutions_.begin();
  for (size_t i = 0; i < spatial_layer_resolutions.size(); ++i) {
    CHECK_LT(sid_offset + i, spatial_layer_resolutions_.size());
    CHECK_EQ(spatial_layer_resolutions[i],
             spatial_layer_resolutions_[sid_offset + i]);
    original_spatial_indices_[i] = sid_offset + i;
  }
}

void BitstreamFileWriter::ProcessBitstream(
    scoped_refptr<BitstreamRef> bitstream,
    size_t frame_index) {
  if (spatial_layer_index_to_write_ && bitstream->metadata.vp9) {
    const Vp9Metadata& metadata = *bitstream->metadata.vp9;
    if (bitstream->metadata.key_frame)
      ConstructSpatialIndices(metadata.spatial_layer_resolutions);

    const uint8_t spatial_idx = original_spatial_indices_[metadata.spatial_idx];
    if (spatial_idx > *spatial_layer_index_to_write_ ||
        (spatial_idx < *spatial_layer_index_to_write_ &&
         !metadata.referenced_by_upper_spatial_layers)) {
      // Skip |bitstream| because it contains a frame not needed by desired
      // spatial layers.
      return;
    }
  }

  if (temporal_layer_index_to_write_) {
    uint8_t temporal_idx = 255;
    if (bitstream->metadata.vp9)
      temporal_idx = bitstream->metadata.vp9->temporal_idx;
    else if (bitstream->metadata.h264)
      temporal_idx = bitstream->metadata.h264->temporal_idx;
    CHECK_NE(temporal_idx, 255) << "No metadata about temporal idx";

    if (temporal_idx > *temporal_layer_index_to_write_) {
      // Skip |bitstream| because it contains a frame in upper layers than
      // layers to be saved.
      return;
    }
  }

  base::AutoLock auto_lock(writer_lock_);
  num_buffers_writing_++;
  writer_thread_.task_runner()->PostTask(
      FROM_HERE, base::BindOnce(&BitstreamFileWriter::WriteBitstreamTask,
                                base::Unretained(this), std::move(bitstream),
                                frame_index));
}

void BitstreamFileWriter::WriteBitstreamTask(
    scoped_refptr<BitstreamRef> bitstream,
    size_t frame_index) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(writer_thread_sequence_checker_);
  const DecoderBuffer& buffer = *bitstream->buffer.get();
  bool success = frame_file_writer_->WriteFrame(
      static_cast<uint32_t>(buffer.data_size()),
      static_cast<uint64_t>(frame_index), buffer.data());

  base::AutoLock auto_lock(writer_lock_);
  num_errors_ += !success;
  num_buffers_writing_--;
  writer_cv_.Signal();
}

bool BitstreamFileWriter::WaitUntilDone() {
  base::AutoLock auto_lock(writer_lock_);
  while (num_buffers_writing_ > 0u)
    writer_cv_.Wait();
  LOG_IF(ERROR, num_errors_ > 0u) << "Detected error count: " << num_errors_;
  return num_errors_ == 0;
}
}  // namespace test
}  // namespace media


text:
import { TestBed, getTestBed } from '@angular/core/testing';

import { NominatimService } from './nominatim.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('NominatimService', () => {
  let injector: TestBed;
  let service: NominatimService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule]
    });

    injector = getTestBed();
    service = injector.get(NominatimService);
    httpMock = injector.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  it('should be created', () => {
    const service: NominatimService = TestBed.inject(NominatimService);
    expect(service).toBeTruthy();
  });

  it('should return an Observable<Object>', () => {
    const data = {
      features: [{
        geometry: {
          type: 'Point',
          coordinates: [0,0]
        },
        properties: {
          display_name: '123 South'
        }
      }]
    };

    const search = '123 South Madeup Way';
    service.search(search).subscribe((data: any) => {
      expect(data).toEqual(data);
    });

    const req = httpMock.expectOne(req => req.url.startsWith(`${NominatimService.URL}`));
    expect(req.request.method).toBe("GET");
    expect(req.request.params.has('q')).toBeTruthy();
    expect(req.request.params.get('q')).toBe(`${search}`)
    req.flush(data);
  });
});


text:
import errno
import getpass
import logging
import os
import random
import re
import string
import sys
import time
import types
# IPython
from IPython.core.magic import (Magics, magics_class, line_magic,
                                cell_magic, line_cell_magic)
from IPython.display import HTML
# KBase
import biokbase.auth

from biokbase.narrative.common.url_config import URLS
from biokbase.narrative.common.log_common import EVENT_MSG_SEP

# Logging
g_log = logging.getLogger(__name__)

# Module variables for maintaining KBase Notebook state
user_id = None
token = None
user_profile = None
ws_client = None

# Flag set by a JS callback to let is know if we have a browser or not
have_browser = None

# End points for various services
endpoint = { 'workspace': URLS.workspace }
# endpoint = { 'invocation' : 'https://kbase.us/services/invocation',
#              'workspace' : 'https://kbase.us/services/ws/' }

# IPython interpreter object
ip = None

# default start directory
workdir = "/tmp/narrative"

def user_msg(s):
    """Show a message to the user.
    Adds a newline.
    Also logs it for posterity.
    """
    g_log.debug("user_msg{}len={:d}".format(
               EVENT_MSG_SEP, len(s)))
    sys.stderr.write(s + "\n")

def do_login(user, password):
    """Actually performs the login with username and password
    """
    global user_id, token, user_profile
    try:
        t = biokbase.auth.Token(user_id=user, password=password)
        if t.token:
            set_token(t.token)
        else:
            raise biokbase.auth.AuthFail("Could not get token with username and password given")
    except biokbase.auth.AuthFail, a:
        user_msg("Failed to login with username password provided. "
                     "Please try again.")
        token = None
    if token is not None:
        user_msg("Logged in as {}".format(user_id))

def set_token(newtoken):
    global user_id, token, user_profile
    if newtoken:
        token = newtoken
        biokbase.auth.set_environ_token(token)
        user_profile = biokbase.auth.User(token = token)
        user_id = user_profile.user_id
        # If we had a previous session, clear it out
        ws_client = None

def clear_token():
    global user_id, token, user_profile
    if token is not None:
        user_msg("Clearing credentials and profile for {}".format(user_id))
        user_id = None
        token = None
        user_profile = None
    biokbase.auth.set_environ_token( None)
    ws_client = None

# Define the KBase notebook magics

@magics_class
class kbasemagics(Magics):

    @line_magic
    def kblogin(self, line):
        """
        Login using username and password to KBase and then push login token into the environment.
        Usage is: kblogin {userid}
        If you have an ssh-agent with keys loaded, kblogin will attempt to use your ssh-key to
        get an Globus token, if not, then you will be prompted for your password.
        The token will be pushed into the KBASE_AUTH_TOKEN environment variable and picked up
        by any libraries that have implemented that support.
        """
        try:
            (user, password) = line.strip().split()
        except ValueError:
            user = line
            password = None
        global user_id, token, user_profile #, inv_client, inv_session

        if user_id is not None:
            user_msg("Already logged in as {}. "
                     "Please kblogout first if you want to re-login"
                     .format(user_id))
        elif user is None:
            user_msg("kblogin requires at least a username")
        else:
            try:
                # XXX: SSH_AGENT NOT WORKING, so it's been deprecated
                # try to login with only user_id in case there is
                # an ssh_agent running
                # t = biokbase.auth.Token(user_id=user)
                # if t.token is None:
                if password is None:
                    password = getpass.getpass("Please enter the KBase "
                                               "password for '%s': " % user)
                t = biokbase.auth.Token(user_id=user, password=password)
                if t.token:
                    set_token(t.token)
                else:
                    raise biokbase.auth.AuthFail(
                        "Could not get token with username and password given")
            except biokbase.auth.AuthFail, a:
                user_msg("Failed to login with username password provided. "
                         "Please try again.")
                token = None
        if token is not None:
            return user_id
        else:
            return None

    @line_magic
    def kblogout(self, line):
        """Logout by removing credentials from environment and
           clearing session objects
        """
        # Call the clear_token method
        clear_token()
        return

    # @line_magic
    # def uploader(self, line):
    #     """
    #     Bring up basic input form that allows you to upload files into /tmp/narrative
    #     using PLUpload client libraries
    #     Note that this is a demonstration prototype!
    #     """
    #     return HTML(biokbase.narrative.upload_handler.HTML_EXAMPLE)

    # @line_magic
    # def jquploader(self, line):
    #     """
    #     Bring up an html cell with JQuery UI PLUpload widget that supports drag and drop
    #     Note that this is a demonstration prototype!
    #     """
    #     return HTML(biokbase.narrative.upload_handler.JQUERY_UI_EXAMPLE)

    # @line_magic
    # def inv_session(self, line=None):
    #     """Return the current invocation session id, create one if necessary.
    #     Parameters are ignored
    #     """
    #     global user_id, token, user_profile, inv_client, inv_session, endpoint

    #     if inv_client is None:
    #         if token is None:
    #             user_msg("You are not currently logged in. Using anonymous,"
    #                          " unauthenticated access")
    #         try:
    #             inv_client = InvocationClient( url = endpoint['invocation'], token = token)
    #             sess_id = "nrtv_" + str(int(time.time())) + "_" + ''.join(random.choice(string.hexdigits) for x in range(6))
    #             inv_session = inv_client.start_session(sess_id)
    #             if inv_session == sess_id:
    #                 user_msg("New anonymous session created : %s"
    #                              % inv_session)
    #             else:
    #                 user_msg("New authenticated session created "
    #                              "for user %s" % user_id)
    #         except Exception, e:
    #             user_msg("Error initializing a new invocation service "
    #                          "client: %s" % e)
    #     return inv_session

    # @line_cell_magic
    # def inv_run(self, line, cell=None):
    #     """
    #     If we are logged in, make sure we have an invocation session and then use the invocation run_pipeline()
    #     method to executing the rest of the line
    #     """
    #     global user_id, token, user_profile, inv_client, inv_session
    #     sess = self.inv_session()
    #     cwd = self.inv_cwd('')

    #     # if there's just a single line
    #     if len(line) > 0 and cell is None:
    #         res = self.inv_run_line(sess, cwd, line)
    #         if res is not None:
    #             print("".join(res))
    #             return res
    #     if cell is not None:
    #         all_results = []
    #         lines = cell.splitlines()
    #         for command in lines:
    #             res = self.inv_run_line(sess, cwd, command)
    #             if res is not None:
    #                 all_results.append(res)
    #         print("\n".join(all_results))

    #     # try:
    #     #     res = inv_client.run_pipeline( sess, line, [], 200, '/')
    #     #     if res[1]:
    #     #         print("\n".join(res[1]),file=sys.stderr)
    #     # except Exception, e:
    #     #     print("Error: %s" % str(e),file=sys.stderr)
    #     #     return None
    #     # return res[0]

    # def inv_run_line(self, session, cwd, line):
    #     """
    #     This is the workhorse for running an Invocation service command.
    #     In the case where there's a cell full of these, they should be passed here one at a time.
    #     Note that this does NOT set up an Invocation session - that should be set up externally and
    #     passed to this function.
    #     """
    #     try:
    #         line = line.strip()

    #         # get the first token as lower case
    #         first_token = line.split()[0].lower()

    #         # keep the rest of the line parameters, incase we need to pass them along to the other magics
    #         line_params = line[len(first_token):].strip()

    #         # Now, test the first token for convenience commands, and pass them along as necessary:
    #         # ls
    #         # cwd or pwd
    #         # mkdir
    #         # rmdir
    #         # copy or cp
    #         # rm
    #         # mv
    #         if (first_token == 'ls'):
    #             return self.inv_ls(line_params, print_output=False)
    #         elif (first_token == 'cwd' or first_token == 'pwd'):
    #             return self.inv_cwd(line_params)
    #         elif (first_token == 'mkdir'):
    #             return self.inv_make_directory(line_params)
    #         elif (first_token == 'copy' or first_token == 'cp'):
    #             return self.inv_copy(line_params)
    #         elif (first_token == 'rmdir'):
    #             return self.inv_remove_directory(line_params)
    #         elif (first_token == 'rm'):
    #             return self.inv_remove_files(line_params)
    #         elif (first_token == 'mv'):
    #             return self.inv_rename_files(line_params)
    #         elif (first_token == 'cd'):
    #             return self.inv_cd(line_params)
    #         else:
    #             res = inv_client.run_pipeline(session, line, [], 200, cwd)
    #             if res[1]:
    #                 user_msg("\n".join(res[1]))
    #             else:
    #                 return "".join(res[0])
    #     except Exception, e:
    #         g_log.error("inv_run_line msg={}".format(e))
    #         user_msg("Error: %s" % str(e))
    #         return None
    #     # return res[0]

    # @line_magic
    # def inv_ls(self, line, print_output=True):
    #     """
    #     List files on the invocation service for this session
    #     """
    #     global user_id, token, user_profile, inv_client, inv_session, inv_cwd
    #     sess = self.inv_session()
    #     if len(line) > 0:
    #         try:
    #             (cwd,d) = line.split()
    #         except:
    #             cwd = line
    #             d = ''
    #     else:
    #         cwd = inv_cwd
    #         d = ''
    #     try:
    #         res = inv_client.list_files(sess, cwd, d)
    #         dirs = ["%12s   %s   %s" % ('directory', d['mod_date'],
    #                                     d['name']) for d in res[0]]
    #         files = ["%12d   %s   %s" % (f['size'], f['mod_date'],
    #                                      f['name']) for f in res[1]]
    #         print_dir = "\n".join(dirs)
    #         print_file = "\n".join(files)
    #         if print_output is True:
    #             print(print_dir + "\n" + print_file)
    #         res = print_dir + "\n" + print_file
    #     except Exception, e:
    #         user_msg("Error: %s" % str(e))
    #         res = None
    #     return res

    # @line_magic
    # def inv_make_directory(self,line):
    #     "Invocation service make directory"
    #     global user_id, token, user_profile, inv_client, inv_session,inv_cwd
    #     sess = self.inv_session()
    #     if len(line) < 1:
    #         user_msg("Error - must specify a new directory name")
    #         res = None
    #     else:
    #         cwd = inv_cwd
    #         d = line
    #         try:
    #             res = inv_client.make_directory( sess, cwd,d)
    #         except Exception, e:
    #             user_msg("Error: %s" % str(e))
    #             res = None
    #     return res

    # @line_magic
    # def inv_remove_directory(self,line):
    #     """
    #     Invocation service remove directory
    #     """
    #     global user_id, token, user_profile, inv_client, inv_session,inv_cwd
    #     sess = self.inv_session()
    #     if len(line) < 1:
    #         user_msg("Error - must specify a directory to remove")
    #         res = None
    #     else:
    #         cwd = inv_cwd
    #         d = line
    #         try:
    #             res = inv_client.remove_directory( sess, cwd,d)
    #         except Exception, e:
    #             user_msg("Error: %s" % str(e))
    #             res = None
    #     return res

    # @line_magic
    # def inv_cd(self, line):
    #     "Invocation service change directory"
    #     global user_id, token, user_profile, inv_client, inv_session,inv_cwd
    #     sess = self.inv_session()
    #     if len(line) > 0:
    #         d = line
    #         try:
    #             res = inv_client.change_directory( sess, inv_cwd,d)
    #             inv_cwd = res
    #         except Exception as e:
    #             user_msg("Error: %s" % str(e))
    #             res = None
    #     else:
    #         user_msg("Error - please specify a directory")
    #         res = None
    #     return res

    # @line_magic
    # def inv_cwd(self,line):
    #     "Invocation service current working directory"
    #     global user_id, token, user_profile, inv_client, inv_session,cwd
    #     sess = self.inv_session()
    #     return inv_cwd

    # @line_magic
    # def inv_valid_commands(self, line):
    #     "Invocation service inventory of command scripts"
    #     global user_id, token, user_profile, inv_client, inv_session
    #     sess = self.inv_session()
    #     try:
    #         res = inv_client.valid_commands()
    #     except Exception as e:
    #         user_msg("Error: %s" % str(e))
    #         res = None
    #     return res

    # @line_magic
    # def inv_remove_files(self, line):
    #     """
    #     Invocation service remove files
    #     Parameters are: [cwd] filename
    #     If only a single parameter is given, it is assumed to be a filename
    #     """
    #     global user_id, token, user_profile, inv_client, inv_session
    #     res = None
    #     if len(line) < 1:
    #         user_msg("Must specify filename and optionally a cwd")
    #     else:
    #         try:
    #             (cwd, filename) = line.split()
    #         except:
    #             filename = line
    #             cwd = inv_cwd
    #         sess = self.inv_session()
    #         try:
    #             res = inv_client.remove_files( sess, cwd, filename)
    #         except Exception as e:
    #             user_msg("Error: %s" % str(e))
    #     return res

    # @line_magic
    # def inv_rename_files(self, line):
    #     "Invocation service rename files"
    #     global user_id, token, user_profile, inv_client, inv_session
    #     res = None
    #     if len(line) < 1:
    #         user_msg("Must specify: cwd from_filename to_filename")
    #     else:
    #         try:
    #             (cwd, fromfn, tofn) = line.split()
    #         except:
    #             try:
    #                 (fromfn, tofn) = line.split()
    #             except:
    #                 user_msg("Must at least from_filename and to_filename")
    #                 return(None)
    #             cwd = inv_cwd
    #         sess = self.inv_session()
    #         try:
    #             res = inv_client.rename_file( sess, cwd, fromfn, tofn)
    #         except Exception as e:
    #             user_msg("Unable to rename %s to %s in directory %s: %s"
    #                          % (fromfn,tofn,cwd,str(e)))
    #     return res

    # @line_magic
    # def inv_copy(self,line):
    #     "Invocation service copy file"
    #     global user_id, token, user_profile, inv_client, inv_session
    #     res = None
    #     if len(line) < 1:
    #         user_msg("Must specify: cwd from_filename to_filename")
    #     else:
    #         try:
    #             (cwd, fromfn, tofn) = line.split()
    #         except:
    #             try:
    #                 (fromfn, tofn) = line.split()
    #             except:
    #                 user_msg("Must at least from_filename and to_filename")
    #                 return None
    #             cwd = inv_cwd
    #         sess = self.inv_session()
    #         try:
    #             res = inv_client.copy( sess, cwd, fromfn, tofn)
    #         except Exception as e:
    #             user_msg("Unable to copy %s to %s in directory %s: %s" %
    #                          (fromfn,tofn,cwd,str(e)))
    #     return res

    # @line_magic
    # def inv_put_file(self,line):
    #     """
    #     Invocation service put a file on the server.
    #     Parameters are filename contents [cwd]
    #     As usual, parameters are whitespace separated and the contents parameter is evaluated as
    #     a python expression, so you can use a variable to contain file contents, however if contents
    #     is a literal prefixed with a <, it will be treated as a filename in the current working
    #     directory.
    #     Examples:

    #     inv_put_file newdata 012345
    #     The line above will write a file called "newdata" to the invocation server, containing the text "012345"

    #     inv_put_file newdata <newdata.txt
    #     This line will look for a file called newdata.txt and upload the contents to the file newdata

    #     inv_put_file newdata newdata
    #     This line will take the contents of the newdata variable and send it to the newdata file. If there
    #     is an error evaluating the value of newdata (such as, it is undefined) nothing will be written
    #     """
    #     global user_id, token, user_profile, inv_client, inv_session
    #     res = None
    #     constr = None
    #     if len(line) < 1:
    #         user_msg("Must specify filename, contents and optionally a cwd")
    #     else:
    #         try:
    #             (filename, contents, cwd) = line.split()
    #         except:
    #             try:
    #                 (filename, contents) = line.split()
    #             except:
    #                 user_msg("Must at least filename and contents")
    #                 return None
    #             cwd = inv_cwd
    #         sess = self.inv_session()
    #         filematch = re.match('<(.+)',filename)
    #         if filematch:
    #             filename = filematch.groups()[0]
    #             try:
    #                 with open( filename, "r") as myfile:
    #                     constr = myfile.read()
    #             except Exception as e:
    #                 user_msg("Error: %s" % str(e))
    #         else:
    #             try:
    #                 con1 = ip.ev(contents)
    #                 contstr = str(con1)
    #             except Exception as e:
    #                 user_msg("Unable to convert %s to string: %s" %
    #                              (contents, e))
    #                 constr = None
    #         if constr:
    #             try:
    #                 res = inv_client.put_file(sess, filename, contstr, cwd)
    #             except Exception as e:
    #                 user_msg("Error: %s" % str(e))
    #     return res

    # @line_magic
    # def inv_get_file(self, line):
    #     "Invocation service get file contents"
    #     global user_id, token, user_profile, inv_client, inv_session
    #     res = None
    #     if len(line) < 1:
    #         user_msg("Must specify filename and,"
    #                  " optionally, a working directory.")
    #     else:
    #         try:
    #             (filename, wdir) = line.split()
    #         except:
    #             filename = line
    #             wdir = inv_cwd
    #         sess = self.inv_session()
    #         try:
    #             res = inv_client.get_file(sess, filename, wdir)
    #         except Exception as e:
    #             user_msg("Error: %s" % str(e))
    #     return res

    # @line_magic
    # def inv_get_tutorial_text(self, line):
    #     "Invocation service make directory"
    #     global user_id, token, user_profile, inv_client, inv_session
    #     return res

# Grab the ipython object and the config object if available
#
try:
    # XXX: Where are these defined/imported?
    ip = get_ipython()
    conf = get_config()
except NameError:
    # Wasn't running within an ipython instance, skip
    pass
except:
    # Hmmm, bad, rethrow it
    raise
if ip is None:
    user_msg("Cannot fetch IPython instance")
else:
    ip.register_magics(kbasemagics)
    # If we have a browser, have it set the have_browser flag
    # Try to bring in a token to the environment
    t = biokbase.auth.Token()
    if t.token is not None:
        user_id = t.user_id
        token = t.token
        # XXX: This isn't actually used anywhere! But it does trigger a poke at globusonline...
        user_profile = None
#        user_profile = biokbase.auth.User(token=token)
        user_msg("Logged in automatically as %s from environment defaults"
                 % user_id)
    else:
        user_msg("You are not currently logged in. Access to kbase will be "
                 "unauthenticated (where allowed).\n"
                 "Please login with kblogin for personal access.")
    user_msg("KBase narrative module loaded.\n"
             "Use 'kblogin {username}' and "
             "'kblogout' to acquire and dispose of KBase credentials.\n"
             "IPython magics defined for invocation service access are "
             "prefixed with inv_*")

    # build a bunch of helper functions under the "invoker" namespace
    # that simply run the various commands available from "valid_command"
    # Dynamically create the module, and sub-modules based on command categories
    # and then import it.
    # based heavily on method here:
    # http://dietbuddha.blogspot.com/2012/11/python-metaprogramming-dynamic-module.html

    # icmd = types.ModuleType('icmd', "Top level module for invocation command "
    #                                 "helper functions")
    # sys.modules['icmd'] = icmd

    # def mkfn(script):
    #     def fn(*args):
    #         args2 = [script]
    #         args2 += list(args)
    #         if inv_client is None:
    #             ip.magic("inv_session")
    #         stdout, stderr = inv_client.run_pipeline(inv_session," ".join(args2),[],200,'/')
    #         if stderr:
    #             user_msg("\n".join(stderr))
    #         return stdout
    #     return fn

    # # initialize an invocation session
    # ip.magic("inv_session")
    # cmds = inv_client.valid_commands()
    # for category in cmds:
    #     catname = str(category['name']).replace('-','_')
    #     m = types.ModuleType(catname,category['title'])
    #     setattr(icmd,catname, m)
    #     sys.modules['icmd.%s' % catname] = m
    #     for item in category['items']:
    #         script = str(item['cmd']).replace('-','_')
    #         fn = mkfn(str(item['cmd']))
    #         fn.__name__ = script
    #         fn.__doc__ = "Runs the %s script via invocation service" % item['cmd']
    #         setattr(m, script, fn)
    # ip.ex('import icmd')
    try:
        os.makedirs(workdir)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise
    os.chdir(workdir)
    user_msg("Invocation service script helper functions have been loaded "
             "under the icmd.* namespace")


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.sql.planner.plan;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.tree.Node;

import javax.annotation.concurrent.Immutable;

import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

/**
 * For every row from {@link #input} a {@link #subquery} relation is calculated.
 * Then input row is cross joined with subquery relation and returned as a result.
 * <p>
 * INNER - does not return any row for input row when subquery relation is empty
 * LEFT - does return input completed with NULL values when subquery relation is empty
 */
@Immutable
public class LateralJoinNode
        extends PlanNode
{
    public enum Type
    {
        INNER(JoinNode.Type.INNER),
        LEFT(JoinNode.Type.LEFT);

        Type(JoinNode.Type joinNodeType)
        {
            this.joinNodeType = joinNodeType;
        }

        private final JoinNode.Type joinNodeType;

        public JoinNode.Type toJoinNodeType()
        {
            return joinNodeType;
        }
    }

    private final PlanNode input;
    private final PlanNode subquery;

    /**
     * Correlation symbols, returned from input (outer plan) used in subquery (inner plan)
     */
    private final List<Symbol> correlation;
    private final Type type;

    /**
     * HACK!
     * Used for error reporting in case this ApplyNode is not supported
     */
    private final Node originSubquery;

    @JsonCreator
    public LateralJoinNode(
            @JsonProperty("id") PlanNodeId id,
            @JsonProperty("input") PlanNode input,
            @JsonProperty("subquery") PlanNode subquery,
            @JsonProperty("correlation") List<Symbol> correlation,
            @JsonProperty("type") Type type,
            @JsonProperty("originSubquery") Node originSubquery)
    {
        super(id);
        requireNonNull(input, "input is null");
        requireNonNull(subquery, "right is null");
        requireNonNull(correlation, "correlation is null");
        requireNonNull(originSubquery, "originSubquery is null");

        checkArgument(input.getOutputSymbols().containsAll(correlation), "Input does not contain symbols from correlation");

        this.input = input;
        this.subquery = subquery;
        this.correlation = ImmutableList.copyOf(correlation);
        this.type = type;
        this.originSubquery = originSubquery;
    }

    @JsonProperty("input")
    public PlanNode getInput()
    {
        return input;
    }

    @JsonProperty("subquery")
    public PlanNode getSubquery()
    {
        return subquery;
    }

    @JsonProperty("correlation")
    public List<Symbol> getCorrelation()
    {
        return correlation;
    }

    @JsonProperty("type")
    public Type getType()
    {
        return type;
    }

    @JsonProperty("originSubquery")
    public Node getOriginSubquery()
    {
        return originSubquery;
    }

    @Override
    public List<PlanNode> getSources()
    {
        return ImmutableList.of(input, subquery);
    }

    @Override
    @JsonProperty("outputSymbols")
    public List<Symbol> getOutputSymbols()
    {
        return ImmutableList.<Symbol>builder()
                .addAll(input.getOutputSymbols())
                .addAll(subquery.getOutputSymbols())
                .build();
    }

    @Override
    public PlanNode replaceChildren(List<PlanNode> newChildren)
    {
        checkArgument(newChildren.size() == 2, "expected newChildren to contain 2 nodes");
        return new LateralJoinNode(getId(), newChildren.get(0), newChildren.get(1), correlation, type, originSubquery);
    }

    @Override
    public <R, C> R accept(PlanVisitor<R, C> visitor, C context)
    {
        return visitor.visitLateralJoin(this, context);
    }
}