text:
Template.boardListHeaderBar.events({
  'click .js-open-archived-board'() {
    Modal.open('archivedBoards');
  },
});

BlazeComponent.extendComponent({
  onCreated() {
    this.subscribe('archivedBoards');
  },

  archivedBoards() {
    return Boards.find({ archived: true }, {
      sort: ['title'],
    });
  },

  events() {
    return [{
      'click .js-restore-board'() {
        // TODO : Make isSandstorm variable global
        const isSandstorm = Meteor.settings && Meteor.settings.public &&
          Meteor.settings.public.sandstorm;
        if (isSandstorm && Session.get('currentBoard')) {
          const currentBoard = Boards.findOne(Session.get('currentBoard'));
          currentBoard.archive();
        }
        const board = this.currentData();
        board.restore();
        Utils.goBoardId(board._id);
      },
      'click .js-delete-board': Popup.afterConfirm('boardDelete', function() {
        Popup.close();
        const isSandstorm = Meteor.settings && Meteor.settings.public &&
          Meteor.settings.public.sandstorm;
        if (isSandstorm && Session.get('currentBoard')) {
          const currentBoard = Boards.findOne(Session.get('currentBoard'));
          Boards.remove(currentBoard._id);
        }
        const board = this.currentData();
        Boards.remove(board._id);
        FlowRouter.go('home');
      }),
    }];
  },
}).register('archivedBoards');


text:
public class DefaultPackageClass
{
    private int m_int;
    private char m_char;
    private Character m_character;
    private boolean m_boolean;
    private DefaultPackageClass m_linked;

    public boolean isBoolean() {
        return m_boolean;
    }
    public void setBoolean(boolean b) {
        m_boolean = b;
    }
    public int getInt() {
        return m_int;
    }
    public void setInt(int i) {
        m_int = i;
    }
    public DefaultPackageClass getLinked() {
        return m_linked;
    }
    public void setLinked(DefaultPackageClass linked) {
        m_linked = linked;
    }
    public char getChar() {
        return m_char;
    }
    public void setChar(char chr) {
        m_char = chr;
    }
    public Character getCharacter() {
        return m_character;
    }
    public void setCharacter(Character chr) {
        m_character = chr;
    }
}

redpajama_set_name: RedPajamaGithub


text:
pub use self::{flow::FlowStat, mon_socket::MonProxySocket, mon_stream::MonProxyStream};

pub mod flow;
pub mod mon_socket;
pub mod mon_stream;
pub mod utils;


text:
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Markup;

namespace TimeTortoise.WPF.Commands
{
	/// <summary>
	/// Basic implementation of the <see cref="ICommand"/>
	/// interface, which is also accessible as a markup
	/// extension.
	///
	/// Forked from https://bitbucket.org/hardcodet/notifyicon-wpf/src/a72c42d41e187761d27486f4c031f78f0018f2b1/Hardcodet.NotifyIcon.Wpf/Source/Sample%20Project/Commands/CommandBase.cs?at=master&fileviewer=file-view-default
	/// </summary>
	public abstract class CommandBase<T> : MarkupExtension, ICommand
		where T : class, ICommand, new()
	{
		/// <summary>
		/// A singleton instance.
		/// </summary>
		private static T _command;

		/// <summary>
		/// Gets a shared command instance.
		/// </summary>
		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			return _command ?? (_command = new T());
		}

		/// <summary>
		/// Fires when changes occur that affect whether
		/// or not the command should execute.
		/// </summary>
		public event EventHandler CanExecuteChanged
		{
			add => CommandManager.RequerySuggested += value;
			remove => CommandManager.RequerySuggested -= value;
		}

		/// <summary>
		/// Defines the method to be called when the command is invoked.
		/// </summary>
		/// <param name="parameter">Data used by the command.
		/// If the command does not require data to be passed,
		/// this object can be set to null.
		/// </param>
		public abstract void Execute(object parameter);

		/// <summary>
		/// Defines the method that determines whether the command
		/// can execute in its current state.
		/// </summary>
		/// <returns>
		/// This default implementation always returns true.
		/// </returns>
		/// <param name="parameter">Data used by the command.
		/// If the command does not require data to be passed,
		/// this object can be set to null.
		/// </param>
		public virtual bool CanExecute(object parameter)
		{
			return !IsDesignMode;
		}

		private static bool IsDesignMode => (bool)
			DependencyPropertyDescriptor.FromProperty(DesignerProperties.IsInDesignModeProperty,
					typeof (FrameworkElement))
				.Metadata.DefaultValue;
	}
}


text:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CSS Multi-column Layout: parsing column-rule-width with valid values</title>
<link rel="help" href="https://drafts.csswg.org/css-multicol/#propdef-column-rule-width">
<meta name="assert" content="column-rule-width supports the full <line-width> grammar '<length> | thin | medium | thick'.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/css/support/parsing-testcommon.js"></script>
</head>
<body>
<script>
test_valid_value("column-rule-width", "thin");
test_valid_value("column-rule-width", "medium");
test_valid_value("column-rule-width", "thick");

test_valid_value("column-rule-width", "0", "0px");
test_valid_value("column-rule-width", "10px");
</script>
</body>
</html>


text:
namespace CymaticLabs.Unity3D.Amqp
{
    /// <summary>
    /// Unity-specific AMQP queue subscription that exposes Unity events for the
    /// subscription's message received handler.
    /// </summary>
    [System.Serializable]
    public class UnityAmqpQueueSubscription : AmqpQueueSubscription
    {
        /// <summary>
        /// Occurs when a message is received by the subscription.
        /// </summary>
        public AmqpQueueMessageReceivedUnityEvent OnMessageReceived;
    }
}


text:
XFTP.configure do |config|
  # Logging configuration
  #
  # Default logger fallbacks to `Rails.logger` if available, otherwise `STDOUT` will be used.
  #
  # config.logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT),

  # FTP connection settings
  #
  # config.ftp = {
  #   binary: true,
  #   passive: true,
  #   debug_mode: false,
  #   open_timeout: nil,
  #   resume: false
  # }

  # SSH (SFTP) connection settings
  #
  # config.ssh = {
  #   keepalive: true,
  #   keepalive_interval: 30,
  #   forward_agent: true,
  #   verbose: :error
  # }
end


text:
<?php
/**
 * ALIPAY API: alipay.user.get request
 *
 * @author auto create
 * @since 1.0, 2019-03-08 15:29:11
 */
class AlipayUserGetRequest
{
	/**
	 * 需要返回的字段列表。alipay_user_id:支付宝用户userId,user_status:支付宝用户状态,user_type:支付宝用户类型,certified:是否通过实名认证,real_name:真实姓名,logon_id:支付宝登录号,sex:用户性别
	 **/
	private $fields;

	private $apiParas = array();
	private $terminalType;
	private $terminalInfo;
	private $prodCode;
	private $apiVersion="1.0";
	private $notifyUrl;
	private $returnUrl;
    private $needEncrypt=false;

	public function setFields($fields)
	{
		$this->fields = $fields;
		$this->apiParas["fields"] = $fields;
	}

	public function getFields()
	{
		return $this->fields;
	}

	public function getApiMethodName()
	{
		return "alipay.user.get";
	}

	public function setNotifyUrl($notifyUrl)
	{
		$this->notifyUrl=$notifyUrl;
	}

	public function getNotifyUrl()
	{
		return $this->notifyUrl;
	}

	public function setReturnUrl($returnUrl)
	{
		$this->returnUrl=$returnUrl;
	}

	public function getReturnUrl()
	{
		return $this->returnUrl;
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function getTerminalType()
	{
		return $this->terminalType;
	}

	public function setTerminalType($terminalType)
	{
		$this->terminalType = $terminalType;
	}

	public function getTerminalInfo()
	{
		return $this->terminalInfo;
	}

	public function setTerminalInfo($terminalInfo)
	{
		$this->terminalInfo = $terminalInfo;
	}

	public function getProdCode()
	{
		return $this->prodCode;
	}

	public function setProdCode($prodCode)
	{
		$this->prodCode = $prodCode;
	}

	public function setApiVersion($apiVersion)
	{
		$this->apiVersion=$apiVersion;
	}

	public function getApiVersion()
	{
		return $this->apiVersion;
	}

  public function setNeedEncrypt($needEncrypt)
  {

     $this->needEncrypt=$needEncrypt;

  }

  public function getNeedEncrypt()
  {
    return $this->needEncrypt;
  }

}


text:
title: Overview
page_title: Reports Management Overview
description: Reports Management Overview
slug: reports-management
tags: reports,management
published: True
position: 100
---

# Reports Management

In the **Reports** view you can manage the reports which reside on the server.

The Reports view provides the following functions:

  - [New report]({%slug new-report%})
  - [Upload report]({%slug upload-report%})
  - [Preview report]({%slug preview-report%})
  - [Design report]({%slug design-report%})
  - [Edit]({%slug edit-metadata%})
  - [Download report]({%slug download-report%})
  - [Copy report]({%slug copy-report%})
  - [Delete report]({%slug delete-report%})
  - [Favorite report]({%slug favorite-report%})
  - [Search]({%slug search%}) by Name, Description, Category or Date.

When a report has been selected you can see a details view on the right side of the grid. The details view shows additional information about the report as well as the report's history.


text:
package configsyncer

import (
	"fmt"
	"reflect"
	"testing"
	"time"

	"github.com/prometheus/common/model"
	v32 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"
	"github.com/rancher/rancher/pkg/controllers/managementuserlegacy/alert/manager"
	v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var (
	clusterAlertTests = []struct {
		caseName     string
		in           map[string][]*v3.ClusterAlertRule
		outGroupBy   []model.LabelName
		outTimeField v32.TimingField
	}{
		{"event alert", eventRulesMap, eventGroupBy, eventTimingField},
		{"node alert", nodeRulesMap, nodeGroupBy, defaultTimingField},
		{"system service alert", systemServiceRulesMap, systemServiceGroupBy, defaultTimingField},
		{"metric alert", metricRulesMap, metricGroupBy, defaultTimingField},
	}
)

func TestAddClusterAlert2Config(t *testing.T) {

	for _, tt := range clusterAlertTests {
		keys := []string{groupID}
		config := manager.GetAlertManagerDefaultConfig()

		configSyncer := ConfigSyncer{
			clusterName: clusterName,
		}

		if err := configSyncer.addClusterAlert2Config(config, tt.in, keys, clusterGroupMap, notifiers); err != nil {
			t.Error(err)
			return
		}

		if len(config.Route.Routes) == 0 {
			t.Errorf("test %s failed, routes is empty", tt.caseName)
		}

		if len(config.Route.Routes[0].Routes) == 0 {
			t.Errorf("test %s failed, sub routes is empty", tt.caseName)
		}

		subRoute := config.Route.Routes[0].Routes[0]
		if !reflect.DeepEqual(subRoute.GroupBy, tt.outGroupBy) {
			t.Errorf("test %s failed, expect group by %v, actual %v", tt.caseName, tt.outGroupBy, subRoute.GroupBy)
		}

		if *subRoute.GroupWait != model.Duration(time.Duration(tt.outTimeField.GroupWaitSeconds)*time.Second) {
			t.Errorf("test %s failed, expect group wait %v, actual %v", tt.caseName, tt.outTimeField.GroupWaitSeconds, subRoute.GroupWait)
		}

		if *subRoute.GroupInterval != model.Duration(time.Duration(tt.outTimeField.GroupIntervalSeconds)*time.Second) {
			t.Errorf("test %s failed, expect group interval %v, actual %v", tt.caseName, tt.outTimeField.GroupIntervalSeconds, subRoute.GroupInterval)
		}

		if *subRoute.RepeatInterval != model.Duration(time.Duration(tt.outTimeField.RepeatIntervalSeconds)*time.Second) {
			t.Errorf("test %s failed, expect repeat interval %v, actual %v", tt.caseName, tt.outTimeField.RepeatIntervalSeconds, subRoute.RepeatInterval)
		}
	}

}

var (
	projectAlertTests = []struct {
		caseName     string
		in           map[string]map[string][]*v3.ProjectAlertRule
		outGroupBy   []model.LabelName
		outTimeField v32.TimingField
	}{
		{"pod alert", podRulesMap, podGroupBy, defaultTimingField},
		{"workload alert", workloadRulesMap, workloadGroupBy, defaultTimingField},
		{"metric alert", projectMetricRulesMap, projectMetricGroupBy, defaultTimingField},
	}
)

func TestAddProjectAlert2Config(t *testing.T) {

	for _, tt := range projectAlertTests {
		keys := []string{projectID}
		config := manager.GetAlertManagerDefaultConfig()

		configSyncer := ConfigSyncer{
			clusterName: clusterName,
		}

		if err := configSyncer.addProjectAlert2Config(config, tt.in, keys, projectGroupMap, notifiers); err != nil {
			t.Error(err)
			return
		}

		fmt.Println(config.String())

		if len(config.Route.Routes) == 0 {
			t.Errorf("test %s failed, routes is empty", tt.caseName)
		}

		if len(config.Route.Routes[0].Routes) == 0 {
			t.Errorf("test %s failed, sub routes is empty", tt.caseName)
		}

		subRoute := config.Route.Routes[0].Routes[0]
		if !reflect.DeepEqual(subRoute.GroupBy, tt.outGroupBy) {
			t.Errorf("test %s failed, expect group by %v, actual %v", tt.caseName, tt.outGroupBy, subRoute.GroupBy)
		}

		if *subRoute.GroupWait != model.Duration(time.Duration(tt.outTimeField.GroupWaitSeconds)*time.Second) {
			t.Errorf("test %s failed, expect group wait %v, actual %v", tt.caseName, tt.outTimeField.GroupWaitSeconds, subRoute.GroupWait)
		}

		if *subRoute.GroupInterval != model.Duration(time.Duration(tt.outTimeField.GroupIntervalSeconds)*time.Second) {
			t.Errorf("test %s failed, expect group interval %v, actual %v", tt.caseName, tt.outTimeField.GroupIntervalSeconds, subRoute.GroupInterval)
		}

		if *subRoute.RepeatInterval != model.Duration(time.Duration(tt.outTimeField.RepeatIntervalSeconds)*time.Second) {
			t.Errorf("test %s failed, expect repeat interval %v, actual %v", tt.caseName, tt.outTimeField.RepeatIntervalSeconds, subRoute.RepeatInterval)
		}
	}

}

var (
	clusterName = "testCluster"
	projectName = "testProject"
	projectID   = clusterName + ":" + projectName
	groupID     = "testcluster:testGroup"
	displayName = "test"
	serverity   = "critical"
	inherited   = false

	defaultTimingField = v32.TimingField{
		GroupWaitSeconds:      30,
		GroupIntervalSeconds:  180,
		RepeatIntervalSeconds: 3600,
	}

	commonRuleField = v32.CommonRuleField{
		DisplayName: displayName,
		Severity:    serverity,
		Inherited:   &inherited,
		TimingField: defaultTimingField,
	}

	alertStatus = v32.AlertStatus{
		AlertState: "active",
	}
)

var (
	commonGroupField = v32.CommonGroupField{
		DisplayName: displayName,
		TimingField: defaultTimingField,
	}

	clusterGroupMap = map[string]*v3.ClusterAlertGroup{
		groupID: &v3.ClusterAlertGroup{
			Spec: v32.ClusterGroupSpec{
				ClusterName:      clusterName,
				CommonGroupField: commonGroupField,
				Recipients:       recipients,
			},
			Status: alertStatus,
		},
	}

	projectGroupMap = map[string]*v3.ProjectAlertGroup{
		groupID: &v3.ProjectAlertGroup{
			Spec: v32.ProjectGroupSpec{
				ProjectName:      projectID,
				CommonGroupField: commonGroupField,
				Recipients:       recipients,
			},
			Status: alertStatus,
		},
	}
)

var (
	defaultChannel = "testChannel"
	slack          = "slack"
	namespace      = "cattle-alerting"
	notifiers      = []*v3.Notifier{
		{
			ObjectMeta: metav1.ObjectMeta{
				Name:      slack,
				Namespace: namespace,
			},
			Spec: v32.NotifierSpec{
				ClusterName: clusterName,
				DisplayName: displayName,
				SlackConfig: &v32.SlackConfig{
					DefaultRecipient: defaultChannel,
					URL:              "www.slack.com",
				},
			},
		},
	}

	recipients = []v32.Recipient{
		{
			Recipient:    defaultChannel,
			NotifierName: clusterName + ":" + slack,
			NotifierType: slack,
		},
	}
)

// event
var (
	name = "eventRule"

	podEventRule = v32.EventRule{
		EventType:    "normal",
		ResourceKind: "Pod",
	}

	eventTimingField = v32.TimingField{
		GroupWaitSeconds:      eventGroupWait,
		GroupIntervalSeconds:  eventGroupInterval,
		RepeatIntervalSeconds: eventRepeatInterval,
	}

	eventCommonRuleField = v32.CommonRuleField{
		DisplayName: displayName,
		Severity:    serverity,
		Inherited:   &inherited,
		TimingField: eventTimingField,
	}

	eventAlert = v3.ClusterAlertRule{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: namespace,
		},
		Spec: v32.ClusterAlertRuleSpec{
			ClusterName:     clusterName,
			GroupName:       groupID,
			CommonRuleField: eventCommonRuleField,
			EventRule:       &podEventRule,
		},
		Status: alertStatus,
	}

	eventRulesMap = map[string][]*v3.ClusterAlertRule{
		groupID: {
			&eventAlert,
		},
	}

	eventGroupBy = getClusterAlertGroupBy(eventAlert.Spec)
)

// node
var (
	nodeRule = v32.NodeRule{
		NodeName:  "node1",
		Condition: "notready",
	}

	nodeAlert = v3.ClusterAlertRule{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "nodeRule",
			Namespace: namespace,
		},
		Spec: v32.ClusterAlertRuleSpec{
			ClusterName:     clusterName,
			GroupName:       groupID,
			CommonRuleField: commonRuleField,
			NodeRule:        &nodeRule,
		},
		Status: alertStatus,
	}

	nodeRulesMap = map[string][]*v3.ClusterAlertRule{
		groupID: {
			&nodeAlert,
		},
	}

	nodeGroupBy = getClusterAlertGroupBy(nodeAlert.Spec)
)

// system service
var (
	systemServiceRule = v32.SystemServiceRule{
		Condition: "etcd",
	}

	systemServiceAlert = v3.ClusterAlertRule{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "systemServiceRule",
			Namespace: namespace,
		},
		Spec: v32.ClusterAlertRuleSpec{
			ClusterName:       clusterName,
			GroupName:         groupID,
			CommonRuleField:   commonRuleField,
			SystemServiceRule: &systemServiceRule,
		},
		Status: alertStatus,
	}

	systemServiceRulesMap = map[string][]*v3.ClusterAlertRule{
		groupID: {
			&systemServiceAlert,
		},
	}

	systemServiceGroupBy = getClusterAlertGroupBy(systemServiceAlert.Spec)
)

// metric
var (
	metricRule = v32.MetricRule{
		Expression:     `sum(node_load5) by (instance) / count(node_cpu_seconds_total{mode="system"})`,
		Duration:       "1m",
		Comparison:     "equal",
		ThresholdValue: 1,
	}

	metricAlert = v3.ClusterAlertRule{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "metricRule",
			Namespace: namespace,
		},
		Spec: v32.ClusterAlertRuleSpec{
			ClusterName:     clusterName,
			GroupName:       groupID,
			CommonRuleField: commonRuleField,
			MetricRule:      &metricRule,
		},
		Status: alertStatus,
	}

	metricRulesMap = map[string][]*v3.ClusterAlertRule{
		groupID: {
			&metricAlert,
		},
	}

	metricGroupBy = getClusterAlertGroupBy(metricAlert.Spec)
)

// pod
var (
	podRule = v32.PodRule{
		PodName:   "pod1",
		Condition: "notrunning",
	}

	podAlert = v3.ProjectAlertRule{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "podRule",
			Namespace: projectName,
		},
		Spec: v32.ProjectAlertRuleSpec{
			ProjectName:     projectID,
			GroupName:       groupID,
			CommonRuleField: commonRuleField,
			PodRule:         &podRule,
		},
		Status: alertStatus,
	}

	podRulesMap = map[string]map[string][]*v3.ProjectAlertRule{
		projectID: {
			groupID: {
				&podAlert,
			},
		},
	}

	podGroupBy = getProjectAlertGroupBy(podAlert.Spec)
)

// workload
var (
	workloadRule = v32.WorkloadRule{
		WorkloadID:          "workloadID1",
		AvailablePercentage: 50,
	}

	workloadAlert = v3.ProjectAlertRule{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "workloadRule",
			Namespace: projectName,
		},
		Spec: v32.ProjectAlertRuleSpec{
			ProjectName:     projectID,
			GroupName:       groupID,
			CommonRuleField: commonRuleField,
			WorkloadRule:    &workloadRule,
		},
		Status: alertStatus,
	}

	workloadRulesMap = map[string]map[string][]*v3.ProjectAlertRule{
		projectID: {
			groupID: {
				&workloadAlert,
			},
		},
	}

	workloadGroupBy = getProjectAlertGroupBy(workloadAlert.Spec)
)

// metric
var (
	projectMetricRule = v32.MetricRule{
		Expression: `sum(rate(container_cpu_user_seconds_total{container_name!="POD",namespace=~"cattle-alerting",pod_name=~"alert-manager",
			container_name!=""}[5m])) by (container_name)`,
		Duration:       "1m",
		Comparison:     "equal",
		ThresholdValue: 1,
	}

	projectMetricAlert = v3.ProjectAlertRule{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "metricRule",
			Namespace: projectName,
		},
		Spec: v32.ProjectAlertRuleSpec{
			ProjectName:     projectID,
			GroupName:       groupID,
			CommonRuleField: commonRuleField,
			MetricRule:      &projectMetricRule,
		},
		Status: alertStatus,
	}

	projectMetricRulesMap = map[string]map[string][]*v3.ProjectAlertRule{
		projectID: {
			groupID: {
				&projectMetricAlert,
			},
		},
	}

	projectMetricGroupBy = getProjectAlertGroupBy(projectMetricAlert.Spec)
)


text:
/* ---------------------------------------------------------------------------
 *
 *		Physical_Environment2D class - Michael Brandon Williams
 *
 *		Physical_Environment2D.h
 *
 * ---------------------------------------------------------------------------
 */

#ifndef _PHYSICAL_ENVIRONMENT2D_H
#define _PHYSICAL_ENVIRONMENT2D_H

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>

#include "NeHeGL.h"

#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glu32.lib")
#pragma comment (lib, "glaux.lib")

#include <cmath>
#include <assert.h>

#include "Kinematic_Object2D.h"
#include "Particle.h"
#include "Rigid_Body2D.h"

#include "Vector2D.h"
#include "Matrix2x2.h"
#include "Array.h"

#include "Force2D.h"
#include "Spring2D.h"

#include "Math_Extras.h"

// two indexes of the vertices of a rigid body that make up an edge
typedef int edge[2];

// determines if the physical environment is paused or not
enum PHYSICAL_ENVIRONMENT_STATUS
{
	PLAYING,
	PAUSED
};

class Physical_Environment2D
{
	public:

		// default constructor
		Physical_Environment2D ();

		// constructor for when you know the outside force in the environment
		Physical_Environment2D (float force_x, float force_y);
		Physical_Environment2D (const Vector2D &F);

		// constructor for when you know the gravitational constant of the environment
		Physical_Environment2D (float gravitational_constant);

		// constructor for when you know the bounds of the environment
		Physical_Environment2D (float right, float left, float up, float down);

		// constructor for when you know everything about the environment
		Physical_Environment2D (float force_x, float force_y, float right, float left, float up, float down, float gravitational_constant);
		Physical_Environment2D (const Vector2D &F, float right, float left, float up, float down, float gravitational_constant);

		// destructor
		virtual ~Physical_Environment2D ();

		// reset the integration time step of the environment
		void Reset_Integration_Step (float dt);

		// methods for adding primitives to the environment

		// adds a triangle to the environment
		void Add_Triangle_Body (float x, float y, float base, float height, float p);
		void Add_Triangle_Body (const Vector2D &C, float base, float height, float p);

		// adds a square to the environment
		void Add_Square_Body (float x, float y, float side, float p);
		void Add_Square_Body (const Vector2D &C, float side, float p);

		// adds a diamond to the environment
		void Add_Diamond_Body (float x, float y, float side, float p);
		void Add_Diamond_Body (const Vector2D &C, float side, float p);

		// adds a rectangle to the environment
		void Add_Rectangle_Body (float x, float y, float width, float height, float p);
		void Add_Rectangle_Body (const Vector2D &C, float width, float height, float p);

		// adds an n-gon to the environment
		void Add_NGon_Body (float x, float y, int n, float radius, float p);
		void Add_NGon_Body (const Vector2D &C, int n, float radius, float p);

		// change the outside force
		void Change_Outside_Force (float force_x, float force_y);
		void Change_Outside_Force (const Vector2D &V);

		// change the outside acceleration
		void Change_Outside_Acceleration (float acc_x, float acc_y);
		void Change_Outside_Acceleration (const Vector2D &A);

		// renders the physical environment
		void Render_Environment ();
		void Render_Environment (int num_turns, float turn_mag, bool draw_boxes, bool draw_forces);

		// change whether or not the environment is playing or paused
		void Play ();
		void Pause ();
		void Toggle_Status ();

		// adds a kinematic object to the environment
		void Add_Kinematic_Object ();
		void Add_Kinematic_Object (float center_x, float center_y);
		void Add_Kinematic_Object (const Vector2D &center);
		void Add_Kinematic_Object (const Kinematic_Object2D &K);

		// adds a particle to the environment
		void Add_Particle (float center_x, float center_y);
		void Add_Particle (const Vector2D &center);
		void Add_Particle (float particle_mass);
		void Add_Particle (float center_x, float center_y, float particle_mass);
		void Add_Particle (const Vector2D &center, float particle_mass);
		void Add_Particle (float center_x, float center_y, float particle_mass, float damping, float restitution);
		void Add_Particle (const Vector2D &center, float particle_mass, float damping, float restitution);
		void Add_Particle (const Particle &P);

		// adds a rigid body to the environment
		void Add_Rigid_Body ();
		void Add_Rigid_Body (float p);
		void Add_Rigid_Body (float center_x, float center_y);
		void Add_Rigid_Body (const Vector2D &center);
		void Add_Rigid_Body (float center_x, float center_y, float p);
		void Add_Rigid_Body (const Vector2D &center, float p);
		void Add_Rigid_Body (float p, float linear_damping, float angular_damping, float restitution);
		void Add_Rigid_Body (float center_x, float center_y, float p, float linear_damping, float angular_damping, float restitution);
		void Add_Rigid_Body (const Vector2D &center, float p, float linear_damping, float angular_damping, float restitution);
		void Add_Rigid_Body (const Rigid_Body2D &R);

		// adds a spring to the environment
		void Add_Spring ();
		void Add_Spring (float ks, float kd);
		void Add_Spring (int b1, float x1, float y1, SPRING_CONNECTIONS connection1,
						 int b2, float x2, float y2, SPRING_CONNECTIONS connection2);
		void Add_Spring (int b1, const Vector2D &p1, SPRING_CONNECTIONS connection1,
						 int b2, const Vector2D &p2, SPRING_CONNECTIONS connection2);
		void Add_Spring (int b1, float x1, float y1, SPRING_CONNECTIONS connection1,
						 int b2, float x2, float y2, SPRING_CONNECTIONS connection2, float length);
		void Add_Spring (int b1, const Vector2D &p1, SPRING_CONNECTIONS connection1,
						 int b2, const Vector2D &p2, SPRING_CONNECTIONS connection2, float length);
		void Add_Spring (float length);
		void Add_Spring (float length, float ks, float kd);
		void Add_Spring (int b1, float x1, float y1, SPRING_CONNECTIONS connection1,
						 int b2, float x2, float y2, SPRING_CONNECTIONS connection2,
						 float length, float ks, float kd);
		void Add_Spring (int b1, const Vector2D &p1, SPRING_CONNECTIONS connection1,
						 int b2, const Vector2D &p2, SPRING_CONNECTIONS connection2,
						 float length, float ks, float kd);
		void Add_Spring (int b1, int v1, SPRING_CONNECTIONS connection1,
						 int b2, int v2, SPRING_CONNECTIONS connection2);
		void Add_Spring (int b1, int v1, SPRING_CONNECTIONS connection1,
						 int b2, int v2, SPRING_CONNECTIONS connection2, float length);
		void Add_Spring (int b1, int v1, SPRING_CONNECTIONS connection1,
						 int b2, int v2, SPRING_CONNECTIONS connection2,
						 float length, float ks, float kd);

		// changes the properties of the nth kinematic object
		void Kinematic_Reset_Position (int n, const float x, const float y);
		void Kinematic_Reset_Position (int n, const Vector2D &pos);
		void Kinematic_Reset_Orientation (int n, const float rotation);
		void Kinematic_Reset_Velocity (int n, const float vel_x, const float vel_y);
		void Kinematic_Reset_Velocity (int n, const Vector2D &vel);
		void Kinematic_Reset_Acceleration (int n, const float acc_x, const float acc_y);
		void Kinematic_Reset_Acceleration (int n, const Vector2D &acc);
		void Kinematic_Reset_Angular_Velocity (int n, const float omega);
		void Kinematic_Reset_Angular_Acceleration (int n, const float alpha);

		// changes the properties of the nth particle
		void Particle_Reset_State (int n, enum PARTICLE_TYPE new_state);
		void Particle_Add_Force (int n, const Vector2D &F);
		void Particle_Add_Force (int n, float force_x, float force_y);
		void Particle_Reset_Force_Vector (int n, int f, const Vector2D &F);
		void Particle_Reset_Force_Vector (int n, int f, float force_x, float force_y);
		void Particle_Remove_Force (int n, int f);
		void Particle_Reset_Mass (int n, float m);
		void Particle_Reset_Position (int n, float x, float y);
		void Particle_Reset_Position (int n, const Vector2D &pos);
		void Particle_Reset_Velocity (int n, float vel_x, float vel_y);
		void Particle_Reset_Velocity (int n, const Vector2D &vel);
		void Particle_Reset_Collision_State (int n, enum PARTICLE_COLLISION_TYPE new_state);

		// changes the properties of the nth rigid body
		void Body_Reset_State (int n, enum RIGID_BODY_TYPE new_state);
		void Body_Add_Force (int n, const Force2D &F);
		void Body_Add_Force (int n, float force_x, float force_y, float position_x, float position_y, ID_TAG system);
		void Body_Add_Force (int n, const Vector2D &F, const Vector2D &P, ID_TAG system);
		void Body_Reset_Force (int n, int f, const Force2D &F);
		void Body_Reset_Force_Vector (int n, int f, const Vector2D &F);
		void Body_Reset_Force_Vector (int n, int f, float force_x, float force_y);
		void Body_Reset_Force_Position (int n, int f, const Vector2D &P);
		void Body_Reset_Force_Position (int n, int f, float position_x, float position_y);
		void Body_Reset_Force_ID (int n, int f, ID_TAG system);
		void Body_Add_Vertex_Before (int n, int v, float x, float y);
		void Body_Add_Vertex_Before (int n, int v, const Vector2D &V);
		void Body_Add_Vertex_After (int n, int v, float x, float y);
		void Body_Add_Vertex_After (int n, int v, const Vector2D &V);
		void Body_Push_Vertex (int n, float x, float y);
		void Body_Push_Vertex (int n, const Vector2D &V);
		void Body_Remove_Vertices (int n, int v, int num);
		void Body_Reset_Vertex (int n, int v, float x, float y);
		void Body_Reset_Vertex (int n, int v, const Vector2D &V);
		void Body_Reset_Density (int n, float p);
		void Body_Reset_Position (int n, float x, float y);
		void Body_Reset_Position (int n, const Vector2D &pos);
		void Body_Reset_Orientation (int n, float rotation);
		void Body_Reset_Velocity (int n, float vel_x, float vel_y);
		void Body_Reset_Velocity (int n, const Vector2D &vel);
		void Body_Reset_Angular_Velocity (int n, float omega);
		void Body_Reset_Linear_Damping (int n, float ld);
		void Body_Reset_Angular_Damping (int n, float ad);
		void Body_Reset_Restitution (int n, float r);
		void Body_Reset_Collision_State (int n, enum RIGID_BODY_COLLISION_TYPE new_state);

		// changes the properties of the nth spring
		void Remove_Spring (int n);
		void Spring_Reset_Body1 (int n, int body1);
		void Spring_Reset_Body2 (int n, int body2);
		void Spring_Reset_Vertex1 (int n, int vertex1);
		void Spring_Reset_Vertex2 (int n, int vertex2);
		void Spring_Reset_Vertex1 (int n, float x, float y);
		void Spring_Reset_Vertex1 (int n, const Vector2D &V);
		void Spring_Reset_Vertex2 (int n, float x, float y);
		void Spring_Reset_Vertex2 (int n, const Vector2D &V);
		void Spring_Reset_Connection1 (int n, SPRING_CONNECTIONS connection1);
		void Spring_Reset_Connection2 (int n, SPRING_CONNECTIONS connection2);
		void Spring_Reset_Length (int n, float length);
		void Spring_Reset_Constant (int n, float ks);
		void Spring_Reset_Damping (int n, float kd);

		// integrates system over a time step to find the newest positions of the objects
		void Simulate ();

	//private:

		// integration methods
		void Euler_Integrate ();

		// totals up all forces and calculates the acceleration of every particle and rigid body
		void Calculate_Accelerations ();

		// handles all the forces acting in the system
		void Reset_Forces ();
		void Calculate_Particle_Forces ();
		void Calculate_Rigid_Body_Forces ();
		void Calculate_Spring_Forces ();
		void Calculate_Gravitational_Forces ();
		void Calculate_Total_Forces ();

		// does the collision detection and handling for the entire environment
		void Environment_Collision_Check ();
		inline bool Body_Body_Bounding_Box_Test (int j, int k);
		inline bool Point_Body_Bounding_Box_Test (const Vector2D &V, int n);
		inline int  Body_Body_Collision_Test (int j, int k);
		inline bool Point_Body_Collision_Test (const Vector2D &V, int n);
		inline bool Body_Edge_Intersection_Test (int j, int k);
		inline Array<int>  Find_Colliding_Vertex (int j, int k);
		Array<int>  Find_Colliding_Edge (const Vector2D &V, int n);

		void Body_Body_Collision_Handle (int j, int k, const Vector2D &N, const Vector2D &P);

		// list of kinematic objects in the environment
		Array <Kinematic_Object2D> kinematic_object_list;

		// list of particles in the environment
		Array <Particle> particle_list;

		// list of rigid bodies in the environment
		Array <Rigid_Body2D> rigid_body_list;

		// list of springs acting on the particles and rigid bodies in the environment
		Array <Spring2D> spring_list;

		// an outside force acting on the entire system
		Vector2D outside_force;

		// acceleration due to outside forces in the environment (for accelerations that
		// you do not want to depend on mass)
		Vector2D outside_acceleration;

		// gravitational constant of the environment
		float G;

		// boundaries of the environment
		float left_bound, right_bound, upper_bound, lower_bound;

		// determines if the physical environment is paused or not
		PHYSICAL_ENVIRONMENT_STATUS environment_status;

		// integration time step of the environment
		float delta_t;

		bool collision_occuring;
};

#endif


text:
import unittest
import json

from mock import Mock, patch

import pyeapi.eapilib

class TestEapiConnection(unittest.TestCase):

    def test_execute_valid_response(self):
        response_dict = dict(jsonrpc='2.0', result=[], id=id(self))
        mock_send = Mock(name='send')
        mock_send.return_value = json.dumps(response_dict)

        instance = pyeapi.eapilib.EapiConnection()
        instance.send = mock_send

        result = instance.execute(['command'])
        self.assertEqual(json.loads(result), response_dict)

    def test_execute_raises_type_error(self):
        instance = pyeapi.eapilib.EapiConnection()
        with self.assertRaises(TypeError):
            instance.execute(None, encoding='invalid')

    def test_execute_raises_connection_error(self):
        mock_send = Mock(name='send')
        mock_send.side_effect = pyeapi.eapilib.ConnectionError('test', 'test')

        instance = pyeapi.eapilib.EapiConnection()
        instance.send = mock_send

        with self.assertRaises(pyeapi.eapilib.ConnectionError):
            instance.execute('test')

    def test_execute_raises_command_error(self):
        mock_send = Mock(name='send')
        mock_send.side_effect = pyeapi.eapilib.CommandError('1000', 'test')

        instance = pyeapi.eapilib.EapiConnection()
        instance.send = mock_send

        with self.assertRaises(pyeapi.eapilib.CommandError):
            instance.execute('test')

    def test_create_socket_connection(self):
        instance = pyeapi.eapilib.SocketEapiConnection()
        self.assertIsInstance(instance, pyeapi.eapilib.EapiConnection)
        self.assertIsNotNone(str(instance.transport))

    @patch('pyeapi.eapilib.socket')
    def test_socket_connection_create(self, mock_socket):
        instance = pyeapi.eapilib.SocketConnection('/path/to/sock')
        instance.connect()
        mock_socket.socket.return_value.connect.assert_called_with('/path/to/sock')

    def test_create_http_local_connection(self):
        instance = pyeapi.eapilib.HttpLocalEapiConnection()
        self.assertIsInstance(instance, pyeapi.eapilib.EapiConnection)
        self.assertIsNotNone(str(instance.transport))

    def test_create_http_connection(self):
        instance = pyeapi.eapilib.HttpEapiConnection('localhost')
        self.assertIsInstance(instance, pyeapi.eapilib.EapiConnection)
        self.assertIsNotNone(str(instance.transport))

    def test_create_https_connection(self):
        instance = pyeapi.eapilib.HttpsEapiConnection('localhost')
        self.assertIsInstance(instance, pyeapi.eapilib.EapiConnection)
        self.assertIsNotNone(str(instance.transport))

    def test_send(self):
        response_dict = dict(jsonrpc='2.0', result=[{}], id=id(self))
        response_json = json.dumps(response_dict)

        mock_transport = Mock(name='transport')
        mockcfg = {'getresponse.return_value.read.return_value': response_json}
        mock_transport.configure_mock(**mockcfg)

        instance = pyeapi.eapilib.EapiConnection()
        instance.transport = mock_transport
        instance.send('test')

        self.assertTrue(mock_transport.close.called)

    def test_send_with_authentication(self):
        response_dict = dict(jsonrpc='2.0', result=[{}], id=id(self))
        response_json = json.dumps(response_dict)

        mock_transport = Mock(name='transport')
        mockcfg = {'getresponse.return_value.read.return_value': response_json}
        mock_transport.configure_mock(**mockcfg)

        instance = pyeapi.eapilib.EapiConnection()
        instance.authentication('username', 'password')
        instance.transport = mock_transport
        instance.send('test')

        self.assertTrue(mock_transport.close.called)

    def test_send_raises_connection_error(self):
        mock_transport = Mock(name='transport')
        mockcfg = {'getresponse.return_value.read.side_effect': ValueError}
        mock_transport.configure_mock(**mockcfg)

        instance = pyeapi.eapilib.EapiConnection()
        instance.transport = mock_transport

        with self.assertRaises(pyeapi.eapilib.ConnectionError):
            instance.send('test')

    def test_send_raises_command_error(self):
        error = dict(code=9999, message='test', data=[{'errors': ['test']}])
        response_dict = dict(jsonrpc='2.0', error=error, id=id(self))
        response_json = json.dumps(response_dict)

        mock_transport = Mock(name='transport')
        mockcfg = {'getresponse.return_value.read.return_value': response_json}
        mock_transport.configure_mock(**mockcfg)

        instance = pyeapi.eapilib.EapiConnection()
        instance.transport = mock_transport

        with self.assertRaises(pyeapi.eapilib.CommandError):
            instance.send('test')

class TestCommandError(unittest.TestCase):

    def test_create_command_error(self):
        result = pyeapi.eapilib.CommandError(9999, 'test')
        self.assertIsInstance(result, pyeapi.eapilib.EapiError)

    def test_command_error_trace(self):
        commands = ['test command', 'test command', 'test command']
        output = [{}, 'test output']
        result = pyeapi.eapilib.CommandError(9999, 'test', commands=commands,
                                             output=output)
        self.assertIsNotNone(result.trace)


text:
		{{Strings.MANAGE_SERVERS}}

		{{Strings.DB_COMPARE}}

		{{Strings.CONNECT_TO}}

		{{Strings.DISCONNECT_FROM}}

		{{Strings.DISCONNECT_ALL}}

		{{Strings.SET_EDITOR_CONNECTION}}

		{{Strings.EXECUTE_CURRENT_SELECTION}}

		{{Strings.EXECUTE_CURRENT_FILE}}

			{{BROWSER_PANEL_ACTION}} {{Strings.BROWSER_PANEL}}

		{{Strings.RESULT_SETS}}

{{Strings.CLEAR_RESULT_SETS}}

{{PANEL_ACTION}} {{Strings.RESULT_PANEL}}

		{{Strings.LOGS}}

{{Strings.CLEAR_LOG}}

{{Strings.VIEW_LOG}}

		{{Strings.MODIFICATIONS}}

				{{Strings.CLEAR_MODIFICATIONS}}

				{{Strings.VIEW_MODIFICATIONS}}

				{{Strings.VIEW_MODIFICATIONS_SCRIPT}}

			{{Strings.CLOSE}}
			×


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".opening_screen"
    android:weightSum="1"
    >

    <ImageView
        android:id="@+id/imageview_main_activity_name_tag"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/vr_uncle"
        />
</LinearLayout>


text:
require "rspec"

RSpec.describe "Google::Apis::RemotebuildexecutionV2" do
  # Minimal test just to ensure no syntax errors in generated code
  it "should load" do
    expect do
      require "google/apis/remotebuildexecution_v2"
    end.not_to raise_error
    expect do
      Google::Apis::RemotebuildexecutionV2::RemoteBuildExecutionService.new
    end.not_to raise_error
  end
end


text:
package O2::Obj::Object::Query;

use strict;

use base 'O2::Obj::Object';

use O2 qw($context $db);
use O2::Util::List qw(upush);
use Time::HiRes    qw(gettimeofday);

#-----------------------------------------------------------------------------
sub searchArchiveToo {
  my ($obj) = @_;
  return $obj->getSearchArchiveToo();
}
#-----------------------------------------------------------------------------
sub setOrderBy {
  my ($obj, $value) = @_;

  # Validate:
  if ($value ne '_random') {
    my @parts = split /\s*,\s*/, $value;
    foreach my $part (@parts) {
      my ($fieldName, $sortDirection) = $part =~ m{ \A (\w+) (?: \s+ (\w+) )? \z }xms;
      die "Invalid 'orderBy' value ($value)" unless $fieldName;
      die "Invalid sort direction ($sortDirection) in orderBy ($part)" if $sortDirection && $sortDirection !~ m{ \A asc | desc \z }xms;
      eval {
        $obj->_getSearchMgr()->getModel()->getFieldByName($fieldName);
      };
      die "Invalid 'sortBy' value ($value): $@" if $@;
    }
  }
  $obj->setModelValue('orderBy', $value);
}
#-----------------------------------------------------------------------------
sub getOrderBySql {
  my ($obj) = @_;
  my $orderBy = $obj->getModelValue('orderBy');
  return $orderBy unless $orderBy;
  return 'rand()'     if $orderBy eq '_random';

  my $orderBySql = '';
  my @parts = split /\s*,\s*/, $orderBy;
  foreach my $part (@parts) {
    my ($fieldName, $sortDirection) = $part =~ m{ \A (\w+) (?: \s+ (\w+) )? \z }xms;
    die "Didn't understand '$part' in 'orderBy' attribute" unless $fieldName;

    $sortDirection = '' unless defined $sortDirection;
    my $field = $obj->_getSearchMgr()->getModel()->getFieldByName($fieldName);
    $orderBySql .= $field->getTableName() . '.' . $field->getTableFieldName() . " $sortDirection, ";
  }
  return substr $orderBySql, 0, -2;
}
#-----------------------------------------------------------------------------
sub setClassNameByManagerClassName {
  my ($obj, $mgrClassName) = @_;
  my $className = $context->getUniversalMgr()->managerClassNameToObjectClassName($mgrClassName);
  $obj->setClassName($className);
}
#-----------------------------------------------------------------------------
sub addUnionQuery {
  my ($obj, $query) = @_;
  if ($obj->getUnionQuery()) {
    $obj->getUnionQuery()->addUnionQuery($query);
  }
  else {
    $obj->setUnionQuery($query);
  }
}
#-----------------------------------------------------------------------------
sub newConditionGroup {
  my ($obj) = @_;
  my $conditionGroup = $context->getSingleton('O2::Mgr::Object::Query::ConditionGroupManager')->newObject();
  $conditionGroup->{query} = $obj; # Link back to query object, so we can find the condition group's query object even when the condition group isn't saved
  my @conditionGroups = $obj->getConditionGroups();
  $obj->setConditionGroups(@conditionGroups, $conditionGroup);
  return $conditionGroup;
}
#-----------------------------------------------------------------------------
sub getSql {
  my ($obj, %params) = @_;
  my $whatToSelect = $params{whatToSelect} || 'distinct(O2_OBJ_OBJECT.objectId)';
  my $unionQuery = $obj->getUnionQuery();
  my $orderBySql = $obj->getOrderBySql();
  if ($unionQuery || $params{isUnionQuery}) {
    my $orderByFields = $orderBySql;
    $orderByFields =~ s{ asc | desc }{}xmsg;
    $whatToSelect .= ", $orderByFields" if $orderByFields;
  }

  my @usedTables = $obj->getUsedTables();
  my $sql = sprintf "select $whatToSelect from %s where ", join ', ', @usedTables;

  # Join on objectId:
  my $joinSql = '';
  for (my $i = 0; $i < @usedTables-1; $i++) {
    $joinSql .= 'and ' if $i > 0;
    $joinSql .= "$usedTables[$i].objectId = $usedTables[$i+1].objectId ";
  }
  $sql .= $joinSql if $joinSql;

  my (@placeHolders, @subSqls);

  foreach my $conditionGroup ($obj->getConditionGroups()) {
    my ($_sql, @_placeHolders) = $conditionGroup->getSql();
    next unless $_sql;

    push @subSqls,      $_sql;
    push @placeHolders, @_placeHolders;
  }

  my $joinWith = $obj->getJoinWith();
  my $includeParentheses = $joinSql && @subSqls >= 2 && $joinWith eq 'or';
  $sql .= 'and ' if $joinSql && @subSqls;
  $sql .= '('    if $includeParentheses;
  $sql .= join " $joinWith ", @subSqls;
  $sql .= ')'    if $includeParentheses;

  if ($unionQuery) {
    my ($_sql, @_placeHolders) = $unionQuery->getSql(isUnionQuery => 1);
    $orderBySql =~ s{ \w+ [.] }{}xmsg;
    my $alias = $context->getSingleton('O2::Util::Password')->generatePassword(8); # An alias is required in the "union" query
    $sql  = "select objectId from ($sql union $_sql) as $alias";
    $sql .= " order by $orderBySql" if $orderBySql;
    push @placeHolders, @_placeHolders;
  }
  elsif (!$params{isUnionQuery} && $orderBySql) {
    $sql .= " order by $orderBySql";
  }

  return ($sql, @placeHolders);
}
#-----------------------------------------------------------------------------
sub getMin {
  my ($obj, $fieldName) = @_;
  die 'getMin: field name is required' unless $fieldName;

  my ($sql, @placeHolders) = $obj->getSql( whatToSelect => $obj->_getWhatToSelect('min', $fieldName) );
  warn $sql if $obj->getDebug();

  my $t0 = gettimeofday();
  my $min = $db->fetch($sql, @placeHolders);
  my $dt = gettimeofday() - $t0;
  warn "Min is $min. It took $dt seconds" if $obj->getDebug();

  return $min;
}
#-----------------------------------------------------------------------------
sub getMax {
  my ($obj, $fieldName) = @_;
  die 'getMax: field name is required' unless $fieldName;

  my ($sql, @placeHolders) = $obj->getSql( whatToSelect => $obj->_getWhatToSelect('max', $fieldName) );
  warn $sql if $obj->getDebug();

  my $t0 = gettimeofday();
  my $max = $db->fetch($sql, @placeHolders);
  my $dt = gettimeofday() - $t0;
  warn "Max is $max. It took $dt seconds" if $obj->getDebug();

  return $max;
}
#-----------------------------------------------------------------------------
sub getCount {
  my ($obj) = @_;
  my ($sql, @placeHolders) = $obj->getSql(whatToSelect => 'count(*)');
  warn $sql if $obj->getDebug();

  my $t0 = gettimeofday();
  my $count = $db->fetch($sql, @placeHolders);
  my $dt = gettimeofday() - $t0;
  warn "Count is $count. It took $dt seconds" if $obj->getDebug();

  return $count;
}
#-----------------------------------------------------------------------------
sub _getWhatToSelect {
  my ($obj, $type, $fieldName) = @_;
  my $field = $obj->_getSearchMgr()->getModel()->getFieldByName($fieldName);
  $obj->addUsedTables( $field->getTableName() );
  return $type . '(' . $field->getTableName() . '.' . $field->getTableFieldName() . ')';
}
#-----------------------------------------------------------------------------
sub getDistinct {
  my ($obj, $fieldName) = @_;
  my ($sql, @placeHolders) = $obj->getSql( whatToSelect => $obj->_getWhatToSelect('distinct', $fieldName) );
  warn $sql if $obj->getDebug();

  my $t0 = gettimeofday();
  my @values = $db->selectColumn($sql, @placeHolders);
  my $dt = gettimeofday() - $t0;
  warn scalar (@values) . " results. It took $dt seconds" if $obj->getDebug();

  return @values;
}
#-----------------------------------------------------------------------------
sub getDistinctSql {
  my ($obj, $fieldName) = @_;
  my $field = $obj->_getSearchMgr()->getModel()->getFieldByName($fieldName);
  return $obj->getSql( whatToSelect => 'distinct(' . $field->getTableName() . '.' . $field->getTableFieldName() . ')' );
}
#-----------------------------------------------------------------------------
sub addUsedTables {
  my ($obj, @tableNames) = @_;
  my @usedTables = @{ $obj->{usedTables} || [] };
  upush @usedTables, @tableNames;
  $obj->{usedTables} = \@usedTables;
}
#-----------------------------------------------------------------------------
sub getUsedTables {
  my ($obj) = @_;
  my $tableName  = $obj->getManager()->_classNameToTableName( $obj->getClassName() );
  my @tableNames = @{ $obj->{usedTables} || [] };
  upush @tableNames, $tableName;
  foreach my $conditionGroup ($obj->getConditionGroups()) {
    upush @tableNames, $conditionGroup->getUsedTables();
  }
  return @tableNames;
}
#-----------------------------------------------------------------------------
sub getObjectIds {
  my ($obj, %params) = @_;
  my ($sql, @placeHolders) = $obj->getSql();
  if ($params{useArchiveDbh}) {
    warn "Using archive database for the next query" if $obj->getDebug();
    $context->useArchiveDbh();
  }
  warn $db->_expandPH($sql, @placeHolders) if $obj->getDebug();
  my $t0 = gettimeofday();
  my @objectIds = $db->selectColumn($sql, @placeHolders);
  $context->usePreviousDbh() if $params{useArchiveDbh};
  my $dt = gettimeofday() - $t0;
  warn "It took $dt seconds. " . scalar(@objectIds) . ' results' if $obj->getDebug();

  @objectIds = $obj->_filterObjectIds(\@objectIds);

  $obj->_setTotalNumSearchResults( scalar @objectIds );
  my $skip  = $obj->getSkip();
  my $limit = $obj->getLimit();
  splice @objectIds, 0, $skip if $skip;
  splice @objectIds, $limit   if $limit && @objectIds > $limit;
  if ($obj->searchArchiveToo() && !$params{useArchiveDbh}) {
    my @moreObjectIds = $obj->getObjectIds(useArchiveDbh => 1);
    push @objectIds, @moreObjectIds;
  }
  return wantarray ? @objectIds : \@objectIds;
}
#-----------------------------------------------------------------------------
sub getObjects {
  my ($obj) = @_;
  my @objectIds = $obj->getObjectIds();
  my @objects;
  foreach my $id (@objectIds) {
    my $object = $context->getObjectById($id) || $context->getUniversalMgr()->getTrashedObjectById($id);
    push @objects, $object if $object;
  }
  return wantarray ? @objects : \@objects;
}
#-----------------------------------------------------------------------------
sub getTotalNumSearchResults { # Can be called after objectSearch or objectIdSearch
  my ($obj) = @_;
  return $obj->{objectSearchTotalNumResults};
}
#-----------------------------------------------------------------------------
sub _setTotalNumSearchResults {
  my ($obj, $numResults) = @_;
  $obj->{objectSearchTotalNumResults} = $numResults;
}
#-----------------------------------------------------------------------------
sub _filterObjectIds {
  my ($obj, $objectIds) = @_;
  my @objectIds = @{$objectIds};

  if (my $condition = $obj->getInFolderCondition()) {
    warn "Filtering search results with -ancestorId" if $obj->getDebug();
    my $t0 = gettimeofday();
    my $operator = $condition->getOperator();
    if ($operator ne '=' && $operator ne '!=' && $operator ne 'in' && $operator ne 'not in') {
      die "Invalid operator $operator for -ancestorId";
    }

    my (@validIds, @invalidIds);
    my @conditionValues = $condition->can('getValue') ? ($condition->getValue()) : $condition->getValues();
    foreach my $id (@objectIds) {
    CONDITION_VALUE:
      foreach my $conditionValue (@conditionValues) {
        if ($operator eq '=' || $operator eq 'in') {
          if ($obj->_idHasOtherIdAsAncestor($id, $conditionValue)) {
            push @validIds, $id;
            last CONDITION_VALUE;
          }
        }
        elsif ($operator eq '!=') {
          if (!$obj->_idHasOtherIdAsAncestor($id, $conditionValue)) {
            push @validIds, $id;
            last CONDITION_VALUE;
          }
        }
        elsif ($operator eq 'not in') {
          if ($obj->_idHasOtherIdAsAncestor($id, $conditionValue)) {
            push @invalidIds, $id;
            last CONDITION_VALUE;
          }
        }
      }
    }

    if ($operator eq 'not in') {
      my %ids = map { $_ => 1 } @objectIds;
      foreach my $id (@invalidIds) {
        delete $ids{$id};
      }
      @validIds = keys %ids;
    }

    my $dt = gettimeofday() - $t0;
    my $numRemoved = @{$objectIds} - @validIds;
    @{$objectIds} = @validIds;
    warn "Filtering took $dt seconds. Filtered away $numRemoved IDs, " . scalar (@validIds) . ' results left' if $obj->getDebug();
  }
  return @{$objectIds};
}
#-----------------------------------------------------------------------------
sub _idHasOtherIdAsAncestor {
  my ($obj, $id, $otherId) = @_;
  $obj->{parentIds} ||= {};
  my $parentId = $obj->{parentIds}->{$id} = exists $obj->{parentIds}->{$id} ? $obj->{parentIds}->{$id} : $db->fetch("select parentId from O2_OBJ_OBJECT where objectId = ?", $id);
  return 1 if $parentId == $otherId;
  while ($parentId) {
    my $newParentId = exists $obj->{parentIds}->{$parentId} ? $obj->{parentIds}->{$parentId} : $db->fetch("select parentId from O2_OBJ_OBJECT where objectId = ?", $parentId);
    return 1 if $newParentId && $newParentId == $otherId;
    $obj->{parentIds}->{$parentId} ||= $newParentId;
    $parentId = $newParentId;
  }
  return 0;
}
#-----------------------------------------------------------------------------
sub deletePermanently {
  my ($obj) = @_;
  foreach my $conditionGroup ($obj->getConditionGroups()) {
    $conditionGroup->deletePermanently();
  }
  $obj->SUPER::deletePermanently();
}
#-----------------------------------------------------------------------------
sub delete {
  my ($obj) = @_;
  foreach my $conditionGroup ($obj->getConditionGroups()) {
    $conditionGroup->delete();
  }
  $obj->SUPER::delete();
}
#-----------------------------------------------------------------------------
sub isEmpty {
  my ($obj) = @_;
  my @conditionGroups = $obj->getConditionGroups();
  return 0 if @conditionGroups;
  return $obj->getInFolderCondition() ? 0 : 1;
}
#-----------------------------------------------------------------------------
sub getManagerClassName {
  my ($obj) = @_;
  return $context->getUniversalMgr()->objectClassNameToManagerClassName( $obj->getClassName() );
}
#-----------------------------------------------------------------------------
sub _getSearchMgr {
  my ($obj) = @_;
  my $mgrClass = $context->getUniversalMgr()->objectClassNameToManagerClassName( $obj->getClassName() );
  return $context->getSingleton($mgrClass);
}
#-----------------------------------------------------------------------------
1;


text:
<?php

declare(strict_types=1);

namespace app\exceptions;

class CurlException extends \RuntimeException {
    public function __construct($curl_handle, $curl_return) {
        if ($curl_return === false) {
            parent::__construct("cURL error " . curl_error($curl_handle));
        }
        else {
            $http_code = curl_getinfo($curl_handle, CURLINFO_RESPONSE_CODE);
            parent::__construct("Invalid HTTP Code {$http_code}.");
        }
    }
}


text:
//
//  CouchbaseListenerContext.cs
//
//  Author:
//  	Jim Borden  <jim.borden@couchbase.com>
//
//  Copyright (c) 2015 Couchbase, Inc All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;

using Couchbase.Lite.Replicator;
using Couchbase.Lite.Util;

namespace Couchbase.Lite.Listener
{

    /// <summary>
    /// A base class implementation of ICouchbaseListenerContext, for common logic like
    /// parsing URLs
    /// </summary>
    public abstract class CouchbaseListenerContext : ICouchbaseListenerContext2
    {

        #region Constants

        private static readonly string Tag = typeof(CouchbaseListenerContext).Name;

        #endregion

        #region Variables

        private string[] _urlComponents;                    // The URL split by slashes
        private string _viewPrefix = String.Empty;          // The prefix to add to the view (_local or _design)
        private QueryOptions _queryOptions;                 // The options of the HTTP URL query (i.e. stuff after the '?')
        private DocumentContentOptions? _contentOptions;    // The content options specified in the URL query
        private ChangesFeedMode? _changesFeedMode;          // The changes feed mode specified in the URL query

        #endregion

        #region Properties
#pragma warning disable 1591

        // ICouchbaseListenerContext2
        public bool IsLoopbackRequest { get;  set; }

        // ICouchbaseListenerContext2
        public Uri Sender { get; set; }

        // ICouchbaseListenerContext
        public Manager DbManager { get; private set; }

        // ICouchbaseListenerContext
        public string DatabaseName {
            get {
                //Must do this twice because Unity3D requires double escaping of encoded slashes in URL
                var name = Uri.UnescapeDataString(Uri.UnescapeDataString(UrlComponentAt(0)));
                if (!Manager.IsValidDatabaseName(name)) {
                    throw Misc.CreateExceptionAndLog(Log.To.Listener, StatusCode.BadId, Tag,
                        "Invalid database name ({0}) requested", name);
                }

                return name;
            }
        }

        // ICouchbaseListenerContext
        public string DocumentName {
            get {
                if(String.IsNullOrEmpty(_viewPrefix)) {
                    return UrlComponentAt(1);
                }

                return _viewPrefix + UrlComponentAt(2);
            }
        }

        // ICouchbaseListenerContext
        public string AttachmentName {
            get {
                int startPos = !String.IsNullOrEmpty(_viewPrefix) ? 3 : 2;
                return String.Join("/", _urlComponents, startPos, _urlComponents.Length - startPos);
            }
        }

        // ICouchbaseListenerContext
        public string DesignDocName
        {
            get {
                if (UrlComponentAt(1).Equals("_design")) {
                    return UrlComponentAt(2);
                }

                return null;
            }
        }

        // ICouchbaseListenerContext
        public string ViewName
        {
            get {
                if (UrlComponentAt(1).Equals("_design")) {
                    return UrlComponentAt(4);
                }

                return null;
            }
        }

        // ICouchbaseListenerContext
        public QueryOptions QueryOptions {
            get {
                if (_queryOptions != null) {
                    return _queryOptions;
                }

                _queryOptions = new QueryOptions();
                _queryOptions.Skip = GetQueryParam<int>("skip", int.TryParse, _queryOptions.Skip);
                _queryOptions.Limit = GetQueryParam<int>("limit", int.TryParse, _queryOptions.Limit);
                _queryOptions.GroupLevel = GetQueryParam<int>("group_level", int.TryParse, _queryOptions.GroupLevel);
                _queryOptions.Descending = GetQueryParam<bool>("descending", bool.TryParse, _queryOptions.Descending);
                _queryOptions.IncludeDocs = GetQueryParam<bool>("include_docs", bool.TryParse, _queryOptions.IncludeDocs);
                if (GetQueryParam<bool>("include_deleted", bool.TryParse, false)) {
                    _queryOptions.AllDocsMode = AllDocsMode.IncludeDeleted;
                } else if (GetQueryParam<bool>("include_conflicts", bool.TryParse, false)) { //non-standard
                    _queryOptions.AllDocsMode = AllDocsMode.ShowConflicts;
                } else if(GetQueryParam<bool>("only_conflicts", bool.TryParse, false)) { //non-standard
                    _queryOptions.AllDocsMode = AllDocsMode.OnlyConflicts;
                }

                _queryOptions.UpdateSeq = GetQueryParam<bool>("update_seq", bool.TryParse, false);
                _queryOptions.InclusiveEnd = GetQueryParam<bool>("inclusive_end", bool.TryParse, _queryOptions.InclusiveEnd);
                _queryOptions.InclusiveStart = GetQueryParam<bool>("inclusive_start", bool.TryParse, _queryOptions.InclusiveStart); // non-standard
                _queryOptions.PrefixMatchLevel = GetQueryParam<int>("prefix_match_level", int.TryParse, _queryOptions.PrefixMatchLevel); // non-standard
                _queryOptions.ReduceSpecified = GetQueryParam("reduce") != null;
                _queryOptions.Reduce = GetQueryParam<bool>("reduce", bool.TryParse, false);
                _queryOptions.Group = GetQueryParam<bool>("group", bool.TryParse, false);
                _queryOptions.ContentOptions = ContentOptions;

                // Stale options (ok or update_after):
                string stale = GetQueryParam("stale");
                if(stale != null) {
                    if (stale.Equals("ok")) {
                        _queryOptions.Stale = IndexUpdateMode.Never;
                    } else if (stale.Equals("update_after")) {
                        _queryOptions.Stale = IndexUpdateMode.After;
                    } else if(!stale.Equals("false")) {
                        Log.To.Router.W(Tag, $"Unrecognized stale option '{stale}', returning null...");
                        return null;
                    }
                }

                IList<object> keys = null;
                try {
                    keys = GetJsonQueryParam("keys").AsList<object>();
                    if (keys == null) {
                        var key = GetJsonQueryParam("key");
                        if (key != null) {
                            keys = new List<object> { key };
                        }
                    }
                } catch(CouchbaseLiteException) {
                    return null;
                }

                if (keys != null) {
                    _queryOptions.Keys = keys;
                } else {
                    try {
                        _queryOptions.StartKey = GetJsonQueryParam("start_key");
                        _queryOptions.EndKey = GetJsonQueryParam("end_key");
                        _queryOptions.StartKeyDocId = GetJsonQueryParam("startkey_docid") as string;
                        _queryOptions.EndKeyDocId = GetJsonQueryParam("endkey_docid") as string;
                    } catch(CouchbaseLiteException) {
                        return null;
                    }
                }

                //TODO:  Full text and bbox

                return _queryOptions;
            }
        }

        // ICouchbaseListenerContext
        public DocumentContentOptions ContentOptions {
            get {
                if (_contentOptions.HasValue) {
                    return _contentOptions.Value;
                }

                _contentOptions = DocumentContentOptions.None;
                if (GetQueryParam<bool>("attachments", bool.TryParse, false)) {
                    _contentOptions |= DocumentContentOptions.IncludeAttachments;
                }

                if (GetQueryParam<bool>("local_seq", bool.TryParse, false)) {
                    _contentOptions |= DocumentContentOptions.IncludeLocalSeq;
                }

                if (GetQueryParam<bool>("conflicts", bool.TryParse, false)) {
                    _contentOptions |= DocumentContentOptions.IncludeConflicts;
                }

                if (GetQueryParam<bool>("revs", bool.TryParse, false)) {
                    _contentOptions |= DocumentContentOptions.IncludeRevs;
                }

                if (GetQueryParam<bool>("revs_info", bool.TryParse, false)) {
                    _contentOptions |= DocumentContentOptions.IncludeRevsInfo;
                }

                if(GetQueryParam<bool>("show_exp", bool.TryParse, false)) {
                    _contentOptions |= DocumentContentOptions.IncludeExpiration;
                }

                return _contentOptions.Value;
            }
        }

        // ICouchbaseListenerContext
        public ChangesFeedMode ChangesFeedMode
        {
            get {
                if (_changesFeedMode.HasValue) {
                    return _changesFeedMode.Value;
                }

                _changesFeedMode = ChangesFeedMode.Normal;
                string feed = GetQueryParam("feed");
                if (feed == null) {
                    return _changesFeedMode.Value;
                }

                if (feed.Equals("longpoll")) {
                    _changesFeedMode = ChangesFeedMode.LongPoll;
                } else if (feed.Equals("continuous")) {
                    _changesFeedMode = ChangesFeedMode.Continuous;
                } else if (feed.Equals("eventsource")) {
                    _changesFeedMode = ChangesFeedMode.EventSource;
                }

                return _changesFeedMode.Value;
            }
        }

        // ICouchbaseListenerContext
        public abstract NameValueCollection RequestHeaders { get; }

        // ICouchbaseListenerContext
        public abstract Uri RequestUrl { get; }

        // ICouchbaseListenerContext
        public abstract Stream BodyStream { get; }

        // ICouchbaseListenerContext
        public abstract string Method { get; }

        // ICouchbaseListenerContext
        public abstract long ContentLength { get; }

#pragma warning restore 1591
        #endregion

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="manager">The manager responsible for opening DBs, etc</param>
        protected CouchbaseListenerContext(Manager manager)
        {
            DbManager = manager;
        }

        #endregion

        #region ICouchbaseListenerContext
#pragma warning disable 1591

        public object GetJsonQueryParam(string key)
        {
            string value = GetQueryParam(key);
            if (value == null) {
                return null;
            }

            return Manager.GetObjectMapper().ReadValue<object>(Uri.UnescapeDataString(value));
        }

        public T GetQueryParam<T>(string key, TryParseDelegate<T> parseDelegate, T defaultVal = default(T))
        {
            string value = GetQueryParam(key);
            if (value == null) {
                return defaultVal;
            }

            T retVal;
            if (!parseDelegate(value, out retVal)) {
                return defaultVal;
            }

            return retVal;
        }

        public bool ExplicitlyAcceptsType(string type)
        {
            string accept = RequestHeaders.Get("Accept");
            return accept != null && accept.Contains(type);
        }

        public string IfMatch()
        {
            string ifMatch = RequestHeaders.Get("If-Match");
            if (ifMatch == null) {
                return null;
            }

            // Value of If-Match is an ETag, so have to trim the quotes around it:
            if (ifMatch.Length > 2 && ifMatch.StartsWith("\"") && ifMatch.EndsWith("\"")) {
                return ifMatch.Trim('"');
            }

            return null;
        }

        public T BodyAs<T>() where T : class, new()
        {
            var bodyStream = BodyStream;
            if(bodyStream != null) {
                try {
                    var body = Manager.GetObjectMapper().ReadValue<T>(BodyStream);
                    return body;
                } catch(CouchbaseLiteException) {
                    return null;
                } catch(IOException e) {
                    throw Misc.CreateExceptionAndLog(Log.To.Router, e, StatusCode.RequestTimeout, Tag, "IOException when attempting to read body");
                }
            }

            return new T();
        }

        public abstract CouchbaseLiteResponse CreateResponse(StatusCode code = StatusCode.Ok);

        public abstract string GetQueryParam(string key);

        public abstract IDictionary<string, object> GetQueryParams();

        public abstract bool CacheWithEtag(string etag);

#pragma warning restore 1591
        #endregion

        #region Private Methods

        // Processes the URL string and splits it into components, then returns the component
        // at the specified index
        private string UrlComponentAt(int index)
        {
            if (_urlComponents == null) {
                var tmp = RequestUrl.AbsolutePath.Split('?')[0];
                _urlComponents = tmp.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (_urlComponents.Length >= 3) {
                    var secondComponent = _urlComponents[1];
                    if (secondComponent.Equals("_local") || secondComponent.Equals("_design")) {
                        _viewPrefix = secondComponent + "/";
                    }
                }
            }

            return _urlComponents.ElementAtOrDefault(index);
        }

        #endregion
    }
}


text:
require 'vcardigan'
require 'base64'
require_relative "../lib/parser_factory"
require_relative "../lib/parser"
class ContactImporter

  attr_accessor :data

  def initialize(data)
    self.data = data
  end

  def parse
    parser = find_parser_class_by_data(data)
    parser.get_contacts
  end

  def find_parser_class_by_data(data)
    parser_class = ParserFactory.find_parser(data)
    parser = parser_class.new(data)
  end
end
class CarrierStringIO < StringIO
  def original_filename
    # the real name does not matter
    "photo.jpeg"
  end

  def content_type
    # this should reflect real content type, but for this example it's ok
    "image/jpeg"
  end
end


text:
This service returns a JSON-formatted timestamp for the supplied date:
```
{"unixtime":1454994000000,"natural":"February 9, 2016"}
```

Query the service with either a valid JavaScript date string or a number representing Unix epoch time:
```
https://murmuring-crag-64497.herokuapp.com/February%209,%202016
https://murmuring-crag-64497.herokuapp.com/February 9, 2016
https://murmuring-crag-64497.herokuapp.com/1454994000000
```

If an invalid date string or number is entered, the service will return null values:
```
{"unixtime":null,"natural":null}
```

###### References:
###### https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
###### Built upon Clementine.js:
###### https://github.com/johnstonbl01/clementinejs.git


text:
/*global define */
define(
  [
    "./lb.base",
    "./lb.base.template",
    "./lb.base.object",
    "./lb.base.type"
  ],
  function(
    lbBase,
    lbBaseTemplate,
    object,
    type
  ) {

    // Declare aliases
    var no = lbBase.no,
        or = lbBase.or,
        has = object.has,
        is = type.is,

    // Private fields

        // PARAM_REGEXP - regular expression, format of parameters to replace:
        //                - ASCII letters and digits: a-zA-Z0-9
        //                - special characters intended as separators: \_\-\.
        //                - surrounded by hash signs: #...#
        //                - no white-space allowed
        PARAM_REGEXP = /#([a-zA-Z0-9\_\-\.]+)#/g;

    function withValuesFrom(data){
      // Function: withValuesFrom([data]): function
      // Get a closure function that gets values of properties in data.
      //
      // This method is intended for use in combination with replaceParams(),
      // to get a filter to replace parameters in a string template with values
      // from given data:
      // | var filter = replaceParams( withValuesFrom(data) )
      //
      // Parameter:
      //   data - object, optional, properties for parameter replacement, which
      //          may be nested in sections and subsections. Defaults to {}.
      //          Example:
      //          | {
      //          |   section: {
      //          |     subsection: {
      //          |       name: 'value'
      //          |     }
      //          |   }
      //          | }
      //
      // Returns:
      //   function, a closure wrapped around the given data, with the following
      //   signature:
      //   | Function: getDataValue(key): any
      //   | Get the value of a property, possibly nested, in wrapped data.
      //   |
      //   | Parameter:
      //   |   key - string, the key identifying a property, which may be:
      //   |           * a string refering to the name of a property: 'name'
      //   |           * a dotted string for a nested property: 'section.name'
      //   |
      //   | Returns:
      //   |   * any, the value of corresponding property, if found
      //   |   * null otherwise
      data = or(data, {});
      return function(key){
        var properties = data,
            path = key.split('.'),
            pathElement,
            i,
            length;
        for (i=0,length=path.length; i<length && properties; i++){
          pathElement = path[i];
          if ( has(properties,pathElement) && i===length-1 ){
            return properties[pathElement];
          }
          properties = properties[pathElement];
        }
        return null;
      };
    }

    function replaceParams(getValue){
      // Function: replaceParams(getValue): function
      // Get a filter function to replace parameters in a string template.
      //
      // The parameters to replace are surrounded by '#' characters, and
      // allow the folowing characters in the name:
      // - letters in the ranges a-z and A-Z
      // - numbers 0-9
      // - symbols '_' and '-', intended as word separators
      // - dot character '.' for properties nested in sections and subsections,
      //   e.g. 'section.subsection.name' which reference the property at the
      //   following location in the data object:
      //   | {
      //   |   section: {
      //   |     subsection: {
      //   |       name: 'value'
      //   |     }
      //   |   }
      //   | }
      //
      // Parameters for which no value is found are left unreplaced.
      //
      // Parameter:
      //   getValue - function, a getter function returning values for the
      //              replacement of parameters:
      //              | function(name): any
      //              The name argument is the name of the parameter to replace.
      //              The getter value should return string values when a
      //              matching property is found, and null otherwise.
      //
      // Returns:
      //   * function, a closure wrapped around the given getter function, with
      //   the following signature:
      //   | Function: filter(string): string
      //   | Replace parameters in given string with values from wrapped getter.
      //   |
      //   | Parameters:
      //   |   string - string, the template string with parameters to replace
      //   |
      //   | Returns:
      //   |   string, a string computed from the template string by replacing
      //   |   named parameters with corresponding values returned by getValue()
      //   * null when the required getter argument is missing or not a function
      if ( !is(getValue,'function') ){
        return null;
      }

      return function(string){
        return string.replace(PARAM_REGEXP, function(match,param){
          var value = getValue(param);
          if ( no(value) ){
            // no replacement found - return unreplaced param
            return match;
          } else {
            return value;
          }
        });
      };
    }

    // Assign to lb.base.template.string
    // for backward-compatibility in browser environment
    lbBaseTemplate.string = { // public API
      withValuesFrom: withValuesFrom,
      replaceParams: replaceParams
    };
    return lbBaseTemplate.string;
  }
);


text:
import numpy as np
from scipy.interpolate import interp1d
import matplotlib
import matplotlib.pyplot as plt
from Make_Timelist import *
#import sys
#sys.path.insert(0, '/tera/phil/nchaparr/python')
import nchap_fun as nc
from nchap_class import *
from matplotlib import rcParams
rcParams.update({'font.size': 10})

"""calculates temperature gradients (discrete) from txt files inturn from ensemble run 3D files
   gets levels where gradient exceeds zero, and where it resumes gamma, and zero crossings for fluxes
   and the maximal points withing the entrainment region.
   Gets Delta Theta and the Mixed Layer average Theta.
   Dumps them in a text file.
   Calcs and dumps rino, invrino, wstar
"""

def Main_Fun(rundate, gamma, flux_s):

     #output times
     if rundate == "Nov302013":
          dump_time_list, Times = Make_Timelists(1, 900, 28800)
          Times = np.array(Times)
     else:
          dump_time_list, Times = Make_Timelists(1, 600, 28800)
          Times = np.array(Times)

     #class for pulling data files
     files = For_Plots(rundate)

     #Create lists of variable lists
     #TODO: need to test Deltatheta
     first_theta_file = files.get_file(dump_time_list[0], "theta_bar")
     theta_file_list = [files.get_file(dump_time, "theta_bar") for dump_time in dump_time_list]
     press_file_list = [files.get_file(dump_time, "press") for dump_time in dump_time_list]
     flux_file_list = [files.get_file(dump_time, "wvelthetapert") for dump_time in dump_time_list]
     height_file = files.get_file("0000000600", "heights")

     AvProfLims = []
     invrinos = []
     #loop over text files files
     for i in range(len(theta_file_list)):
         print i, theta_file_list[i]
         theta0=np.genfromtxt(first_theta_file)
         theta = np.genfromtxt(theta_file_list[i])
         print theta.shape
         height = np.genfromtxt(height_file)

         press = np.genfromtxt(press_file_list[i])
         rhow = nc.calc_rhow(press, height, theta[0])
         wvelthetapert = np.genfromtxt(flux_file_list[i])

         #only need up to 1900meters
         if rundate == "Jan152014_1":
             top_index = np.where(abs(2000 - height) < 26.)[0][0] #may need to be higher (e.g. for 60/2.5)
         else:
             top_index = np.where(abs(1700 - height) < 26.)[0][0] #may need to be higher (e.g. for 60/2.5)

         print height.shape, press.shape, theta.shape, wvelthetapert.shape, gamma, top_index

         #function for calcuating heights
         [elbot_dthetadz, h, eltop_dthetadz, elbot_flux ,h_flux  ,eltop_flux, deltatheta, Deltatheta, mltheta]= nc.Get_CBLHeights(height, press, theta, theta0, wvelthetapert, gamma, flux_s, top_index)

         print elbot_dthetadz, h, eltop_dthetadz, elbot_flux ,h_flux  ,eltop_flux, deltatheta, mltheta

         delta_h=eltop_dthetadz - elbot_dthetadz

         [rino, invrino, wstar, S, pi3, pi4] =  nc.calc_rino(h, mltheta, 1.0*flux_s/(rhow[0]*1004), deltatheta, gamma, delta_h)

         AvProfLims.append([elbot_dthetadz, h, eltop_dthetadz, elbot_flux, h_flux, eltop_flux, deltatheta, Deltatheta, mltheta])
         tau = 1.0*h/wstar
         invrinos.append([rino, invrino, wstar, S, tau, mltheta, deltatheta, pi3, pi4])

     files.save_file(np.array(AvProfLims), "AvProfLims")
     files.save_file(np.array(invrinos), "invrinos")

#to be changed for each run
#rundate = 'Mar52014'
#gamma = .01
#flux_s = 150

run_list = [["Nov302013", .005, 100], ["Dec142013", .01, 100], ["Dec202013", .005, 60], ["Dec252013", .0025, 60], ["Jan152014_1", .005, 150], ["Mar12014", .01, 60], ["Mar52014", .01, 150]]

for run in run_list:
#run = run_list[0]
    Main_Fun(run[0], run[1], run[2])


text:
OPNFV Compliance Verification Program certification workflow

Dovetail Test Tool User Guide


text:
/**
 * @file
 *   This file contains definitions for a SPI interface to the OpenThread stack.
 */

#ifndef NCP_SPI_HPP_
#define NCP_SPI_HPP_

#include "openthread-core-config.h"

#include "ncp/ncp_base.hpp"

namespace ot {
namespace Ncp {

class NcpSpi : public NcpBase
{
public:
    /**
     * This constructor initializes the object.
     *
     * @param[in]  aInstance  A pointer to the OpenThread instance structure.
     *
     */
    NcpSpi(Instance *aInstance);

private:
    enum
    {
        /**
         * SPI tx and rx buffer size (should fit a max length frame + SPI header).
         *
         */
        kSpiBufferSize   = OPENTHREAD_CONFIG_NCP_SPI_BUFFER_SIZE,

        /**
         * Size of SPI header in bytes.
         *
         */
        kSpiHeaderLength = 5,
    };

    enum TxState
    {
        kTxStateIdle,               // No frame to send.
        kTxStateSending,            // A frame is ready to be sent.
        kTxStateHandlingSendDone    // The frame was sent successfully, waiting to prepare the next one (if any).
    };

    static bool SpiTransactionComplete(void *aContext, uint8_t *aOutputBuf, uint16_t aOutputBufLen, uint8_t *aInputBuf,
                                       uint16_t aInputBufLen, uint16_t aTransactionLength);
    bool SpiTransactionComplete(uint8_t *aOutputBuf, uint16_t aOutputBufLen, uint8_t *aInputBuf, uint16_t aInputBufLen,
                                uint16_t aTransactionLength);

    static void SpiTransactionProcess(void *aContext);
    void SpiTransactionProcess(void);

    static void HandleFrameAddedToTxBuffer(void *aContext, NcpFrameBuffer::FrameTag aFrameTag,
                                           NcpFrameBuffer::Priority aPriority, NcpFrameBuffer *aNcpFrameBuffer);

    static void PrepareTxFrame(Tasklet &aTasklet);
    void PrepareTxFrame(void);
    void HandleRxFrame(void);

    otError PrepareNextSpiSendFrame(void);

    volatile TxState mTxState;
    volatile bool mHandlingRxFrame;
    volatile bool mResetFlag;

    Tasklet mPrepareTxFrameTask;

    uint16_t mSendFrameLen;
    uint8_t mSendFrame[kSpiBufferSize];
    uint8_t mReceiveFrame[kSpiBufferSize];

    uint8_t mEmptySendFrameZeroAccept[kSpiHeaderLength];
    uint8_t mEmptySendFrameFullAccept[kSpiHeaderLength];
    uint8_t mEmptyReceiveFrame[kSpiHeaderLength];
};

}  // namespace Ncp
}  // namespace ot

#endif  // NCP_SPI_HPP_


text:
using System;
using System.Threading;

namespace MELHARFI
{
    namespace Lidgren.Network
    {
        /// <summary>
        /// Sender part of Selective repeat ARQ for a particular NetChannel
        /// </summary>
        internal sealed class NetUnreliableSenderChannel : NetSenderChannelBase
        {
            private NetConnection m_connection;
            private int m_windowStart;
            private int m_windowSize;
            private int m_sendStart;
            private bool m_doFlowControl;

            private NetBitVector m_receivedAcks;

            internal override int WindowSize { get { return m_windowSize; } }

            internal NetUnreliableSenderChannel(NetConnection connection, int windowSize, NetDeliveryMethod method)
            {
                m_connection = connection;
                m_windowSize = windowSize;
                m_windowStart = 0;
                m_sendStart = 0;
                m_receivedAcks = new NetBitVector(NetConstants.NumSequenceNumbers);
                m_queuedSends = new NetQueue<NetOutgoingMessage>(8);

                m_doFlowControl = true;
                if (method == NetDeliveryMethod.Unreliable && connection.Peer.Configuration.SuppressUnreliableUnorderedAcks == true)
                    m_doFlowControl = false;
            }

            internal override int GetAllowedSends()
            {
                if (!m_doFlowControl)
                    return 2; // always allowed to send without flow control!
                int retval = m_windowSize - ((m_sendStart + NetConstants.NumSequenceNumbers) - m_windowStart) % m_windowSize;
                NetException.Assert(retval >= 0 && retval <= m_windowSize);
                return retval;
            }

            internal override void Reset()
            {
                m_receivedAcks.Clear();
                m_queuedSends.Clear();
                m_windowStart = 0;
                m_sendStart = 0;
            }

            internal override NetSendResult Enqueue(NetOutgoingMessage message)
            {
                int queueLen = m_queuedSends.Count + 1;
                int left = GetAllowedSends();
                if (queueLen > left || (message.LengthBytes > m_connection.m_currentMTU && m_connection.m_peerConfiguration.UnreliableSizeBehaviour == NetUnreliableSizeBehaviour.DropAboveMTU))
                {
                    // drop message
                    return NetSendResult.Dropped;
                }

                m_queuedSends.Enqueue(message);
                m_connection.m_peer.m_needFlushSendQueue = true; // a race condition to this variable will simply result in a single superflous call to FlushSendQueue()
                return NetSendResult.Sent;
            }

            // call this regularely
            internal override void SendQueuedMessages(double now)
            {
                int num = GetAllowedSends();
                if (num < 1)
                    return;

                // queued sends
                while (num > 0 && m_queuedSends.Count > 0)
                {
                    NetOutgoingMessage om;
                    if (m_queuedSends.TryDequeue(out om))
                        ExecuteSend(om);
                    num--;
                }
            }

            private void ExecuteSend(NetOutgoingMessage message)
            {
                m_connection.m_peer.VerifyNetworkThread();

                int seqNr = m_sendStart;
                m_sendStart = (m_sendStart + 1) % NetConstants.NumSequenceNumbers;

                m_connection.QueueSendMessage(message, seqNr);

                if (message.m_recyclingCount <= 0)
                    m_connection.m_peer.Recycle(message);

                return;
            }

            // remoteWindowStart is remote expected sequence number; everything below this has arrived properly
            // seqNr is the actual nr received
            internal override void ReceiveAcknowledge(double now, int seqNr)
            {
                if (m_doFlowControl == false)
                {
                    // we have no use for acks on this channel since we don't respect the window anyway
                    m_connection.m_peer.LogWarning("SuppressUnreliableUnorderedAcks sender/receiver mismatch!");
                    return;
                }

                // late (dupe), on time or early ack?
                int relate = NetUtility.RelativeSequenceNumber(seqNr, m_windowStart);

                if (relate < 0)
                {
                    //m_connection.m_peer.LogDebug("Received late/dupe ack for #" + seqNr);
                    return; // late/duplicate ack
                }

                if (relate == 0)
                {
                    //m_connection.m_peer.LogDebug("Received right-on-time ack for #" + seqNr);

                    // ack arrived right on time
                    NetException.Assert(seqNr == m_windowStart);

                    m_receivedAcks[m_windowStart] = false;
                    m_windowStart = (m_windowStart + 1) % NetConstants.NumSequenceNumbers;

                    return;
                }

                // Advance window to this position
                m_receivedAcks[seqNr] = true;

                while (m_windowStart != seqNr)
                {
                    m_receivedAcks[m_windowStart] = false;
                    m_windowStart = (m_windowStart + 1) % NetConstants.NumSequenceNumbers;
                }
            }
        }
    }
}


text:
require 'capybara'
require 'capybara/cucumber'
require 'selenium-webdriver'
require 'site_prism'

class YouInFourWordsDialog < SitePrism::Page

  element :dialog_header,             :css, 'div#fourwords > div > div > div > h4.modal-title'
  element :user_character_word1,      :css, 'input#user_character_word_1'
  element :user_character_word2,      :css, 'input#user_character_word_2'
  element :user_character_word3,      :css, 'input#user_character_word_3'
  element :user_character_word4,      :css, 'input#user_character_word_4'
  element :done_button,               :css, 'div#fourwords > div > div > div.modal-footer > button.btn.btn-primary'
  element :cancel_button,             :css, 'div#fourwords > div > div > div.modal-footer > button.btn.btn-link'

  #character1
  element :character1_weight_list,    :css,   "button[data-id='user_character_label_1']"
  element :character1_not_at_all,     :xpath, "//form[@id='edit_user_character_22'] // div // div[1] // div // div // ul // li[1] //a // span[1]"
  element :character1_a_little,       :xpath, "//form[@id='edit_user_character_22'] // div // div[1] // div // div // ul // li[2] //a // span[1]"
  element :character1_kind_of,        :xpath, "//form[@id='edit_user_character_22'] // div // div[1] // div // div // ul // li[3] //a // span[1]"
  element :character1_mostly,         :xpath, "//form[@id='edit_user_character_22'] // div // div[1] // div // div // ul // li[4] //a // span[1]"
  element :character1_totally,        :xpath, "//form[@id='edit_user_character_22'] // div // div[1] // div // div // ul // li[5] //a // span[1]"

  #character2
  element :character2_weight_list,    :css,   "button[data-id='user_character_label_2']"
  element :character2_not_at_all,     :xpath, "//form[@id='edit_user_character_22'] // div // div[2] // div // div // ul // li[1] //a // span[1]"
  element :character2_a_little,       :xpath, "//form[@id='edit_user_character_22'] // div // div[2] // div // div // ul // li[2] //a // span[1]"
  element :character2_kind_of,        :xpath, "//form[@id='edit_user_character_22'] // div // div[2] // div // div // ul // li[3] //a // span[1]"
  element :character2_mostly,         :xpath, "//form[@id='edit_user_character_22'] // div // div[2] // div // div // ul // li[4] //a // span[1]"
  element :character2_totally,        :xpath, "//form[@id='edit_user_character_22'] // div // div[2] // div // div // ul // li[5] //a // span[1]"

  #character3
  element :character3_weight_list,    :css,   "button[data-id='user_character_label_3']"
  element :character3_not_at_all,     :xpath, "//form[@id='edit_user_character_22'] // div // div[3] // div // div // ul // li[1] //a // span[1]"
  element :character3_a_little,       :xpath, "//form[@id='edit_user_character_22'] // div // div[3] // div // div // ul // li[2] //a // span[1]"
  element :character3_kind_of,        :xpath, "//form[@id='edit_user_character_22'] // div // div[3] // div // div // ul // li[3] //a // span[1]"
  element :character3_mostly,         :xpath, "//form[@id='edit_user_character_22'] // div // div[3] // div // div // ul // li[4] //a // span[1]"
  element :character3_totally,        :xpath, "//form[@id='edit_user_character_22'] // div // div[3] // div // div // ul // li[5] //a // span[1]"

  #character4
  element :character4_weight_list,    :css,   "button[data-id='user_character_label_4']"
  element :character4_not_at_all,     :xpath, "//form[@id='edit_user_character_22'] // div // div[4] // div // div // ul // li[1] //a // span[1]"
  element :character4_a_little,       :xpath, "//form[@id='edit_user_character_22'] // div // div[4] // div // div // ul // li[2] //a // span[1]"
  element :character4_kind_of,        :xpath, "//form[@id='edit_user_character_22'] // div // div[4] // div // div // ul // li[3] //a // span[1]"
  element :character4_mostly,         :xpath, "//form[@id='edit_user_character_22'] // div // div[4] // div // div // ul // li[4] //a // span[1]"
  element :character4_totally,        :xpath, "//form[@id='edit_user_character_22'] // div // div[4] // div // div // ul // li[5] //a // span[1]"

  def enter_character_description(user_character, description)
    case user_character
      when 'user character1'
        user_character_word1.set('')
        user_character_word1.set(description)
      when 'user character2'
        user_character_word2.set('')
        user_character_word2.set(description)
      when 'user character3'
        user_character_word3.set('')
        user_character_word3.set(description)
      when 'user character4'
        user_character_word4.set('')
        user_character_word4.set(description)
    end
  end

  def select_character_weight(user_character, weight)
    case user_character
      when 'user character1'
        character1_weight_list.click
        if weight == 'Not at all'
          character1_not_at_all.click
        end
        if weight == 'A little'
          character1_a_little.click
        end
        if weight == 'Kind of'
          character1_kind_of.click
        end
        if weight == 'Mostly'
          character1_mostly.click
        end
        if weight == 'Totally'
          character1_totally.click
        end
      when 'user character2'
        character2_weight_list.click
        if weight == 'Not at all'
          character2_not_at_all.click
        end
        if weight == 'A little'
          character2_a_little.click
        end
        if weight == 'Kind of'
          character2_kind_of.click
        end
        if weight == 'Mostly'
          character2_mostly.click
        end
        if weight == 'Totally'
          character2_totally.click
        end
      when 'user character3'
        character3_weight_list.click
        if weight == 'Not at all'
          character3_not_at_all.click
        end
        if weight == 'A little'
          character3_a_little.click
        end
        if weight == 'Kind of'
          character3_kind_of.click
        end
        if weight == 'Mostly'
          character3_mostly.click
        end
        if weight == 'Totally'
          character3_totally.click
        end
      when 'user character4'
        character4_weight_list.click
        if weight == 'Not at all'
          character4_not_at_all.click
        end
        if weight == 'A little'
          character4_a_little.click
        end
        if weight == 'Kind of'
          character4_kind_of.click
        end
        if weight == 'Mostly'
          character4_mostly.click
        end
        if weight == 'Totally'
          character4_totally.click
        end
    end
  end

end