text:
#ifndef CREDENTIALS_H
#define CREDENTIALS_H

#define SSID "..."
#define PASS "..."
#define MQTT_BROKER "..."

#endif /* CREDENTIALS_H */


text:
<meta>
	<info author="vG MTA Scripting Team" type="script" description="Save Vehicle System"/>

	<script src="s_savevehicle_system.lua" type="server" />
	<export function="saveVehicleOnExit" type="server"/>
</meta>

redpajama_set_name: RedPajamaGithub


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: android.gesture.GestureUtils
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ANDROID_GESTURE_GESTUREUTILS_HPP_DECL
#define J2CPP_ANDROID_GESTURE_GESTUREUTILS_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace util { class ArrayList; } } }
namespace j2cpp { namespace android { namespace gesture { class OrientedBoundingBox; } } }
namespace j2cpp { namespace android { namespace gesture { class GestureStroke; } } }
namespace j2cpp { namespace android { namespace gesture { class Gesture; } } }

#include <android/gesture/Gesture.hpp>
#include <android/gesture/GestureStroke.hpp>
#include <android/gesture/OrientedBoundingBox.hpp>
#include <java/lang/Object.hpp>
#include <java/util/ArrayList.hpp>

namespace j2cpp {

namespace android { namespace gesture {

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

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_METHOD(4)
		J2CPP_DECLARE_METHOD(5)

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

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

		static local_ref< array<jfloat,1> > spatialSampling(local_ref< android::gesture::Gesture >  const&, jint);
		static local_ref< array<jfloat,1> > spatialSampling(local_ref< android::gesture::Gesture >  const&, jint, jboolean);
		static local_ref< array<jfloat,1> > temporalSampling(local_ref< android::gesture::GestureStroke >  const&, jint);
		static local_ref< android::gesture::OrientedBoundingBox > computeOrientedBoundingBox(local_ref< java::util::ArrayList >  const&);
		static local_ref< android::gesture::OrientedBoundingBox > computeOrientedBoundingBox(local_ref< array<jfloat,1> >  const&);
	}; //class GestureUtils

} //namespace gesture
} //namespace android

} //namespace j2cpp

#endif //J2CPP_ANDROID_GESTURE_GESTUREUTILS_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ANDROID_GESTURE_GESTUREUTILS_HPP_IMPL
#define J2CPP_ANDROID_GESTURE_GESTUREUTILS_HPP_IMPL

namespace j2cpp {

android::gesture::GestureUtils::operator local_ref<java::lang::Object>() const
{
	return local_ref<java::lang::Object>(get_jobject());
}

local_ref< array<jfloat,1> > android::gesture::GestureUtils::spatialSampling(local_ref< android::gesture::Gesture > const &a0, jint a1)
{
	return call_static_method<
		android::gesture::GestureUtils::J2CPP_CLASS_NAME,
		android::gesture::GestureUtils::J2CPP_METHOD_NAME(1),
		android::gesture::GestureUtils::J2CPP_METHOD_SIGNATURE(1),
		local_ref< array<jfloat,1> >
	>(a0, a1);
}

local_ref< array<jfloat,1> > android::gesture::GestureUtils::spatialSampling(local_ref< android::gesture::Gesture > const &a0, jint a1, jboolean a2)
{
	return call_static_method<
		android::gesture::GestureUtils::J2CPP_CLASS_NAME,
		android::gesture::GestureUtils::J2CPP_METHOD_NAME(2),
		android::gesture::GestureUtils::J2CPP_METHOD_SIGNATURE(2),
		local_ref< array<jfloat,1> >
	>(a0, a1, a2);
}

local_ref< array<jfloat,1> > android::gesture::GestureUtils::temporalSampling(local_ref< android::gesture::GestureStroke > const &a0, jint a1)
{
	return call_static_method<
		android::gesture::GestureUtils::J2CPP_CLASS_NAME,
		android::gesture::GestureUtils::J2CPP_METHOD_NAME(3),
		android::gesture::GestureUtils::J2CPP_METHOD_SIGNATURE(3),
		local_ref< array<jfloat,1> >
	>(a0, a1);
}

local_ref< android::gesture::OrientedBoundingBox > android::gesture::GestureUtils::computeOrientedBoundingBox(local_ref< java::util::ArrayList > const &a0)
{
	return call_static_method<
		android::gesture::GestureUtils::J2CPP_CLASS_NAME,
		android::gesture::GestureUtils::J2CPP_METHOD_NAME(4),
		android::gesture::GestureUtils::J2CPP_METHOD_SIGNATURE(4),
		local_ref< android::gesture::OrientedBoundingBox >
	>(a0);
}

local_ref< android::gesture::OrientedBoundingBox > android::gesture::GestureUtils::computeOrientedBoundingBox(local_ref< array<jfloat,1> > const &a0)
{
	return call_static_method<
		android::gesture::GestureUtils::J2CPP_CLASS_NAME,
		android::gesture::GestureUtils::J2CPP_METHOD_NAME(5),
		android::gesture::GestureUtils::J2CPP_METHOD_SIGNATURE(5),
		local_ref< android::gesture::OrientedBoundingBox >
	>(a0);
}

J2CPP_DEFINE_CLASS(android::gesture::GestureUtils,"android/gesture/GestureUtils")
J2CPP_DEFINE_METHOD(android::gesture::GestureUtils,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::gesture::GestureUtils,1,"spatialSampling","(Landroid/gesture/Gesture;I)[F")
J2CPP_DEFINE_METHOD(android::gesture::GestureUtils,2,"spatialSampling","(Landroid/gesture/Gesture;IZ)[F")
J2CPP_DEFINE_METHOD(android::gesture::GestureUtils,3,"temporalSampling","(Landroid/gesture/GestureStroke;I)[F")
J2CPP_DEFINE_METHOD(android::gesture::GestureUtils,4,"computeOrientedBoundingBox","(Ljava/util/ArrayList;)Landroid/gesture/OrientedBoundingBox;")
J2CPP_DEFINE_METHOD(android::gesture::GestureUtils,5,"computeOrientedBoundingBox","([F)Landroid/gesture/OrientedBoundingBox;")

} //namespace j2cpp

#endif //J2CPP_ANDROID_GESTURE_GESTUREUTILS_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
    <form [formGroup]="hiveForm" novalidate (ngSubmit)="onSubmit(numOfHives.value)">

                    Name
                    <input type="text" class="form-control" formControlName="name">

                    Hive Type
                    <select formControlName="typeId" class="form-control">
                        <option value="" disabled [selected]="!hive.typeId">
                            Select hive type
                        </option>
                        <option *ngFor="let type of hiveTypes" [value]="type.name">{{type.name}}</option>
                    </select>

                        Select Apiary
                        <select formControlName="apiaryId" class="form-control">
                            <option value="" disabled>
                                Select apiary
                            </option>
                            <option *ngFor="let apiary of apiaries" [value]="apiary.id">{{apiary.name}}</option>
                        </select>

                        <input class="form-check-input" type="checkbox" formControlName="active" value="">
                        Active

                        <input class="form-check-input" type="checkbox" formControlName="queen" value="">
                        Queen

                        <input checked class="form-check-input white" type="radio" formControlName="queenColor" value="#fff">

                        <input class="form-check-input blue" type="radio" formControlName="queenColor" value="#6495ff">

                        <input class="form-check-input red" type="radio" formControlName="queenColor" value="#ff573e">

                        <input class="form-check-input green" type="radio" formControlName="queenColor" value="#8cff5a">

                        <input class="form-check-input yellow" type="radio" formControlName="queenColor" value="#ffd613" >

                    Frame Number
                    <input type="number" class="form-control" formControlName="frameNumber">

                    Note
                    <textarea formControlName="note" class="form-control" rows="10"></textarea>

Create multiple hives with the same specs

                    Num of hives
                    <input type="number" class="form-control" min="1" #numOfHives value="1">

        <button class="btn btn-outline-primary" (click)="multiHives(numOfHives.value)">Save</button>

    </form>


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

namespace Stratus
{
	/// <summary>
	/// Field that allows custom methods to be set for an inspector window and run
	/// </summary>
	[Serializable]
	public class StratusRuntimeMethodField
	{
		/// <summary>
		/// The method which this button will invoke
		/// </summary>
		public Action[] methods { get; private set; }

		public StratusRuntimeMethodField(params Action[] methods)
		{
			this.methods = methods;
		}

		public StratusRuntimeMethodField(Action method)
		{
			this.methods = new Action[] { method };
		}

	}
}


text:
<Library>
  <class name="Global">
    <method name="isXMLName" returnType="boolean">
      <param name="str" type="String"/>
    </method>
  </class>

  <class name="XMLList" extends="XML">
    <method name="__constructor__">
      <param name="value" type="Object"/>
    </method>
    <method name="attribute" returnType="XMLList">
      <param name="attributeName" type="*"/>
    </method>
    <method name="attributes" returnType="XMLList"/>
    <method name="child" returnType="XMLList">
      <param name="propertyName" type="*"/>
    </method>
    <method name="children" returnType="XMLList"/>
    <method name="comments" returnType="XMLList"/>
    <method name="contains" returnType="boolean">
      <param name="value" type="XML"/>
    </method>
    <method name="copy" returnType="XMLList"/>
    <method name="descendants" returnType="XMLList">
      <param name="name" type="*"/>
    </method>
    <method name="elements" returnType="XMLList">
      <param name="name" type="*"/>
    </method>
    <method name="hasComplexContent" returnType="boolean"/>
    <method name="hasSimpleContent" returnType="boolean"/>
    <method name="normalize" returnType="XMLList"/>
    <method name="parent" returnType="XML"/>
    <method name="processingInstructions" returnType="XMLList">
      <param name="name" type="String"/>
    </method>
    <method name="text" returnType="XMLList"/>
    <method name="valueOf" returnType="XMLList"/>
  </class>

  <class name="XML">
    <property name="ignoreComments" type="boolean"/>
    <property name="ignoreProcessingInstructions" type="boolean"/>
    <property name="ignoreWhitespace" type="boolean"/>
    <property name="prettyPrinting" type="boolean"/>
    <method name="__constructor__">
      <param name="value" type="*"/>
    </method>
    <method name="addNamespace" returnType="XML">
      <param name="ns" type="*"/>
    </method>
    <method name="appendChild" returnType="XML">
      <param name="child" type="*"/>
    </method>
    <method name="attribute" returnType="XMLList">
      <param name="attributeName" type="*"/>
    </method>
    <method name="attributes" returnType="XMLList"/>
    <method name="child" returnType="XMLList">
      <param name="propertyName" type="*"/>
    </method>
    <method name="childIndex" returnType="Number"/>
    <method name="children" returnType="XMLList"/>
    <method name="comments" returnType="XMLList"/>
    <method name="contains" returnType="boolean">
      <param name="value" type="XML"/>
    </method>
    <method name="copy" returnType="XML"/>
    <method name="defaultSettings" returnType="Object"/>
    <method name="descendants" returnType="XMLList">
      <param name="name" type="*"/>
    </method>
    <method name="elements" returnType="XMLList">
      <param name="name" type="*"/>
    </method>
    <method name="hasComplexContent" returnType="boolean"/>
    <method name="hasSimpleContent" returnType="boolean"/>
    <method name="inScopeNamespaces" returnType="Array"/>
    <method name="insertChildAfter" returnType="XMLList|undefined">
      <param name="child1" type="Object"/>
      <param name="child2" type="Object"/>
    </method>
    <method name="insertChildBefore" returnType="XMLList|undefined">
      <param name="child1" type="Object"/>
      <param name="child2" type="Object"/>
    </method>
    <method name="localName" returnType="String"/>
    <method name="name" returnType="Object"/>
    <method name="namespace" returnType="*">
      <param name="prefix" type="String"/>
    </method>
    <method name="namespaceDeclaration" returnType="Array"/>
    <method name="nodeKind" returnType="String"/>
    <method name="normalize" returnType="XML"/>
    <method name="parent" returnType="XML"/>
    <method name="prependChild" returnType="XML">
      <param name="value" type="*"/>
    </method>
    <method name="processingInstructions" returnType="XMLList">
      <param name="name" type="String"/>
    </method>
    <method name="removeNamespace" returnType="XML">
      <param name="ns" type="Namespace"/>
    </method>
    <method name="replace" returnType="XML">
      <param name="propertyName" type="*"/>
      <param name="value" type="*"/>
    </method>
    <method name="setChildren" returnType="XML">
      <param name="value" type="*"/>
    </method>
    <method name="setLocalName">
      <param name="name" type="String"/>
    </method>
    <method name="setName">
      <param name="name" type="String"/>
    </method>
    <method name="setNamespace">
      <param name="name" type="String"/>
    </method>
    <method name="setSettings">
      <param name="settings" rest="true" type="*"/>
    </method>
    <method name="settings" returnType="Object"/>
    <method name="text" returnType="XMLList"/>
    <method name="toXMLString" returnType="String"/>
    <method name="valueOf" returnType="XML"/>
  </class>

  <class name="Namespace">
    <property name="prefix" type="String"/>
    <property name="prefix" type="uri"/>
    <method name="__constructor__">
      <param name="prefixValue" type="*"/>
      <param name="urlValue" type="*"/>
    </method>
    <method name="valueOf" returnType="Namespace"/>
  </class>

  <class name="QName">
    <property name="localName" type="String" attribute="readOnly"/>
    <property name="uri" type="String" attribute="readOnly"/>
    <method name="__constructor__">
      <param name="uri" type="*"/>
      <param name="localName" type="*"/>
    </method>
  </class>
</Library>


text:
package org.apache.activemq.artemis.junit;

import java.util.HashMap;
import java.util.Map;

import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;

import static org.junit.Assert.assertNotNull;

public class ActiveMQProducerResourceTest {

   static final SimpleString TEST_QUEUE = new SimpleString("test.queue");
   static final SimpleString TEST_ADDRESS = new SimpleString("test.queue");
   static final String TEST_BODY = "Test Message";
   static final Map<String, Object> TEST_PROPERTIES;

   static final String ASSERT_SENT_FORMAT = "Message should have been sent to %s";
   static final String ASSERT_RECEIVED_FORMAT = "Message should have been received from %s";
   static final String ASSERT_COUNT_FORMAT = "Unexpected message count in queue %s";

   static {
      TEST_PROPERTIES = new HashMap<String, Object>(2);
      TEST_PROPERTIES.put("PropertyOne", "Property Value 1");
      TEST_PROPERTIES.put("PropertyTwo", "Property Value 2");

      ThreadLeakCheckRule.addKownThread("MemoryPoolMXBean notification dispatcher");
      ThreadLeakCheckRule.addKownThread("threadDeathWatcher");
   }

   EmbeddedActiveMQResource server = new EmbeddedActiveMQResource();

   ActiveMQProducerResource producer = new ActiveMQProducerResource(server.getVmURL(), TEST_ADDRESS);

   @Rule
   public RuleChain ruleChain = RuleChain.outerRule(new ThreadLeakCheckRule()).around(server).around(producer);

   ClientMessage sent = null;

   @After
   public void checkResults() throws Exception {
      assertNotNull(String.format(ASSERT_SENT_FORMAT, TEST_ADDRESS), sent);

      ClientMessage received = server.receiveMessage(TEST_QUEUE);
      assertNotNull(String.format(ASSERT_RECEIVED_FORMAT, TEST_QUEUE), received);
   }

   @Test
   public void testSendBytes() throws Exception {
      sent = producer.sendMessage(TEST_BODY.getBytes());
   }

   @Test
   public void testSendString() throws Exception {
      sent = producer.sendMessage(TEST_BODY);
   }

   @Test
   public void testSendBytesAndProperties() throws Exception {
      sent = producer.sendMessage(TEST_BODY.getBytes(), TEST_PROPERTIES);
   }

   @Test
   public void testSendStringAndProperties() throws Exception {
      sent = producer.sendMessage(TEST_BODY, TEST_PROPERTIES);
   }

}


text:
class QPCounter {
private:
    double PCFreq = 0.0;
    __int64 CounterStart = 0;
public:
    void StartCounter();
    double GetCounter();
};

#endif //DIPLOMSKI_HOG_QPCOUNTER_H


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class ManagementApiClient
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class ManagementApiClient
   ">
    <meta name="generator" content="docfx 2.33.1.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

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

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class ManagementApiClient

Represents the Management API client.

Inheritance

System.Object

ManagementApiClient

Implements

IManagementApiClient

Inherited Members

      System.Object.ToString()

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

Namespace: Auth0.ManagementApi

Assembly: cs.temp.dll.dll

Syntax

public class ManagementApiClient : IManagementApiClient

Constructors

ManagementApiClient(String, String)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, string domain)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        System.String
        domain

Your Auth0 domain, e.g. tenant.auth0.com.

ManagementApiClient(String, String, DiagnosticsHeader)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, string domain, DiagnosticsHeader diagnostics)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        System.String
        domain

Your Auth0 domain, e.g. tenant.auth0.com.

        DiagnosticsHeader
        diagnostics

The diagnostics.

ManagementApiClient(String, String, DiagnosticsHeader, HttpClient)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, string domain, DiagnosticsHeader diagnostics, HttpClient httpClient)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        System.String
        domain

Your Auth0 domain, e.g. tenant.auth0.com.

        DiagnosticsHeader
        diagnostics

The diagnostics.

        HttpClient
        httpClient

The <see cref="!:HttpClient"></see> which is used for HTTP requests

ManagementApiClient(String, String, DiagnosticsHeader, HttpMessageHandler)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, string domain, DiagnosticsHeader diagnostics, HttpMessageHandler handler)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        System.String
        domain

Your Auth0 domain, e.g. tenant.auth0.com.

        DiagnosticsHeader
        diagnostics

The diagnostics.

        HttpMessageHandler
        handler

The <see cref="!:HttpMessageHandler"></see> which is used for HTTP requests

ManagementApiClient(String, String, HttpClient)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, string domain, HttpClient httpClient)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        System.String
        domain

Your Auth0 domain, e.g. tenant.auth0.com.

        HttpClient
        httpClient

The <see cref="!:HttpClient"></see> which is used for HTTP requests

ManagementApiClient(String, String, HttpMessageHandler)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, string domain, HttpMessageHandler handler)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        System.String
        domain

Your Auth0 domain, e.g. tenant.auth0.com.

        HttpMessageHandler
        handler

The <see cref="!:HttpMessageHandler"></see> which is used for HTTP requests

ManagementApiClient(String, Uri)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, Uri baseUri)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        Uri
        baseUri

The base URI.

ManagementApiClient(String, Uri, DiagnosticsHeader)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, Uri baseUri, DiagnosticsHeader diagnostics)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        Uri
        baseUri

The base URI.

        DiagnosticsHeader
        diagnostics

The diagnostics.

ManagementApiClient(String, Uri, DiagnosticsHeader, HttpClient)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, Uri baseUri, DiagnosticsHeader diagnostics, HttpClient httpClient)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        Uri
        baseUri

The base URI.

        DiagnosticsHeader
        diagnostics

The diagnostics.

        HttpClient
        httpClient

The <see cref="!:HttpClient"></see> which is used for HTTP requests

ManagementApiClient(String, Uri, DiagnosticsHeader, HttpMessageHandler)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, Uri baseUri, DiagnosticsHeader diagnostics, HttpMessageHandler handler)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        Uri
        baseUri

The base URI.

        DiagnosticsHeader
        diagnostics

The diagnostics.

        HttpMessageHandler
        handler

The <see cref="!:HttpMessageHandler"></see> which is used for HTTP requests

ManagementApiClient(String, Uri, HttpClient)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, Uri baseUri, HttpClient httpClient)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        Uri
        baseUri

The base URI.

        HttpClient
        httpClient

The <see cref="!:HttpClient"></see> which is used for HTTP requests

ManagementApiClient(String, Uri, HttpMessageHandler)

Initializes a new instance of the ManagementApiClient class.

Declaration

public ManagementApiClient(string token, Uri baseUri, HttpMessageHandler handler)

Parameters

        Type
        Name
        Description

        System.String
        token

The token.

        Uri
        baseUri

The base URI.

        HttpMessageHandler
        handler

The <see cref="!:HttpMessageHandler"></see> which is used for HTTP requests

Properties

BlacklistedTokens

Contains all the methods to call the /blacklists/tokens endpoints.

Declaration

public IBlacklistedTokensClient BlacklistedTokens { get; }

Property Value

        Type
        Description

        IBlacklistedTokensClient

The blacklisted tokens.

ClientGrants

Contains all the methods to call the /client-grants endpoints

Declaration

public IClientGrantsClient ClientGrants { get; }

Property Value

        Type
        Description

        IClientGrantsClient

Clients

Contains all the methods to call the /clients endpoints.

Declaration

public IClientsClient Clients { get; }

Property Value

        Type
        Description

        IClientsClient

The clients.

Connections

Contains all the methods to call the /connections endpoints.

Declaration

public IConnectionsClient Connections { get; }

Property Value

        Type
        Description

        IConnectionsClient

The connections.

DeviceCredentials

Contains all the methods to call the /device-credentials endpoints.

Declaration

public IDeviceCredentialsClient DeviceCredentials { get; }

Property Value

        Type
        Description

        IDeviceCredentialsClient

The device credentials.

EmailProvider

Contains all the methods to call the /emails/provider endpoints.

Declaration

public IEmailProviderClient EmailProvider { get; }

Property Value

        Type
        Description

        IEmailProviderClient

The email provider.

EmailTemplates

Contains all the methods to call the /email-templates endpoints.

Declaration

public IEmailTemplatesClient EmailTemplates { get; }

Property Value

        Type
        Description

        IEmailTemplatesClient

Jobs

Contains all the methods to call the /jobs endpoints.

Declaration

public IJobsClient Jobs { get; }

Property Value

        Type
        Description

        IJobsClient

The jobs.

Logs

Contains all the methods to call the /logs endpoints.

Declaration

public ILogsClient Logs { get; }

Property Value

        Type
        Description

        ILogsClient

The rules.

ResourceServers

Contains all the methods to call the /resource-servers endpoints.

Declaration

public IResourceServersClient ResourceServers { get; }

Property Value

        Type
        Description

        IResourceServersClient

Rules

Contains all the methods to call the /rules endpoints.

Declaration

public IRulesClient Rules { get; }

Property Value

        Type
        Description

        IRulesClient

The rules.

Stats

Contains all the methods to call the /stats endpoints.

Declaration

public IStatsClient Stats { get; }

Property Value

        Type
        Description

        IStatsClient

The stats.

TenantSettings

Contains all the methods to call the /tenants/settings endpoints.

Declaration

public ITenantSettingsClient TenantSettings { get; set; }

Property Value

        Type
        Description

        ITenantSettingsClient

The tenant settings.

Tickets

Contains all the methods to call the /tickets endpoints.

Declaration

public ITicketsClient Tickets { get; }

Property Value

        Type
        Description

        ITicketsClient

The tickets.

UserBlocks

Contains all the methods to call the /user-blocks endpoints.

Declaration

public IUserBlocksClient UserBlocks { get; }

Property Value

        Type
        Description

        IUserBlocksClient

Users

Contains all the methods to call the /users endpoints.

Declaration

public IUsersClient Users { get; }

Property Value

        Type
        Description

        IUsersClient

The users.

Methods

GetLastApiInfo()

Gets information about the last API call;

Declaration

public ApiInfo GetLastApiInfo()

Returns

        Type
        Description

        ApiInfo

Implements

      IManagementApiClient

              Back to top

            Generated by DocFX


text:
class <%= migration_class_name %> < ActiveRecord::Migration
  def self.up
    create_table :managed_emails do |t|
      t.datetime :date_sent
      t.text :from
      t.text :reply_to
      t.text :to
      t.text :cc
      t.text :bcc
      t.text :headers
      t.string :message_id
      t.text :subject
      t.text :body
      t.text :caller

      t.timestamps
    end
  end

  def self.down
    drop_table :managed_emails
  end
end


text:
import os
from multiprocessing import Queue

import pytest
from mock import Mock

from doit.dependency import Dependency
from doit.task import Task
from doit.control import TaskDispatcher, ExecNode
from doit import runner

# sample actions
def my_print(*args):
    pass
def _fail():
    return False
def _error():
    raise Exception("I am the exception.\n")
def _exit():
    raise SystemExit()

class FakeReporter(object):
    """Just log everything in internal attribute - used on tests"""
    def __init__(self, outstream=None, options=None):
        self.log = []

    def get_status(self, task):
        self.log.append(('start', task))

    def execute_task(self, task):
        self.log.append(('execute', task))

    def add_failure(self, task, exception):
        self.log.append(('fail', task))

    def add_success(self, task):
        self.log.append(('success', task))

    def skip_uptodate(self, task):
        self.log.append(('up-to-date', task))

    def skip_ignore(self, task):
        self.log.append(('ignore', task))

    def cleanup_error(self, exception):
        self.log.append(('cleanup_error',))

    def runtime_error(self, msg):
        self.log.append(('runtime_error',))

    def teardown_task(self, task):
        self.log.append(('teardown', task))

    def complete_run(self):
        pass

@pytest.fixture
def reporter(request):
    return FakeReporter()

class TestRunner(object):
    def testInit(self, reporter, depfile):
        my_runner = runner.Runner(depfile.name, reporter)
        assert False == my_runner._stop_running
        assert runner.SUCCESS == my_runner.final_result

class TestRunner_SelectTask(object):
    def test_ready(self, reporter, depfile):
        t1 = Task("taskX", [(my_print, ["out a"] )])
        my_runner = runner.Runner(depfile.name, reporter)
        assert True == my_runner.select_task(ExecNode(t1, None), {})
        assert ('start', t1) == reporter.log.pop(0)
        assert not reporter.log

    def test_DependencyError(self, reporter, depfile):
        t1 = Task("taskX", [(my_print, ["out a"] )],
                  file_dep=["i_dont_exist"])
        my_runner = runner.Runner(depfile.name, reporter)
        assert False == my_runner.select_task(ExecNode(t1, None), {})
        assert ('start', t1) == reporter.log.pop(0)
        assert ('fail', t1) == reporter.log.pop(0)
        assert not reporter.log

    def test_upToDate(self, reporter, depfile):
        t1 = Task("taskX", [(my_print, ["out a"] )], file_dep=[__file__])
        my_runner = runner.Runner(depfile.name, reporter)
        my_runner.dep_manager.save_success(t1)
        assert False == my_runner.select_task(ExecNode(t1, None), {})
        assert ('start', t1) == reporter.log.pop(0)
        assert ('up-to-date', t1) == reporter.log.pop(0)
        assert not reporter.log

    def test_ignore(self, reporter, depfile):
        t1 = Task("taskX", [(my_print, ["out a"] )])
        my_runner = runner.Runner(depfile.name, reporter)
        my_runner.dep_manager.ignore(t1)
        assert False == my_runner.select_task(ExecNode(t1, None), {})
        assert ('start', t1) == reporter.log.pop(0)
        assert ('ignore', t1) == reporter.log.pop(0)
        assert not reporter.log

    def test_alwaysExecute(self, reporter, depfile):
        t1 = Task("taskX", [(my_print, ["out a"] )])
        my_runner = runner.Runner(depfile.name, reporter, always_execute=True)
        my_runner.dep_manager.save_success(t1)
        assert True == my_runner.select_task(ExecNode(t1, None), {})
        assert ('start', t1) == reporter.log.pop(0)
        assert not reporter.log

    def test_noSetup_ok(self, reporter, depfile):
        t1 = Task("taskX", [(my_print, ["out a"] )])
        my_runner = runner.Runner(depfile.name, reporter)
        assert True == my_runner.select_task(ExecNode(t1, None), {})
        assert ('start', t1) == reporter.log.pop(0)
        assert not reporter.log

    def test_withSetup(self, reporter, depfile):
        t1 = Task("taskX", [(my_print, ["out a"] )], setup=["taskY"])
        my_runner = runner.Runner(depfile.name, reporter)
        # defer execution
        n1 = ExecNode(t1, None)
        assert False == my_runner.select_task(n1, {})
        assert ('start', t1) == reporter.log.pop(0)
        assert not reporter.log
        # trying to select again
        assert True == my_runner.select_task(n1, {})
        assert not reporter.log

    def test_getargs_ok(self, reporter, depfile):
        def ok(): return {'x':1}
        def check_x(my_x): return my_x == 1
        t1 = Task('t1', [(ok,)])
        n1 = ExecNode(t1, None)
        t2 = Task('t2', [(check_x,)], getargs={'my_x':('t1','x')})
        n2 = ExecNode(t2, None)
        my_runner = runner.Runner(depfile.name, reporter)

        # t2 gives chance for setup tasks to be executed
        assert False == my_runner.select_task(n2, {})
        assert ('start', t2) == reporter.log.pop(0)

        # execute task t1 to calculate value
        assert True == my_runner.select_task(n1, {})
        assert ('start', t1) == reporter.log.pop(0)
        t1_result = my_runner.execute_task(t1)
        assert ('execute', t1) == reporter.log.pop(0)
        my_runner.process_task_result(n1, t1_result)
        assert ('success', t1) == reporter.log.pop(0)

        # t2.options are set on select_task
        assert {} == t2.options
        assert True == my_runner.select_task(n2, {})
        assert not reporter.log
        assert {'my_x': 1} == t2.options

    def test_getargs_fail(self, reporter, depfile):
        # invalid getargs. Exception wil be raised and task will fail
        def check_x(my_x): return True
        t1 = Task('t1', [lambda :True])
        n1 = ExecNode(t1, None)
        t2 = Task('t2', [(check_x,)], getargs={'my_x':('t1','x')})
        n2 = ExecNode(t2, None)
        my_runner = runner.Runner(depfile.name, reporter)

        # t2 gives chance for setup tasks to be executed
        assert False == my_runner.select_task(n2, {})
        assert ('start', t2) == reporter.log.pop(0)

        # execute task t1 to calculate value
        assert True == my_runner.select_task(n1, {})
        assert ('start', t1) == reporter.log.pop(0)
        t1_result = my_runner.execute_task(t1)
        assert ('execute', t1) == reporter.log.pop(0)
        my_runner.process_task_result(n1, t1_result)
        assert ('success', t1) == reporter.log.pop(0)

        # select_task t2 fails
        assert False == my_runner.select_task(n2, {})
        assert ('fail', t2) == reporter.log.pop(0)
        assert not reporter.log

    def test_getargs_dict(self, reporter, depfile):
        def ok(): return {'x':1}
        t1 = Task('t1', [(ok,)])
        n1 = ExecNode(t1, None)
        t2 = Task('t2', None, getargs={'my_x':('t1', None)})
        tasks_dict = {'t1': t1, 't2':t2}
        my_runner = runner.Runner(depfile.name, reporter)
        t1_result = my_runner.execute_task(t1)
        my_runner.process_task_result(n1, t1_result)

        # t2.options are set on _get_task_args
        assert {} == t2.options
        my_runner._get_task_args(t2, tasks_dict)
        assert {'my_x': {'x':1}} == t2.options

    def test_getargs_group(self, reporter, depfile):
        def ok(): return {'x':1}
        t1 = Task('t1', None, task_dep=['t1:a'], has_subtask=True)
        t1a = Task('t1:a', [(ok,)], is_subtask=True)
        t2 = Task('t2', None, getargs={'my_x':('t1', None)})
        tasks_dict = {'t1': t1, 't1a':t1a, 't2':t2}
        my_runner = runner.Runner(depfile.name, reporter)
        t1a_result = my_runner.execute_task(t1a)
        my_runner.process_task_result(ExecNode(t1a, None), t1a_result)

        # t2.options are set on _get_task_args
        assert {} == t2.options
        my_runner._get_task_args(t2, tasks_dict)
        assert {'my_x': [{'x':1}]} == t2.options

class TestTask_Teardown(object):
    def test_ok(self, reporter, depfile):
        touched = []
        def touch():
            touched.append(1)
        t1 = Task('t1', [], teardown=[(touch,)])
        my_runner = runner.Runner(depfile.name, reporter)
        my_runner.teardown_list = [t1]
        my_runner.teardown()
        assert 1 == len(touched)
        assert ('teardown', t1) == reporter.log.pop(0)
        assert not reporter.log

    def test_reverse_order(self, reporter, depfile):
        def do_nothing():pass
        t1 = Task('t1', [], teardown=[do_nothing])
        t2 = Task('t2', [], teardown=[do_nothing])
        my_runner = runner.Runner(depfile.name, reporter)
        my_runner.teardown_list = [t1, t2]
        my_runner.teardown()
        assert ('teardown', t2) == reporter.log.pop(0)
        assert ('teardown', t1) == reporter.log.pop(0)
        assert not reporter.log

    def test_errors(self, reporter, depfile):
        def raise_something(x):
            raise Exception(x)
        t1 = Task('t1', [], teardown=[(raise_something,['t1 blow'])])
        t2 = Task('t2', [], teardown=[(raise_something,['t2 blow'])])
        my_runner = runner.Runner(depfile.name, reporter)
        my_runner.teardown_list = [t1, t2]
        my_runner.teardown()
        assert ('teardown', t2) == reporter.log.pop(0)
        assert ('cleanup_error',) == reporter.log.pop(0)
        assert ('teardown', t1) == reporter.log.pop(0)
        assert ('cleanup_error',) == reporter.log.pop(0)
        assert not reporter.log

class TestTask_RunAll(object):
    def test_reporter_runtime_error(self, reporter, depfile):
        t1 = Task('t1', [], calc_dep=['t2'])
        t2 = Task('t2', [lambda: {'file_dep':[1]}])
        my_runner = runner.Runner(depfile.name, reporter)
        my_runner.run_all(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))
        assert ('start', t2) == reporter.log.pop(0)
        assert ('execute', t2) == reporter.log.pop(0)
        assert ('success', t2) == reporter.log.pop(0)
        assert ('runtime_error',) == reporter.log.pop(0)
        assert not reporter.log

# run tests in both single process runner and multi-process runner
RUNNERS = [runner.Runner]
# TODO: test should be added and skipped!
if runner.MRunner.available():
    RUNNERS.append(runner.MRunner)
@pytest.fixture(params=RUNNERS)
def RunnerClass(request):
    return request.param

# decorator to force coverage on function.
# used to get coverage using multiprocessing.
def cov_dec(func): # pragma: no cover
    try:
        import coverage
    except:
        # coverage should not be required
        return func
    def wrap(*args, **kwargs):
        cov = coverage.coverage(data_suffix=True)
        cov.start()
        try:
            return  func(*args, **kwargs)
        finally:
            cov.stop()
            cov.save()
    return wrap

# monkey patch function executed in a subprocess to get coverage
# TODO - disabled because it was not working anymore...
#runner.MRunner.execute_task = cov_dec(runner.MRunner.execute_task)

def ok(): return "ok"
def ok2(): return "different"

class TestRunner_run_tasks(object):

    def test_teardown(self, reporter, RunnerClass, depfile):
        t1 = Task('t1', [], teardown=[ok])
        t2 = Task('t2', [])
        my_runner = RunnerClass(depfile.name, reporter)
        assert [] == my_runner.teardown_list
        my_runner.run_tasks(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))
        my_runner.finish()
        assert ('teardown', t1) == reporter.log[-1]

    # testing whole process/API
    def test_success(self, reporter, RunnerClass, depfile):
        t1 = Task("t1", [(my_print, ["out a"] )] )
        t2 = Task("t2", [(my_print, ["out a"] )] )
        my_runner = RunnerClass(depfile.name, reporter)
        my_runner.run_tasks(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))
        assert runner.SUCCESS == my_runner.finish()
        assert ('start', t1) == reporter.log.pop(0), reporter.log
        assert ('execute', t1) == reporter.log.pop(0)
        assert ('success', t1) == reporter.log.pop(0)
        assert ('start', t2) == reporter.log.pop(0)
        assert ('execute', t2) == reporter.log.pop(0)
        assert ('success', t2) == reporter.log.pop(0)

    # test result, value, out, err are saved into task
    def test_result(self, reporter, RunnerClass, depfile):
        def my_action():
            import sys
            sys.stdout.write('out here')
            sys.stderr.write('err here')
            return {'bb': 5}
        task = Task("taskY", [my_action] )
        my_runner = RunnerClass(depfile.name, reporter)
        assert None == task.result
        assert {} == task.values
        assert [None] == [a.out for a in task.actions]
        assert [None] == [a.err for a in task.actions]
        my_runner.run_tasks(TaskDispatcher({'taskY':task}, [], ['taskY']))
        assert runner.SUCCESS == my_runner.finish()
        assert {'bb': 5} == task.result
        assert {'bb': 5} == task.values
        assert ['out here'] == [a.out for a in task.actions]
        assert ['err here'] == [a.err for a in task.actions]

    # whenever a task fails remaining task are not executed
    def test_failureOutput(self, reporter, RunnerClass, depfile):
        t1 = Task("t1", [_fail])
        t2 = Task("t2", [_fail])
        my_runner = RunnerClass(depfile.name, reporter)
        my_runner.run_tasks(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))
        assert runner.FAILURE == my_runner.finish()
        assert ('start', t1) == reporter.log.pop(0)
        assert ('execute', t1) == reporter.log.pop(0)
        assert ('fail', t1) == reporter.log.pop(0)
        # second task is not executed
        assert 0 == len(reporter.log)

    def test_error(self, reporter, RunnerClass, depfile):
        t1 = Task("t1", [_error])
        t2 = Task("t2", [_error])
        my_runner = RunnerClass(depfile.name, reporter)
        my_runner.run_tasks(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))
        assert runner.ERROR == my_runner.finish()
        assert ('start', t1) == reporter.log.pop(0)
        assert ('execute', t1) == reporter.log.pop(0)
        assert ('fail', t1) == reporter.log.pop(0)
        # second task is not executed
        assert 0 == len(reporter.log)

    # when successful dependencies are updated
    def test_updateDependencies(self, reporter, RunnerClass, depfile):
        depPath = os.path.join(os.path.dirname(__file__),"data/dependency1")
        ff = open(depPath,"a")
        ff.write("xxx")
        ff.close()
        dependencies = [depPath]

        filePath = os.path.join(os.path.dirname(__file__),"data/target")
        ff = open(filePath,"a")
        ff.write("xxx")
        ff.close()
        targets = [filePath]

        t1 = Task("t1", [my_print], dependencies, targets)
        my_runner = RunnerClass(depfile.name, reporter)
        my_runner.run_tasks(TaskDispatcher({'t1':t1}, [], ['t1']))
        assert runner.SUCCESS == my_runner.finish()
        d = Dependency(depfile.name)
        assert d._get("t1", os.path.abspath(depPath))

    def test_continue(self, reporter, RunnerClass, depfile):
        t1 = Task("t1", [(_fail,)] )
        t2 = Task("t2", [(_error,)] )
        t3 = Task("t3", [(ok,)])
        my_runner = RunnerClass(depfile.name, reporter, continue_=True)
        disp = TaskDispatcher({'t1':t1, 't2':t2, 't3':t3}, [], ['t1', 't2', 't3'])
        my_runner.run_tasks(disp)
        assert runner.ERROR == my_runner.finish()
        assert ('start', t1) == reporter.log.pop(0)
        assert ('execute', t1) == reporter.log.pop(0)
        assert ('fail', t1) == reporter.log.pop(0)
        assert ('start', t2) == reporter.log.pop(0)
        assert ('execute', t2) == reporter.log.pop(0)
        assert ('fail', t2) == reporter.log.pop(0)
        assert ('start', t3) == reporter.log.pop(0)
        assert ('execute', t3) == reporter.log.pop(0)
        assert ('success', t3) == reporter.log.pop(0)
        assert 0 == len(reporter.log)

    def test_continue_dont_execute_parent_of_failed_task(self, reporter,
                                                         RunnerClass, depfile):
        t1 = Task("t1", [(_error,)] )
        t2 = Task("t2", [(ok,)], task_dep=['t1'])
        t3 = Task("t3", [(ok,)])
        my_runner = RunnerClass(depfile.name, reporter, continue_=True)
        disp = TaskDispatcher({'t1':t1, 't2':t2, 't3':t3}, [], ['t1', 't2', 't3'])
        my_runner.run_tasks(disp)
        assert runner.ERROR == my_runner.finish()
        assert ('start', t1) == reporter.log.pop(0)
        assert ('execute', t1) == reporter.log.pop(0)
        assert ('fail', t1) == reporter.log.pop(0)
        assert ('start', t2) == reporter.log.pop(0)
        assert ('fail', t2) == reporter.log.pop(0)
        assert ('start', t3) == reporter.log.pop(0)
        assert ('execute', t3) == reporter.log.pop(0)
        assert ('success', t3) == reporter.log.pop(0)
        assert 0 == len(reporter.log)

    def test_continue_dep_error(self, reporter, RunnerClass, depfile):
        t1 = Task("t1", [(ok,)], file_dep=['i_dont_exist'] )
        t2 = Task("t2", [(ok,)], task_dep=['t1'])
        my_runner = RunnerClass(depfile.name, reporter, continue_=True)
        disp = TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2'])
        my_runner.run_tasks(disp)
        assert runner.ERROR == my_runner.finish()
        assert ('start', t1) == reporter.log.pop(0)
        assert ('fail', t1) == reporter.log.pop(0)
        assert ('start', t2) == reporter.log.pop(0)
        assert ('fail', t2) == reporter.log.pop(0)
        assert 0 == len(reporter.log)

    def test_continue_ignored_dep(self, reporter, RunnerClass, depfile):
        t1 = Task("t1", [(ok,)], )
        t2 = Task("t2", [(ok,)], task_dep=['t1'])
        my_runner = RunnerClass(depfile.name, reporter, continue_=True)
        my_runner.dep_manager.ignore(t1)
        disp = TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2'])
        my_runner.run_tasks(disp)
        assert runner.SUCCESS == my_runner.finish()
        assert ('start', t1) == reporter.log.pop(0)
        assert ('ignore', t1) == reporter.log.pop(0)
        assert ('start', t2) == reporter.log.pop(0)
        assert ('ignore', t2) == reporter.log.pop(0)
        assert 0 == len(reporter.log)

    def test_getargs(self, reporter, RunnerClass, depfile):
        def use_args(arg1):
            print arg1
        def make_args(): return {'myarg':1}
        t1 = Task("t1", [(use_args,)], getargs=dict(arg1=('t2','myarg')) )
        t2 = Task("t2", [(make_args,)])
        my_runner = RunnerClass(depfile.name, reporter)
        my_runner.run_tasks(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))
        assert runner.SUCCESS == my_runner.finish()
        assert ('start', t1) == reporter.log.pop(0)
        assert ('start', t2) == reporter.log.pop(0)
        assert ('execute', t2) == reporter.log.pop(0)
        assert ('success', t2) == reporter.log.pop(0)
        assert ('execute', t1) == reporter.log.pop(0)
        assert ('success', t1) == reporter.log.pop(0)
        assert 0 == len(reporter.log)

    # SystemExit runner should not interfere with SystemExit
    def testSystemExitRaises(self, reporter, RunnerClass, depfile):
        t1 = Task("t1", [_exit])
        my_runner = RunnerClass(depfile.name, reporter)
        disp = TaskDispatcher({'t1':t1}, [], ['t1'])
        pytest.raises(SystemExit, my_runner.run_tasks, disp)
        my_runner.finish()

class TestMReporter(object):
    class MyRunner(object):
        def __init__(self):
            self.result_q = Queue()

    def testReporterMethod(self, reporter):
        fake_runner = self.MyRunner()
        mp_reporter = runner.MReporter(fake_runner, reporter)
        my_task = Task("task x", [])
        mp_reporter.add_success(my_task)
        got = fake_runner.result_q.get(True, 1)
        assert {'name': "task x", "reporter": 'add_success'} == got

    def testNonReporterMethod(self, reporter):
        fake_runner = self.MyRunner()
        mp_reporter = runner.MReporter(fake_runner, reporter)
        assert hasattr(mp_reporter, 'add_success')
        assert not hasattr(mp_reporter, 'no_existent_method')
# python2.5 dont have class decorators
pytest.mark.skipif('not runner.MRunner.available()')(TestMReporter)

class TestMRunner_get_next_task(object):
    # simple normal case
    def test_run_task(self, reporter, depfile):
        t1 = Task('t1', [])
        t2 = Task('t2', [])
        run = runner.MRunner(depfile.name, reporter)
        run._run_tasks_init(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))
        assert t1 == run.get_next_task(None).task
        assert t2 == run.get_next_task(None).task
        assert None == run.get_next_task(None)

    def test_stop_running(self, reporter, depfile):
        t1 = Task('t1', [])
        t2 = Task('t2', [])
        run = runner.MRunner(depfile.name, reporter)
        run._run_tasks_init(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))
        assert t1 == run.get_next_task(None).task
        run._stop_running = True
        assert None == run.get_next_task(None)

    def test_waiting(self, reporter, depfile):
        t1 = Task('t1', [])
        t2 = Task('t2', [], setup=('t1',))
        run = runner.MRunner(depfile.name, reporter)
        run._run_tasks_init(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t2']))

        # first start task 1
        n1 = run.get_next_task(None)
        assert t1 == n1.task

        # hold until t1 is done
        assert isinstance(run.get_next_task(None), runner.Hold)
        assert isinstance(run.get_next_task(None), runner.Hold)
        n1.run_status = 'done'

        n2 = run.get_next_task(n1)
        assert t2 == n2.task
        assert None == run.get_next_task(n2)

    def test_waiting_controller(self, reporter, depfile):
        t1 = Task('t1', [])
        t2 = Task('t2', [], calc_dep=('t1',))
        run = runner.MRunner(depfile.name, reporter)
        run._run_tasks_init(TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2']))

        # first task ok
        assert t1 == run.get_next_task(None).task

        # hold until t1 finishes
        assert 0 == run.free_proc
        assert isinstance(run.get_next_task(None), runner.Hold)
        assert 1 == run.free_proc
# python2.5 dont have class decorators
pytest.mark.skipif('not runner.MRunner.available()')(TestMRunner_get_next_task)

class TestMRunner_start_process(object):
    # 2 process, 3 tasks
    def test_all_processes(self, reporter, monkeypatch, depfile):
        mock_process = Mock()
        monkeypatch.setattr(runner, 'Process', mock_process)
        t1 = Task('t1', [])
        t2 = Task('t2', [])
        td = TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2'])
        run = runner.MRunner(depfile.name, reporter, num_process=2)
        run._run_tasks_init(td)
        result_q = Queue()
        task_q = Queue()

        proc_list = run._run_start_processes(task_q, result_q)
        run.finish()
        assert 2 == len(proc_list)
        assert t1.name == task_q.get().name
        assert t2.name == task_q.get().name

    # 2 process, 1 task
    def test_less_processes(self, reporter, monkeypatch, depfile):
        mock_process = Mock()
        monkeypatch.setattr(runner, 'Process', mock_process)
        t1 = Task('t1', [])
        td = TaskDispatcher({'t1':t1}, [], ['t1'])
        run = runner.MRunner(depfile.name, reporter, num_process=2)
        run._run_tasks_init(td)
        result_q = Queue()
        task_q = Queue()

        proc_list = run._run_start_processes(task_q, result_q)
        run.finish()
        assert 1 == len(proc_list)
        assert t1.name == task_q.get().name

    # 2 process, 2 tasks (but only one task can be started)
    def test_waiting_process(self, reporter, monkeypatch, depfile):
        mock_process = Mock()
        monkeypatch.setattr(runner, 'Process', mock_process)
        t1 = Task('t1', [])
        t2 = Task('t2', [], task_dep=['t1'])
        td = TaskDispatcher({'t1':t1, 't2':t2}, [], ['t1', 't2'])
        run = runner.MRunner(depfile.name, reporter, num_process=2)
        run._run_tasks_init(td)
        result_q = Queue()
        task_q = Queue()

        proc_list = run._run_start_processes(task_q, result_q)
        run.finish()
        assert 2 == len(proc_list)
        assert t1.name == task_q.get().name
        assert isinstance(task_q.get(), runner.Hold)
# python2.5 dont have class decorators
pytest.mark.skipif('not runner.MRunner.available()')(TestMRunner_start_process)

class TestMRunner_execute_task(object):
    def test_hold(self, reporter, depfile):
        run = runner.MRunner(depfile.name, reporter)
        task_q = Queue()
        task_q.put(runner.Hold()) # to test
        task_q.put(None) # to terminate function
        result_q = Queue()
        run.execute_task_subprocess(task_q, result_q)
        run.finish()
        # nothing was done
        assert result_q.empty() # pragma: no cover (coverage bug?)
# python2.5 dont have class decorators
pytest.mark.skipif('not runner.MRunner.available()')(TestMRunner_execute_task)


text:
package command

import (
	"fmt"
	"net"
	"regexp"
	"sort"
	"strings"

	consulapi "github.com/hashicorp/consul/api"
	"github.com/hashicorp/serf/serf"
	"github.com/ryanuber/columnize"
)

// MembersCommand is a Command implementation that queries a running
// Consul agent what members are part of the cluster currently.
type MembersCommand struct {
	BaseCommand
}

func (c *MembersCommand) Help() string {
	helpText := `
Usage: consul members [options]

  Outputs the members of a running Consul agent.

` + c.BaseCommand.Help()

	return strings.TrimSpace(helpText)
}

func (c *MembersCommand) Run(args []string) int {
	var detailed bool
	var wan bool
	var statusFilter string

	f := c.BaseCommand.NewFlagSet(c)
	f.BoolVar(&detailed, "detailed", false,
		"Provides detailed information about nodes.")
	f.BoolVar(&wan, "wan", false,
		"If the agent is in server mode, this can be used to return the other "+
			"peers in the WAN pool.")
	f.StringVar(&statusFilter, "status", ".*",
		"If provided, output is filtered to only nodes matching the regular "+
			"expression for status.")

	if err := c.BaseCommand.Parse(args); err != nil {
		return 1
	}

	// Compile the regexp
	statusRe, err := regexp.Compile(statusFilter)
	if err != nil {
		c.UI.Error(fmt.Sprintf("Failed to compile status regexp: %v", err))
		return 1
	}

	client, err := c.BaseCommand.HTTPClient()
	if err != nil {
		c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
		return 1
	}

	members, err := client.Agent().Members(wan)
	if err != nil {
		c.UI.Error(fmt.Sprintf("Error retrieving members: %s", err))
		return 1
	}

	// Filter the results
	n := len(members)
	for i := 0; i < n; i++ {
		member := members[i]
		statusString := serf.MemberStatus(member.Status).String()
		if !statusRe.MatchString(statusString) {
			members[i], members[n-1] = members[n-1], members[i]
			i--
			n--
			continue
		}
	}
	members = members[:n]

	// No matching members
	if len(members) == 0 {
		return 2
	}

	sort.Sort(ByMemberName(members))

	// Generate the output
	var result []string
	if detailed {
		result = c.detailedOutput(members)
	} else {
		result = c.standardOutput(members)
	}

	// Generate the columnized version
	output := columnize.SimpleFormat(result)
	c.UI.Output(output)

	return 0
}

// so we can sort members by name
type ByMemberName []*consulapi.AgentMember

func (m ByMemberName) Len() int           { return len(m) }
func (m ByMemberName) Swap(i, j int)      { m[i], m[j] = m[j], m[i] }
func (m ByMemberName) Less(i, j int) bool { return m[i].Name < m[j].Name }

// standardOutput is used to dump the most useful information about nodes
// in a more human-friendly format
func (c *MembersCommand) standardOutput(members []*consulapi.AgentMember) []string {
	result := make([]string, 0, len(members))
	header := "Node|Address|Status|Type|Build|Protocol|DC"
	result = append(result, header)
	for _, member := range members {
		addr := net.TCPAddr{IP: net.ParseIP(member.Addr), Port: int(member.Port)}
		protocol := member.Tags["vsn"]
		build := member.Tags["build"]
		if build == "" {
			build = "< 0.3"
		} else if idx := strings.Index(build, ":"); idx != -1 {
			build = build[:idx]
		}
		dc := member.Tags["dc"]

		statusString := serf.MemberStatus(member.Status).String()
		switch member.Tags["role"] {
		case "node":
			line := fmt.Sprintf("%s|%s|%s|client|%s|%s|%s",
				member.Name, addr.String(), statusString, build, protocol, dc)
			result = append(result, line)
		case "consul":
			line := fmt.Sprintf("%s|%s|%s|server|%s|%s|%s",
				member.Name, addr.String(), statusString, build, protocol, dc)
			result = append(result, line)
		default:
			line := fmt.Sprintf("%s|%s|%s|unknown|||",
				member.Name, addr.String(), statusString)
			result = append(result, line)
		}
	}
	return result
}

// detailedOutput is used to dump all known information about nodes in
// their raw format
func (c *MembersCommand) detailedOutput(members []*consulapi.AgentMember) []string {
	result := make([]string, 0, len(members))
	header := "Node|Address|Status|Tags"
	result = append(result, header)
	for _, member := range members {
		// Get the tags sorted by key
		tagKeys := make([]string, 0, len(member.Tags))
		for key := range member.Tags {
			tagKeys = append(tagKeys, key)
		}
		sort.Strings(tagKeys)

		// Format the tags as tag1=v1,tag2=v2,...
		var tagPairs []string
		for _, key := range tagKeys {
			tagPairs = append(tagPairs, fmt.Sprintf("%s=%s", key, member.Tags[key]))
		}

		tags := strings.Join(tagPairs, ",")

		addr := net.TCPAddr{IP: net.ParseIP(member.Addr), Port: int(member.Port)}
		line := fmt.Sprintf("%s|%s|%s|%s",
			member.Name, addr.String(), serf.MemberStatus(member.Status).String(), tags)
		result = append(result, line)
	}
	return result
}

func (c *MembersCommand) Synopsis() string {
	return "Lists the members of a Consul cluster"
}


text:
package edu.ucla.nesl.flowengine.node.feature;

import java.util.ArrayList;

import edu.ucla.nesl.flowengine.DataType;
import edu.ucla.nesl.flowengine.DebugHelper;
import edu.ucla.nesl.flowengine.InvalidDataReporter;
import edu.ucla.nesl.flowengine.node.DataFlowNode;

public class IERatio extends DataFlowNode {
	private static final String TAG = IERatio.class.getSimpleName();

	@Override
	protected String processParentNodeName(String parentNodeName) {
		if (parentNodeName.contains("|PeakValley")) {
			return parentNodeName.split("\\|PeakValley")[0];
		}
		return parentNodeName;
	}

	private int[] calculateIERatio(int[] data, int length) {
		int inhalation = 0,exhalation = 0;

		ArrayList<Integer> list=new ArrayList<Integer>();
		int temp=length;
		for(int i=0;i<temp;i+=4)
		{
			//check the starting whether it starts from valley or not. It should be valley
			if((i==0) && (data[i+1]>data[i+3]))
				continue;						//it escaping if first member is a peak. in that case we can not find the inspiration. inspiration always starts from a valley

			//check last element whether it is valley or peak. it should be valley
			if((i==0)&&(data[length-1]>data[length-3]))		//at the beginning the stopping condition is changed
				temp=length-2;						//skipping the last one if it is peak

			if(i+4<length)
			{
				inhalation=data[i+2]-data[i];
				exhalation=data[i+4]-data[i+2];
				float ieRatio=(float)inhalation/exhalation;
				int raoundedIeRatio=(int)(ieRatio*10000);
				list.add(new Integer(raoundedIeRatio));
			}
		}

		//converting the ArrayList to array
		int ieRatio[]=new int[list.size()];
		for(int j=0;j<list.size();j++)
		{
			ieRatio[j]=list.get(j).intValue();
		}

		DebugHelper.dump(TAG, ieRatio);

		return ieRatio;
	}

	@Override
	protected void processInput(String name, String type, Object inputData, int length, long timestamp) {
		if (length <= 0) {
			InvalidDataReporter.report("in " + TAG + ": name: " + name + ", type: " + type + ", length: " + length);
			return;
		}
		if (!type.equals(DataType.INTEGER_ARRAY)) {
			throw new UnsupportedOperationException("Unsupported type: " + type);
		}

		int[] ieRatio = calculateIERatio((int[])inputData, length);

		output(name.replace("PeakValley", "IERatio"), DataType.INTEGER_ARRAY, ieRatio, ieRatio.length, timestamp);
	}

}


text:
package org.fandev.lang.fan.psi.api.statements;

import org.fandev.lang.fan.psi.FanElement;
import org.fandev.lang.fan.psi.FanType;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.intellij.psi.PsiNameIdentifierOwner;
import com.intellij.psi.PsiNamedElement;

/**
 * Date: Apr 28, 2009
 * Time: 5:20:45 PM
 *
 * @author Dror Bereznitsky
 */
public interface FanVariable extends FanElement, PsiNamedElement, PsiNameIdentifierOwner
{
	@Nonnull
	FanType getType();

	@Nullable
	FanType getDeclaredType();
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Wikipedia Search</title>
	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" media="screen" />
	<link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />

			<input type="text" id="searchinput" class="search-query" placeholder="Search Wikipedia" data-provide="typeahead">

            <button id="cancel" class="btn" type="submit">
                Close
            </button>


text:
* issue #18: Fixed checking expire value in queries.
* Fix PHP coding standards.

## v2.1.0
* issue #15: Convert Memcached to MySQL.

## v2.0.3
* issue #11: Added warning popup alerting with the user who's editing object.
* issue #12: Fixed realtime caching of edit users.

## v2.0.2
* issue #5: Load ActiveEdits script only when editing an object.
* issue #8: [HeartbeatCmsController] Force slugs parameter to be array.

## v2.0.1
* issue #3: [HeartbeatCmsController] Ensure that a lock for a given slug expires in 10 seconds, not 1 hour.
* issue #3: [HeartbeatCmsController] Reduce cache ttl to 2 minutes for all active edit keys.

## v2.0.0
* issue #1: Removed all NCR references and store data in cache.
* issue #1: Create an SQL purge script to remove all `active_edit_*` tables, and all related tags with `ElementID` and `Role=active-edit-record` from all tables.

> Note: ElementID is different per site.

## v1.4.0
* Removed _updateSaveMessage method and calls to it, with the updated history plugin, history elements/aspects/etc are no longer available and this method is no longer valid. Ticket #221
* Removed config `$properties['active.edit.saved.record.check.frequency']`.

## v1.3.0
* Added maintenance cli controller, /cli/activeeditmaintenance/deleteInactiveRecords?hourOffset=6. This allows a cron/etc to delete inactive nodes still in 'draft' mode.
* Updating api/find-all requests to specific Status.eq = 'draft'.  This should speed up active-edit queries greatly.  Code relies on active-edit records to be 'draft' mode (and currently active-edit nodes are never published, in 'draft' or 'deleted')

## v1.2.0
* Tagging active-edit does not generate a history record. Ticket #2251

## v1.1.0
* initial versioned commit


text:
#include "talk/xmpp/pubsubtasks.h"

#include <string>
#include <vector>

#include "talk/xmpp/constants.h"
#include "talk/xmpp/receivetask.h"

// An implementation of the tasks for XEP-0060
// (http://xmpp.org/extensions/xep-0060.html).

namespace buzz {

namespace {

bool IsPubSubEventItemsElem(const XmlElement* stanza,
                            const std::string& expected_node) {
  if (stanza->Name() != QN_MESSAGE) {
    return false;
  }

  const XmlElement* event_elem = stanza->FirstNamed(QN_PUBSUB_EVENT);
  if (event_elem == NULL) {
    return false;
  }

  const XmlElement* items_elem = event_elem->FirstNamed(QN_PUBSUB_EVENT_ITEMS);
  if (items_elem == NULL) {
    return false;
  }

  const std::string& actual_node = items_elem->Attr(QN_NODE);
  return (actual_node == expected_node);
}

// Creates <pubsub node="node"><items></pubsub>
XmlElement* CreatePubSubItemsElem(const std::string& node) {
  XmlElement* items_elem = new XmlElement(QN_PUBSUB_ITEMS, false);
  items_elem->AddAttr(QN_NODE, node);
  XmlElement* pubsub_elem = new XmlElement(QN_PUBSUB, false);
  pubsub_elem->AddElement(items_elem);
  return pubsub_elem;
}

// Creates <pubsub node="node"><publish><item id="itemid">payload</item>...
// Takes ownership of payload.
XmlElement* CreatePubSubPublishItemElem(
    const std::string& node,
    const std::string& itemid,
    const std::vector<XmlElement*>& children) {
  XmlElement* pubsub_elem = new XmlElement(QN_PUBSUB, true);
  XmlElement* publish_elem = new XmlElement(QN_PUBSUB_PUBLISH, false);
  publish_elem->AddAttr(QN_NODE, node);
  XmlElement* item_elem = new XmlElement(QN_PUBSUB_ITEM, false);
  item_elem->AddAttr(QN_ID, itemid);
  for (std::vector<XmlElement*>::const_iterator child = children.begin();
       child != children.end(); ++child) {
    item_elem->AddElement(*child);
  }
  publish_elem->AddElement(item_elem);
  pubsub_elem->AddElement(publish_elem);
  return pubsub_elem;
}

// Creates <pubsub node="node"><publish><item id="itemid">payload</item>...
// Takes ownership of payload.
XmlElement* CreatePubSubRetractItemElem(const std::string& node,
                                        const std::string& itemid) {
  XmlElement* pubsub_elem = new XmlElement(QN_PUBSUB, true);
  XmlElement* retract_elem = new XmlElement(QN_PUBSUB_RETRACT, false);
  retract_elem->AddAttr(QN_NODE, node);
  retract_elem->AddAttr(QN_NOTIFY, "true");
  XmlElement* item_elem = new XmlElement(QN_PUBSUB_ITEM, false);
  item_elem->AddAttr(QN_ID, itemid);
  retract_elem->AddElement(item_elem);
  pubsub_elem->AddElement(retract_elem);
  return pubsub_elem;
}

void ParseItem(const XmlElement* item_elem,
               std::vector<PubSubItem>* items) {
  PubSubItem item;
  item.itemid = item_elem->Attr(QN_ID);
  item.elem = item_elem;
  items->push_back(item);
}

// Right now, <retract>s are treated the same as items with empty
// payloads.  We may want to change it in the future, but right now
// it's sufficient for our needs.
void ParseRetract(const XmlElement* retract_elem,
                  std::vector<PubSubItem>* items) {
  ParseItem(retract_elem, items);
}

void ParseEventItemsElem(const XmlElement* stanza,
                         std::vector<PubSubItem>* items) {
  const XmlElement* event_elem = stanza->FirstNamed(QN_PUBSUB_EVENT);
  if (event_elem != NULL) {
    const XmlElement* items_elem =
        event_elem->FirstNamed(QN_PUBSUB_EVENT_ITEMS);
    if (items_elem != NULL) {
      for (const XmlElement* item_elem =
             items_elem->FirstNamed(QN_PUBSUB_EVENT_ITEM);
           item_elem != NULL;
           item_elem = item_elem->NextNamed(QN_PUBSUB_EVENT_ITEM)) {
        ParseItem(item_elem, items);
      }
      for (const XmlElement* retract_elem =
             items_elem->FirstNamed(QN_PUBSUB_EVENT_RETRACT);
           retract_elem != NULL;
           retract_elem = retract_elem->NextNamed(QN_PUBSUB_EVENT_RETRACT)) {
        ParseRetract(retract_elem, items);
      }
    }
  }
}

void ParsePubSubItemsElem(const XmlElement* stanza,
                          std::vector<PubSubItem>* items) {
  const XmlElement* pubsub_elem = stanza->FirstNamed(QN_PUBSUB);
  if (pubsub_elem != NULL) {
    const XmlElement* items_elem = pubsub_elem->FirstNamed(QN_PUBSUB_ITEMS);
    if (items_elem != NULL) {
      for (const XmlElement* item_elem = items_elem->FirstNamed(QN_PUBSUB_ITEM);
           item_elem != NULL;
           item_elem = item_elem->NextNamed(QN_PUBSUB_ITEM)) {
        ParseItem(item_elem, items);
      }
    }
  }
}

}  // namespace

PubSubRequestTask::PubSubRequestTask(XmppTaskParentInterface* parent,
                                     const Jid& pubsubjid,
                                     const std::string& node)
    : IqTask(parent, STR_GET, pubsubjid, CreatePubSubItemsElem(node)) {
}

void PubSubRequestTask::HandleResult(const XmlElement* stanza) {
  std::vector<PubSubItem> items;
  ParsePubSubItemsElem(stanza, &items);
  SignalResult(this, items);
}

bool PubSubReceiveTask::WantsStanza(const XmlElement* stanza) {
  return MatchStanzaFrom(stanza, pubsubjid_) &&
      IsPubSubEventItemsElem(stanza, node_);
}

void PubSubReceiveTask::ReceiveStanza(const XmlElement* stanza) {
  std::vector<PubSubItem> items;
  ParseEventItemsElem(stanza, &items);
  SignalUpdate(this, items);
}

PubSubPublishTask::PubSubPublishTask(XmppTaskParentInterface* parent,
                                     const Jid& pubsubjid,
                                     const std::string& node,
                                     const std::string& itemid,
                                     const std::vector<XmlElement*>& children)
    : IqTask(parent, STR_SET, pubsubjid,
             CreatePubSubPublishItemElem(node, itemid, children)),
      itemid_(itemid) {
}

void PubSubPublishTask::HandleResult(const XmlElement* stanza) {
  SignalResult(this);
}

PubSubRetractTask::PubSubRetractTask(XmppTaskParentInterface* parent,
                                     const Jid& pubsubjid,
                                     const std::string& node,
                                     const std::string& itemid)
    : IqTask(parent, STR_SET, pubsubjid,
             CreatePubSubRetractItemElem(node, itemid)),
      itemid_(itemid) {
}

void PubSubRetractTask::HandleResult(const XmlElement* stanza) {
  SignalResult(this);
}

}  // namespace buzz


text:
// Package downloader finds and downloads the coverage profile file from the latest healthy build
// stored in given gcs directory
package downloader

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"path"
	"sort"
	"strconv"

	"cloud.google.com/go/storage"
	"github.com/sirupsen/logrus"
	"google.golang.org/api/iterator"

	prowv1 "k8s.io/test-infra/prow/apis/prowjobs/v1"
)

//listGcsObjects get the slice of gcs objects under a given path
func listGcsObjects(ctx context.Context, client *storage.Client, bucketName, prefix, delim string) (
	[]string, error) {

	var objects []string
	it := client.Bucket(bucketName).Objects(ctx, &storage.Query{
		Prefix:    prefix,
		Delimiter: delim,
	})

	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return objects, fmt.Errorf("error iterating: %w", err)
		}

		if attrs.Prefix != "" {
			objects = append(objects, path.Base(attrs.Prefix))
		}
	}
	logrus.Info("end of listGcsObjects(...)")
	return objects, nil
}

func readGcsObject(ctx context.Context, client *storage.Client, bucket, object string) ([]byte, error) {
	logrus.Infof("Trying to read gcs object '%s' in bucket '%s'\n", object, bucket)
	o := client.Bucket(bucket).Object(object)
	reader, err := o.NewReader(ctx)
	if err != nil {
		return nil, fmt.Errorf("cannot read object '%s': %w", object, err)
	}
	return ioutil.ReadAll(reader)
}

// FindBaseProfile finds the coverage profile file from the latest healthy build
// stored in given gcs directory
func FindBaseProfile(ctx context.Context, client *storage.Client, bucket, prowJobName, artifactsDirName,
	covProfileName string) ([]byte, error) {

	dirOfJob := path.Join("logs", prowJobName)

	strBuilds, err := listGcsObjects(ctx, client, bucket, dirOfJob+"/", "/")
	if err != nil {
		return nil, fmt.Errorf("error listing gcs objects: %w", err)
	}

	builds := sortBuilds(strBuilds)
	profilePath := ""
	for _, build := range builds {
		buildDirPath := path.Join(dirOfJob, strconv.Itoa(build))
		dirOfStatusJSON := path.Join(buildDirPath, prowv1.FinishedStatusFile)

		statusText, err := readGcsObject(ctx, client, bucket, dirOfStatusJSON)
		if err != nil {
			logrus.Infof("Cannot read finished.json (%s) in bucket '%s'", dirOfStatusJSON, bucket)
		} else if isBuildSucceeded(statusText) {
			artifactsDirPath := path.Join(buildDirPath, artifactsDirName)
			profilePath = path.Join(artifactsDirPath, covProfileName)
			break
		}
	}
	if profilePath == "" {
		return nil, fmt.Errorf("no healthy build found for job '%s' in bucket '%s'; total # builds = %v", dirOfJob, bucket, len(builds))
	}
	return readGcsObject(ctx, client, bucket, profilePath)
}

// sortBuilds converts all build from str to int and sorts all builds in descending order and
// returns the sorted slice
func sortBuilds(strBuilds []string) []int {
	var res []int
	for _, buildStr := range strBuilds {
		num, err := strconv.Atoi(buildStr)
		if err != nil {
			logrus.Infof("Non-int build number found: '%s'", buildStr)
		} else {
			res = append(res, num)
		}
	}
	sort.Sort(sort.Reverse(sort.IntSlice(res)))
	return res
}

type finishedStatus struct {
	Timestamp int
	Passed    bool
}

func isBuildSucceeded(jsonText []byte) bool {
	var status finishedStatus
	err := json.Unmarshal(jsonText, &status)
	return err == nil && status.Passed
}


text:
require "helper"
require "generators/minitest/install/install_generator"

class TestInstallGenerator < GeneratorTest

  def test_install_generator
    assert_output(/create  test\/test_helper.rb/m) do
      Minitest::Generators::InstallGenerator.start
    end
    assert File.exists? "test/test_helper.rb"
    contents = File.read "test/test_helper.rb"
    assert_match(/require "rails\/test_help"/m, contents)
    assert_match(/require "minitest\/rails"/m, contents)
    assert_match(/fixtures :all/m, contents)
  end

  def test_install_generator_without_active_record
    assert_output(/create  test\/test_helper.rb/m) do
      Minitest::Generators::InstallGenerator.start ["--skip-active-record"]
    end
    assert File.exists? "test/test_helper.rb"
    contents = File.read "test/test_helper.rb"
    assert_match(/require "rails\/test_help"/m, contents)
    assert_match(/require "minitest\/rails"/m, contents)
    refute_match(/fixtures :all/m, contents)
  end
end


text:
import express from "express";
import validate from "express-validation";
import Joi from "joi";

import authCtrl from "../controllers/auth";

const router = express.Router();

const validations = {
    login: {
        body: {
            username: Joi.string().required(),
            password: Joi.string().required()
        }
    },
    signup: {
        body: {
            username: Joi.string().regex(/^[a-z0-9_]{1,15}$/).required(),
            email: Joi.string().email().required(),
            password: Joi.string().required().min(6)
        }
    }
};

router.route("/login")
    .post(validate(validations.login), authCtrl.login);

router.route("/signup")
    .post(validate(validations.signup), authCtrl.signup);

router.route("/logout")
    .post(authCtrl.logout);

export default router;


text:
module DeviseMultipleTokenAuth
  VERSION = "0.0.3"
end


text:
JSIL.MakeInterface(
  "System.Collections.Generic.IEnumerable`1", true, ["out T"], function ($) {
      $.Method({}, "GetEnumerator", (new JSIL.MethodSignature($jsilcore.TypeRef("System.Collections.Generic.IEnumerator`1", [new JSIL.GenericParameter("T", "System.Collections.Generic.IEnumerable`1")]), [], [])));
  }, [$jsilcore.TypeRef("System.Collections.IEnumerable")],
  JSIL.$TypeAssignableFromExpression,
  function (interfaceTypeObject, signature, thisReference) {
    var typeProto = JSIL.GetType(thisReference).__PublicInterface__.prototype;
    return typeProto[signature.LookupVariantMethodKey(typeProto)];
  });


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/main.css">

        Pulsars
        Gliders
        Blinker
        Crazyness


text:
<?php
    define('DB_HOST', '127.0.0.1');
    define('DB_USER', 'user');
    define('DB_PASSWORD', 'passowrd');
    define('DB_DATABASE', 'database');

$connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR DIE ("Keine Verbindung zu der Datenbank moeglich.");
$db = mysql_select_db(DB_DATABASE , $connection) OR DIE ("Auswahl der Datenbank nicht moeglich.");

error_reporting(E_ALL ^ E_NOTICE);

define ("ADMIN_LEVEL", 5);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);

require_once('userclass.php');
?>


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../孜/index.html">
<meta http-equiv=refresh content="0; url='../孜/index.html'">

Redirecting...

Click here if you are not redirected.


text:
@implementation SSLabel

@synthesize verticalTextAlignment = _verticalTextAlignment;
@synthesize textEdgeInsets = _textEdgeInsets;

#pragma mark NSObject

- (void)dealloc {
	[self removeObserver:self forKeyPath:@"verticalTextAlignment"];
	[self removeObserver:self forKeyPath:@"textEdgeInsets"];
	[super dealloc];
}

#pragma mark UIView

- (id)initWithFrame:(CGRect)aFrame {
	if ((self = [super initWithFrame:aFrame])) {
		self.verticalTextAlignment = SSLabelVerticalTextAlignmentMiddle;
		self.textEdgeInsets = UIEdgeInsetsZero;

		[self addObserver:self forKeyPath:@"verticalTextAlignment" options:NSKeyValueObservingOptionNew context:nil];
		[self addObserver:self forKeyPath:@"textEdgeInsets" options:NSKeyValueObservingOptionNew context:nil];
	}
	return self;
}

#pragma mark UILabel

- (void)drawTextInRect:(CGRect)rect {
	rect = UIEdgeInsetsInsetRect(rect, _textEdgeInsets);

	if (self.verticalTextAlignment == SSLabelVerticalTextAlignmentTop) {
		CGSize sizeThatFits = [self sizeThatFits:rect.size];
		rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, sizeThatFits.height);
	} else if (self.verticalTextAlignment == SSLabelVerticalTextAlignmentBottom) {
		CGSize sizeThatFits = [self sizeThatFits:rect.size];
		rect = CGRectMake(rect.origin.x, rect.origin.y + (rect.size.height - sizeThatFits.height), rect.size.width, sizeThatFits.height);
	}

	[super drawTextInRect:rect];
}

#pragma mark NSKeyValueObserving

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
	// Relayout when properties change
	if ([keyPath isEqualToString:@"verticalTextAlignment"] || [keyPath isEqualToString:@"textEdgeInsets"]) {
		[self setNeedsLayout];
		return;
	}

	[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
tablesaw.addons.java Class Hierarchy
</TITLE>

<META NAME="date" CONTENT="2016-12-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package tablesaw.addons.java

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

tablesaw.rules.AbstractRule<T> (implements tablesaw.rules.Rule)

tablesaw.rules.AbstractSourceRule<T> (implements tablesaw.rules.SourceFileSet)

tablesaw.rules.AbstractPatternRule<T> (implements tablesaw.BuildEventListener)

tablesaw.addons.java.JavaCRule (implements tablesaw.MakeAction)

tablesaw.rules.AbstractSimpleRule<T>

tablesaw.addons.ZipRule (implements tablesaw.MakeAction)

tablesaw.addons.java.JarRule (implements tablesaw.MakeAction)

tablesaw.addons.java.WarRule (implements tablesaw.MakeAction)

tablesaw.addons.java.Classpath
tablesaw.addons.java.JavaProgram

Interface Hierarchy

tablesaw.addons.java.ClasspathProvider

      Overview
      Package
      Class
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
[![CI Status](http://img.shields.io/travis/David Walsh/STHelpers.svg?style=flat)](https://travis-ci.org/David Walsh/STHelpers)
[![Version](https://img.shields.io/cocoapods/v/STHelpers.svg?style=flat)](http://cocoadocs.org/docsets/STHelpers)
[![License](https://img.shields.io/cocoapods/l/STHelpers.svg?style=flat)](http://cocoadocs.org/docsets/STHelpers)
[![Platform](https://img.shields.io/cocoapods/p/STHelpers.svg?style=flat)](http://cocoadocs.org/docsets/STHelpers)

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

STHelpers is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

    pod "STHelpers"

## Author

David Walsh, dvdwlsh@gmail.com

## License

STHelpers is available under the MIT license. See the LICENSE file for more info.


text:
package spire

import spire.algebra._
import spire.algebra.partial._
import spire.laws.arb._
import spire.laws.Perm
import spire.optional.partialIterable._
import spire.optional.mapIntIntPermutation._
import spire.std.boolean._
import spire.std.int._
import spire.syntax.eq._

import org.scalatest.{FunSuite, Matchers, NonImplicitAssertions}
import org.scalatest.prop.Checkers

import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.Arbitrary._
import org.scalacheck.Prop._

class PartialSyntaxTest extends FunSuite with Checkers with BaseSyntaxTest with NonImplicitAssertions {

  implicit val IntGroup: Group[Int] = implicitly[AdditiveGroup[Int]].additive
  implicit val SeqIntEq: Eq[Seq[Int]] = spire.optional.genericEq.generic[Seq[Int]]

  test("Semigroupoid syntax")(check(forAll { (a: Seq[Int], b: Seq[Int]) => testSemigroupoidSyntax(a, b) }))
  test("Groupoid syntax")(check(forAll { (a: Seq[Int], b: Seq[Int]) => testGroupoidSyntax(a, b) }))
  test("Partial action syntax")(check(forAll { (seq: Seq[Int], perm: Perm) => testPartialActionSyntax(seq, perm.map) }))

  def testSemigroupoidSyntax[A: Semigroupoid: Eq](a: A, b: A) = {
    import spire.syntax.semigroupoid._
    ((a |+|? b) === Semigroupoid[A].partialOp(a, b)) &&
    ((a |+|?? b) === Semigroupoid[A].opIsDefined(a, b))
  }

  def testGroupoidSyntax[A: Groupoid: Eq](a: A, b: A) = {
    import spire.syntax.groupoid._
    (a.isId === Groupoid[A].isId(a)) &&
    (a.leftId === Groupoid[A].leftId(a)) &&
    (a.rightId === Groupoid[A].rightId(a)) &&
    ((a |+|? b) === Groupoid[A].partialOp(a, b)) &&
    ((a |+|?? b) === Groupoid[A].opIsDefined(a, b))
    ((a |-|? b) === Groupoid[A].partialOpInverse(a, b)) &&
    ((a |-|?? b) === Groupoid[A].opInverseIsDefined(a, b))
  }

  def testPartialActionSyntax(seq: Seq[Int], perm: Map[Int, Int]) = {
    import spire.syntax.partialAction._
    ((perm ?|+|> seq) === PartialAction[Seq[Int], Map[Int, Int]].partialActl(perm, seq)) &&
    ((seq <|+|? perm) === PartialAction[Seq[Int], Map[Int, Int]].partialActr(seq, perm)) &&
    ((perm ??|+|> seq) === PartialAction[Seq[Int], Map[Int, Int]].actlIsDefined(perm, seq)) &&
    ((seq <|+|?? perm) === PartialAction[Seq[Int], Map[Int, Int]].actrIsDefined(seq, perm))
  }
}


text:
package org.apache.metron.stellar.common.utils.math;

import org.apache.metron.stellar.dsl.Context;
import org.apache.metron.stellar.dsl.ParseException;
import org.apache.metron.stellar.dsl.StellarFunction;

import java.util.List;

public class StellarMathFunction implements StellarFunction {
  MathOperation _func;
  public StellarMathFunction(MathOperations _func) {
    this._func = _func.op;
  }

  public StellarMathFunction(MathOperation _func) {
    this._func = _func;
  }

  @Override
  public Object apply(List<Object> args, Context context) throws ParseException {
    if(args.size() < _func.getMinArgs()) {
      return Double.NaN;
    }
    Number[] nums = new Number[_func.getMaxArgs()];
    for(int i = 0; i < _func.getMaxArgs();++i) {
      nums[i] = (Number)args.get(i);
      if(nums[i] == null) {
        return Double.NaN;
      }
    }

    Object ret = _func.getOperation().apply(nums);
    return ret;
  }

  @Override
  public void initialize(Context context) {

  }

  @Override
  public boolean isInitialized() {
    return true;
  }
}


text:
A simple python class to interface with QBittorrent. Currently only supporst the 3.1.x version of the API.

For more details on the web api visit https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation-%28qBittorrent-v3.1.x%29

## Example

```python
from qbittorent.client import Client

qb = Client(url='http://localhost:8080')
qb.login('admin', 'secret')

torrents = qb.torrents()

for torrent in torrents:
  print(torrent['name'])
```

## API

.. autoclass:: qbittorrent.client.Client
   :members:


text: Rails.application.config.session_store :cookie_store, key: '_kiss_my_blog_session'


text:
using Phunk.Luan.Interfaces;

namespace Phunk.Luan.Expressions.Operators
{
    internal class SubractionExpression : OperatorExpression
	{
		protected override string Sign => "-";

		public SubractionExpression(IExpression left, IExpression right) : base(left, right)
		{

		}
	}
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
    internal class QueryExpressionFormattingRule : BaseFormattingRule
    {
        internal const string Name = "CSharp Query Expressions Formatting Rule";

        public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<SuppressOperation> nextOperation)
        {
            nextOperation.Invoke(list);

            if (node is QueryExpressionSyntax queryExpression)
            {
                AddSuppressWrappingIfOnSingleLineOperation(list, queryExpression.GetFirstToken(includeZeroWidth: true), queryExpression.GetLastToken(includeZeroWidth: true));
            }
        }

        private void AddIndentBlockOperationsForFromClause(List<IndentBlockOperation> list, FromClauseSyntax fromClause)
        {
            // Only add the indent block operation if the 'in' keyword is present. Otherwise, we'll get the following:
            //
            //     from x
            //         in args
            //
            // Rather than:
            //
            //     from x
            //     in args
            //
            // However, we want to get the following result if the 'in' keyword is present to allow nested queries
            // to be formatted properly.
            //
            //     from x in
            //         args

            if (fromClause.InKeyword.IsMissing)
            {
                return;
            }

            var baseToken = fromClause.FromKeyword;
            var startToken = fromClause.Expression.GetFirstToken(includeZeroWidth: true);
            var endToken = fromClause.Expression.GetLastToken(includeZeroWidth: true);

            AddIndentBlockOperation(list, baseToken, startToken, endToken);
        }

        public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<IndentBlockOperation> nextOperation)
        {
            nextOperation.Invoke(list);

            if (node is QueryExpressionSyntax queryExpression)
            {
                AddIndentBlockOperationsForFromClause(list, queryExpression.FromClause);

                foreach (var queryClause in queryExpression.Body.Clauses)
                {
                    // if it is nested query expression
                    if (queryClause is FromClauseSyntax fromClause)
                    {
                        AddIndentBlockOperationsForFromClause(list, fromClause);
                    }
                }

                // set alignment line for query expression
                var baseToken = queryExpression.GetFirstToken(includeZeroWidth: true);
                var endToken = queryExpression.GetLastToken(includeZeroWidth: true);
                if (!baseToken.IsMissing && !baseToken.Equals(endToken))
                {
                    var startToken = baseToken.GetNextToken(includeZeroWidth: true);
                    SetAlignmentBlockOperation(list, baseToken, startToken, endToken);
                }
            }
        }

        public override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<AnchorIndentationOperation> nextOperation)
        {
            nextOperation.Invoke(list);
            switch (node)
            {
                case QueryClauseSyntax queryClause:
                    {
                        var firstToken = queryClause.GetFirstToken(includeZeroWidth: true);
                        AddAnchorIndentationOperation(list, firstToken, queryClause.GetLastToken(includeZeroWidth: true));
                        return;
                    }

                case SelectOrGroupClauseSyntax selectOrGroupClause:
                    {
                        var firstToken = selectOrGroupClause.GetFirstToken(includeZeroWidth: true);
                        AddAnchorIndentationOperation(list, firstToken, selectOrGroupClause.GetLastToken(includeZeroWidth: true));
                        return;
                    }

                case QueryContinuationSyntax continuation:
                    AddAnchorIndentationOperation(list, continuation.IntoKeyword, continuation.GetLastToken(includeZeroWidth: true));
                    return;
            }
        }

        public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation<AdjustNewLinesOperation> nextOperation)
        {
            if (previousToken.IsNestedQueryExpression())
            {
                return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
            }

            // skip the very first from keyword
            if (currentToken.IsFirstFromKeywordInExpression())
            {
                return nextOperation.Invoke();
            }

            switch (currentToken.Kind())
            {
                case SyntaxKind.FromKeyword:
                case SyntaxKind.WhereKeyword:
                case SyntaxKind.LetKeyword:
                case SyntaxKind.JoinKeyword:
                case SyntaxKind.OrderByKeyword:
                case SyntaxKind.GroupKeyword:
                case SyntaxKind.SelectKeyword:
                    if (currentToken.GetAncestor<QueryExpressionSyntax>() != null)
                    {
                        if (optionSet.GetOption(CSharpFormattingOptions.NewLineForClausesInQuery))
                        {
                            return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
                        }
                        else
                        {
                            return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
                        }
                    }

                    break;
            }

            return nextOperation.Invoke();
        }
    }
}


text:
using JetBrains.Annotations;
using JoinRpg.DataModel;

namespace JoinRpg.Services.Interfaces.Search;

public interface ISearchResult : ILinkable
{
    [NotNull]
    string Name { get; }
    [NotNull]
    MarkdownString Description { get; }
    bool IsPublic { get; }
    bool IsActive { get; }
    /// <summary>
    /// Used to indicate that a perfect match was found and other search results are odd and useless.
    /// </summary>
    bool IsPerfectMatch { get; }
}


text:
module Deano

  def self.template_dir
    File.expand_path(File.join("..", "..", "..", "template_app"), File.dirname(__FILE__))
  end

  class Command

    def self.command
      nil
    end

    def self.commands
      @commands ||= []
    end

    def self.inherited(klass)
      self.commands << klass
    end

    def cmd(command)
      puts command
      system command
    end

    def rm(path)
      begin
        FileUtils.rm path, verbose: true
      rescue Errno::ENOENT => e
      end
    end

    def rm_r(path)
      begin
        FileUtils.rm_r path, verbose: true
      rescue Errno::ENOENT => e
      end
    end

    def app_path(*path)
      File.expand_path(File.join(@app_dir, *path))
    end

    def template_path(*path)
      File.expand_path(File.join(Deano.template_dir, *path))
    end

  end
end


text:
import os
from setuptools import setup

setup(
    name='bookwormDB',
    packages=["bookwormDB"],
    version='1.0',
    entry_points={
        'console_scripts': [
            'bookworm = bookwormDB.manager:run_arguments'
        ],
    },
    description="Create, deploy, and serve a Bookworm instance.",
    long_description="\n".join(open("README.rst").readlines()),
    package_data={'bookwormDB':['etc/*','bin/*']},
    url="http://github.com/Bookworm-Project",
    author="Benjamin Schmidt",
    author_email="bmschmidt@gmail.com",
    license="MIT",
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Intended Audience :: Education',
        "Natural Language :: English",
        # Pick your license as you wish (should match "license" above)
        'License :: OSI Approved :: MIT License',
        "Operating System :: Unix",
        # Specify the Python versions you support here. In particular, ensure
        # that you indicate whether you support Python 2, Python 3 or both.
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        "Topic :: Sociology :: History",
        "Topic :: Text Processing :: Indexing",
        "Topic :: Text Processing :: Linguistic"
    ],
    install_requires=["numpy","pandas","mysqlclient",
                      "python-dateutil", "psutil", "bounter",
                      "gunicorn"
    ]
)