text:
import {
  CONSTANTS,
  deserializeMessage,
  listen,
  serializeMessage,
} from '../src/3p-frame-messaging';
import {Observable} from '../src/observable';
import {dev} from '../src/log';
import {dict, map} from '../src/utils/object';
import {getData} from '../src/event-helper';
import {getMode} from '../src/mode';

export class IframeMessagingClient {
  /**
   *  @param {!Window} win A window object.
   */
  constructor(win) {
    /** @private {!Window} */
    this.win_ = win;
    /** @private {?string} */
    this.rtvVersion_ = getMode().rtvVersion || null;
    /** @private {!Window} */
    this.hostWindow_ = win.parent;
    /** @private {?string} */
    this.sentinel_ = null;
    /** @type {number} */
    this.nextMessageId_ = 1;
    /**
     * Map messageType keys to observables to be fired when messages of that
     * type are received.
     * @private {!Object}
     */
    this.observableFor_ = map();
    this.setupEventListener_();
  }

  /**
   * Retrieves data from host.
   *
   * @param {string} requestType
   * @param {?Object} payload
   * @param {function(*)} callback
   */
  getData(requestType, payload, callback) {
    const responseType = requestType + CONSTANTS.responseTypeSuffix;
    const messageId = this.nextMessageId_++;
    const unlisten = this.registerCallback(responseType, result => {
      if (result[CONSTANTS.messageIdFieldName] === messageId) {
        unlisten();
        callback(result[CONSTANTS.contentFieldName]);
      }
    });
    const data = dict();
    data[CONSTANTS.payloadFieldName] = payload;
    data[CONSTANTS.messageIdFieldName] = messageId;
    this.sendMessage(requestType, data);
  }

  /**
   * Make an event listening request to the host window.
   *
   * @param {string} requestType The type of the request message.
   * @param {string} responseType The type of the response message.
   * @param {function(JsonObject)} callback The callback function to call
   *   when a message with type responseType is received.
   * @return {function()}
   */
  makeRequest(requestType, responseType, callback) {
    const unlisten = this.registerCallback(responseType, callback);
    this.sendMessage(requestType);
    return unlisten;
  }

  /**
   * Make a one time event listening request to the host window.
   * Will unlisten after response is received
   *
   * @param {string} requestType The type of the request message.
   * @param {string} responseType The type of the response message.
   * @param {function(Object)} callback The callback function to call
   *   when a message with type responseType is received.
   * @return {*} TODO(#23582): Specify return type
   */
  requestOnce(requestType, responseType, callback) {
    const unlisten = this.registerCallback(responseType, event => {
      unlisten();
      callback(event);
    });
    this.sendMessage(requestType);
    return unlisten;
  }

  /**
   * Register callback function for message with type messageType.
   *   As it stands right now, only one callback can exist at a time.
   *   All future calls will overwrite any previously registered
   *   callbacks.
   * @param {string} messageType The type of the message.
   * @param {function(?JsonObject)} callback The callback function to call
   *   when a message with type messageType is received.
   * @return {function()}
   */
  registerCallback(messageType, callback) {
    // NOTE : no validation done here. any callback can be register
    // for any callback, and then if that message is received, this
    // class *will execute* that callback
    return this.getOrCreateObservableFor_(messageType).add(callback);
  }

  /**
   * Send a postMessage to Host Window
   * @param {string} type The type of message to send.
   * @param {JsonObject=} opt_payload The payload of message to send.
   */
  sendMessage(type, opt_payload) {
    const msg = serializeMessage(
      type,
      dev().assertString(this.sentinel_),
      opt_payload,
      this.rtvVersion_
    );

    // opt in the userActivation feature
    // see https://github.com/dtapuska/useractivation
    if (this.isMessageOptionsSupported_()) {
      this.postMessageWithUserActivation_(msg);
    } else {
      this.hostWindow_./*OK*/ postMessage(msg, '*');
    }
  }

  /**
   * @param {string} msg
   * @suppress {checkTypes} // Can be removed after closure compiler update their externs.
   */
  postMessageWithUserActivation_(msg) {
    this.hostWindow_./*OK*/ postMessage(
      msg,
      dict({
        'targetOrigin': '*',
        'includeUserActivation': true,
      })
    );
  }

  /**
   * Sets up event listener for post messages of the desired type.
   *   The actual implementation only uses a single event listener for all of
   *   the different messages, and simply diverts the message to be handled
   *   by different callbacks.
   *   To add new messages to listen for, call registerCallback with the
   *   messageType to listen for, and the callback function.
   * @private
   */
  setupEventListener_() {
    listen(this.win_, 'message', event => {
      // Does it look a message from AMP?
      if (event.source != this.hostWindow_) {
        return;
      }

      const message = deserializeMessage(getData(event));
      if (!message || message['sentinel'] != this.sentinel_) {
        return;
      }

      message['origin'] = event.origin;

      this.fireObservable_(message['type'], message);
    });
  }

  /**
   * @param {!Window} win
   */
  setHostWindow(win) {
    this.hostWindow_ = win;
  }

  /**
   * @param {string} sentinel
   */
  setSentinel(sentinel) {
    this.sentinel_ = sentinel;
  }

  /**
   * @param {string} messageType
   * @return {!Observable<?JsonObject>}
   */
  getOrCreateObservableFor_(messageType) {
    if (!(messageType in this.observableFor_)) {
      this.observableFor_[messageType] = new Observable();
    }
    return this.observableFor_[messageType];
  }

  /**
   * @param {string} messageType
   * @param {Object} message
   */
  fireObservable_(messageType, message) {
    if (messageType in this.observableFor_) {
      this.observableFor_[messageType].fire(message);
    }
  }

  /**
   * @return {boolean}
   */
  isMessageOptionsSupported_() {
    // Learned from https://github.com/dtapuska/useractivation
    return this.hostWindow_ && this.hostWindow_.postMessage.length == 1;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <View
        android:id="@+id/view_temp"
        android:layout_width="match_parent"
        android:layout_height="0.1dp"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:background="#d9d9d9" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="52dp"
        android:background="#ffffff" >

        <ImageView
            android:id="@+id/iv_avatar"
            android:layout_width="36dp"
            android:layout_height="36dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="12dp"
            android:src="@drawable/default_useravatar" />

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="12dp"
            android:layout_toRightOf="@id/iv_avatar"
            android:text="微信客服"
            android:textColor="#353535"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tv_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="20dp"
            android:text="很久以前"
            android:textColor="#888888"
            android:textSize="15sp" />
    </RelativeLayout>

</LinearLayout>


text:
export * from './schedular';

export * from './components/calendar/week/services/index';


text:
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PCMRBot
{
    class GCPing : IGroupCommand
    {
        int requiredPermsGroup = 1;

        public List<ChatReply> RunGroupCommand(string[] args, SteamKit2.SteamFriends.ChatMsgCallback callback)
        {
            List<ChatReply> chatreply = new List<ChatReply>();
            chatreply.Add(new ChatReply(callback.ChatterID, "Pong"));
            return chatreply;
        }
        public int RequiredPermsForGroup
        {
            get
            {
                return requiredPermsGroup;
            }
            set
            {
                requiredPermsGroup = value;
            }
        }

    }
}


text:
package protostream

import (
	"bufio"
	"io"

	"go.pedge.io/google-protobuf"
)

// StreamingBytesServer represents a server for an rpc method of the form:
//   rpc Foo(Bar) returns (stream google.protobuf.BytesValue) {}
type StreamingBytesServer interface {
	Send(bytesValue *google_protobuf.BytesValue) error
}

// StreamingBytesClient represents a client for an rpc method of the form:
//   rpc Foo(Bar) returns (stream google.protobuf.BytesValue) {}
type StreamingBytesClient interface {
	Recv() (*google_protobuf.BytesValue, error)
}

// StreamingBytesClientHandler handles a StreamingBytesClient.
type StreamingBytesClientHandler interface {
	Handle(streamingBytesClient StreamingBytesClient) error
}

// NewStreamingBytesReader returns an io.Reader for a StreamingBytesClient.
func NewStreamingBytesReader(streamingBytesClient StreamingBytesClient) io.Reader {
	return newStreamingBytesReader(streamingBytesClient)
}

// NewStreamingBytesWriter returns an io.Writer for a StreamingBytesServer.
func NewStreamingBytesWriter(streamingBytesServer StreamingBytesServer) io.Writer {
	return newStreamingBytesWriter(streamingBytesServer)
}

// WriteToStreamingBytesServer writes the data from the io.Reader to the StreamingBytesServer.
func WriteToStreamingBytesServer(reader io.Reader, streamingBytesServer StreamingBytesServer) error {
	_, err := bufio.NewReader(reader).WriteTo(NewStreamingBytesWriter(streamingBytesServer))
	return err
}

// NewStreamingBytesClientHandler returns a StreamingBytesClientHandler for the given handleFunc.
func NewStreamingBytesClientHandler(handleFunc func(*google_protobuf.BytesValue) error) StreamingBytesClientHandler {
	return newStreamingBytesClientHandler(handleFunc)
}

// WriteFromStreamingBytesClient writes from the StreamingBytesClient to the io.Writer.
func WriteFromStreamingBytesClient(streamingBytesClient StreamingBytesClient, writer io.Writer) error {
	return NewStreamingBytesClientHandler(
		func(bytesValue *google_protobuf.BytesValue) error {
			_, err := writer.Write(bytesValue.Value)
			return err
		},
	).Handle(streamingBytesClient)
}

// RelayFromStreamingBytesClient relays *google_protobuf.BytesValues from the StreamingBytesClient to the StreamingBytesServer.
func RelayFromStreamingBytesClient(streamingBytesClient StreamingBytesClient, streamingBytesServer StreamingBytesServer) error {
	return NewStreamingBytesClientHandler(
		func(bytesValue *google_protobuf.BytesValue) error {
			return streamingBytesServer.Send(bytesValue)
		},
	).Handle(streamingBytesClient)
}


text:
namespace MarkerDesigner
{
    partial class Form1
    {
        /// <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()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.drawBoard1 = new MarkerDesigner.DrawBoard();
            this.radioButton1 = new System.Windows.Forms.RadioButton();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.drawDiagram1 = new MarkerDesigner.DrawDiagram();
            this.radioButton2 = new System.Windows.Forms.RadioButton();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
            this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(118, 225);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(88, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Clear";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(6, 225);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(88, 23);
            this.button2.TabIndex = 2;
            this.button2.Text = "Normalize";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.drawBoard1);
            this.groupBox1.Controls.Add(this.button2);
            this.groupBox1.Controls.Add(this.button1);
            this.groupBox1.Location = new System.Drawing.Point(11, 50);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(215, 253);
            this.groupBox1.TabIndex = 3;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Image";
            //
            // drawBoard1
            //
            this.drawBoard1.Location = new System.Drawing.Point(6, 19);
            this.drawBoard1.Name = "drawBoard1";
            this.drawBoard1.Size = new System.Drawing.Size(200, 200);
            this.drawBoard1.TabIndex = 0;
            this.drawBoard1.Text = "drawBoard1";
            //
            // radioButton1
            //
            this.radioButton1.AutoSize = true;
            this.radioButton1.Checked = true;
            this.radioButton1.Location = new System.Drawing.Point(11, 27);
            this.radioButton1.Name = "radioButton1";
            this.radioButton1.Size = new System.Drawing.Size(75, 17);
            this.radioButton1.TabIndex = 4;
            this.radioButton1.TabStop = true;
            this.radioButton1.Text = "Edit Image";
            this.radioButton1.UseVisualStyleBackColor = true;
            this.radioButton1.CheckedChanged += new System.EventHandler(this.radioButton1_CheckedChanged);
            //
            // groupBox2
            //
            this.groupBox2.Controls.Add(this.drawDiagram1);
            this.groupBox2.Location = new System.Drawing.Point(232, 50);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(217, 253);
            this.groupBox2.TabIndex = 5;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Graphs";
            //
            // drawDiagram1
            //
            this.drawDiagram1.Location = new System.Drawing.Point(7, 20);
            this.drawDiagram1.Name = "drawDiagram1";
            this.drawDiagram1.PointList = new System.Drawing.Point[] {
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0),
        new System.Drawing.Point(0, 0)};
            this.drawDiagram1.Size = new System.Drawing.Size(200, 200);
            this.drawDiagram1.TabIndex = 0;
            this.drawDiagram1.Text = "drawDiagram1";
            //
            // radioButton2
            //
            this.radioButton2.AutoSize = true;
            this.radioButton2.Location = new System.Drawing.Point(232, 27);
            this.radioButton2.Name = "radioButton2";
            this.radioButton2.Size = new System.Drawing.Size(80, 17);
            this.radioButton2.TabIndex = 4;
            this.radioButton2.Text = "Edit Graphs";
            this.radioButton2.UseVisualStyleBackColor = true;
            //
            // menuStrip1
            //
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fileToolStripMenuItem,
            this.helpToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
            this.menuStrip1.Size = new System.Drawing.Size(458, 24);
            this.menuStrip1.TabIndex = 6;
            this.menuStrip1.Text = "menuStrip1";
            //
            // fileToolStripMenuItem
            //
            this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.newToolStripMenuItem,
            this.openToolStripMenuItem,
            this.toolStripMenuItem1,
            this.saveToolStripMenuItem,
            this.saveAsToolStripMenuItem,
            this.toolStripMenuItem2,
            this.exitToolStripMenuItem});
            this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
            this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
            this.fileToolStripMenuItem.Text = "File";
            //
            // newToolStripMenuItem
            //
            this.newToolStripMenuItem.Name = "newToolStripMenuItem";
            this.newToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
            this.newToolStripMenuItem.Text = "New";
            this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
            //
            // openToolStripMenuItem
            //
            this.openToolStripMenuItem.Name = "openToolStripMenuItem";
            this.openToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
            this.openToolStripMenuItem.Text = "Open...";
            this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
            //
            // toolStripMenuItem1
            //
            this.toolStripMenuItem1.Name = "toolStripMenuItem1";
            this.toolStripMenuItem1.Size = new System.Drawing.Size(133, 6);
            //
            // saveToolStripMenuItem
            //
            this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
            this.saveToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
            this.saveToolStripMenuItem.Text = "Save";
            this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
            //
            // saveAsToolStripMenuItem
            //
            this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
            this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
            this.saveAsToolStripMenuItem.Text = "Save As...";
            this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click);
            //
            // toolStripMenuItem2
            //
            this.toolStripMenuItem2.Name = "toolStripMenuItem2";
            this.toolStripMenuItem2.Size = new System.Drawing.Size(133, 6);
            //
            // exitToolStripMenuItem
            //
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(136, 22);
            this.exitToolStripMenuItem.Text = "Exit";
            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
            //
            // helpToolStripMenuItem
            //
            this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.aboutToolStripMenuItem});
            this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
            this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
            this.helpToolStripMenuItem.Text = "Help";
            //
            // aboutToolStripMenuItem
            //
            this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
            this.aboutToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.aboutToolStripMenuItem.Text = "About...";
            this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(458, 307);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.radioButton2);
            this.Controls.Add(this.radioButton1);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.menuStrip1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MainMenuStrip = this.menuStrip1;
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.Text = "Marker Designer";
            this.groupBox1.ResumeLayout(false);
            this.groupBox2.ResumeLayout(false);
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private DrawBoard drawBoard1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.RadioButton radioButton1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.RadioButton radioButton2;
        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
        private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
        private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
        private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
        private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
        private DrawDiagram drawDiagram1;
    }
}


text:
import Ember from 'ember';
import ENV from 'kalliope-ember/config/environment';

export default Ember.Component.extend({
  tagName: 'tr',
  load_ignored_synapses: function() {
    if (typeof(Storage) !== "undefined") {
      var tmp = localStorage.getItem('kr:ignored-synapses');
      if (tmp == null) {
        tmp = [];
      }
      else {
        tmp = JSON.parse(tmp);
      }
      return tmp;
    } else {
      console.log('no local cache found');
    }
  },

  saved_ignored_synapses: function(synapse, remove) {
    var tmp = this.load_ignored_synapses();
    if (tmp == null) {
      tmp = [];
    }
    var position = tmp.indexOf(synapse.get('name'));
    if (position === -1 && remove !== false) {
      tmp.push(synapse.get('name'));
    }
    else if (position !== -1 && remove === true) {
      tmp.splice(position, 1);
    }
    localStorage.setItem('kr:ignored-synapses', JSON.stringify(tmp));
  },

  actions: {
    launch_synapse: function(synapse) {
      Ember.$.ajax({
        headers: {
          withCredentials: true,
          Authorization: 'Basic ' + btoa(ENV.APP.KALLIOPE.LOGIN + ':' + ENV.APP.KALLIOPE.PASS),
        },
        url: ENV.APP.KALLIOPE.HOST + ':' + ENV.APP.KALLIOPE.PORT + '/synapses/start/id/' + synapse.get('name'),
        type: 'POST'
      }).then(function(response) {
        // TODO: When kalliopé will return the response of the neuron instead of the brain used.
      });
    },

    ignore_synapse: function(synapse) {
      if (typeof(Storage) !== "undefined") {
        // Save in local store.
        this.saved_ignored_synapses(synapse);
        // Change synapse object value.
        synapse.set('hidden', true);
      } else {
        console.log('no local cache found');
      }
    },

    unignore_synapse: function(synapse) {
      if (typeof(Storage) !== "undefined") {
        // Save in local store.
        this.saved_ignored_synapses(synapse, true);
        // Change synapse object value.
        synapse.set('hidden', false);
      } else {
        console.log('no local cache found');
      }
    }
  }
});


text:
(function() {
"use strict";
angular.module('mjv')
.controller('HeaViewCtrl', function ($scope,   $http, $sce) {
    var monthNames = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"
];
     $http.get("../MJV_SERVICES/services/services.php?q=getSoc&p=2").then(function(response){
         console.log(response);
         $scope.details = response.data;
     });
	 $scope.toTrustedHTML = function( html ){
    return $sce.trustAsHtml( html );
}
$scope.dateNum = function(date){
    var day = date.split(' ')[0].split('-')[2];
    return day;
}
$scope.dateMonth = function(date){
    var day = date.split(' ')[0].split('-')[1];
    day = day.replace(/^0+/, '');
    return monthNames[Number(day)-1];
}

});
})();


text:
/**
 * @name FilePath
 * @description
 *
 * This plugin allows you to resolve the native filesystem path for Android content URIs and is based on code in the aFileChooser library.
 *
 * @usage
 * ```
 * import {FilePath} from 'ionic-native';
 *
 * FilePath.resolveNativePath(path)
 *   .then(filePath => console.log(filePath);
 *   .catch(err => console.log(err);
 *
 * ```
 */
export declare class FilePath {
    /**
     * Resolve native path for given content URL/path.
     * @param {String} path  Content URL/path.
     * @returns {Promise<string>}
     */
    static resolveNativePath(path: string): Promise<string>;
}


text:
// This file implements unit tests for class StreamBank.

#include "core/cross/skin.h"
#include "core/cross/stream_bank.h"
#include "core/cross/object_manager.h"
#include "core/cross/pack.h"
#include "core/cross/service_dependency.h"
#include "core/cross/pointer_utils.h"
#include "core/cross/fake_vertex_source.h"
#include "tests/common/win/testing_common.h"

namespace o3d {

namespace {

static const float kEpsilon = 0.0000001f;

bool CompareVertices(StreamBank* source,
                     Stream::Semantic semantic,
                     int semantic_index,
                     const float* values,
                     float multiplier) {
  const Stream* stream = source->GetVertexStream(semantic, semantic_index);
  if (!stream) {
    return false;
  }

  const Field& field = stream->field();
  Buffer* buffer = field.buffer();
  if (!buffer) {
    return false;
  }
  BufferLockHelper helper(buffer);
  void* data = helper.GetData(Buffer::READ_ONLY);
  if (!data) {
    return false;
  }

  unsigned num_vertices = stream->GetMaxVertices();
  unsigned stride = buffer->stride();

  const float* source_values = PointerFromVoidPointer<const float*>(
      data, field.offset());
  while (num_vertices) {
    for (unsigned jj = 0; jj < 3; ++jj) {
      float difference = fabsf(source_values[jj] - values[jj] * multiplier);
      if (difference > kEpsilon) {
        return false;
      }
    }
    values += 3;
    source_values = AddPointerOffset(source_values, stride);
    --num_vertices;
  }
  return true;
}

}  // anonymous namespace

class StreamBankTest : public testing::Test {
 protected:

  StreamBankTest()
      : object_manager_(g_service_locator) {}

  virtual void SetUp();
  virtual void TearDown();

  Pack* pack() { return pack_; }

 private:
  ServiceDependency<ObjectManager> object_manager_;
  Pack *pack_;
};

void StreamBankTest::SetUp() {
  pack_ = object_manager_->CreatePack();
}

void StreamBankTest::TearDown() {
  pack_->Destroy();
}

TEST_F(StreamBankTest, Basic) {
  static float cube_vertices[][3] = {
    { -1.0f, -1.0f,  1.0f, },  // vertex v0
    { +1.0f, -1.0f,  1.0f, },  // vertex v1
    { +1.0f, -1.0f, -1.0f, },  // vertex v2
    { -1.0f, -1.0f, -1.0f, },  // vertex v3
    { -1.0f,  1.0f,  1.0f, },  // vertex v4
    { +1.0f,  1.0f,  1.0f, },  // vertex v5
    { +1.0f,  1.0f, -1.0f, },  // vertex v6
    { -1.0f,  1.0f, -1.0f, },  // vertex v7
  };
  const unsigned kNumVertices = arraysize(cube_vertices);
  const unsigned kNumComponents = arraysize(cube_vertices[0]);

  StreamBank* stream_bank = pack()->Create<StreamBank>();
  // Check that StreamBank got created.
  ASSERT_TRUE(stream_bank != NULL);
  EXPECT_TRUE(stream_bank->IsA(StreamBank::GetApparentClass()));
  EXPECT_TRUE(stream_bank->IsA(VertexSource::GetApparentClass()));
  EXPECT_TRUE(stream_bank->renderable());

  // Check Setting Vertex Streams.
  VertexBuffer* vertex_buffer = pack()->Create<VertexBuffer>();
  ASSERT_TRUE(vertex_buffer != NULL);

  Field* field = vertex_buffer->CreateField(FloatField::GetApparentClass(),
                                            kNumComponents);
  ASSERT_TRUE(field != NULL);
  ASSERT_TRUE(vertex_buffer->AllocateElements(kNumVertices));
  field->SetFromFloats(&cube_vertices[0][0], kNumComponents, 0, kNumVertices);

  EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
                                           0,
                                           field,
                                           0));
  // Check getting a stream.
  const Stream* vertex_stream = stream_bank->GetVertexStream(Stream::POSITION,
                                                             0);
  ASSERT_TRUE(vertex_stream != NULL);
  EXPECT_EQ(&vertex_stream->field(), field);
  EXPECT_EQ(vertex_stream->semantic(), Stream::POSITION);
  EXPECT_EQ(vertex_stream->semantic_index(), 0);

  // Check removing the streams.
  EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::POSITION, 1));
  EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::BINORMAL, 0));
  EXPECT_TRUE(stream_bank->RemoveVertexStream(Stream::POSITION, 0));
  EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::POSITION, 0));
}

TEST_F(StreamBankTest, Renderable) {
  StreamBank* stream_bank = pack()->Create<StreamBank>();
  ASSERT_TRUE(stream_bank != NULL);

  VertexBuffer* vertex_buffer = pack()->Create<VertexBuffer>();
  ASSERT_TRUE(vertex_buffer != NULL);
  SourceBuffer* source_buffer = pack()->Create<SourceBuffer>();
  ASSERT_TRUE(source_buffer != NULL);

  Field* field1 = vertex_buffer->CreateField(FloatField::GetApparentClass(), 1);
  Field* field2 = source_buffer->CreateField(FloatField::GetApparentClass(), 1);
  ASSERT_TRUE(field1 != NULL);
  ASSERT_TRUE(field2 != NULL);

  EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION, 0, field1, 0));
  EXPECT_TRUE(stream_bank->renderable());
  EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION, 1, field2, 0));
  EXPECT_FALSE(stream_bank->renderable());
  EXPECT_TRUE(stream_bank->RemoveVertexStream(Stream::POSITION, 1));
  EXPECT_TRUE(stream_bank->renderable());
  EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION, 0, field2, 0));
  EXPECT_FALSE(stream_bank->renderable());
  EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION, 0, field1, 0));
  EXPECT_TRUE(stream_bank->renderable());
  EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::POSITION, 1));
  EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::BINORMAL, 0));
  EXPECT_TRUE(stream_bank->RemoveVertexStream(Stream::POSITION, 0));
  EXPECT_FALSE(stream_bank->RemoveVertexStream(Stream::POSITION, 0));
}

TEST_F(StreamBankTest, BindStream) {
  static float some_vertices[][3] = {
    { 1.0f, 2.0f, 3.0f, },
    { 7.0f, 8.0f, 9.0f, },
    { 4.0f, 5.0f, 6.0f, },
  };
  const unsigned kNumVertices = arraysize(some_vertices);
  const unsigned kNumComponents = arraysize(some_vertices[0]);

  StreamBank* stream_bank = pack()->Create<StreamBank>();
  ASSERT_TRUE(stream_bank != NULL);

  // Create 2 Vertex Buffers.
  VertexBuffer* vertex_buffer_1 = pack()->Create<VertexBuffer>();
  VertexBuffer* vertex_buffer_2 = pack()->Create<VertexBuffer>();
  ASSERT_TRUE(vertex_buffer_1 != NULL);
  ASSERT_TRUE(vertex_buffer_2 != NULL);

  // Create a field on each buffer.
  Field* vertex_field_1 = vertex_buffer_1->CreateField(
      FloatField::GetApparentClass(), kNumComponents);
  Field* vertex_field_2 = vertex_buffer_2->CreateField(
      FloatField::GetApparentClass(), kNumComponents);
  ASSERT_TRUE(vertex_field_1 != NULL);
  ASSERT_TRUE(vertex_field_2 != NULL);
  ASSERT_TRUE(vertex_buffer_1->AllocateElements(kNumVertices));
  ASSERT_TRUE(vertex_buffer_2->AllocateElements(kNumVertices));

  // Set up streams on StreamBank.
  EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
                                           0,
                                           vertex_field_1,
                                           0));
  EXPECT_TRUE(stream_bank->SetVertexStream(Stream::POSITION,
                                           1,
                                           vertex_field_2,
                                           0));

  // Create 2 source buffers.
  SourceBuffer* source_buffer_1 = pack()->Create<SourceBuffer>();
  SourceBuffer* source_buffer_2 = pack()->Create<SourceBuffer>();
  ASSERT_TRUE(source_buffer_1 != NULL);
  ASSERT_TRUE(source_buffer_2 != NULL);

  // Create a field on each buffer.
  Field* source_field_1 = source_buffer_1->CreateField(
      FloatField::GetApparentClass(), kNumComponents);
  Field* source_field_2 = source_buffer_2->CreateField(
      FloatField::GetApparentClass(), kNumComponents);
  ASSERT_TRUE(source_field_1 != NULL);
  ASSERT_TRUE(source_field_2 != NULL);

  // Put some vertices in the source streams.
  ASSERT_TRUE(source_buffer_1->AllocateElements(kNumVertices));
  source_field_1->SetFromFloats(&some_vertices[0][0], kNumComponents, 0,
                                kNumVertices);
  ASSERT_TRUE(source_buffer_2->AllocateElements(kNumVertices));
  source_field_2->SetFromFloats(&some_vertices[0][0], kNumComponents, 0,
                                kNumVertices);

  scoped_ptr<FakeVertexSource> source(new FakeVertexSource(
      pack()->service_locator()));
  ASSERT_TRUE(source != NULL);

  // Set up streams on source
  EXPECT_TRUE(source->SetVertexStream(Stream::POSITION,
                                      0,
                                      source_field_1,
                                      0));
  EXPECT_TRUE(source->SetVertexStream(Stream::POSITION,
                                      1,
                                      source_field_2,
                                      0));

  // Bind the vertices to both dest streams.
  EXPECT_TRUE(stream_bank->BindStream(source.get(), Stream::POSITION, 0));
  EXPECT_TRUE(stream_bank->BindStream(source.get(), Stream::POSITION, 1));
  // Non-existant streams should fail.
  EXPECT_FALSE(stream_bank->BindStream(source.get(), Stream::POSITION, 2));
  EXPECT_FALSE(stream_bank->BindStream(source.get(), Stream::COLOR, 10));

  // Cause the vertices to get updated.
  stream_bank->UpdateStreams();

  // Test that vertices get updated.
  EXPECT_TRUE(CompareVertices(stream_bank,
                              Stream::POSITION,
                              0,
                              &some_vertices[0][0],
                              2.0f));
  EXPECT_TRUE(CompareVertices(stream_bank,
                              Stream::POSITION,
                              1,
                              &some_vertices[0][0],
                              3.0f));

  // Check that UpdateOutputs only got called once.
  EXPECT_EQ(source->update_outputs_call_count(), 1U);
}

}  // namespace o3d


text:
package org.inferred.freebuilder.processor.naming;

import static org.inferred.freebuilder.processor.model.ModelUtils.getReturnType;
import static org.inferred.freebuilder.processor.source.IsInvalidTypeVisitor.isLegalType;

import static javax.tools.Diagnostic.Kind.ERROR;

import org.inferred.freebuilder.processor.property.Property;

import java.beans.Introspector;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.processing.Messager;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;

class BeanConvention implements NamingConvention {

  /**
   * Regular expression matching bean-convention method names.
   *
   * <p>We deviate slightly from the JavaBean convention by insisting that there must be a
   * non-lowercase character immediately following the get/is prefix; this prevents ugly cases like
   * 'get()' or 'getter()'.
   */
  static final Pattern GETTER_PATTERN = Pattern.compile("^(get|is)([^\\p{javaLowerCase}].*)");
  static final String GET_PREFIX = "get";
  static final String IS_PREFIX = "is";

  BeanConvention(Messager messager, Types types) {
    this.messager = messager;
    this.types = types;
  }

  private final Messager messager;
  private final Types types;

  /**
   * Verifies {@code method} is an abstract getter following the JavaBean convention. Any
   * deviations will be logged as an error.
   */
  @Override
  public Optional<Property.Builder> getPropertyNames(
      TypeElement valueType, ExecutableElement method) {
    boolean declaredOnValueType = method.getEnclosingElement().equals(valueType);
    String name = method.getSimpleName().toString();
    Matcher getterMatcher = GETTER_PATTERN.matcher(name);
    if (!getterMatcher.matches()) {
      if (declaredOnValueType) {
        messager.printMessage(
            ERROR,
            "Only getter methods (starting with '" + GET_PREFIX
                + "' or '" + IS_PREFIX + "') may be declared abstract on FreeBuilder types",
            method);
      } else {
        printNoImplementationMessage(valueType, method);
      }
      return Optional.empty();
    }
    String prefix = getterMatcher.group(1);
    String capitalizedName = getterMatcher.group(2);
    if (hasUpperCase(capitalizedName.codePointAt(0))) {
      if (declaredOnValueType) {
        String message = new StringBuilder()
            .append("Getter methods cannot have a lowercase character immediately after the '")
            .append(prefix)
            .append("' prefix on FreeBuilder types (did you mean '")
            .append(prefix)
            .appendCodePoint(Character.toUpperCase(capitalizedName.codePointAt(0)))
            .append(capitalizedName.substring(capitalizedName.offsetByCodePoints(0, 1)))
            .append("'?)")
            .toString();
        messager.printMessage(ERROR, message, method);
      } else {
        printNoImplementationMessage(valueType, method);
      }
      return Optional.empty();
    }
    TypeMirror returnType = getReturnType(valueType, method, types);
    if (returnType.getKind() == TypeKind.VOID) {
      if (declaredOnValueType) {
        messager.printMessage(
            ERROR, "Getter methods must not be void on FreeBuilder types", method);
      } else {
        printNoImplementationMessage(valueType, method);
      }
      return Optional.empty();
    }
    if (prefix.equals(IS_PREFIX) && (returnType.getKind() != TypeKind.BOOLEAN)) {
      if (declaredOnValueType) {
        messager.printMessage(
            ERROR,
            "Getter methods starting with '" + IS_PREFIX
                + "' must return a boolean on FreeBuilder types",
            method);
      } else {
        printNoImplementationMessage(valueType, method);
      }
      return Optional.empty();
    }
    if (!method.getParameters().isEmpty()) {
      if (declaredOnValueType) {
        messager.printMessage(
            ERROR, "Getter methods cannot take parameters on FreeBuilder types", method);
      } else {
        printNoImplementationMessage(valueType, method);
      }
      return Optional.empty();
    }
    if (!isLegalType(returnType)) {
      // The compiler should already have issued an error.
      return Optional.empty();
    }

    String camelCaseName = Introspector.decapitalize(capitalizedName);
    return Optional.of(new Property.Builder()
        .setUsingBeanConvention(true)
        .setName(camelCaseName)
        .setCapitalizedName(capitalizedName)
        .setGetterName(getterMatcher.group(0)));
  }

  private static boolean hasUpperCase(int codepoint) {
    return Character.toUpperCase(codepoint) != codepoint;
  }

  private void printNoImplementationMessage(TypeElement valueType, ExecutableElement method) {
    messager.printMessage(
        ERROR,
        "No implementation found for non-getter method '" + method + "'; "
            + "cannot generate FreeBuilder implementation",
        valueType);
  }

}


text:
default:
	@echo "You need to supply an argument to make"
.PHONY: default

# Docker commands
docker-start:
	docker-compose pull && \
	docker-compose up -d
up: docker-start
.PHONY: docker-start up

docker-stop:
	docker-compose down -v
down: docker-stop
.PHONY: docker-stop down

docker-restart: docker-stop docker-start
restart: docker-restart
.PHONY: docker-restart restart

# Cache commands
cache-clear:
	bin/console cache:clear --env=prod
cc: cache-clear
.PHONY: cache-clear cc

cache-warmup: cache-clear
	bin/console cache:warmup --env=prod
.PHONY: cache-warmup

# DB commands
update: migrate
.PHONY: update

migrate:
	bin/console doctrine:migrations:migrate --no-interaction
.PHONY: migrate


text:
<?php
class Session {
	//Properties
	public $sessionId;
	public $token;
	public $users = array();

	//Default constructor
	function Session($sessionId, $token, $users) {
		$this->$sessionId = $sessionId;
		$this->$token = $token;
		$this->$users = $users;
	}

	//Check if a user is in the session
	function isInSession($userId) {
		return in_array($userId, $users);
	}

	//Add a user to the session
	function addUser($userId) {
		if(!in_array($userId, $users)) {
			$users[] = $userId; //Equivalent to array_push() but w/o the function overhead
		}
	}

	//Remove a user from the session
	//Credit: stackoverflow.com/questions/7225070/php-array-delete-by-value-not-key
	function removeUser($userId) {
		if(($key = array_search($userId, $users)) !== false) {
			unset($users[$key]);
		}
	}
}
?>


text:
{{include.episode.title}}

{{include.episode.description}}

{{include.episode.picture.alt}}

      {% if include.episode.picture.credit %}

photo: {{include.episode.picture.credit.name}} via {% if include.episode.picture.credit.license.url %}{{include.episode.picture.credit.license.name}}{% else %}{{include.episode.picture.credit.license.name}}{% endif %}

      {% endif %}

Listen

    <audio preload="none" controls>
      <source src="{{include.episode.audio.src}}" type="audio/mp3">
    </audio>

iTunes

Stitcher

Download

    {{include.episode.content | markdownify}}


text:
"""
    tests.helpers
    ~~~~~~~~~~~~~~~~~~~~~~~

    Various helpers.

    :copyright: (c) 2015 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""

import pytest

import os
import uuid
import datetime

import flask
from logging import StreamHandler
from werkzeug.datastructures import Range
from werkzeug.exceptions import BadRequest, NotFound
from werkzeug.http import parse_cache_control_header, parse_options_header
from werkzeug.http import http_date
from flask._compat import StringIO, text_type

def has_encoding(name):
    try:
        import codecs
        codecs.lookup(name)
        return True
    except LookupError:
        return False

class TestJSON(object):

    def test_ignore_cached_json(self):
        app = flask.Flask(__name__)
        with app.test_request_context('/', method='POST', data='malformed',
                                      content_type='application/json'):
            assert flask.request.get_json(silent=True, cache=True) is None
            with pytest.raises(BadRequest):
                flask.request.get_json(silent=False, cache=False)

    def test_post_empty_json_adds_exception_to_response_content_in_debug(self):
        app = flask.Flask(__name__)
        app.config['DEBUG'] = True
        @app.route('/json', methods=['POST'])
        def post_json():
            flask.request.get_json()
            return None
        c = app.test_client()
        rv = c.post('/json', data=None, content_type='application/json')
        assert rv.status_code == 400
        assert b'Failed to decode JSON object' in rv.data

    def test_post_empty_json_wont_add_exception_to_response_if_no_debug(self):
        app = flask.Flask(__name__)
        app.config['DEBUG'] = False
        @app.route('/json', methods=['POST'])
        def post_json():
            flask.request.get_json()
            return None
        c = app.test_client()
        rv = c.post('/json', data=None, content_type='application/json')
        assert rv.status_code == 400
        assert b'Failed to decode JSON object' not in rv.data

    def test_json_bad_requests(self):
        app = flask.Flask(__name__)
        @app.route('/json', methods=['POST'])
        def return_json():
            return flask.jsonify(foo=text_type(flask.request.get_json()))
        c = app.test_client()
        rv = c.post('/json', data='malformed', content_type='application/json')
        assert rv.status_code == 400

    def test_json_custom_mimetypes(self):
        app = flask.Flask(__name__)
        @app.route('/json', methods=['POST'])
        def return_json():
            return flask.request.get_json()
        c = app.test_client()
        rv = c.post('/json', data='"foo"', content_type='application/x+json')
        assert rv.data == b'foo'

    def test_json_body_encoding(self):
        app = flask.Flask(__name__)
        app.testing = True
        @app.route('/')
        def index():
            return flask.request.get_json()

        c = app.test_client()
        resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),
                     content_type='application/json; charset=iso-8859-15')
        assert resp.data == u'Hällo Wörld'.encode('utf-8')

    def test_json_as_unicode(self):
        app = flask.Flask(__name__)

        app.config['JSON_AS_ASCII'] = True
        with app.app_context():
            rv = flask.json.dumps(u'\N{SNOWMAN}')
            assert rv == '"\\u2603"'

        app.config['JSON_AS_ASCII'] = False
        with app.app_context():
            rv = flask.json.dumps(u'\N{SNOWMAN}')
            assert rv == u'"\u2603"'

    def test_json_dump_to_file(self):
        app = flask.Flask(__name__)
        test_data = {'name': 'Flask'}
        out = StringIO()

        with app.app_context():
            flask.json.dump(test_data, out)
            out.seek(0)
            rv = flask.json.load(out)
            assert rv == test_data

    @pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])
    def test_jsonify_basic_types(self, test_value):
        """Test jsonify with basic types."""
        app = flask.Flask(__name__)
        c = app.test_client()

        url = '/jsonify_basic_types'
        app.add_url_rule(url, url, lambda x=test_value: flask.jsonify(x))
        rv = c.get(url)
        assert rv.mimetype == 'application/json'
        assert flask.json.loads(rv.data) == test_value

    def test_jsonify_dicts(self):
        """Test jsonify with dicts and kwargs unpacking."""
        d = dict(
            a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,
            h=['test list', 10, False],
            i={'test':'dict'}
        )
        app = flask.Flask(__name__)
        @app.route('/kw')
        def return_kwargs():
            return flask.jsonify(**d)
        @app.route('/dict')
        def return_dict():
            return flask.jsonify(d)
        c = app.test_client()
        for url in '/kw', '/dict':
            rv = c.get(url)
            assert rv.mimetype == 'application/json'
            assert flask.json.loads(rv.data) == d

    def test_jsonify_arrays(self):
        """Test jsonify of lists and args unpacking."""
        l = [
            0, 42, 3.14, 't', 'hello', True, False,
            ['test list', 2, False],
            {'test':'dict'}
        ]
        app = flask.Flask(__name__)
        @app.route('/args_unpack')
        def return_args_unpack():
            return flask.jsonify(*l)
        @app.route('/array')
        def return_array():
            return flask.jsonify(l)
        c = app.test_client()
        for url in '/args_unpack', '/array':
            rv = c.get(url)
            assert rv.mimetype == 'application/json'
            assert flask.json.loads(rv.data) == l

    def test_jsonify_date_types(self):
        """Test jsonify with datetime.date and datetime.datetime types."""
        test_dates = (
            datetime.datetime(1973, 3, 11, 6, 30, 45),
            datetime.date(1975, 1, 5)
        )
        app = flask.Flask(__name__)
        c = app.test_client()

        for i, d in enumerate(test_dates):
            url = '/datetest{0}'.format(i)
            app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))
            rv = c.get(url)
            assert rv.mimetype == 'application/json'
            assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())

    def test_jsonify_uuid_types(self):
        """Test jsonify with uuid.UUID types"""

        test_uuid = uuid.UUID(bytes=b'\xDE\xAD\xBE\xEF' * 4)
        app = flask.Flask(__name__)
        url = '/uuid_test'
        app.add_url_rule(url, url, lambda: flask.jsonify(x=test_uuid))

        c = app.test_client()
        rv = c.get(url)

        rv_x = flask.json.loads(rv.data)['x']
        assert rv_x == str(test_uuid)
        rv_uuid = uuid.UUID(rv_x)
        assert rv_uuid == test_uuid

    def test_json_attr(self):
        app = flask.Flask(__name__)
        @app.route('/add', methods=['POST'])
        def add():
            json = flask.request.get_json()
            return text_type(json['a'] + json['b'])
        c = app.test_client()
        rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),
                            content_type='application/json')
        assert rv.data == b'3'

    def test_template_escaping(self):
        app = flask.Flask(__name__)
        render = flask.render_template_string
        with app.test_request_context():
            rv = flask.json.htmlsafe_dumps('</script>')
            assert rv == u'"\\u003c/script\\u003e"'
            assert type(rv) == text_type
            rv = render('{{ "</script>"|tojson }}')
            assert rv == '"\\u003c/script\\u003e"'
            rv = render('{{ "<\0/script>"|tojson }}')
            assert rv == '"\\u003c\\u0000/script\\u003e"'
            rv = render('{{ "


text:
/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false, createTag:false*/

'use strict';

togglbutton.render('#Pagearea:not(.toggl)', {observe: true}, function (elem) {
  var link, container = createTag('li', 'ticket-btns'),
    //duration,
    description,
    titleElem = $('h2.subject', elem),
    idElem = $('#ticket-display-id'),
    //trackedContainer = createTag('div', 'open-box toggl-time-tracked'),
    //trackedElem = $('.open-box'),
    projectElem = $('.logo_text'),
    buttonsElem = $('.ticket-actions > ul');

  description = idElem.textContent.trim() + ' ' + titleElem.textContent.trim();
  link = togglbutton.createTimerLink({
    className: 'freshdesk',
    description: description,
    projectName: projectElem && projectElem.textContent.trim(),
    calculateTotal: true
  });

  container.appendChild(link);
  buttonsElem.appendChild(container, buttonsElem);
/*
  duration = togglbutton.calculateTrackedTime(description);
  h3 = document.createElement("h3");
  h3.textContent = "Time tracked";

  p = document.createElement("p");
  p.setAttribute("title", "Time tracked with Toggl: " + duration);
  p.textContent = duration;

  trackedContainer.appendChild(h3);
  trackedContainer.appendChild(p);
  trackedElem.parentNode.insertBefore(trackedContainer, trackedElem.nextSibling);
*/
});


text:
reach-scoreboard
================


text:
xhr2
====

Simple XMLHttpRequest wrapper with minimalistic API.

## License
MIT


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function rangeInRange(r, range) {
    return positionInRange(r.start, range) === 0 && positionInRange(r.end, range) === 0;
}
exports.rangeInRange = rangeInRange;
/**
 * Check if two ranges have overlap character.
 */
function rangeOverlap(r, range) {
    let { start, end } = r;
    if (comparePosition(end, range.start) <= 0) {
        return false;
    }
    if (comparePosition(start, range.end) >= 0) {
        return false;
    }
    return true;
}
exports.rangeOverlap = rangeOverlap;
/**
 * Check if two ranges have overlap or nested
 */
function rangeIntersect(r, range) {
    if (positionInRange(r.start, range) == 0) {
        return true;
    }
    if (positionInRange(r.end, range) == 0) {
        return true;
    }
    if (rangeInRange(range, r)) {
        return true;
    }
    return false;
}
exports.rangeIntersect = rangeIntersect;
function lineInRange(line, range) {
    let { start, end } = range;
    return line >= start.line && line <= end.line;
}
exports.lineInRange = lineInRange;
function emptyRange(range) {
    let { start, end } = range;
    return start.line == end.line && start.character == end.character;
}
exports.emptyRange = emptyRange;
function positionInRange(position, range) {
    let { start, end } = range;
    if (comparePosition(position, start) < 0)
        return -1;
    if (comparePosition(position, end) > 0)
        return 1;
    return 0;
}
exports.positionInRange = positionInRange;
function comparePosition(position, other) {
    if (position.line > other.line)
        return 1;
    if (other.line == position.line && position.character > other.character)
        return 1;
    if (other.line == position.line && position.character == other.character)
        return 0;
    return -1;
}
exports.comparePosition = comparePosition;
function isSingleLine(range) {
    return range.start.line == range.end.line;
}
exports.isSingleLine = isSingleLine;
function getChangedPosition(start, edit) {
    let { range, newText } = edit;
    if (comparePosition(range.end, start) <= 0) {
        let lines = newText.split('\n');
        let lineCount = lines.length - (range.end.line - range.start.line) - 1;
        let characterCount = 0;
        if (range.end.line == start.line) {
            let single = isSingleLine(range) && lineCount == 0;
            let removed = single ? range.end.character - range.start.character : range.end.character;
            let added = single ? newText.length : lines[lines.length - 1].length;
            characterCount = added - removed;
        }
        return { line: lineCount, character: characterCount };
    }
    return { line: 0, character: 0 };
}
exports.getChangedPosition = getChangedPosition;
function adjustPosition(pos, edit) {
    let { range, newText } = edit;
    if (comparePosition(range.start, pos) > 1)
        return pos;
    let { start, end } = range;
    let newLines = newText.split('\n');
    let delta = (end.line - start.line) - newLines.length + 1;
    let lastLine = newLines[newLines.length - 1];
    let line = pos.line - delta;
    if (pos.line != end.line)
        return { line, character: pos.character };
    let pre = newLines.length == 1 && start.line != end.line ? start.character : 0;
    let removed = start.line == end.line && newLines.length == 1 ? end.character - start.character : end.character;
    let character = pre + pos.character + lastLine.length - removed;
    return {
        line,
        character
    };
}
exports.adjustPosition = adjustPosition;
function positionToOffset(lines, line, character) {
    let offset = 0;
    for (let i = 0; i <= line; i++) {
        if (i == line) {
            offset += character;
        }
        else {
            offset += lines[i].length + 1;
        }
    }
    return offset;
}
exports.positionToOffset = positionToOffset;
// edit a range to newText
function editRange(range, text, edit) {
    // outof range
    if (!rangeInRange(edit.range, range))
        return text;
    let { start, end } = edit.range;
    let lines = text.split('\n');
    let character = start.line == range.start.line ? start.character - range.start.character : start.character;
    let startOffset = positionToOffset(lines, start.line - range.start.line, character);
    character = end.line == range.start.line ? end.character - range.start.character : end.character;
    let endOffset = positionToOffset(lines, end.line - range.start.line, character);
    return `${text.slice(0, startOffset)}${edit.newText}${text.slice(endOffset, text.length)}`;
}
exports.editRange = editRange;
function getChangedFromEdits(start, edits) {
    let changed = { line: 0, character: 0 };
    for (let edit of edits) {
        let d = getChangedPosition(start, edit);
        changed = { line: changed.line + d.line, character: changed.character + d.character };
    }
    return changed.line == 0 && changed.character == 0 ? null : changed;
}
exports.getChangedFromEdits = getChangedFromEdits;
//# sourceMappingURL=position.js.map


text:
================================================================================
HostCpuPackage
================================================================================

.. describe:: Property of

    :py:class:`~pyvisdk.do.host_hardware_info.HostHardwareInfo`

.. describe:: See also

    :py:class:`~pyvisdk.do.host_cpu_id_info.HostCpuIdInfo`

.. describe:: Extends

    :py:class:`~pyvisdk.mo.dynamic_data.DynamicData`

.. class:: pyvisdk.do.host_cpu_package.HostCpuPackage

    .. py:attribute:: busHz

        Bus speed in HZ.

    .. py:attribute:: cpuFeature

        The CPU feature bit on this particular CPU. This is independent of the product and licensing capabilities.

    .. py:attribute:: description

        String summary description of CPU (for display purposes).

    .. py:attribute:: hz

        CPU speed in HZ.

    .. py:attribute:: index

        Package index, starting from zero.

    .. py:attribute:: threadId

        The logical CPU threads on this package.

    .. py:attribute:: vendor

        CPU vendor name, possible names currently are "Intel", "AMD", or "unknown".


text:
/**
 * Lists generic controls
 */

(function($)
{
	// List styles setup
	$.fn.addTemplateSetup(function()
	{
		// Closed elements
		this.find('.close').toggleBranchOpen().removeClass('close');

		// :first-of-type is buggy with jQuery under IE
		this.find('dl.accordion dt:first-child + dd').siblings('dd').hide();

		// Tasks dialog
		if (!$.browser.msie || $.browser.version > 8)	// IE is buggy on this animation
		{
			this.find('.task-dialog').parent().hover(function()
			{
				$(this).find('.task-dialog > li.auto-hide').expand();

			}, function()
			{
				$(this).find('.task-dialog > li.auto-hide').fold();
			});
		}
	}, true);

	// Document initial setup
	$(document).ready(function()
	{
		// Arbo elements controls
		$('.arbo .toggle, .collapsible-list li:has(ul) > :first-child, .collapsible-list li:has(ul) > :first-child + span').live('click', function(event)
		{
			// Toggle style
			$(this).toggleBranchOpen();

			// Prevent link action
			if (this.nodeName.toLowerCase() == 'a')
			{
				event.preventDefault();
			}
		});

		// Accordions effect
		$('dl.accordion dt').live('click', function()
		{
			$(this).next('dd').slideDown().siblings('dd').slideUp().prev('dt');

			// Effect need for rounded corners
			$(this).addClass('opened').siblings('dt').removeClass('opened');
		});
	});

	/**
	 * Open/close branch
	 */
	$.fn.toggleBranchOpen = function()
	{
		this.each(function()
		{
			/*
			 * Tip: if you want to add animation or do anything that should not occur at startup closing,
			 * check if the element has the class 'close':
			 * if (!$(this).hasClass('close')) { // Anything that sould no occur at startup }
			 */

			// Change
			$(this).closest('li').toggleClass('closed');
		});

		return this;
	};

})(jQuery);


text:
package org.apache.drill.exec.store.xml;

import org.apache.drill.categories.RowSetTests;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.physical.rowSet.RowSet;
import org.apache.drill.exec.record.metadata.SchemaBuilder;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.test.ClusterFixture;
import org.apache.drill.test.ClusterTest;
import org.apache.drill.test.rowSet.RowSetComparison;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.nio.file.Paths;

import static org.apache.drill.test.QueryTestUtil.generateCompressedFile;
import static org.apache.drill.test.rowSet.RowSetUtilities.mapArray;
import static org.apache.drill.test.rowSet.RowSetUtilities.objArray;
import static org.apache.drill.test.rowSet.RowSetUtilities.strArray;
import static org.junit.Assert.assertEquals;

@Category(RowSetTests.class)
public class TestXMLReader extends ClusterTest {

  @BeforeClass
  public static void setup() throws Exception {
    ClusterTest.startCluster(ClusterFixture.builder(dirTestWatcher));

    XMLFormatConfig formatConfig = new XMLFormatConfig(null, 2);
    cluster.defineFormat("cp", "xml", formatConfig);
    cluster.defineFormat("dfs", "xml", formatConfig);

    // Needed for compressed file unit test
    dirTestWatcher.copyResourceToRoot(Paths.get("xml/"));
  }

  /**
   * This unit test tests a simple XML file with no nesting or attributes
   * @throws Exception Throw exception if anything goes wrong
   */
  @Test
  public void testWildcard() throws Exception {
    String sql = "SELECT * FROM cp.`xml/simple.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();
    assertEquals(3, results.rowCount());

    TupleMetadata expectedSchema = new SchemaBuilder()
      .add("attributes", MinorType.MAP)
      .addNullable("groupID", MinorType.VARCHAR)
      .addNullable("artifactID", MinorType.VARCHAR)
      .addNullable("version", MinorType.VARCHAR)
      .addNullable("classifier", MinorType.VARCHAR)
      .addNullable("scope", MinorType.VARCHAR)
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(mapArray(), "org.apache.drill.exec", "drill-java-exec", "${project.version}", null, null)
      .addRow(mapArray(),"org.apache.drill.exec", "drill-java-exec", "${project.version}", "tests", "test")
      .addRow(mapArray(),"org.apache.drill", "drill-common", "${project.version}", "tests", "test")
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testSelfClosingTags() throws Exception {
    String sql = "SELECT * FROM cp.`xml/weather.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();
    assertEquals(1, results.rowCount());

      TupleMetadata expectedSchema = new SchemaBuilder()
        .addMap("attributes")
          .addNullable("forecast_information_city_data", MinorType.VARCHAR)
          .addNullable("forecast_information_postal_code_data", MinorType.VARCHAR)
          .addNullable("forecast_information_latitude_e6_data", MinorType.VARCHAR)
          .addNullable("forecast_information_longitude_e6_data", MinorType.VARCHAR)
          .addNullable("forecast_information_forecast_date_data", MinorType.VARCHAR)
          .addNullable("forecast_information_current_date_time_data", MinorType.VARCHAR)
          .addNullable("forecast_information_unit_system_data", MinorType.VARCHAR)
          .addNullable("current_conditions_condition_data", MinorType.VARCHAR)
          .addNullable("current_conditions_temp_f_data", MinorType.VARCHAR)
          .addNullable("current_conditions_temp_c_data", MinorType.VARCHAR)
          .addNullable("current_conditions_humidity_data", MinorType.VARCHAR)
          .addNullable("current_conditions_icon_data", MinorType.VARCHAR)
          .addNullable("current_conditions_wind_condition_data", MinorType.VARCHAR)
        .resumeSchema()
        .addNullable("city", MinorType.VARCHAR)
        .addNullable("postal_code", MinorType.VARCHAR)
        .addNullable("latitude_e6", MinorType.VARCHAR)
        .addNullable("longitude_e6", MinorType.VARCHAR)
        .addNullable("forecast_date", MinorType.VARCHAR)
        .addNullable("current_date_time", MinorType.VARCHAR)
        .addNullable("unit_system", MinorType.VARCHAR)
        .addNullable("condition", MinorType.VARCHAR)
        .addNullable("temp_f", MinorType.VARCHAR)
        .addNullable("temp_c", MinorType.VARCHAR)
        .addNullable("humidity", MinorType.VARCHAR)
        .addNullable("icon", MinorType.VARCHAR)
        .addNullable("wind_condition", MinorType.VARCHAR)
        .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(strArray("Seattle, WA", "Seattle WA", "", "", "2011-09-29", "2011-09-29 17:53:00 +0000", "US", "Clear", "62", "17", "Humidity: 62%", "/ig/images/weather" +
        "/sunny.gif", "Wind: N at 4 mph"), null, null, null, null, null, null, null, null, null, null, null, null, null)
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  /**
   * This unit test tests a simple XML file with no nesting or attributes, but with explicitly selected fields.
   * @throws Exception Throw exception if anything goes wrong
   */
  @Test
  public void testExplicitWithSimpleXMLFile() throws Exception {
    String sql = "SELECT groupID, artifactID, version, classifier, scope FROM cp.`xml/simple.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    assertEquals(3, results.rowCount());

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addNullable("groupID", MinorType.VARCHAR)
      .addNullable("artifactID", MinorType.VARCHAR)
      .addNullable("version", MinorType.VARCHAR)
      .addNullable("classifier", MinorType.VARCHAR)
      .addNullable("scope", MinorType.VARCHAR)
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow("org.apache.drill.exec", "drill-java-exec", "${project.version}", null, null)
      .addRow("org.apache.drill.exec", "drill-java-exec", "${project.version}", "tests", "test")
      .addRow("org.apache.drill", "drill-common", "${project.version}", "tests", "test")
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testWildcardWithFilter() throws Exception {
    String sql = "SELECT * FROM cp.`xml/simple.xml` WHERE scope='test'";
    RowSet results = client.queryBuilder().sql(sql).rowSet();
    assertEquals(2, results.rowCount());

    TupleMetadata expectedSchema = new SchemaBuilder()
      .add("attributes", MinorType.MAP)
      .addNullable("groupID", MinorType.VARCHAR)
      .addNullable("artifactID", MinorType.VARCHAR)
      .addNullable("version", MinorType.VARCHAR)
      .addNullable("classifier", MinorType.VARCHAR)
      .addNullable("scope", MinorType.VARCHAR)
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(mapArray(),"org.apache.drill.exec", "drill-java-exec", "${project.version}", "tests", "test")
      .addRow(mapArray(),"org.apache.drill", "drill-common", "${project.version}", "tests", "test")
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testWildcardWithSingleNestedDataField() throws Exception {
    String sql = "SELECT * FROM cp.`xml/really-simple-nested.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();
    assertEquals(3, results.rowCount());

    TupleMetadata expectedSchema = new SchemaBuilder()
      .add("attributes", MinorType.MAP, DataMode.REQUIRED)
      .addMap("field1")
        .addNullable("key1", MinorType.VARCHAR)
        .addNullable("key2", MinorType.VARCHAR)
      .resumeSchema()
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(mapArray(), strArray("value1", "value2"))
      .addRow(mapArray(), strArray("value3", "value4"))
      .addRow(mapArray(), strArray("value5", "value6"))
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testExplicitWithSingleNestedDataField() throws Exception {
    String sql = "SELECT t1.field1.key1 as key1, t1.field1.key2 as key2 FROM cp.`xml/really-simple-nested.xml` as t1";
    RowSet results = client.queryBuilder().sql(sql).rowSet();
    assertEquals(3, results.rowCount());

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addNullable("key1", MinorType.VARCHAR)
      .addNullable("key2", MinorType.VARCHAR)
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow("value1", "value2")
      .addRow("value3", "value4")
      .addRow("value5", "value6")
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testSerDe() throws Exception {
    String sql = "SELECT COUNT(*) FROM cp.`xml/simple.xml`";
    String plan = queryBuilder().sql(sql).explainJson();
    long cnt = queryBuilder().physical(plan).singletonLong();
    assertEquals("Counts should match", 3L, cnt);
  }

  @Test
  public void testExplicitWithCompressedSimpleXMLFile() throws Exception {
    generateCompressedFile("xml/simple.xml", "zip", "xml/simple.xml.zip");

    String sql = "SELECT groupID, artifactID, version, classifier, scope FROM dfs.`xml/simple.xml.zip`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    assertEquals(3, results.rowCount());

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addNullable("groupID", MinorType.VARCHAR)
      .addNullable("artifactID", MinorType.VARCHAR)
      .addNullable("version", MinorType.VARCHAR)
      .addNullable("classifier", MinorType.VARCHAR)
      .addNullable("scope", MinorType.VARCHAR)
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow("org.apache.drill.exec", "drill-java-exec", "${project.version}", null, null)
      .addRow("org.apache.drill.exec", "drill-java-exec", "${project.version}", "tests", "test")
      .addRow("org.apache.drill", "drill-common", "${project.version}", "tests", "test")
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testDeepNestedSpecificFields() throws Exception {
    String sql = "select xml.level2.level3.level4.level5.level6.level7.field1 as field1, xml.level2.level3.level4.level5.level6.level7.field2 as field2, xml.level2.level3.level4" +
      ".level5.level6.level7.field3 as field3 FROM cp.`xml/deep-nested.xml` as xml";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    assertEquals(2, results.rowCount());

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addNullable("field1", MinorType.VARCHAR)
      .addNullable("field2", MinorType.VARCHAR)
      .addNullable("field3", MinorType.VARCHAR)
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow("f1", "f2", "f3")
      .addRow("f4", "f5", "f6")
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testDeepNesting() throws Exception {
    String sql = "SELECT * FROM cp.`xml/deep-nested.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    assertEquals(2, results.rowCount());

    TupleMetadata expectedSchema = new SchemaBuilder()
      .add("attributes", MinorType.MAP, DataMode.REQUIRED)
      .addMap("level2")
        .addNullable("field1-level2", MinorType.VARCHAR)
        .addMap("level3")
        .addNullable("field1-level3", MinorType.VARCHAR)
          .addMap("level4")
          .addNullable("field1-level4", MinorType.VARCHAR)
            .addMap("level5")
            .addNullable("field1-level5", MinorType.VARCHAR)
              .addMap("level6")
              .addNullable("field1-level6", MinorType.VARCHAR)
                .addMap("level7")
                .addNullable("field1", MinorType.VARCHAR)
                .addNullable("field2", MinorType.VARCHAR)
                .addNullable("field3", MinorType.VARCHAR)
              .resumeMap()  // End level 7
              .resumeMap()   // End level 6
            .resumeMap() // End level 5
          .resumeMap() // End level 4
        .resumeMap() // End level 3
      .resumeSchema()
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(mapArray(), objArray(
        objArray(
          "l2",
          objArray("l3",
            objArray("l4",
              objArray("l5",
                objArray("l6",
                  strArray("f1", "f2", "f3")
                )
              )
            )
          )
        )
      ))
      .addRow(mapArray(), objArray(
        objArray(
          null,
          objArray(null,
            objArray(null,
              objArray(null,
                objArray(null,
                  strArray("f4", "f5", "f6")
                )
              )
            )
          )
        )
      ))
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testDataLevel() throws Exception {
    String sql = "SELECT * FROM table(cp.`xml/deep-nested2.xml` (type => 'xml', dataLevel => 8))";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .add("attributes", MinorType.MAP, DataMode.REQUIRED)
      .addNullable("field1", MinorType.VARCHAR)
      .addNullable("field2", MinorType.VARCHAR)
      .addNullable("field3", MinorType.VARCHAR)
      .addNullable("field1-level6", MinorType.VARCHAR)
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(mapArray(), "f4", "f5", "f6", null)
      .addRow(mapArray(), "f1", "f2", "f3", "l6")
      .build();

    assertEquals(2, results.rowCount());
    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testExplicitDataLevel() throws Exception {
    String sql = "SELECT field1, field2, field3 FROM table(cp.`xml/deep-nested2.xml` (type => 'xml', dataLevel => 8))";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addNullable("field1", MinorType.VARCHAR)
      .addNullable("field2", MinorType.VARCHAR)
      .addNullable("field3", MinorType.VARCHAR)
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow("f4", "f5", "f6")
      .addRow("f1", "f2", "f3")
      .build();

    assertEquals(2, results.rowCount());
    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testComplexWildcardStar() throws Exception {
    String sql = "SELECT * FROM cp.`xml/nested.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .add("attributes", MinorType.MAP, DataMode.REQUIRED)
      .addMap("field1")
        .addNullable("key1", MinorType.VARCHAR)
        .addNullable("key2", MinorType.VARCHAR)
      .resumeSchema()
      .addMap("field2")
        .addNullable("key3", MinorType.VARCHAR)
        .addMap("nestedField1")
          .addNullable("nk1", MinorType.VARCHAR)
          .addNullable("nk2", MinorType.VARCHAR)
          .addNullable("nk3", MinorType.VARCHAR)
        .resumeMap()
      .resumeSchema()
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(mapArray(), strArray("value1", "value2"), objArray("k1", strArray("nk_value1", "nk_value2", "nk_value3")))
      .addRow(mapArray(), strArray("value3", "value4"), objArray("k2", strArray("nk_value4", "nk_value5", "nk_value6")))
      .addRow(mapArray(), strArray("value5", "value6"), objArray("k3", strArray("nk_value7", "nk_value8", "nk_value9")))
      .build();

    assertEquals(3, results.rowCount());
    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testComplexNestedExplicit() throws Exception {
    String sql = "SELECT xml.field2.nestedField1.nk1 as nk1, xml.field2.nestedField1.nk2 as nk2, xml.field2.nestedField1.nk3 as nk3 FROM cp.`xml/nested.xml` AS xml";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addNullable("nk1", MinorType.VARCHAR)
      .addNullable("nk2", MinorType.VARCHAR)
      .addNullable("nk3", MinorType.VARCHAR)
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow("nk_value1", "nk_value2", "nk_value3")
      .addRow("nk_value4", "nk_value5", "nk_value6")
      .addRow("nk_value7", "nk_value8", "nk_value9")
      .build();

    assertEquals(3, results.rowCount());
    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testAttributes() throws Exception {
    String sql = "SELECT attributes FROM cp.`xml/attributes.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addMap("attributes")
        .addNullable("title_binding", MinorType.VARCHAR)
        .addNullable("title_subcategory", MinorType.VARCHAR)
      .resumeSchema()
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow((Object) mapArray(null, null))
      .addRow((Object) strArray("paperback", null))
      .addRow((Object) strArray("hardcover", "non-fiction"))
      .build();

    assertEquals(3, results.rowCount());
    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testNestedAttributes() throws Exception {
    String sql = "SELECT * FROM cp.`xml/nested-with-attributes.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addMap("attributes")
        .addNullable("field1_f1", MinorType.VARCHAR)
        .addNullable("field2_f2", MinorType.VARCHAR)
        .addNullable("field2_key3_f3", MinorType.VARCHAR)
        .addNullable("field2_nestedField1_f4", MinorType.VARCHAR)
        .addNullable("field2_nestedField1_f5", MinorType.VARCHAR)
        .addNullable("field2_nestedField1_nk1_f6", MinorType.VARCHAR)
        .addNullable("field2_nestedField1_nk1_f7", MinorType.VARCHAR)
        .addNullable("field2_nestedField1_nk3_f8", MinorType.VARCHAR)
      .resumeSchema()
      .addMap("field1")
      .addNullable("key1", MinorType.VARCHAR)
      .addNullable("key2", MinorType.VARCHAR)
      .resumeSchema()
      .addMap("field2")
      .addNullable("key3", MinorType.VARCHAR)
      .addMap("nestedField1")
      .addNullable("nk1", MinorType.VARCHAR)
      .addNullable("nk2", MinorType.VARCHAR)
      .addNullable("nk3", MinorType.VARCHAR)
      .resumeMap()
      .resumeSchema()
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(strArray("k1", "k2", "k3", "k4", "k5", "k6", "k7", null), strArray("value1", "value2"), objArray("k1", strArray("nk_value1", "nk_value2", "nk_value3")))
      .addRow(strArray(null, null, null, null, null, null, null, null), strArray("value3", "value4"), objArray("k2", strArray("nk_value4", "nk_value5", "nk_value6")))
      .addRow(strArray(null, null, null, null, null, null, null, "k8"), strArray("value5", "value6"), objArray("k3", strArray("nk_value7", "nk_value8", "nk_value9")))
      .build();

    assertEquals(3, results.rowCount());
    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testExplicitNestedAttributes() throws Exception {
    String sql = "SELECT data.attributes.field1_f1 AS field1_f1," +
      "data.attributes.field2_f2 AS field2_f2, " +
      "data.attributes.field2_key3_f3 AS field2_key3_f3," +
      "data.attributes.field2_nestedField1_f4 AS field2_nestedField1_f4," +
      "data.attributes.field2_nestedField1_f5 AS field2_nestedField1_f5, " +
      "data.attributes.field2_nestedField1_nk1_f6 AS field2_nestedField1_nk1_f6, " +
      "data.attributes.field2_nestedField1_nk1_f7 AS field2_nestedField1_nk1_f7," +
      "data.attributes.field2_nestedField1_nk3_f8 AS field2_nestedField1_nk3_f8 " +
      "FROM cp.`xml/nested-with-attributes.xml` AS data";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addNullable("field1_f1", MinorType.VARCHAR)
      .addNullable("field2_f2", MinorType.VARCHAR)
      .addNullable("field2_key3_f3", MinorType.VARCHAR)
      .addNullable("field2_nestedField1_f4", MinorType.VARCHAR)
      .addNullable("field2_nestedField1_f5", MinorType.VARCHAR)
      .addNullable("field2_nestedField1_nk1_f6", MinorType.VARCHAR)
      .addNullable("field2_nestedField1_nk1_f7", MinorType.VARCHAR)
      .addNullable("field2_nestedField1_nk3_f8", MinorType.VARCHAR)
      .buildSchema();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow("k1", "k2", "k3", "k4", "k5", "k6", "k7", null)
      .addRow(null, null, null, null, null, null, null, null)
      .addRow(null, null, null, null, null, null, null, "k8")
      .build();
    assertEquals(3, results.rowCount());
    new RowSetComparison(expected).verifyAndClearAll(results);
  }

  @Test
  public void testLimitPushdown() throws Exception {
    String sql = "SELECT * FROM cp.`xml/simple.xml` LIMIT 2";

    queryBuilder()
      .sql(sql)
      .planMatcher()
      .include("Limit", "limit=2")
      .match();
  }

  @Test
  public void testMapError() throws Exception {
    String sql = "SELECT * FROM cp.`xml/schemaChange.xml`";
    RowSet results = client.queryBuilder().sql(sql).rowSet();

    TupleMetadata expectedSchema = new SchemaBuilder()
      .addMap("attributes")
      .resumeSchema()
      .addMap("parent")
        .addNullable("link", MinorType.VARCHAR)
        .addNullable("value", MinorType.VARCHAR)
      .resumeSchema()
      .build();

    RowSet expected = client.rowSetBuilder(expectedSchema)
      .addRow(mapArray(), mapArray(null, null))
      .addRow(mapArray(), strArray("https://dev57595.service-now.com/api/now/table/task/46eaa7c9a9fe198100bbe282da0d4b7d", "46eaa7c9a9fe198100bbe282da0d4b7d"))
      .build();

    new RowSetComparison(expected).verifyAndClearAll(results);
  }
}


text:
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using ImaginationServer.Common;
using ImaginationServer.Common.CdClientData;
using ImaginationServer.Common.CharacterData;
using ImaginationServer.Common.Data;
using ImaginationServer.Common.Handlers;
using ImaginationServer.World.Replica.Objects;
using static ImaginationServer.Common.PacketEnums;
using static ImaginationServer.Common.PacketEnums.WorldServerPacketId;

namespace ImaginationServer.World.Handlers.World
{
    public class ClientLevelLoadCompleteHandler : PacketHandler
    {
        public override void Handle(BinaryReader reader, LuClient client)
        {
            using (var database = new DbUtils())
            {
                if (!client.Authenticated) return;

                var zone = (ZoneId) reader.ReadUInt16();
                var instance = reader.ReadUInt16();
                var clone = reader.ReadInt32();

                Console.WriteLine(
                    $"Got clientside level load complete packet from {client.Username}. Zone: {zone}, Instance: {instance}, Clone: {clone}.");

                var account = database.GetAccount(client.Username);
                var character = database.GetCharacter(account.SelectedCharacter);

                using (var bitStream = new WBitStream())
                {
                    bitStream.WriteHeader(RemoteConnection.Client, (uint) MsgClientCreateCharacter);

                    using (var ldf = new Ldf())
                    {
                        // TODO: Improve LDF code here
                        ldf.WriteS64("accountID", account.Id);
                        ldf.WriteS32("chatmode", 0);
                        ldf.WriteBool("editor_enabled", false);
                        ldf.WriteS32("editor_level", 0);
                        ldf.WriteBool("freetrial", false);
                        ldf.WriteS32("gmlevel", character.GmLevel);
                        ldf.WriteBool("legoclub", true);
                        var levelid = character.ZoneId + (((long) character.MapInstance) << 16) +
                                      (((long) character.MapClone) << 32);
                        ldf.WriteS64("levelid", levelid);
                        ldf.WriteWString("name", character.Name);
                        ldf.WriteId("objid", Character.GetObjectId(character));
                        ldf.WriteFloat("position.x", character.Position[0]);
                        ldf.WriteFloat("position.y", character.Position[1]);
                        ldf.WriteFloat("position.z", character.Position[2]);
                        ldf.WriteS64("reputation", character.Reputation);
                        ldf.WriteS32("template", 1);
                        using (var xmlData = GenXmlData(character)) ldf.WriteBytes("xmlData", xmlData);

                        bitStream.Write(ldf.GetSize() + 1);
                        bitStream.Write((byte) 0);
                        ldf.WriteToPacket(bitStream);
                        WorldServer.Server.Send(bitStream, WPacketPriority.SystemPriority,
                            WPacketReliability.ReliableOrdered, 0, client.Address, false);
                        File.WriteAllBytes("Temp/" + character.Name + ".world_2a.bin", bitStream.GetBytes());
                    }
                }

                WorldServer.Server.SendGameMessage(client.Address, Character.GetObjectId(character), 1642);
                WorldServer.Server.SendGameMessage(client.Address, Character.GetObjectId(character), 509);
                using (var gameMessage = LuServer.CreateGameMessage(Character.GetObjectId(character), 472))
                {
                    gameMessage.Write((uint) 185);
                    gameMessage.Write((byte) 0);
                    WorldServer.Server.Send(gameMessage, WPacketPriority.SystemPriority,
                        WPacketReliability.ReliableOrdered, 0, client.Address, false);
                }

                var playerObject = new PlayerObject(Character.GetObjectId(character), character.Name);
                playerObject.Construct(WorldServer.Server, client.Address);
            }
        }

        private static WBitStream GenXmlData(Character character)
        {
            using(var cdclient = new CdClientDb())
            {
                var xml = "";
                xml += "<?xml version=\"1.0\"?>";

                xml += "<obj v=\"1\">";
                xml += "<buff/>";
                xml += "<skil/>";

                xml += "<inv>";
                xml += "<bag>";
                xml += "<b t=\"0\" m=\"24\"/>";
                xml += "</bag>";

                xml += "<items>";
                xml += "<in>";

                // TODO: Write items

                //foreach (var item in character.Items)
                //{
                //    writer.WriteStartElement("i"); // <i>
                //    writer.WriteAttributeString("l", item.);
                //    writer.WriteEndElement(); // </i>
                //}

                xml += "</in>";
                xml += "</items>";

                xml += "</inv>";

                xml += "<mf/>";

                xml += "<chars cc=\"100\"></char>";

                xml += $"<lvl l=\"{character.Level}\"/>";

                xml += "<flag/>";
                xml += "<pet/>";

                if (character.Missions?.Any() ?? false)
                {
                    xml += "<mis>";
                    xml += "<done>";
                    xml = character.Missions.Select(mission => CharacterMission.FromJson(mission)).Aggregate(xml, (current, missionData) => current + $"<m id=\"{missionData.Id}\" cts=\"{missionData.Timestamp}\" cct=\"{missionData.Count}\"/>");
                    xml += "</done>";
                    xml += "</mis>";
                }

                xml += "<mnt/>";
                xml += "<dest/>";
                xml += "</obj>";
                var bitStream = new WBitStream();
                Console.WriteLine(xml);
                bitStream.WriteChars(xml);

                return bitStream;
            }
        }
    }
}


text:
package hypergo

/*
#cgo LDFLAGS: -lhyperdex-admin
#include "hyperdex/admin.h"
*/
import "C"

import (
	"fmt"
	"strings"
)

// Admin APIs
func (admin *Admin) DumpConfig() string {
	return <-admin.AsyncDumpConfig()
}

func (admin *Admin) AsyncDumpConfig() chan string {
	return admin.AsyncDumpConfigOrListSpaces("dump_config")
}

func (admin *Admin) ListSpaces() []string {
	c := admin.AsyncListSpaces()
	strs := make([]string, 0)
	for {
		s, ok := <-c
		if ok {
			if len(s) > 0 {
				strs = append(strs, s)
			}
		} else {
			break
		}
	}

	return strs
}

func (admin *Admin) AsyncListSpaces() chan string {
	return admin.AsyncDumpConfigOrListSpaces("list_spaces")
}

func (admin *Admin) AsyncDumpConfigOrListSpaces(funcName string) chan string {
	c := make(chan string, CHANNEL_BUFFER_SIZE)
	var C_return_code C.enum_hyperdex_admin_returncode
	var C_string *C.char
	var req_id int64
	var success func()

	switch funcName {
	case "dump_config":
		req_id = int64(C.hyperdex_admin_dump_config(admin.ptr, &C_return_code, &C_string))
		success = func() {
			c <- C.GoString(C_string)
		}
	case "list_spaces":
		req_id = int64(C.hyperdex_admin_list_spaces(admin.ptr, &C_return_code, &C_string))
		success = func() {
			spaces := C.GoString(C_string)
			for _, s := range strings.Split(spaces, "\n") {
				c <- s
			}
			close(c)
		}
	}

	if req_id < 0 {
		panic(fmt.Sprintf("%s failed", funcName))
	}

	req := adminRequest{
		id:      req_id,
		status:  &C_return_code,
		success: success,
	}

	admin.requests = append(admin.requests, req)
	return c
}

func (admin *Admin) ValidateSpace(description string) bool {
	var C_return_code C.enum_hyperdex_admin_returncode

	valid := C.hyperdex_admin_validate_space(admin.ptr,
		C.CString(description), &C_return_code)

	if valid < 0 {
		return false
	} else {
		return true
	}
}

func (admin *Admin) AddSpace(description string) error {
	return <-admin.AsyncAddSpace(description)
}

func (admin *Admin) AsyncAddSpace(description string) ErrorChannel {
	return admin.AsyncAddOrRemoveSpace(description, "add")
}

func (admin *Admin) RemoveSpace(description string) error {
	return <-admin.AsyncRemoveSpace(description)
}

func (admin *Admin) AsyncRemoveSpace(description string) ErrorChannel {
	return admin.AsyncAddOrRemoveSpace(description, "remove")
}

func (admin *Admin) AsyncAddOrRemoveSpace(description string, funcName string) ErrorChannel {
	var C_return_code C.enum_hyperdex_admin_returncode
	errCh := make(chan error, CHANNEL_BUFFER_SIZE)
	var req_id int64
	switch funcName {
	case "add":
		req_id = int64(C.hyperdex_admin_add_space(admin.ptr,
			C.CString(description), &C_return_code))
	case "remove":
		req_id = int64(C.hyperdex_admin_rm_space(admin.ptr,
			C.CString(description), &C_return_code))
	}

	req := adminRequest{
		id:     req_id,
		status: &C_return_code,
		success: func() {
			errCh <- nil
		},
		failure: errChannelFailureCallbackForAdmin(errCh),
	}

	admin.requests = append(admin.requests, req)

	return errCh
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:gravity="center_vertical"
	android:minHeight="?android:attr/listPreferredItemHeight"
	android:paddingLeft="@dimen/preference_item_padding_side"
	android:paddingRight="?android:attr/scrollbarSize" >
	<LinearLayout
		android:layout_width="wrap_content"
		android:layout_height="match_parent"
		android:gravity="center"
		android:minWidth="@dimen/preference_icon_minWidth"
		android:orientation="horizontal" >
		<ImageView
			android:id="@+id/icon"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_gravity="center"
			android:paddingRight="@dimen/preference_item_padding_inner" />
	</LinearLayout>
	<RelativeLayout
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_weight="1"
		android:paddingBottom="6dip"
		android:paddingRight="@dimen/preference_item_padding_inner"
		android:paddingTop="6dip" >
		<TextView
			android:id="@+id/title"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:singleLine="true"
			android:textAppearance="?android:attr/textAppearanceMedium"
			android:textColor="?android:attr/textColorSecondary" />
		<TextView
			android:id="@+id/summary"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_alignLeft="@android:id/title"
			android:layout_below="@android:id/title"
			android:maxLines="10"
			android:textAppearance="?android:attr/textAppearanceSmall"
			android:textColor="?android:attr/textColorSecondary" />
	</RelativeLayout>
	<LinearLayout
		android:id="@+id/widget_frame"
		android:layout_width="wrap_content"
		android:layout_height="match_parent"
		android:gravity="center_vertical"
		android:orientation="vertical" />
</LinearLayout>


text:
name: Bug report
about: Some input not render as you expect? Include an example so we can help
title: ''
labels: bug
assignees: ''

---

Steps to reproduce the problem (provide example Markdown if applicable):

```
my markdown
```

Expected behavior:

```
expected HTML
```

Actual behavior:

```
actual HTML
```

(Also see what the reference implementation does: https://spec.commonmark.org/dingus/)


text:
function sOut = rsaddnoise(sIn, fs, sNR, noise, noiseFs)
%   RSADDNOISE adds noise to obtain signal with specified SNR value
%   RSADDNOISE(sIn, fs, sNR)
%   RSADDNOISE(sIn, fs, sNR, noise, noiseFs)
%
%   Inputs:
%       sIn 	- Input signal vetor
%       fs 	- Sampling frequency of input signal
%	sNR 	- required SNR value
%
%   Optional inputs:
%	noise	- Noise vector
%		  This vector should be at least as long as input
%		  signal.
%		  When no noise vector provided, white gaussian
%		  noise is generated
%	noiseFs	- Noise sampling frequency

margin                  = 1; % in seconds
normalizationMethod     = 'RMS'; % 'max'/'RMS'

if nargin > 3
    noise               = resample(noise, fs, noiseFs);
    noise               = noise(margin*fs:end-margin*fs, 1);
else
    noise               = randn(size(sIn));
end

noiseStart              = randi(length(noise)-length(sIn));
noiseIn                 = noise(noiseStart:noiseStart+length(sIn)-1);

switch normalizationMethod
    case 'RMS'
        sNorm                   = sIn/sqrt(sum(sIn.^2));
        noiseNorm               = noiseIn/sqrt(sum(noiseIn.^2));
    case 'max'
        sNorm                   = sIn/max(abs(sIn));
        noiseNorm               = noiseIn/max(abs(noiseIn));
end

% noiseFactor             = sqrt((sum(sNorm.^2)/sum(noiseIn.^2))*10^(-0.1*sNR));

noiseFactor             = 10^((rspowerdb(sNorm)-rspowerdb(noiseNorm)-sNR)/20);

noiseNorm               = noiseFactor*noiseIn;
sOut                    = sNorm+noiseNorm;

switch normalizationMethod
    case 'RMS'
        sOut                    = sOut/sqrt(sum(sOut.^2));
    case 'max'
        sOut                    = sOut/max(abs(sOut));
end