text:
Component

Component ID {NODE.id}

{FILE "bo/node/default_top.html"}

Template

Controller

Parameters

			<fieldset>
				<legend></legend>

					Template

						<input type="text" class="text long" id="component_template" name="node[component][template]" value="{NODE.component.template}" />

									Local
									{ONXSHOP_REQUEST_template_project #bo/component/server_browser_menu~directory=templates/component/:scope=project:trim_extension=1:expand_all=1:id=null~}

									Global
									{ONXSHOP_REQUEST_template_onxshop #bo/component/server_browser_menu~directory=templates/component/:scope=onxshop:trim_extension=1:expand_all=1:id=null~}

			</fieldset>

			<fieldset>
				<legend></legend>

					Controller

						<input type="text" class="text long" id="component_controller" name="node[component][controller]" value="{NODE.component.controller}" />

									Local
									{ONXSHOP_REQUEST_controller_project #bo/component/server_browser_menu~directory=controllers/component/:scope=project:trim_extension=1:expand_all=1:id=null~}

									Global
									{ONXSHOP_REQUEST_controller_onxshop #bo/component/server_browser_menu~directory=controllers/component/:scope=onxshop:trim_extension=1:expand_all=1:id=null~}

			</fieldset>

			<fieldset>
				<legend></legend>

					GET parameters:
					<input type="text" class="text long" name="node[component][parameter]" value="{NODE.component.parameter}" />

			</fieldset>

{FILE "bo/node/default_bottom.html"}


text:
Imports System.Data
Imports bv.common.Core
Imports bv.common.db.Security
Imports bv.common.Enums

Public Class Person_DB
    Inherits BaseDbService

    Public Const TablePerson As String = "Person"
    Public Const TableUser As String = "UserTable"
    Public Const PersonKeyFieldName As String = "idfPerson"

    Public Sub New()
        ObjectName = "Person"
    End Sub

    Public Overrides Function GetDetail(ByVal ID As Object) As DataSet
        Dim ds As New DataSet
        Try
            Dim cmd As IDbCommand = CreateSPCommand("spPerson_SelectDetail")
            AddParam(cmd, "@idfPerson", ID)
            AddParam(cmd, "@LangID", bv.model.Model.Core.ModelUserContext.CurrentLanguage)

            FillDataset(cmd, ds, TablePerson)
            CorrectTable(ds.Tables(0), TablePerson)
            CorrectTable(ds.Tables(1), TableUser)
            ClearColumnsAttibutes(ds)
            ds.EnforceConstraints = False
            If ID Is Nothing Then
                ID = NewIntID()
                Dim r As DataRow = ds.Tables(TablePerson).NewRow
                r(PersonKeyFieldName) = ID
                ds.Tables(TablePerson).Rows.Add(r)
                m_IsNewObject = True
            End If
            m_ID = ID

            Dim dbs As BaseDbService = New SecurityPolicy_DB
            ds.Merge(dbs.GetDetail(Nothing))

            Dim t As DataTable = ds.Tables(TableUser)
            t.Columns.Add("idfsSite1", GetType(Long), "idfsSite")
            t.Columns.Add("idfsSite2", GetType(Long), "idfsSite")
            Return ds
        Catch ex As Exception
            m_Error = New ErrorMessage(StandardError.FillDatasetError, ex)
            Return Nothing
        End Try
    End Function

    Public Overrides Function PostDetail(ByVal ds As DataSet, ByVal postType As Integer, Optional ByVal transaction As IDbTransaction = Nothing) As Boolean
        If ds Is Nothing Then Return True
        Try
            Dim changes As DataTable = ds.Tables(TableUser).GetChanges(DataRowState.Added Or DataRowState.Modified)
            ExecPostProcedure("spPerson_Post", ds.Tables(TablePerson), Connection, transaction)
            ExecPostProcedure("spUser_Post", ds.Tables(TableUser), Connection, transaction)

            If Not (changes Is Nothing) Then
                For Each row As DataRow In changes.Rows
                    Dim pass As Object = row("strPassword")
                    If Utils.IsEmpty(pass) Then Continue For
                    Dim manager As New SecurityManager2()
                    Dim res As Integer = manager.SetPassword( _
                        row("idfUserID"), _
                        Utils.Str(pass), _
                        Connection, _
                        transaction)
                    If (res <> 0) Then
                        m_Error = SecurityMessages.GetLoginErrorMessage(res)
                        Return False
                    End If
                Next
            End If
            db.Core.LookupCache.NotifyChange("Person", transaction, ID)
        Catch ex As Exception
            m_Error = New ErrorMessage(StandardError.PostError, ex)
            Return False
        End Try
        Return True
    End Function

    Public Function SetLogin(ByVal ds As DataSet, ByVal login As String, ByVal passowrd As String) As Boolean
        If ds.Tables(TableUser).Rows.Count = 0 Then
            Dim r As DataRow = ds.Tables(TableUser).NewRow
            r.BeginEdit()
            r("idfUserID") = NewIntID()
            r("idfPerson") = ID
            r("idfsSite") = model.Core.EidssSiteContext.Instance.SiteID
            r("strAccountName") = login
            r("strPassword") = passowrd
            r.EndEdit()
            ds.Tables(TableUser).Rows.Add(r)
        Else
            Dim r As DataRow = ds.Tables(TableUser).Rows(0)
            r.BeginEdit()
            r("strAccountName") = login
            r("strPassword") = passowrd
            r.EndEdit()
        End If
        Return True
    End Function

    Public Sub DeleteLogin(ByVal ds As DataSet)
        If ds.Tables(TableUser).Rows.Count > 0 Then
            For i As Integer = ds.Tables(TableUser).Rows.Count - 1 To 0
                If ds.Tables(TableUser).Rows(i).RowState <> DataRowState.Deleted Then
                    ds.Tables(TableUser).Rows(i).Delete()
                End If
            Next
        End If
    End Sub
    '0 - no such login
    '1 - empty UserName/organization
    '2 - login exists
    '-1 - db error
    Public Function ValidateLogin(ByVal login As String) As Integer
        Dim cmd As IDbCommand = CreateSPCommand("dbo.spLogin_Validate", Connection)
        AddParam(cmd, "@idfPerson", ID)
        AddParam(cmd, "@UserName", login)
        AddParam(cmd, "@Result", 0, ParameterDirection.Output)
        m_Error = ExecCommand(cmd, Connection)
        If m_Error Is Nothing Then
            Return CInt(GetParamValue(cmd, "@Result"))
        Else
            Return -1
        End If
    End Function

    '0 - no such login
    '1 - empty UserName/organization
    '2 - login exists
    '-1 - db error
    Public Function ValidateLogin(ByVal employee As Object, ByVal site As Object, ByVal login As String) As Integer
        Dim cmd As IDbCommand = CreateSPCommand("dbo.spLogin_Validate", Connection)
        AddParam(cmd, "@idfPerson", employee)
        AddParam(cmd, "@idfsSite", site)
        AddParam(cmd, "@strAccountName", login)
        AddParam(cmd, "@Result", 0, ParameterDirection.Output)
        m_Error = ExecCommand(cmd, Connection)
        If m_Error Is Nothing Then
            Return CInt(GetParamValue(cmd, "@Result"))
        Else
            Return -1
        End If
    End Function

    Public Sub SetPasswordExpiration(ByVal dr As DataRow, Optional ByVal transaction As IDbTransaction = Nothing)

        Dim userID As Integer = CType(dr("idfUserID"), Integer)
        Dim userMustChange As Boolean = CType(dr("MustChangePassword"), Boolean)
        Dim expirMonths As Integer = CType(dr("intExpirationPeriod"), Integer)
        SetPasswordExpiration(userID, expirMonths, userMustChange, transaction)
    End Sub

    Public Sub SetPasswordExpiration(ByVal userID As Integer, ByVal userMustChange As Boolean)
        SetPasswordExpiration(userID, -1, userMustChange)
    End Sub

    Sub SetPasswordExpiration(ByVal userID As Integer, ByVal expirMonths As Integer, ByVal userMustChange As Boolean, Optional ByVal transaction As IDbTransaction = Nothing)

        Dim expirationDate As DateTime

        If (expirMonths = 0) Then
            expirMonths = 12 * 100 ' Pass Never Expired ;)
            expirationDate = New DateTime(2100, 1, 1)
        Else
            expirationDate = New DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddMonths(expirMonths)
        End If

        If (userMustChange) Then expirationDate = DateTime.Now()

        Dim cmd As IDbCommand = CreateSPCommand("spPerson_SetPasswordExpiration", Connection)
        AddParam(cmd, "@UserID", userID)
        AddParam(cmd, "@ExpirationDate", expirationDate)

        If (expirMonths > -1) Then ' do not change ExpirationPerion if ExpirMonths= -1
            AddParam(cmd, "@ExpirationPeriod", expirMonths)
        End If

        ExecCommand(cmd, Connection, transaction, True)

    End Sub

    Public Sub GetPasswordExpiration(ByVal employeeID As Object, ByVal loginName As String, ByRef expirationDate As DateTime)

        expirationDate = New DateTime(2100, 1, 1)

        Dim cmd As IDbCommand = CreateSPCommand("spPerson_CheckNeedChangePassword", Connection)
        AddParam(cmd, "@EmployeeID", employeeID)
        AddParam(cmd, "@LoginName", loginName)
        Dim dt As New DataTable
        FillTable(cmd, dt)
        If (dt.Rows.Count = 0) Then Return

        If (IsDBNull(dt.Rows(0)("ExpirationDate")) = False) Then
            expirationDate = CType(dt.Rows(0)("ExpirationDate"), DateTime)
        End If

    End Sub

    Public Function IsPasswordAlreadyUsed(ByVal employeeID As Object, ByVal password As String) As Boolean

        Dim cmd As IDbCommand = CreateSPCommand("spPerson_CheckPasswordReuse", Connection)
        AddParam(cmd, "@EmployeeID", employeeID)
        AddParam(cmd, "@Password", password)
        Dim dt As DataTable = ExecTable(cmd)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            Return False
        End If
        Dim isExists As Boolean = CType(dt.Rows(0)("IsExists"), Boolean)

        Return isExists

    End Function

    Private Function GetSecurityQuestion(ByVal userID As Object, ByVal login As String, ByVal siteName As String) As DataRow

        Dim cmd As IDbCommand = CreateSPCommand("spPerson_GetSecurityQuestion", Connection)
        If (userID Is Nothing) Then
            AddParam(cmd, "@Login", login)
            AddParam(cmd, "@SiteName", siteName)
        Else
            AddParam(cmd, "@UserID", userID)
        End If

        Dim dt As DataTable = ExecTable(cmd)

        If dt Is Nothing OrElse dt.Rows.Count = 0 Then Return Nothing
        Return dt.Rows(0)
    End Function

    Public Function GetSecurityQuestion(ByVal userID As Object) As DataRow
        Return GetSecurityQuestion(userID, "", "")
    End Function

    Public Function GetSecurityQuestion(ByVal login As String, ByVal siteName As String) As DataRow
        Return GetSecurityQuestion(Nothing, login, siteName)
    End Function

    Public Sub UpdatePassword(ByVal employeeID As Object, ByVal password As String, ByVal question As String, ByVal answer As String)

        Dim cmd As IDbCommand = CreateSPCommand("spPerson_UpdatePassword", Connection)
        AddParam(cmd, "@UserID", employeeID)
        AddParam(cmd, "@Password", password)
        AddParam(cmd, "@Question", question)
        AddParam(cmd, "@Answer", answer)

        ExecCommand(cmd, Connection, Nothing, True)

    End Sub

End Class

redpajama_set_name: RedPajamaGithub


text:
{% assign entries = site[include.collection] %}

{% if include.sort_by == 'title' %}
  {% if include.sort_order == 'reverse' %}
    {% assign entries = entries | sort: 'title' | reverse %}
  {% else %}
    {% assign entries = entries | sort: 'title' %}
  {% endif %}
{% elsif include.sort_by == 'date' %}
  {% if include.sort_order == 'reverse' %}
    {% assign entries = entries | sort: 'date' | reverse %}
  {% else %}
    {% assign entries = entries | sort: 'date' %}
  {% endif %}
{% endif %}

{%- for post in entries -%}
  {% include archive-single.html %}
{%- endfor -%}


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:rep="internal"
          jcr:primaryType="rep:ACL">
    <allow
            jcr:primaryType="rep:GrantACE"
            rep:principalName="acs-commons-review-task-asset-mover-service"
            rep:privileges="{Name}[jcr:read,jcr:versionManagement,rep:write]"/>
</jcr:root>


text:
<!DOCTYPE html>

    <title>6. Point in Circle</title>
    <link href="../Doncho's%20Console/styles/js-console.css" rel="stylesheet" />
    <link href="styles/StyleSheet.css" rel="stylesheet" />

        Enter value for point X:
        <input type="text" id="x"/>
        Enter value for point Y:
        <input type="text" id="y" />
        <button id="submit">Submit</button>


text:
jQuery.fn.fadeSlideShow = function(options) {
	return this.each(function(){
		settings = jQuery.extend({
     		width: 640, // default width of the slideshow
     		height: 480, // default height of the slideshow
			speed: 'slow', // default animation transition speed
			interval: 3000, // default interval between image change
			PlayPauseElement: 'fssPlayPause', // default css id for the play / pause element
			PlayText: 'Play', // default play text
			PauseText: 'Pause', // default pause text
			NextElement: 'fssNext', // default id for next button
			NextElementText: 'Next >', // default text for next button
			PrevElement: 'fssPrev', // default id for prev button
			PrevElementText: '< Prev', // default text for prev button
			ListElement: 'fssList', // default id for image / content controll list
			ListLi: 'fssLi', // default class for li's in the image / content controll
			ListLiActive: 'fssActive', // default class for active state in the controll list
			addListToId: false, // add the controll list to special id in your code - default false
			allowKeyboardCtrl: true, // allow keyboard controlls left / right / space
			autoplay: true // autoplay the slideshow
	 	}, options);

		// set style for wrapper element
		jQuery(this).css({
			width: settings.width,
			height: settings.height,
			position: 'relative',
			overflow: 'hidden'
		});

		// set styles for child element
		jQuery('> *',this).css({
			position: 'absolute',
			width: settings.width,
			height: settings.height
		});

		// count number of slides
		Slides = jQuery('> *', this).length;
		Slides = Slides - 1;
		ActSlide = Slides;
		// Set jQuery Slide short var
		jQslide = jQuery('> *', this);
		// save this
		fssThis = this;

		autoplay = function(){
			intval = setInterval(function(){
				jQslide.eq(ActSlide).fadeOut(settings.speed);

				// if list is on change the active class
				if(settings.ListElement){
					setActLi = (Slides - ActSlide) + 1;
					if(setActLi > Slides){setActLi=0;}
					jQuery('#'+settings.ListElement+' li').removeClass(settings.ListLiActive);
					jQuery('#'+settings.ListElement+' li').eq(setActLi).addClass(settings.ListLiActive);
				}

				if(ActSlide <= 0){
					jQslide.fadeIn(settings.speed);
					ActSlide = Slides;
				}else{
					ActSlide = ActSlide - 1;
				}
			}, settings.interval);

			if(settings.PlayPauseElement){
				jQuery('#'+settings.PlayPauseElement).html(settings.PauseText);
			}
		}

		stopAutoplay = function(){
			clearInterval(intval);
			intval = false;
			if(settings.PlayPauseElement){
				jQuery('#'+settings.PlayPauseElement).html(settings.PlayText);
			}
		}

		jumpTo = function(newIndex){
			if(newIndex < 0){newIndex = Slides;}
			else if(newIndex > Slides){newIndex = 0;}
			if( newIndex >= ActSlide ){
				jQuery('> *:lt('+(newIndex+1)+')', fssThis).fadeIn(settings.speed);
			}else if(newIndex <= ActSlide){
				jQuery('> *:gt('+newIndex+')', fssThis).fadeOut(settings.speed);
			}

			// set the active slide
			ActSlide = newIndex;

			if(settings.ListElement){
				// set active
				jQuery('#'+settings.ListElement+' li').removeClass(settings.ListLiActive);
				jQuery('#'+settings.ListElement+' li').eq((Slides-newIndex)).addClass(settings.ListLiActive);
			}
		}

		// if list is on render it
		if(settings.ListElement){
			i=0;
			li = '';
			while(i<=Slides){
				if(i==0){
					li = li+'
'+(i+1)+'<\/a><\/li>';
				}else{
					li = li+'
'+(i+1)+'<\/a><\/li>';
				}
				i++;
			}
			List = '
'+li+'<\/ul>';

			// add list to a special id or append after the slideshow
			if(settings.addListToId){
				jQuery('#'+settings.addListToId).append(List);
			}else{
				jQuery(this).after(List);
			}

			jQuery('#'+settings.ListElement+' a').bind('click', function(){
				index = jQuery('#'+settings.ListElement+' a').index(this);
				stopAutoplay();
				ReverseIndex = Slides-index;

				jumpTo(ReverseIndex);

				return false;
			});
		}

		if(settings.PlayPauseElement){
			if(!jQuery('#'+settings.PlayPauseElement).css('display')){
				jQuery(this).after('<\/a>');
			}

			if(settings.autoplay){
				jQuery('#'+settings.PlayPauseElement).html(settings.PauseText);
			}else{
				jQuery('#'+settings.PlayPauseElement).html(settings.PlayText);
			}

			jQuery('#'+settings.PlayPauseElement).bind('click', function(){
				if(intval){
					stopAutoplay();
				}else{
					autoplay();
				}
				return false;
			});
		}

		if(settings.NextElement){
			if(!jQuery('#'+settings.NextElement).css('display')){
				jQuery(this).after(''+settings.NextElementText+'<\/a>');
			}

			jQuery('#'+settings.NextElement).bind('click', function(){
				nextSlide = ActSlide-1;
				stopAutoplay();
				jumpTo(nextSlide);
				return false;
			});
		}

		if(settings.PrevElement){
			if(!jQuery('#'+settings.PrevElement).css('display')){
				jQuery(this).after(''+settings.PrevElementText+'<\/a>');
			}

			jQuery('#'+settings.PrevElement).bind('click', function(){
				prevSlide = ActSlide+1;
				stopAutoplay();
				jumpTo(prevSlide);
				return false;
			});
		}

		if(settings.allowKeyboardCtrl){
			jQuery(document).bind('keydown', function(e){
				if(e.which==39){
					nextSlide = ActSlide-1;
					stopAutoplay();
					jumpTo(nextSlide);
				}else if(e.which==37){
					prevSlide = ActSlide+1;
					stopAutoplay();
					jumpTo(prevSlide);
				}else if(e.which==32){
					if(intval){stopAutoplay();}
					else{autoplay();}
					return false;
				}
			});
		}

		// start autoplay or set it to false
		if(settings.autoplay){autoplay();}else{intval=false;}
	});
};


text:
package fm.serializer

import fm.json.{JsonNode, JsonObject}
import fm.serializer.bson.BSON
import fm.serializer.jackson.Jackson
import fm.serializer.json.JSON
import fm.serializer.protobuf.Protobuf
import fm.serializer.validation.ValidationResult
import org.bson.{BsonDocument, RawBsonDocument}

/**
 * Usage Pattern:
 *
 * import fm.serializer.{SerializableCompanion, SerializableInstance, SimpleSerializer}
 *
 * object Foo extends SerializableCompanion[Foo] {
 *   protected val serializer: SimpleSerializer[Foo] = makeSerializer[Foo]
 * }
 *
 * final case class Foo(bar: String) extends SerializableInstance[Foo] {
 *   protected def companion: SerializableCompanion[Foo] = Foo
 * }
 */
trait SerializableCompanion[A] {
  protected def makeSerializer[T](): SimpleObjectSerializer[T] = macro Macros.makeSimpleObjectSerializer[T]

  protected val serializer: SimpleSerializer[A]

  //
  // JSON Methods
  //
  def toJSON(v: A): String = JSON.toJSON(v)(serializer)
  def toJSONWithoutNulls(v: A): String = JSON.toJSONWithoutNulls(v)(serializer)
  def toMinimalJSON(v: A): String = JSON.toMinimalJSON(v)(serializer)
  def toPrettyJSON(v: A): String = JSON.toPrettyJSON(v)(serializer)
  def toPrettyJSONWithoutNulls(v: A): String = JSON.toPrettyJSONWithoutNulls(v)(serializer)

  def fromJSON(json: String): A = JSON.fromJSON(json)(serializer)
  def validateJson(json: String): ValidationResult = JSON.validate(json)(serializer)

  //
  // Jackson JsonNode Methods
  //
  def fromJsonNode(node: JsonNode): A = Jackson.fromJsonNode(node)(serializer)
  def toJsonNode(v: A): JsonNode = Jackson.toJsonNode(v)(serializer)
  def toJsonNodeWithoutNulls(v: A): JsonNode = Jackson.toJsonNodeWithoutNulls(v)(serializer)
  def validateJsonNode(node: JsonNode): ValidationResult = Jackson.validate(node)(serializer)

  //
  // Jackson JsonObject Methods
  //
  def fromJsonObject(node: JsonObject): A = Jackson.fromJsonNode(node)(serializer)
  def toJsonObject(v: A): JsonObject = Jackson.toJsonObject(v)(serializer)
  def toJsonObjectWithoutNulls(v: A): JsonObject = Jackson.toJsonObjectWithoutNulls(v)(serializer)
  def validateJsonObject(node: JsonObject): ValidationResult = Jackson.validate(node)(serializer)

  //
  // Protobuf Methods
  //
  def toBytes(v: A): Array[Byte] = Protobuf.toBytes(v)(serializer)
  def fromBytes(bytes: Array[Byte]): A = Protobuf.fromBytes(bytes)(serializer)

  //
  // BSON Methods
  //
  def toBsonBytes(v: A): Array[Byte] = BSON.toBsonBytes(v)(serializer)
  def fromBsonBytes(bytes: Array[Byte]): A = BSON.fromBsonBytes(bytes)(serializer)

  def toRawBsonDocument(v: A): RawBsonDocument = BSON.toRawBsonDocument(v)(serializer)
  def toBsonDocument(v: A): BsonDocument = BSON.toBsonDocument(v)(serializer)
  def addToBsonDocument(v: A, doc: BsonDocument): Unit = BSON.addToBsonDocument(v, doc)(serializer)

  def fromBsonDocument(doc: BsonDocument): A = BSON.fromBsonDocument(doc)(serializer)
}

/**
 * Usage Pattern:
 *
 * import fm.serializer.{SerializableCompanion, SerializableInstance, SimpleSerializer}
 *
 * object Foo extends SerializableCompanion[Foo] {
 *   protected val serializer: SimpleSerializer[Foo] = makeSerializer[Foo]
 * }
 *
 * final case class Foo(bar: String) extends SerializableInstance[Foo] {
 *   protected def companion: SerializableCompanion[Foo] = Foo
 * }
 */
trait SerializableInstance[A] { self: A =>
  protected def companion: SerializableCompanion[A]

  def toJSON: String = companion.toJSON(this)
  def toJSONWithoutNulls: String = companion.toJSONWithoutNulls(this)
  def toMinimalJSON: String = companion.toMinimalJSON(this)
  def toPrettyJSON: String = companion.toPrettyJSON(this)
  def toPrettyJSONWithoutNulls: String = companion.toPrettyJSONWithoutNulls(this)

  def toJsonObject: JsonObject = companion.toJsonObject(this)
  def toJsonObjectWithoutNulls: JsonObject = companion.toJsonObjectWithoutNulls(this)

  def toBytes: Array[Byte] = companion.toBytes(this)

  def toRawBsonDocument: RawBsonDocument = companion.toRawBsonDocument(this)
  def toBsonDocument: BsonDocument = companion.toBsonDocument(this)
  def addToBsonDocument(doc: BsonDocument): Unit = companion.addToBsonDocument(this, doc)
}


text:
- In this section, we will:

  - define authentication and authorization

  - explain how they are implemented in Kubernetes

  - talk about tokens, certificates, service accounts, RBAC ...

- But first: why do we need all this?

---

## The need for fine-grained security

- The Kubernetes API should only be available for identified users

  - we don't want "guest access" (except in very rare scenarios)

  - we don't want strangers to use our compute resources, delete our apps ...

  - our keys and passwords should not be exposed to the public

- Users will often have different access rights

  - cluster admin (similar to UNIX "root") can do everything

  - developer might access specific resources, or a specific namespace

  - supervision might have read only access to *most* resources

---

## Example: custom HTTP load balancer

- Let's imagine that we have a custom HTTP load balancer for multiple apps

- Each app has its own *Deployment* resource

- By default, the apps are "sleeping" and scaled to zero

- When a request comes in, the corresponding app gets woken up

- After some inactivity, the app is scaled down again

- This HTTP load balancer needs API access (to scale up/down)

- What if *a wild vulnerability appears*?

---

## Consequences of vulnerability

- If the HTTP load balancer has the same API access as we do:

  *full cluster compromise (easy data leak, cryptojacking...)*

- If the HTTP load balancer has `update` permissions on the Deployments:

  *defacement (easy), MITM / impersonation (medium to hard)*

- If the HTTP load balancer only has permission to `scale` the Deployments:

  *denial-of-service*

- All these outcomes are bad, but some are worse than others

---

## Definitions

- Authentication = verifying the identity of a person

  On a UNIX system, we can authenticate with login+password, SSH keys ...

- Authorization = listing what they are allowed to do

  On a UNIX system, this can include file permissions, sudoer entries ...

- Sometimes abbreviated as "authn" and "authz"

- In good modular systems, these things are decoupled

   (so we can e.g. change a password or SSH key without having to reset access rights)

---

## Authentication in Kubernetes

- When the API server receives a request, it tries to authenticate it

  (it examines headers, certificates... anything available)

- Many authentication methods are available and can be used simultaneously

  (we will see them on the next slide)

- It's the job of the authentication method to produce:

  - the user name
  - the user ID
  - a list of groups

- The API server doesn't interpret these; that'll be the job of *authorizers*

---

## Authentication methods

- TLS client certificates

  (that's what we've been doing with `kubectl` so far)

- Bearer tokens

  (a secret token in the HTTP headers of the request)

- [HTTP basic auth](https://en.wikipedia.org/wiki/Basic_access_authentication)

  (carrying user and password in an HTTP header; [deprecated since Kubernetes 1.19](https://github.com/kubernetes/kubernetes/pull/89069))

- Authentication proxy

  (sitting in front of the API and setting trusted headers)

---

## Anonymous requests

- If any authentication method *rejects* a request, it's denied

  (`401 Unauthorized` HTTP code)

- If a request is neither rejected nor accepted by anyone, it's anonymous

  - the user name is `system:anonymous`

  - the list of groups is `[system:unauthenticated]`

- By default, the anonymous user can't do anything

  (that's what you get if you just `curl` the Kubernetes API)

---

## Authentication with TLS certificates

- This is enabled in most Kubernetes deployments

- The user name is derived from the `CN` in the client certificates

- The groups are derived from the `O` fields in the client certificate

- From the point of view of the Kubernetes API, users do not exist

  (i.e. they are not stored in etcd or anywhere else)

- Users can be created (and added to groups) independently of the API

- The Kubernetes API can be set up to use your custom CA to validate client certs

---

class: extra-details

## Viewing our admin certificate

- Let's inspect the certificate we've been using all this time!

.exercise[

- This command will show the `CN` and `O` fields for our certificate:
  ```bash
  kubectl config view \
          --raw \
          -o json \
          | jq -r .users[0].user[\"client-certificate-data\"] \
          | openssl base64 -d -A \
          | openssl x509 -text \
          | grep Subject:
  ```

]

Let's break down that command together! 😅

---

class: extra-details

## Breaking down the command

- `kubectl config view` shows the Kubernetes user configuration
- `--raw` includes certificate information (which shows as REDACTED otherwise)
- `-o json` outputs the information in JSON format
- `| jq ...` extracts the field with the user certificate (in base64)
- `| openssl base64 -d -A` decodes the base64 format (now we have a PEM file)
- `| openssl x509 -text` parses the certificate and outputs it as plain text
- `| grep Subject:` shows us the line that interests us

→ We are user `kubernetes-admin`, in group `system:masters`.

(We will see later how and why this gives us the permissions that we have.)

---

## User certificates in practice

- The Kubernetes API server does not support certificate revocation

  (see issue [#18982](https://github.com/kubernetes/kubernetes/issues/18982))

- As a result, we don't have an easy way to terminate someone's access

  (if their key is compromised, or they leave the organization)

- Option 1: re-create a new CA and re-issue everyone's certificates

  → Maybe OK if we only have a few users; no way otherwise

- Option 2: don't use groups; grant permissions to individual users

  → Inconvenient if we have many users and teams; error-prone

- Option 3: issue short-lived certificates (e.g. 24 hours) and renew them often

  → This can be facilitated by e.g. Vault or by the Kubernetes CSR API

---

## Authentication with tokens

- Tokens are passed as HTTP headers:

  `Authorization: Bearer and-then-here-comes-the-token`

- Tokens can be validated through a number of different methods:

  - static tokens hard-coded in a file on the API server

  - [bootstrap tokens](https://kubernetes.io/docs/reference/access-authn-authz/bootstrap-tokens/) (special case to create a cluster or join nodes)

  - [OpenID Connect tokens](https://kubernetes.io/docs/reference/access-authn-authz/authentication/#openid-connect-tokens) (to delegate authentication to compatible OAuth2 providers)

  - service accounts (these deserve more details, coming right up!)

---

## Service accounts

- A service account is a user that exists in the Kubernetes API

  (it is visible with e.g. `kubectl get serviceaccounts`)

- Service accounts can therefore be created / updated dynamically

  (they don't require hand-editing a file and restarting the API server)

- A service account is associated with a set of secrets

  (the kind that you can view with `kubectl get secrets`)

- Service accounts are generally used to grant permissions to applications, services...

  (as opposed to humans)

---

class: extra-details

## Token authentication in practice

- We are going to list existing service accounts

- Then we will extract the token for a given service account

- And we will use that token to authenticate with the API

---

class: extra-details

## Listing service accounts

.exercise[

- The resource name is `serviceaccount` or `sa` for short:
  ```bash
  kubectl get sa
  ```

]

There should be just one service account in the default namespace: `default`.

---

class: extra-details

## Finding the secret

.exercise[

- List the secrets for the `default` service account:
  ```bash
  kubectl get sa default -o yaml
  SECRET=$(kubectl get sa default -o json | jq -r .secrets[0].name)
  ```

]

It should be named `default-token-XXXXX`.

---

class: extra-details

## Extracting the token

- The token is stored in the secret, wrapped with base64 encoding

.exercise[

- View the secret:
  ```bash
  kubectl get secret $SECRET -o yaml
  ```

- Extract the token and decode it:
  ```bash
  TOKEN=$(kubectl get secret $SECRET -o json \
          | jq -r .data.token | openssl base64 -d -A)
  ```

]

---

class: extra-details

## Using the token

- Let's send a request to the API, without and with the token

.exercise[

- Find the ClusterIP for the `kubernetes` service:
  ```bash
  kubectl get svc kubernetes
  API=$(kubectl get svc kubernetes -o json | jq -r .spec.clusterIP)
  ```

- Connect without the token:
  ```bash
  curl -k https://$API
  ```

- Connect with the token:
  ```bash
  curl -k -H "Authorization: Bearer $TOKEN" https://$API
  ```

]

---

class: extra-details

## Results

- In both cases, we will get a "Forbidden" error

- Without authentication, the user is `system:anonymous`

- With authentication, it is shown as `system:serviceaccount:default:default`

- The API "sees" us as a different user

- But neither user has any rights, so we can't do nothin'

- Let's change that!

---

## Authorization in Kubernetes

- There are multiple ways to grant permissions in Kubernetes, called [authorizers](https://kubernetes.io/docs/reference/access-authn-authz/authorization/#authorization-modules):

  - [Node Authorization](https://kubernetes.io/docs/reference/access-authn-authz/node/) (used internally by kubelet; we can ignore it)

  - [Attribute-based access control](https://kubernetes.io/docs/reference/access-authn-authz/abac/) (powerful but complex and static; ignore it too)

  - [Webhook](https://kubernetes.io/docs/reference/access-authn-authz/webhook/) (each API request is submitted to an external service for approval)

  - [Role-based access control](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) (associates permissions to users dynamically)

- The one we want is the last one, generally abbreviated as RBAC

---

## Role-based access control

- RBAC allows to specify fine-grained permissions

- Permissions are expressed as *rules*

- A rule is a combination of:

  - [verbs](https://kubernetes.io/docs/reference/access-authn-authz/authorization/#determine-the-request-verb) like create, get, list, update, delete...

  - resources (as in "API resource," like pods, nodes, services...)

  - resource names (to specify e.g. one specific pod instead of all pods)

  - in some case, [subresources](https://kubernetes.io/docs/reference/access-authn-authz/rbac/#referring-to-resources) (e.g. logs are subresources of pods)

---

## From rules to roles to rolebindings

- A *role* is an API object containing a list of *rules*

  Example: role "external-load-balancer-configurator" can:
  - [list, get] resources [endpoints, services, pods]
  - [update] resources [services]

- A *rolebinding* associates a role with a user

  Example: rolebinding "external-load-balancer-configurator":
  - associates user "external-load-balancer-configurator"
  - with role "external-load-balancer-configurator"

- Yes, there can be users, roles, and rolebindings with the same name

- It's a good idea for 1-1-1 bindings; not so much for 1-N ones

---

## Cluster-scope permissions

- API resources Role and RoleBinding are for objects within a namespace

- We can also define API resources ClusterRole and ClusterRoleBinding

- These are a superset, allowing us to:

  - specify actions on cluster-wide objects (like nodes)

  - operate across all namespaces

- We can create Role and RoleBinding resources within a namespace

- ClusterRole and ClusterRoleBinding resources are global

---

## Pods and service accounts

- A pod can be associated with a service account

  - by default, it is associated with the `default` service account

  - as we saw earlier, this service account has no permissions anyway

- The associated token is exposed to the pod's filesystem

  (in `/var/run/secrets/kubernetes.io/serviceaccount/token`)

- Standard Kubernetes tooling (like `kubectl`) will look for it there

- So Kubernetes tools running in a pod will automatically use the service account

---

## In practice

- We are going to create a service account

- We will use a default cluster role (`view`)

- We will bind together this role and this service account

- Then we will run a pod using that service account

- In this pod, we will install `kubectl` and check our permissions

---

## Creating a service account

- We will call the new service account `viewer`

  (note that nothing prevents us from calling it `view`, like the role)

.exercise[

- Create the new service account:
  ```bash
  kubectl create serviceaccount viewer
  ```

- List service accounts now:
  ```bash
  kubectl get serviceaccounts
  ```

]

---

## Binding a role to the service account

- Binding a role = creating a *rolebinding* object

- We will call that object `viewercanview`

  (but again, we could call it `view`)

.exercise[

- Create the new role binding:
  ```bash
  kubectl create rolebinding viewercanview \
          --clusterrole=view \
          --serviceaccount=default:viewer
  ```

]

It's important to note a couple of details in these flags...

---

## Roles vs Cluster Roles

- We used `--clusterrole=view`

- What would have happened if we had used `--role=view`?

  - we would have bound the role `view` from the local namespace

(instead of the cluster role `view`)

  - the command would have worked fine (no error)

  - but later, our API requests would have been denied

- This is a deliberate design decision

  (we can reference roles that don't exist, and create/update them later)

---

## Users vs Service Accounts

- We used `--serviceaccount=default:viewer`

- What would have happened if we had used `--user=default:viewer`?

  - we would have bound the role to a user instead of a service account

  - again, the command would have worked fine (no error)

  - ...but our API requests would have been denied later

- What's about the `default:` prefix?

  - that's the namespace of the service account

  - yes, it could be inferred from context, but... `kubectl` requires it

---

## Testing

- We will run an `alpine` pod and install `kubectl` there

.exercise[

- Run a one-time pod:
  ```bash
  kubectl run eyepod --rm -ti --restart=Never \
          --serviceaccount=viewer \
          --image alpine
  ```

- Install `curl`, then use it to install `kubectl`:
  ```bash
  apk add --no-cache curl
  URLBASE=https://storage.googleapis.com/kubernetes-release/release
  KUBEVER=$(curl -s $URLBASE/stable.txt)
  curl -LO $URLBASE/$KUBEVER/bin/linux/amd64/kubectl
  chmod +x kubectl
  ```

]

---

## Running `kubectl` in the pod

- We'll try to use our `view` permissions, then to create an object

.exercise[

- Check that we can, indeed, view things:
  ```bash
  ./kubectl get all
  ```

- But that we can't create things:
  ```
  ./kubectl create deployment testrbac --image=nginx
  ```

- Exit the container with `exit` or `^D`

]

---

## Testing directly with `kubectl`

- We can also check for permission with `kubectl auth can-i`:
  ```bash
  kubectl auth can-i list nodes
  kubectl auth can-i create pods
  kubectl auth can-i get pod/name-of-pod
  kubectl auth can-i get /url-fragment-of-api-request/
  kubectl auth can-i '*' services
  ```

- And we can check permissions on behalf of other users:
  ```bash
  kubectl auth can-i list nodes \
          --as some-user
  kubectl auth can-i list nodes \
          --as system:serviceaccount:<namespace>:<name-of-service-account>
  ```

---

class: extra-details

## Where does this `view` role come from?

- Kubernetes defines a number of ClusterRoles intended to be bound to users

- `cluster-admin` can do *everything* (think `root` on UNIX)

- `admin` can do *almost everything* (except e.g. changing resource quotas and limits)

- `edit` is similar to `admin`, but cannot view or edit permissions

- `view` has read-only access to most resources, except permissions and secrets

*In many situations, these roles will be all you need.*

*You can also customize them!*

---

class: extra-details

## Customizing the default roles

- If you need to *add* permissions to these default roles (or others),

  you can do it through the [ClusterRole Aggregation](https://kubernetes.io/docs/reference/access-authn-authz/rbac/#aggregated-clusterroles) mechanism

- This happens by creating a ClusterRole with the following labels:
  ```yaml
    metadata:
      labels:
        rbac.authorization.k8s.io/aggregate-to-admin: "true"
        rbac.authorization.k8s.io/aggregate-to-edit: "true"
        rbac.authorization.k8s.io/aggregate-to-view: "true"
  ```

- This ClusterRole permissions will be added to `admin`/`edit`/`view` respectively

- This is particulary useful when using CustomResourceDefinitions

  (since Kubernetes cannot guess which resources are sensitive and which ones aren't)

---

class: extra-details

## Where do our permissions come from?

- When interacting with the Kubernetes API, we are using a client certificate

- We saw previously that this client certificate contained:

  `CN=kubernetes-admin` and `O=system:masters`

- Let's look for these in existing ClusterRoleBindings:
  ```bash
  kubectl get clusterrolebindings -o yaml |
    grep -e kubernetes-admin -e system:masters
  ```

  (`system:masters` should show up, but not `kubernetes-admin`.)

- Where does this match come from?

---

class: extra-details

## The `system:masters` group

- If we eyeball the output of `kubectl get clusterrolebindings -o yaml`, we'll find out!

- It is in the `cluster-admin` binding:
  ```bash
  kubectl describe clusterrolebinding cluster-admin
  ```

- This binding associates `system:masters` with the cluster role `cluster-admin`

- And the `cluster-admin` is, basically, `root`:
  ```bash
  kubectl describe clusterrole cluster-admin
  ```

---

class: extra-details

## Figuring out who can do what

- For auditing purposes, sometimes we want to know who can perform an action

- There are a few tools to help us with that

  - [kubectl-who-can](https://github.com/aquasecurity/kubectl-who-can) by Aqua Security

  - [Review Access (aka Rakkess)](https://github.com/corneliusweig/rakkess)

- Both are available as standalone programs, or as plugins for `kubectl`

  (`kubectl` plugins can be installed and managed with `krew`)

???

:EN:- Authentication and authorization in Kubernetes
:EN:- Authentication with tokens and certificates
:EN:- Authorization with RBAC (Role-Based Access Control)
:EN:- Restricting permissions with Service Accounts
:EN:- Working with Roles, Cluster Roles, Role Bindings, etc.

:FR:- Identification et droits d'accès dans Kubernetes
:FR:- Mécanismes d'identification par jetons et certificats
:FR:- Le modèle RBAC *(Role-Based Access Control)*
:FR:- Restreindre les permissions grâce aux *Service Accounts*
:FR:- Comprendre les *Roles*, *Cluster Roles*, *Role Bindings*, etc.


text:
package com.navercorp.pinpoint.collector.receiver.tcp;

/**
 * @author Taejin Koo
 */
public interface TCPReceiver {

    void start();

    void shutdown();

}


text:
package org.iq80.leveldb.impl;

import org.iq80.leveldb.Options;
import org.iq80.leveldb.fileenv.EnvImpl;
import org.iq80.leveldb.table.BytewiseComparator;
import org.iq80.leveldb.util.Slice;
import org.iq80.leveldb.util.TestUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

public class VersionSetTest
{
    private List<FileMetaData> files = new ArrayList<>();

    @BeforeMethod
    public void setUp() throws Exception
    {
        files.clear();
    }

    void add(String smallest, String largest,
             long smallestSeq,
             long largestSeq)
    {
        files.add(new FileMetaData(files.size() + 1, 0, new InternalKey(TestUtils.asciiToSlice(smallest), smallestSeq, ValueType.VALUE), new InternalKey(TestUtils.asciiToSlice(largest), largestSeq, ValueType.VALUE)));
    }

    int find(String key)
    {
        InternalKey target = new InternalKey(TestUtils.asciiToSlice(key), 100, ValueType.VALUE);
        return newLevel().findFile(target);
    }

    private Level newLevel()
    {
        InternalKeyComparator internalKeyComparator = new InternalKeyComparator(new BytewiseComparator());
        return new Level(1, files, new TableCache(EnvImpl.createEnv().toFile("xxxxxxxxxxx"), 0, new BytewiseComparator(), new Options(), EnvImpl.createEnv()), internalKeyComparator);
    }

    boolean overlaps(String smallest, String largest)
    {
        Slice s = smallest != null ? TestUtils.asciiToSlice(smallest) : null;
        Slice l = largest != null ? TestUtils.asciiToSlice(largest) : null;
        return newLevel().someFileOverlapsRange(true, s, l);
    }

    @Test
    public void testEmpty() throws Exception
    {
        assertEquals(find("foo"), 0);
        assertFalse(overlaps("z", "a"));
        assertFalse(overlaps("z", null));
        assertFalse(overlaps("a", null));
        assertFalse(overlaps(null, null));
    }

    @Test
    public void testSingle() throws Exception
    {
        add("p", "q", 100, 100);
        assertEquals(find("a"), 0);
        assertEquals(find("p"), 0);
        assertEquals(find("pl"), 0);
        assertEquals(find("q"), 0);
        assertEquals(find("ql"), 1);
        assertEquals(find("z"), 1);

        assertTrue(!overlaps("a", "b"));
        assertTrue(!overlaps("z1", "z2"));
        assertTrue(overlaps("a", "p"));
        assertTrue(overlaps("a", "q"));
        assertTrue(overlaps("a", "z"));
        assertTrue(overlaps("p", "p1"));
        assertTrue(overlaps("p", "q"));
        assertTrue(overlaps("p", "z"));
        assertTrue(overlaps("p1", "p2"));
        assertTrue(overlaps("p1", "z"));
        assertTrue(overlaps("q", "q"));
        assertTrue(overlaps("q", "q1"));

        assertTrue(!overlaps(null, "j"));
        assertTrue(!overlaps("r", null));
        assertTrue(overlaps(null, "p"));
        assertTrue(overlaps(null, "p1"));
        assertTrue(overlaps("q", null));
        assertTrue(overlaps(null, null));
    }

    @Test
    public void testMultiple() throws Exception
    {
        add("150", "200", 100, 100);
        add("200", "250", 100, 100);
        add("300", "350", 100, 100);
        add("400", "450", 100, 100);
        assertEquals(0, find("100"));
        assertEquals(0, find("150"));
        assertEquals(0, find("151"));
        assertEquals(0, find("199"));
        assertEquals(0, find("200"));
        assertEquals(1, find("201"));
        assertEquals(1, find("249"));
        assertEquals(1, find("250"));
        assertEquals(2, find("251"));
        assertEquals(2, find("299"));
        assertEquals(2, find("300"));
        assertEquals(2, find("349"));
        assertEquals(2, find("350"));
        assertEquals(3, find("351"));
        assertEquals(3, find("400"));
        assertEquals(3, find("450"));
        assertEquals(4, find("451"));

        assertTrue(!overlaps("100", "149"));
        assertTrue(!overlaps("251", "299"));
        assertTrue(!overlaps("451", "500"));
        assertTrue(!overlaps("351", "399"));

        assertTrue(overlaps("100", "150"));
        assertTrue(overlaps("100", "200"));
        assertTrue(overlaps("100", "300"));
        assertTrue(overlaps("100", "400"));
        assertTrue(overlaps("100", "500"));
        assertTrue(overlaps("375", "400"));
        assertTrue(overlaps("450", "450"));
        assertTrue(overlaps("450", "500"));
    }

    @Test
    public void testMultipleNullBoundaries() throws Exception
    {
        add("150", "200", 100, 100);
        add("200", "250", 100, 100);
        add("300", "350", 100, 100);
        add("400", "450", 100, 100);
        assertTrue(!overlaps(null, "149"));
        assertTrue(!overlaps("451", null));
        assertTrue(overlaps(null, null));
        assertTrue(overlaps(null, "150"));
        assertTrue(overlaps(null, "199"));
        assertTrue(overlaps(null, "200"));
        assertTrue(overlaps(null, "201"));
        assertTrue(overlaps(null, "400"));
        assertTrue(overlaps(null, "800"));
        assertTrue(overlaps("100", null));
        assertTrue(overlaps("200", null));
        assertTrue(overlaps("449", null));
        assertTrue(overlaps("450", null));
    }

    @Test
    public void testOverlapSequenceChecks() throws Exception
    {
        add("200", "200", 5000, 3000);
        assertTrue(!overlaps("199", "199"));
        assertTrue(!overlaps("201", "300"));
        assertTrue(overlaps("200", "200"));
        assertTrue(overlaps("190", "200"));
        assertTrue(overlaps("200", "210"));
    }
}


text:
class PrefsClass {
	private final android.content.SharedPreferences __prefs;
	private int myInt;

	@java.lang.SuppressWarnings("all")
	public PrefsClass(android.content.SharedPreferences prefs) {
		this.__prefs = prefs;
	}

	@java.lang.SuppressWarnings("all")
	public int getMyInt() {
		return this.__prefs.getInt("myInt", this.myInt);
	}

	@java.lang.SuppressWarnings("all")
	public void setMyInt(int myInt) {
		this.__prefs.edit().putInt("myInt", myInt).apply();
	}

	@java.lang.SuppressWarnings("all")
	public boolean containsMyInt() {
		return this.__prefs.contains("myInt");
	}

	@java.lang.SuppressWarnings("all")
	public void removeMyInt() {
		this.__prefs.edit().remove("myInt").apply();
	}
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ArticlesTablosunaUrlAlaniEklendi extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('articles', function($table){
            $table->text('url')->nullable();
            $table->text('permalink')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('articles', function($table) {
            $table->dropColumn('url');
            $table->dropColumn('permalink');
        });
    }
}


text:
package org.artificer.server;

import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateful;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;

import org.artificer.common.query.ArtifactSummary;
import org.artificer.common.query.ReverseRelationship;
import org.artificer.repository.query.ArtificerQuery;
import org.artificer.repository.query.ArtificerQueryArgs;
import org.artificer.repository.query.PagedResult;
import org.artificer.server.core.api.QueryService;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.StoredQuery;

/**
 * @author Brett Meyer.
 */
@Stateful(name = "QueryService")
@Remote(QueryService.class)
// Required so that artificer-repository-hibernate can control the transactions during EJB calls.
@TransactionManagement(TransactionManagementType.BEAN)
public class QueryServiceImpl extends AbstractServiceImpl implements QueryService {

    @Override
    public PagedResult<ArtifactSummary> query(String query) throws Exception {
        return query(query, "name", true);
    }

    @Override
    public PagedResult<ArtifactSummary> query(String query, String orderBy, Boolean ascending) throws Exception { // Add on the "/s-ramp/" if it's missing
		String xpath = formatXpath(query);

        ArtificerQueryArgs args = new ArtificerQueryArgs(orderBy, ascending);
        ArtificerQuery artificerQuery = queryManager().createQuery(xpath, args);
        return artificerQuery.executeQuery();
    }

    @Override
    public PagedResult<ArtifactSummary> query(String query, Integer startPage, Integer startIndex, Integer count,
            String orderBy, Boolean ascending) throws Exception {
        String xpath = formatXpath(query);

        ArtificerQueryArgs args = new ArtificerQueryArgs(orderBy, ascending, startPage, startIndex, count);
        ArtificerQuery artificerQuery = queryManager().createQuery(xpath, args);
        return artificerQuery.executeQuery();
    }

	private String formatXpath(String query) {
		String xpath = query;
		if (xpath.equals("/s-ramp/")) {
			// If query is "/s-ramp/" exactly, trim off the trailing "/" -- screws with the parser.
			xpath = "/s-ramp";
		} else if (!xpath.startsWith("/s-ramp")) {
			// Add on the "/s-ramp/" if it's missing
			if (query.startsWith("/"))
				xpath = "/s-ramp" + query;
			else
				xpath = "/s-ramp/" + query;
		}
		return xpath;
	}

    @Override
    public StoredQuery createStoredQuery(StoredQuery storedQuery) throws Exception {
        return persistenceManager().persistStoredQuery(storedQuery);
    }

    @Override
    public void updateStoredQuery(String queryName, StoredQuery storedQuery) throws Exception {
        persistenceManager().updateStoredQuery(queryName, storedQuery);
    }

    @Override
    public StoredQuery getStoredQuery(String queryName) throws Exception {
        return persistenceManager().getStoredQuery(queryName);
    }

    @Override
    public List<StoredQuery> getStoredQueries() throws Exception {
        return persistenceManager().getStoredQueries();
    }

    @Override
    public void deleteStoredQuery(String queryName) throws Exception {
        persistenceManager().deleteStoredQuery(queryName);
    }

    @Override
    public List<ReverseRelationship> reverseRelationships(String uuid) throws Exception {
        return queryManager().reverseRelationships(uuid);
    }

    @Override
    public List<String> getTypes() throws Exception {
        return queryManager().getTypes();
    }
}


text: from .resource import W_Resource


text:
@interface MOBProjectionEPSG5795 : MOBProjection

@end


text:
'use strict';
exports.readonly = false; // Inserting 100 rows in a single transaction

exports['better-sqlite3'] = (db, { table, columns }) => {
	const stmt = db.prepare(`INSERT INTO ${table} (${columns.join(', ')}) VALUES (${columns.map(x => '@' + x).join(', ')})`);
	const row = db.prepare(`SELECT * FROM ${table} LIMIT 1`).get();
	const trx = db.transaction((row) => {
		for (let i = 0; i < 100; ++i) stmt.run(row);
	});
	return () => trx(row);
};

exports['node-sqlite3'] = async (db, { table, columns, driver, pragma }) => {
	const sql = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${columns.map(x => '@' + x).join(', ')})`;
	const row = Object.assign({}, ...Object.entries(await db.get(`SELECT * FROM ${table} LIMIT 1`))
		.filter(([k]) => columns.includes(k))
		.map(([k, v]) => ({ ['@' + k]: v })));
	const open = require('../drivers').get(driver);
	/*
		The only way to create an isolated transaction with node-sqlite3 in a
		random-access environment (i.e., a web server) is to open a new database
		connection for each transaction.
		(http://github.com/mapbox/node-sqlite3/issues/304#issuecomment-45242331)
	 */
	return () => open('../temp/benchmark.db', pragma).then(async (db) => {
		try {
			await db.run('BEGIN');
			try {
				for (let i = 0; i < 100; ++i) await db.run(sql, row);
				await db.run('COMMIT');
			} catch (err) {
				try { await db.run('ROLLBACK'); }
				catch (_) { /* this is necessary because there's no db.inTransaction property */ }
				throw err;
			}
		} finally {
			await db.close();
		}
	});
};


text:
namespace doris {

class GzipDecompressor : public Codec {
public:
    GzipDecompressor(MemPool* mem_pool, bool reuse_buffer, bool is_deflate);
    virtual ~GzipDecompressor();

    // Process a block of data.
    virtual Status process_block(int input_length, uint8_t* input,
                                int* output_length, uint8_t** output);

protected:
    // Initialize the decompressor.
    virtual Status init();

private:
    // If set assume deflate format, otherwise zlib or gzip
    bool _is_deflate;

    z_stream _stream;

    // These are magic numbers from zlib.h.  Not clear why they are not defined there.
    const static int WINDOW_BITS = 15;    // Maximum window size
    const static int DETECT_CODEC = 32;   // Determine if this is libz or gzip from header.
};

class BzipDecompressor : public Codec {
public:
    BzipDecompressor(MemPool* mem_pool, bool reuse_buffer);
    virtual ~BzipDecompressor() { }

    // Process a block of data.
    virtual Status process_block(int input_length, uint8_t* input,
                                int* output_length, uint8_t** output);
protected:
    // Bzip does not need initialization
    virtual Status init() {
        return Status::OK();
    }
};

class SnappyDecompressor : public Codec {
public:
    SnappyDecompressor(MemPool* mem_pool, bool reuse_buffer);
    virtual ~SnappyDecompressor() { }

    // Process a block of data.
    virtual Status process_block(int input_length, uint8_t* input,
                                int* output_length, uint8_t** output);

protected:
    // Snappy does not need initialization
    virtual Status init() {
        return Status::OK();
    }

};

class SnappyBlockDecompressor : public Codec {
public:
    SnappyBlockDecompressor(MemPool* mem_pool, bool reuse_buffer);
    virtual ~SnappyBlockDecompressor() { }

    //Process a block of data.
    virtual Status process_block(int input_length, uint8_t* input,
                                int* output_length, uint8_t** output);

protected:
    // Snappy does not need initialization
    virtual Status init() {
        return Status::OK();
    }
};

}
#endif


text:
require 'spec_helper'

describe BitBucket::Repos::Webhooks, wip: true do
  subject { described_class.new }
  let(:post_put_params) do
    {
      'description' => 'mock_description',
      'url' => 'mock_url',
      'active' => true,
      'events' => ['repo:push']
    }
  end

  let(:missing_key_params) do
    {
      'description' => 'mock_description',
      'active' => true,
      'events' => ['repo:push']
    }
  end

  let(:blank_value_params) do
    {
      'description' => '',
      'url' => 'mock_url',
      'active' => true,
      'events' => ['repo:push']
    }
  end

  let(:bad_event_params) do
    {
      'description' => 'mock_description',
      'url' => 'mock_url',
      'active' => true,
      'events' => ['bad:event']
    }
  end

  let(:missing_events_params) do
    {
      'description' => 'mock_description',
      'url' => 'mock_url',
      'active' => true,
      'events' => []
    }
  end

  describe '#create' do
    context 'when required fields are missing from params' do
      context 'when a required key is missing' do
        it 'raises an instance of BitBucket::Error::RequiredParams' do
          expect do
            subject.create(
              'mock_username',
              'mock_repo',
              missing_key_params
            )
          end.to raise_error(BitBucket::Error::RequiredParams)
        end
      end

      context 'when values of required keys are blank' do
        it 'raises an instance of BitBucket::Error::RequiredParams' do
          expect do
            subject.create(
              'mock_username',
              'mock_repo',
              blank_value_params
            )
          end.to raise_error(
            BitBucket::Error::BlankValue,
            "The value for: 'description', cannot be blank :("
          )
        end
      end
    end

    it 'validates the given events' do
      allow(subject).to(receive(:request))

      expect do
        subject.create(
          'mock_username',
          'mock_repo',
          bad_event_params

        )
      end.to raise_error(
        BitBucket::Error::BadEvents,
        "The event: 'bad:event', does not exist :("
      )
    end

    it 'checks that at least one event is given' do
      allow(subject).to(receive(:request))

      expect do
        subject.create(
          'mock_username',
          'mock_repo',
          missing_events_params
        )
      end.to raise_error(
        BitBucket::Error::NoEvents,
        "At least one event is required, none given :("
      )
    end

    it 'makes a POST request to create a specific webhook' do
      expect(subject).to receive(:request).with(
        :post,
        '/2.0/repositories/mock_username/mock_repo/hooks',
        post_put_params,
        {}
      )

      subject.create(
        'mock_username',
        'mock_repo',
        post_put_params
      )
    end
  end

  describe '#list' do
    it 'makes a GET request for all the webhooks beloning to the given repo' do
      expect(subject).to receive(:request).with(
        :get,
        '/2.0/repositories/mock_username/mock_repo/hooks',
        {},
        {}
      )

      subject.list('mock_username', 'mock_repo')
    end
  end

  describe '#get' do
    it 'makes a GET request for a specific webook' do
      expect(subject).to receive(:request).with(
        :get,
        '/2.0/repositories/mock_username/mock_repo/hooks/mock_uuid',
        {},
        {}
      )

      subject.get('mock_username', 'mock_repo', 'mock_uuid')
    end
  end

  describe '#edit' do
    context 'when required fields are missing from params' do
      context 'when a required key is missing' do
        it 'raises an instance of BitBucket::Error::RequiredParams' do
          expect do
            subject.edit(
              'mock_username',
              'mock_repo',
              'mock_uuid',
              missing_key_params
            )
          end.to raise_error(BitBucket::Error::RequiredParams)
        end
      end

      context 'when values of required keys are blank' do
        it 'raises an instance of BitBucket::Error::RequiredParams' do
          expect do
            subject.edit(
              'mock_username',
              'mock_repo',
              'mock_uuid',
              blank_value_params
            )
          end.to raise_error(
            BitBucket::Error::BlankValue,
            "The value for: 'description', cannot be blank :("
          )
        end
      end
    end

    it 'validates the existence of the given events' do
      allow(subject).to(receive(:request))

      expect do
        subject.edit(
          'mock_username',
          'mock_repo',
          'mock_uuid',
          bad_event_params
        )
      end.to raise_error(
        BitBucket::Error::BadEvents,
        "The event: 'bad:event', does not exist :("
      )
    end

    it 'validates that at least one event is given' do
      allow(subject).to(receive(:request))

      expect do
        subject.edit(
          'mock_username',
          'mock_repo',
          'mock_uuid',
          missing_events_params
        )
      end.to raise_error(
        BitBucket::Error::NoEvents,
        "At least one event is required, none given :("
      )
    end

    it 'makes a PUT request for the given webhook' do
      expect(subject).to receive(:request).with(
        :put,
        '/2.0/repositories/mock_username/mock_repo/hooks/mock_uuid',
        post_put_params,
        {}
      )

      subject.edit(
        'mock_username',
        'mock_repo',
        'mock_uuid',
        post_put_params
      )
    end
  end

  describe '#delete' do
    it 'sends a DELETE request for the given webhook' do
      expect(subject).to receive(:request).with(
        :delete,
        '/2.0/repositories/mock_username/mock_repo/hooks/mock_uuid',
        {},
        {}
      )

      subject.delete('mock_username', 'mock_repo', 'mock_uuid')
    end
  end
end


text:
using SrdReference.Models.Entities;

namespace SrdReference.Repositories.Interfaces
{
    public interface IClassProgressionRepository : ICrudActions<ClassProgression>
    {
    }
}


text:
using Aurora.Web.Auth;
using Microsoft.Extensions.DependencyInjection;

namespace Aurora.Web.DependencyInjection
{
    public static class AspNetRegistration
    {
        public static void Register(IServiceCollection services)
        {
            DomainProxy.DependencyInjection.AspNetRegistration.Register(services);
            services.RegisterBearerPolicy();
            services.RegisterTokenAuthorizationOptions();
        }
    }
}


text:
#ifndef CV_BRIDGE_CV_BRIDGE_H
#define CV_BRIDGE_CV_BRIDGE_H

#include <sensor_msgs/Image.h>
#include <sensor_msgs/CompressedImage.h>
#include <sensor_msgs/image_encodings.h>
#include <ros/static_assert.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgproc/types_c.h>
#include <stdexcept>

namespace cv_bridge {

class Exception : public std::runtime_error
{
public:
  Exception(const std::string& description) : std::runtime_error(description) {}
};

class CvImage;

typedef boost::shared_ptr<CvImage> CvImagePtr;
typedef boost::shared_ptr<CvImage const> CvImageConstPtr;

//from: http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#Mat imread(const string& filename, int flags)
typedef enum {
	BMP, DIB,
	JPG, JPEG, JPE,
	JP2,
	PNG,
	PBM, PGM, PPM,
	SR, RAS,
	TIFF, TIF,
} Format;

/**
 * \brief Image message class that is interoperable with sensor_msgs/Image but uses a
 * more convenient cv::Mat representation for the image data.
 */
class CvImage
{
public:
  std_msgs::Header header; //!< ROS header
  std::string encoding;    //!< Image encoding ("mono8", "bgr8", etc.)
  cv::Mat image;           //!< Image data for use with OpenCV

  /**
   * \brief Empty constructor.
   */
  CvImage() {}

  /**
   * \brief Constructor.
   */
  CvImage(const std_msgs::Header& header, const std::string& encoding,
          const cv::Mat& image = cv::Mat())
    : header(header), encoding(encoding), image(image)
  {
  }

  /**
   * \brief Convert this message to a ROS sensor_msgs::Image message.
   *
   * The returned sensor_msgs::Image message contains a copy of the image data.
   */
  sensor_msgs::ImagePtr toImageMsg() const;

  /**
   * dst_format is compress the image to desire format.
   * Default value is empty string that will convert to jpg format.
   * can be: jpg, jp2, bmp, png, tif at the moment
   * support this format from opencv:
   * http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#Mat imread(const string& filename, int flags)
   */
  sensor_msgs::CompressedImagePtr toCompressedImageMsg(const Format dst_format = JPG) const;

  /**
   * \brief Copy the message data to a ROS sensor_msgs::Image message.
   *
   * This overload is intended mainly for aggregate messages such as stereo_msgs::DisparityImage,
   * which contains a sensor_msgs::Image as a data member.
   */
  void toImageMsg(sensor_msgs::Image& ros_image) const;

  /**
   * dst_format is compress the image to desire format.
   * Default value is empty string that will convert to jpg format.
   * can be: jpg, jp2, bmp, png, tif at the moment
   * support this format from opencv:
   * http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#Mat imread(const string& filename, int flags)
   */
  void toCompressedImageMsg(sensor_msgs::CompressedImage& ros_image, const Format dst_format = JPG) const;

  typedef boost::shared_ptr<CvImage> Ptr;
  typedef boost::shared_ptr<CvImage const> ConstPtr;

protected:
  boost::shared_ptr<void const> tracked_object_; // for sharing ownership

  /// @cond DOXYGEN_IGNORE
  friend
  CvImageConstPtr toCvShare(const sensor_msgs::Image& source,
                            const boost::shared_ptr<void const>& tracked_object,
                            const std::string& encoding);
  /// @endcond
};

/**
 * \brief Convert a sensor_msgs::Image message to an OpenCV-compatible CvImage, copying the
 * image data.
 *
 * \param source   A shared_ptr to a sensor_msgs::Image message
 * \param encoding The desired encoding of the image data, one of the following strings:
 *    - \c "mono8"
 *    - \c "bgr8"
 *    - \c "bgra8"
 *    - \c "rgb8"
 *    - \c "rgba8"
 *    - \c "mono16"
 *
 * If \a encoding is the empty string (the default), the returned CvImage has the same encoding
 * as \a source.
 */
CvImagePtr toCvCopy(const sensor_msgs::ImageConstPtr& source,
                    const std::string& encoding = std::string());

CvImagePtr toCvCopy(const sensor_msgs::CompressedImageConstPtr& source,
                    const std::string& encoding = std::string());

/**
 * \brief Convert a sensor_msgs::Image message to an OpenCV-compatible CvImage, copying the
 * image data.
 *
 * \param source   A sensor_msgs::Image message
 * \param encoding The desired encoding of the image data, one of the following strings:
 *    - \c "mono8"
 *    - \c "bgr8"
 *    - \c "bgra8"
 *    - \c "rgb8"
 *    - \c "rgba8"
 *    - \c "mono16"
 *
 * If \a encoding is the empty string (the default), the returned CvImage has the same encoding
 * as \a source.
 * If the source is 8bit and the encoding 16 or vice-versa, a scaling is applied (65535/255 and
 * 255/65535 respectively). Otherwise, no scaling is applied and the rules from the convertTo OpenCV
 * function are applied (capping): http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-convertto
 */
CvImagePtr toCvCopy(const sensor_msgs::Image& source,
                    const std::string& encoding = std::string());

CvImagePtr toCvCopy(const sensor_msgs::CompressedImage& source,
                    const std::string& encoding = std::string());

/**
 * \brief Convert an immutable sensor_msgs::Image message to an OpenCV-compatible CvImage, sharing
 * the image data if possible.
 *
 * If the source encoding and desired encoding are the same, the returned CvImage will share
 * the image data with \a source without copying it. The returned CvImage cannot be modified, as that
 * could modify the \a source data.
 *
 * \param source   A shared_ptr to a sensor_msgs::Image message
 * \param encoding The desired encoding of the image data, one of the following strings:
 *    - \c "mono8"
 *    - \c "bgr8"
 *    - \c "bgra8"
 *    - \c "rgb8"
 *    - \c "rgba8"
 *    - \c "mono16"
 *
 * If \a encoding is the empty string (the default), the returned CvImage has the same encoding
 * as \a source.
 */
CvImageConstPtr toCvShare(const sensor_msgs::ImageConstPtr& source,
                          const std::string& encoding = std::string());

/**
 * \brief Convert an immutable sensor_msgs::Image message to an OpenCV-compatible CvImage, sharing
 * the image data if possible.
 *
 * If the source encoding and desired encoding are the same, the returned CvImage will share
 * the image data with \a source without copying it. The returned CvImage cannot be modified, as that
 * could modify the \a source data.
 *
 * This overload is useful when you have a shared_ptr to a message that contains a
 * sensor_msgs::Image, and wish to share ownership with the containing message.
 *
 * \param source         The sensor_msgs::Image message
 * \param tracked_object A shared_ptr to an object owning the sensor_msgs::Image
 * \param encoding       The desired encoding of the image data, one of the following strings:
 *    - \c "mono8"
 *    - \c "bgr8"
 *    - \c "bgra8"
 *    - \c "rgb8"
 *    - \c "rgba8"
 *    - \c "mono16"
 *
 * If \a encoding is the empty string (the default), the returned CvImage has the same encoding
 * as \a source.
 */
CvImageConstPtr toCvShare(const sensor_msgs::Image& source,
                          const boost::shared_ptr<void const>& tracked_object,
                          const std::string& encoding = std::string());

/**
 * \brief Convert a CvImage to another encoding using the same rules as toCvCopy
 */
CvImagePtr cvtColor(const CvImageConstPtr& source,
                    const std::string& encoding);

struct CvtColorForDisplayOptions {
  CvtColorForDisplayOptions() :
    do_dynamic_scaling(false),
    min_image_value(0.0),
    max_image_value(0.0),
    colormap(-1),
    bg_label(-1) {}
  bool do_dynamic_scaling;
  double min_image_value;
  double max_image_value;
  int colormap;
  int bg_label;
};

/**
 * \brief Converts an immutable sensor_msgs::Image message to another CvImage for display purposes,
 * using practical conversion rules if needed.
 *
 * Data will be shared between input and output if possible.
 *
 * Recall: sensor_msgs::image_encodings::isColor and isMono tell whether an image contains R,G,B,A, mono
 * (or any combination/subset) with 8 or 16 bit depth.
 *
 * The following rules apply:
 * - if the output encoding is empty, the fact that the input image is mono or multiple-channel is
 * preserved in the ouput image. The bit depth will be 8. it tries to convert to BGR no matter what
 * encoding image is passed.
 * - if the output encoding is not empty, it must have sensor_msgs::image_encodings::isColor and
 * isMono return true. It must also be 8 bit in depth
 * - if the input encoding is an OpenCV format (e.g. 8UC1), and if we have 1,3 or 4 channels, it is
 * respectively converted to mono, BGR or BGRA.
 * - if the input encoding is 32SC1, this estimate that image as label image and will convert it as
 * bgr image with different colors for each label.
 *
 * \param source   A shared_ptr to a sensor_msgs::Image message
 * \param encoding Either an encoding string that returns true in sensor_msgs::image_encodings::isColor
 * isMono or the empty string as explained above.
 * \param options (cv_bridge::CvtColorForDisplayOptions) Options to convert the source image with.
 * - do_dynamic_scaling If true, the image is dynamically scaled between its minimum and maximum value
 * before being converted to its final encoding.
 * - min_image_value Independently from do_dynamic_scaling, if min_image_value and max_image_value are
 * different, the image is scaled between these two values before being converted to its final encoding.
 * - max_image_value Maximum image value
 * - colormap Colormap which the source image converted with.
 */
CvImageConstPtr cvtColorForDisplay(const CvImageConstPtr& source,
                                   const std::string& encoding = std::string(),
                                   const CvtColorForDisplayOptions options = CvtColorForDisplayOptions());

/**
 * \brief Get the OpenCV type enum corresponding to the encoding.
 *
 * For example, "bgr8" -> CV_8UC3, "32FC1" -> CV_32FC1, and "32FC10" -> CV_32FC10.
 */
int getCvType(const std::string& encoding);

} // namespace cv_bridge

// CvImage as a first class message type

// The rest of this file hooks into the roscpp serialization API to make CvImage
// a first-class message type you can publish and subscribe to directly.
// Unfortunately this doesn't yet work with image_transport, so don't rewrite all
// your callbacks to use CvImage! It might be useful for specific tasks, like
// processing bag files.

/// @cond DOXYGEN_IGNORE
namespace ros {

namespace message_traits {

template<> struct MD5Sum<cv_bridge::CvImage>
{
  static const char* value() { return MD5Sum<sensor_msgs::Image>::value(); }
  static const char* value(const cv_bridge::CvImage&) { return value(); }

  static const uint64_t static_value1 = MD5Sum<sensor_msgs::Image>::static_value1;
  static const uint64_t static_value2 = MD5Sum<sensor_msgs::Image>::static_value2;

  // If the definition of sensor_msgs/Image changes, we'll get a compile error here.
  ROS_STATIC_ASSERT(MD5Sum<sensor_msgs::Image>::static_value1 == 0x060021388200f6f0ULL);
  ROS_STATIC_ASSERT(MD5Sum<sensor_msgs::Image>::static_value2 == 0xf447d0fcd9c64743ULL);
};

template<> struct DataType<cv_bridge::CvImage>
{
  static const char* value() { return DataType<sensor_msgs::Image>::value(); }
  static const char* value(const cv_bridge::CvImage&) { return value(); }
};

template<> struct Definition<cv_bridge::CvImage>
{
  static const char* value() { return Definition<sensor_msgs::Image>::value(); }
  static const char* value(const cv_bridge::CvImage&) { return value(); }
};

template<> struct HasHeader<cv_bridge::CvImage> : TrueType {};

} // namespace ros::message_traits

namespace serialization {

template<> struct Serializer<cv_bridge::CvImage>
{
  /// @todo Still ignoring endianness...

  template<typename Stream>
  inline static void write(Stream& stream, const cv_bridge::CvImage& m)
  {
    stream.next(m.header);
    stream.next((uint32_t)m.image.rows); // height
    stream.next((uint32_t)m.image.cols); // width
    stream.next(m.encoding);
    uint8_t is_bigendian = 0;
    stream.next(is_bigendian);
    stream.next((uint32_t)m.image.step);
    size_t data_size = m.image.step*m.image.rows;
    stream.next((uint32_t)data_size);
    if (data_size > 0)
      memcpy(stream.advance(data_size), m.image.data, data_size);
  }

  template<typename Stream>
  inline static void read(Stream& stream, cv_bridge::CvImage& m)
  {
    stream.next(m.header);
    uint32_t height, width;
    stream.next(height);
    stream.next(width);
    stream.next(m.encoding);
    uint8_t is_bigendian;
    stream.next(is_bigendian);
    uint32_t step, data_size;
    stream.next(step);
    stream.next(data_size);
    int type = cv_bridge::getCvType(m.encoding);
    // Construct matrix pointing to the stream data, then copy it to m.image
    cv::Mat tmp((int)height, (int)width, type, stream.advance(data_size), (size_t)step);
    tmp.copyTo(m.image);
  }

  inline static uint32_t serializedLength(const cv_bridge::CvImage& m)
  {
    size_t data_size = m.image.step*m.image.rows;
    return serializationLength(m.header) + serializationLength(m.encoding) + 17 + data_size;
  }
};

} // namespace ros::serialization

namespace message_operations {

template<> struct Printer<cv_bridge::CvImage>
{
  template<typename Stream>
  static void stream(Stream&, const std::string&, const cv_bridge::CvImage&)
  {
    /// @todo Replicate printing for sensor_msgs::Image
  }
};

} // namespace ros::message_operations

} // namespace ros

namespace cv_bridge {

inline std::ostream& operator<<(std::ostream& s, const CvImage& m)
{
  ros::message_operations::Printer<CvImage>::stream(s, "", m);
  return s;
}

} // namespace cv_bridge

/// @endcond

#endif


text:
#define AUDIO_SINK_INTERFACE "org.bluez.AudioSink"

typedef enum {
	SINK_STATE_DISCONNECTED,
	SINK_STATE_CONNECTING,
	SINK_STATE_CONNECTED,
	SINK_STATE_PLAYING,
} sink_state_t;

typedef void (*sink_state_cb) (struct audio_device *dev,
				sink_state_t old_state,
				sink_state_t new_state,
				void *user_data);

unsigned int sink_add_state_cb(sink_state_cb cb, void *user_data);
gboolean sink_remove_state_cb(unsigned int id);

struct sink *sink_init(struct audio_device *dev);
void sink_unregister(struct audio_device *dev);
gboolean sink_is_active(struct audio_device *dev);
avdtp_state_t sink_get_state(struct audio_device *dev);
gboolean sink_new_stream(struct audio_device *dev, struct avdtp *session,
				struct avdtp_stream *stream);
gboolean sink_setup_stream(struct sink *sink, struct avdtp *session);
gboolean sink_shutdown(struct sink *sink);


text:
/**
 * @file
 * @brief RTP support for the SV3V (SVQ3) payload
 * @author Ronald S. Bultje <rbultje@ronald.bitfreak.net>
 * @see http://wiki.multimedia.cx/index.php?title=Sorenson_Video_3#Packetization
 */

#include "XMFFmpeg/libavutil/intreadwrite.h"
#include "internal.h"
#include "rtp.h"
#include "rtpdec.h"
#include "rtpdec_formats.h"

struct PayloadContext {
    AVIOContext *pktbuf;
    int64_t        timestamp;
};

/** return 0 on packet, <0 on partial packet or error... */
static int svq3_parse_packet (AVFormatContext *s, PayloadContext *sv,
                              AVStream *st, AVPacket *pkt,
                              uint32_t *timestamp,
                              const uint8_t *buf, int len, int flags)
{
    int config_packet, start_packet, end_packet;

    if (len < 2)
        return AVERROR_INVALIDDATA;

    config_packet = buf[0] & 0x40;
    start_packet  = buf[0] & 0x20;
    end_packet    = buf[0] & 0x10;
    buf += 2;     // ignore buf[1]
    len -= 2;

    if (config_packet) {

        av_freep(&st->codec->extradata);
        st->codec->extradata_size = 0;

        if (len < 2 || !(st->codec->extradata = (uint8_t *)
                         av_malloc(len + 8 + FF_INPUT_BUFFER_PADDING_SIZE)))
            return AVERROR_INVALIDDATA;

        st->codec->extradata_size = len + 8;
        memcpy(st->codec->extradata, "SEQH", 4);
        AV_WB32(st->codec->extradata + 4, len);
        memcpy(st->codec->extradata + 8, buf, len);

        /* We set codec_id to CODEC_ID_NONE initially to
         * delay decoder initialization since extradata is
         * carried within the RTP stream, not SDP. Here,
         * by setting codec_id to CODEC_ID_SVQ3, we are signalling
         * to the decoder that it is OK to initialize. */
        st->codec->codec_id = CODEC_ID_SVQ3;

        return AVERROR(EAGAIN);
    }

    if (start_packet) {
        int res;

        if (sv->pktbuf) {
            uint8_t *tmp;
            avio_close_dyn_buf(sv->pktbuf, &tmp);
            av_free(tmp);
        }
        if ((res = avio_open_dyn_buf(&sv->pktbuf)) < 0)
            return res;
        sv->timestamp   = *timestamp;
    }

    if (!sv->pktbuf)
        return AVERROR_INVALIDDATA;

    avio_write(sv->pktbuf, buf, len);

    if (end_packet) {
        av_init_packet(pkt);
        pkt->stream_index = st->index;
        *timestamp        = sv->timestamp;
        pkt->size         = avio_close_dyn_buf(sv->pktbuf, &pkt->data);
        pkt->destruct     = av_destruct_packet;
        sv->pktbuf        = NULL;
        return 0;
    }

    return AVERROR(EAGAIN);
}

static PayloadContext *svq3_extradata_new(void)
{
    return (PayloadContext *)av_mallocz(sizeof(PayloadContext));
}

static void svq3_extradata_free(PayloadContext *sv)
{
    if (sv->pktbuf) {
        uint8_t *buf;
        avio_close_dyn_buf(sv->pktbuf, &buf);
        av_free(buf);
    }
    av_free(sv);
}

RTPDynamicProtocolHandler ff_svq3_dynamic_handler = {
    /*.enc_name				= */	"X-SV3V-ES",
    /*.codec_type			= */	AVMEDIA_TYPE_VIDEO,
    /*.codec_id				= */	CODEC_ID_NONE,      // see if (config_packet) above
	/*.static_payload_id	= */	0,
	/*.init					= */	0,
    /*.parse_sdp_a_line		= */	0,
    /*.alloc				= */	svq3_extradata_new,
    /*.free					= */	svq3_extradata_free,
    /*.parse_packet			= */	svq3_parse_packet,
};


text:
namespace reranker {

using std::stringstream;

/// \class RankFeatureExtractor
///
/// Encodes the baseline rank as a boolean feature.
class RankFeatureExtractor : public FeatureExtractor {
 public:
  /// Constructs an instance.
  RankFeatureExtractor() : FeatureExtractor() {
  }
  /// Destroys this instance.
  virtual ~RankFeatureExtractor() { }

  virtual void RegisterInitializers(Initializers &initializers) {
    initializers.Add("add_score_factor", &add_score_factor_);
    initializers.Add("add_score_difference", &add_score_difference_);
  }

  virtual void Extract(Candidate &candidate,
		       FeatureVector<int,double> &features) { }

  /// Extracts symbolic (or <i>string</i>) features.  These will be
  /// automatically compiled when training.
  ///
  /// \param[in]  candidate         the candidate for which to extract features
  /// \param[out] symbolic_features the features extracted for the specified
  ///                               candidate
  virtual void ExtractSymbolic(Candidate &candidate,
                               FeatureVector<string,double> &symbolic_features)
  {
    stringstream ss;
    ss << "orig_rank:" << candidate.index();
    symbolic_features.IncrementWeight(ss.str(), 1.0);

    stringstream lg_rank_ss;
    double lg_rank = floor(log((double)candidate.index() + 1.0) /
                           log(2.0) + 0.5);
    lg_rank_ss << "lg_rank:" << lg_rank;
    symbolic_features.IncrementWeight(lg_rank_ss.str(), 1.0);

    if (add_score_factor_) {
      double top_baseline_score =
          top_baseline_score_ == 0.0 ? 1e-10 : top_baseline_score_;
      double score_factor = candidate.baseline_score() / top_baseline_score;
      symbolic_features.IncrementWeight("score_factor", score_factor);
    }
    if (add_score_difference_) {
      double score_difference =
          candidate.baseline_score() - top_baseline_score_;
      symbolic_features.IncrementWeight("score_difference", score_difference);
    }
  }

  /// Override the default Extract method so that it caches the score of the
  /// top-scoring hypothesis of the baseline system.
  virtual void Extract(CandidateSet &candidate_set) {
    top_baseline_score_ = candidate_set.Get(0).baseline_score();
    FeatureExtractor::Extract(candidate_set);
  }

 private:
  double top_baseline_score_;
  bool add_score_factor_;
  bool add_score_difference_;
};

}  // namespace reranker

#endif


text:
import * as fs from 'fs';
import * as path from 'path';
import { spawn, ChildProcessWithoutNullStreams } from 'child_process';

// i.e. my-app/app-0.1.13/
const appFolder = path.dirname(process.execPath);

// i.e. my-app/Update.exe
const updateExe = path.resolve(appFolder, '..', 'Update.exe');
const exeName = path.basename(process.execPath);
let spawnedArgs: string[] = [];
let spawnedProcess: ChildProcessWithoutNullStreams | undefined;

const isSameArgs = (args: string[]) => args.length === spawnedArgs.length && args.every((e, i) => e === spawnedArgs[i]);

// Spawn a command and invoke the callback when it completes with an error
// and the output from standard out.
const spawnUpdate = function (args: string[], detached: boolean, callback: Function) {
  let error: Error, errorEmitted: boolean, stderr: string, stdout: string;

  try {
    // Ensure we don't spawn multiple squirrel processes
    // Process spawned, same args:        Attach events to already running process
    // Process spawned, different args:   Return with error
    // No process spawned:                Spawn new process
    if (spawnedProcess && !isSameArgs(args)) {
      // Disabled for backwards compatibility:
      // eslint-disable-next-line standard/no-callback-literal
      return callback(`AutoUpdater process with arguments ${args} is already running`);
    } else if (!spawnedProcess) {
      spawnedProcess = spawn(updateExe, args, {
        detached: detached,
        windowsHide: true
      });
      spawnedArgs = args || [];
    }
  } catch (error1) {
    error = error1 as Error;

    // Shouldn't happen, but still guard it.
    process.nextTick(function () {
      return callback(error);
    });
    return;
  }
  stdout = '';
  stderr = '';

  spawnedProcess.stdout.on('data', (data) => { stdout += data; });
  spawnedProcess.stderr.on('data', (data) => { stderr += data; });

  errorEmitted = false;
  spawnedProcess.on('error', (error) => {
    errorEmitted = true;
    callback(error);
  });

  return spawnedProcess.on('exit', function (code, signal) {
    spawnedProcess = undefined;
    spawnedArgs = [];

    // We may have already emitted an error.
    if (errorEmitted) {
      return;
    }

    // Process terminated with error.
    if (code !== 0) {
      // Disabled for backwards compatibility:
      // eslint-disable-next-line standard/no-callback-literal
      return callback(`Command failed: ${signal ?? code}\n${stderr}`);
    }

    // Success.
    callback(null, stdout);
  });
};

// Start an instance of the installed app.
export function processStart () {
  return spawnUpdate(['--processStartAndWait', exeName], true, function () {});
}

// Download the releases specified by the URL and write new results to stdout.
export function checkForUpdate (updateURL: string, callback: (error: Error | null, update?: any) => void) {
  return spawnUpdate(['--checkForUpdate', updateURL], false, function (error: Error, stdout: string) {
    let ref, ref1, update;
    if (error != null) {
      return callback(error);
    }
    try {
      // Last line of output is the JSON details about the releases
      const json = stdout.trim().split('\n').pop();
      update = (ref = JSON.parse(json!)) != null ? (ref1 = ref.releasesToApply) != null ? typeof ref1.pop === 'function' ? ref1.pop() : undefined : undefined : undefined;
    } catch {
      // Disabled for backwards compatibility:
      // eslint-disable-next-line standard/no-callback-literal
      return callback(new Error(`Invalid result:\n${stdout}`));
    }
    return callback(null, update);
  });
}

// Update the application to the latest remote version specified by URL.
export function update (updateURL: string, callback: (error: Error) => void) {
  return spawnUpdate(['--update', updateURL], false, callback);
}

// Is the Update.exe installed with the current application?
export function supported () {
  try {
    fs.accessSync(updateExe, fs.constants.R_OK);
    return true;
  } catch {
    return false;
  }
}


text:
import {ApiResult, ErrorResponse} from "helpers/api_request_builder";
import {MithrilComponent} from "jsx/mithril-component";
import m from "mithril";
import Stream from "mithril/stream";
import {Reset} from "views/components/buttons";
import {FlashMessageModelWithTimeout, MessageType} from "views/components/flash_message";
import {Size, TextAreaField} from "views/components/forms/input_fields";
import * as Icons from "views/components/icons";
import {Link} from "views/components/link";
import {PipelineStatus} from "views/pages/pipeline_activity/common/models/pipeline_status";
import {ConfirmationDialog} from "views/pages/pipeline_activity/confirmation_modal";
import styles from "../index.scss";

interface Attrs {
  pipelineName: string;
  shouldShowPauseUnpause: boolean;
  shouldShowPipelineSettings: boolean;
  flashMessage: FlashMessageModelWithTimeout;
  onPipelinePause?: (result: ApiResult<any>) => any;
  onPipelineUnpause?: (result: ApiResult<any>) => any;
  pipelineStatus?: PipelineStatus;
}

interface State {
  pipelineStatus: Stream<PipelineStatus>;
}

export class PipelinePauseHeader extends MithrilComponent<Attrs, State> {
  oninit(vnode: m.Vnode<Attrs, State>) {
    vnode.state.pipelineStatus = Stream();
    if (vnode.attrs.pipelineStatus) {
      vnode.state.pipelineStatus(vnode.attrs.pipelineStatus);
    } else {
      PipelineStatus.fetch(vnode.attrs.pipelineName).then(vnode.state.pipelineStatus);
    }
  }

  view(vnode: m.Vnode<Attrs, State>): m.Children {
    return

        Pipeline
        {vnode.attrs.pipelineName}

      {this.getPipelinePauseUnpauseButton(vnode)}
      {this.pauseMessageText(vnode)}
      {this.pipelineSettingsLink(vnode)}

;
  }

  private pipelineSettingsLink(vnode: m.Vnode<Attrs, State>) {
    if (vnode.attrs.shouldShowPipelineSettings) {
      return

        <Link href={`/go/admin/pipelines/${vnode.attrs.pipelineName}/general`}>
          <Icons.Settings iconOnly={true}/>
        </Link>

;
    }
  }

  private getPipelinePauseUnpauseButton(vnode: m.Vnode<Attrs, State>) {
    if (!vnode.attrs.shouldShowPauseUnpause || !vnode.state.pipelineStatus()) {
      return;
    }

    const pipelineStatus = vnode.state.pipelineStatus()!;
    if (pipelineStatus.isPaused()) {
      return

        <Reset small={true} data-test-id="page-header-unpause-btn" onclick={() => {
          pipelineStatus.unpause().then((result) => {
            result.do(() => {
              vnode.state.pipelineStatus().isPaused(false);
              vnode.state.pipelineStatus().pausedBy(undefined);
              vnode.state.pipelineStatus().pausedCause(undefined);
              vnode.attrs.flashMessage.setMessage(MessageType.success, "Pipeline unpaused Successfully!");

              if (vnode.attrs.onPipelineUnpause) {
                vnode.attrs.onPipelineUnpause(result);
              }
            }, this.onUpdateFailure.bind(this, vnode));
          });
        }}>UNPAUSE</Reset>

;
    }

    return

      <Reset small={true}
             data-test-id="page-header-pause-btn"
             onclick={this.renderPausePipelineConfirmation.bind(this, vnode)}>
        PAUSE
      </Reset>

;
  }

  private renderPausePipelineConfirmation(vnode: m.Vnode<Attrs, State>) {
    const body = <TextAreaField required={false} size={Size.MATCH_PARENT}
                                property={vnode.state.pipelineStatus()!.pausedCause}
                                rows={5}
                                dataTestId="pause-pipeline-textarea"
                                label="Specify the reason why you want to stop scheduling on this pipeline"/>;

    new ConfirmationDialog("Pause pipeline", body, () => {
      return vnode.state.pipelineStatus().pause().then((result) => {
        result.do(() => {
          const user = document.body.getAttribute("data-user-display-name") as string;
          vnode.state.pipelineStatus().isPaused(true);
          vnode.state.pipelineStatus().pausedBy(user);
          vnode.attrs.flashMessage.setMessage(MessageType.success, "Pipeline paused Successfully!");

          if (vnode.attrs.onPipelinePause) {
            vnode.attrs.onPipelinePause(result);
          }
        }, this.onUpdateFailure.bind(this, vnode));
      });
    }).render();
  }

  private onUpdateFailure(vnode: m.Vnode<Attrs, State>, errorResponse: ErrorResponse) {
    const parsed  = errorResponse.body ? JSON.parse(errorResponse.body!) : {};
    const message = parsed.message ? parsed.message : errorResponse.message;
    vnode.attrs.flashMessage.setMessage(MessageType.alert, message);
  }

  private pauseMessageText(vnode: m.Vnode<Attrs, State>) {
    if (!vnode.state.pipelineStatus() || !vnode.state.pipelineStatus().isPaused()) {
      return;
    }

    let pauseMessage     = "Scheduling is paused";
    const pipelineStatus = vnode.state.pipelineStatus()!;
    if (pipelineStatus.pausedBy()) {
      pauseMessage += ` by ${pipelineStatus.pausedBy()}`;
    }
    if (pipelineStatus.pausedCause()) {
      pauseMessage += ` (${pipelineStatus.pausedCause()})`;
    }

    return
{pauseMessage}
;
  }
}


text:
package vpp1908

import (
	"net"

	"github.com/ligato/vpp-agent/api/models/netalloc"
	vpp_l3 "github.com/ligato/vpp-agent/api/models/vpp/l3"
	"github.com/ligato/vpp-agent/plugins/vpp/binapi/vpp1908/ip"
	"github.com/pkg/errors"
)

const (
	// NextHopViaLabelUnset constant has to be assigned into the field next hop
	// via label in ip_add_del_route binary message if next hop via label is not defined.
	// Equals to MPLS_LABEL_INVALID defined in VPP
	NextHopViaLabelUnset uint32 = 0xfffff + 1

	// ClassifyTableIndexUnset is a default value for field classify_table_index in ip_add_del_route binary message.
	ClassifyTableIndexUnset = ^uint32(0)

	// NextHopOutgoingIfUnset constant has to be assigned into the field next_hop_outgoing_interface
	// in ip_add_del_route binary message if outgoing interface for next hop is not defined.
	NextHopOutgoingIfUnset = ^uint32(0)
)

// vppAddDelRoute adds or removes route, according to provided input. Every route has to contain VRF ID (default is 0).
func (h *RouteHandler) vppAddDelRoute(route *vpp_l3.Route, rtIfIdx uint32, delete bool) error {
	req := &ip.IPRouteAddDel{
		// Multi path is always true
		IsMultipath: 1,
	}
	if delete {
		req.IsAdd = 0
	} else {
		req.IsAdd = 1
	}

	// Common route parameters
	fibPath := ip.FibPath{
		Weight:     uint8(route.Weight),
		Preference: uint8(route.Preference),
	}
	if route.NextHopAddr != "" {
		nextHop, err := h.addrAlloc.GetOrParseIPAddress(route.NextHopAddr,
			route.OutgoingInterface, netalloc.IPAddressForm_ADDR_ONLY)
		if err != nil {
			return err
		}
		fibPath.Nh, fibPath.Proto = setFibPathNhAndProto(nextHop.IP)
	}

	// VRF/Other route parameters based on type
	if route.Type == vpp_l3.Route_INTER_VRF {
		fibPath.SwIfIndex = rtIfIdx
		fibPath.TableID = route.ViaVrfId
	} else if route.Type == vpp_l3.Route_DROP {
		fibPath.Type = ip.FIB_API_PATH_TYPE_DROP
	} else {
		fibPath.SwIfIndex = rtIfIdx
		fibPath.TableID = route.VrfId
	}
	// Destination address
	dstNet, err := h.addrAlloc.GetOrParseIPAddress(route.DstNetwork,
		"", netalloc.IPAddressForm_ADDR_NET)
	if err != nil {
		return err
	}
	prefix := networkToPrefix(dstNet)

	req.Route = ip.IPRoute{
		TableID: route.VrfId,
		Prefix:  prefix,
		NPaths:  1,
		Paths:   []ip.FibPath{fibPath},
	}

	// Send message
	reply := &ip.IPRouteAddDelReply{}
	if err := h.callsChannel.SendRequest(req).ReceiveReply(reply); err != nil {
		return err
	}

	return nil
}

// VppAddRoute implements route handler.
func (h *RouteHandler) VppAddRoute(route *vpp_l3.Route) error {
	swIfIdx, err := h.getRouteSwIfIndex(route.OutgoingInterface)
	if err != nil {
		return err
	}

	return h.vppAddDelRoute(route, swIfIdx, false)
}

// VppDelRoute implements route handler.
func (h *RouteHandler) VppDelRoute(route *vpp_l3.Route) error {
	swIfIdx, err := h.getRouteSwIfIndex(route.OutgoingInterface)
	if err != nil {
		return err
	}

	return h.vppAddDelRoute(route, swIfIdx, true)
}

func setFibPathNhAndProto(netIP net.IP) (nh ip.FibPathNh, proto ip.FibPathNhProto) {
	var ipData [16]byte
	if netIP.To4() == nil {
		proto = ip.FIB_API_PATH_NH_PROTO_IP6
		copy(ipData[:], netIP[:])
	} else {
		proto = ip.FIB_API_PATH_NH_PROTO_IP4
		copy(ipData[:], netIP.To4()[:])
	}
	return ip.FibPathNh{
		Address: ip.AddressUnion{
			XXX_UnionData: ipData,
		},
		ViaLabel:           NextHopViaLabelUnset,
		ClassifyTableIndex: ClassifyTableIndexUnset,
	}, proto
}

func (h *RouteHandler) getRouteSwIfIndex(ifName string) (swIfIdx uint32, err error) {
	swIfIdx = NextHopOutgoingIfUnset
	if ifName != "" {
		meta, found := h.ifIndexes.LookupByName(ifName)
		if !found {
			return 0, errors.Errorf("interface %s not found", ifName)
		}
		swIfIdx = meta.SwIfIndex
	}
	return
}


text:
[![Code Climate](https://codeclimate.com/github/scooterw/geogit-ruby.png)](https://codeclimate.com/github/scooterw/geogit-ruby)

geogit-ruby
===

Use GeoGit in your JRuby applications

NOTE: JRuby is required

In development: `mvn clean install` to get Java/Scala dependencies

`jruby -S rake console` or `bin/geogit_console` to open IRB with geogit loaded

Import a repo from GitHub (with history):

NOTE: Some repos fail due to to inconsistencies in GeoJSON files and strict processing of GeoJSON in GeoTools

```ruby
# without a client_id / client_secret, you will be severely rate limited
# ability to import github repos may be affected
GeoGit.configure do |c|
  c.github = {
    client_id: 'yourclientid',
    client_secret: 'yourclientsecret'
  }
end

GeoGit.import_github_repo 'username/reponame'
```

Create a repo and import a shapefile:

```ruby
GeoGit.create_or_init_repo '~/Desktop/test_repo'
GeoGit.import_shapefile '~/Desktop/test_repo', '~/Desktop/states/states.shp'
# => ["states"]

#GeoGit.import_geojson '~/Desktop/test_repo', '~/Desktop/states/states.geojson'
```

To execute a command (get log for previously imported repo):

```ruby
repo = GeoGit::Repository.new '~/Desktop/test_repo'
# => #<GeoGit::Repository:0x392de91e @repo_path="~/Desktop/test_repo">
log = repo.log
# => {:count=>49, :commits=>[{:id=>"b0524c80b72cf3a7a13ed1edf7114156bae95a3b", :message=>"imported_states/1", :author=>{:name=>"", :email=>""}, :committer=>{:name=>"Scooter Wadsworth", :email=>"scooterwadsworth@gmail.com"}}, {:id=>"838d69be61caffb629373ed9a44a417e5f2b1bfd", :message=>"imported_states/2", :author=>{:name=>"", :email=>""}, :committer=>{:name=>"Scooter Wadsworth", :email=>"scooterwadsworth@gmail.com"}}, ...}
```

CONTRIBUTORS
===
milafrerichs (https://github.com/milafrerichs)


text:
<?php
/**
 * This is the part of 'BmProducts' module for Magento,
 * which allows easy access to product collection
 * with flexible filters
 */

class Bestmagento_BmProducts_Block_Product_Random extends Bestmagento_BmProducts_Block_Product_Abstract
{
    protected $_title = 'Random Products';
    protected $_priceSuffix = '-random';
    protected $_className = 'bmproducts-random';

    protected function _beforeToHtml()
    {
        $collection = $this->getCollection()
            ->addCategoryFilter(Mage::getModel('catalog/category')->load($this->getCategoryId()));

        $this->setProductCollection($collection);

        return parent::_beforeToHtml();
    }

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Herb. Fr. 9: tab. 413, fig. 1 (1789)

#### Original name
Agaricus columbinus Bull., 1789

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Provider;
using System.Text;
using System.Threading.Tasks;

namespace CDrive
{
    public static class DriveFactory
    {

        public static AbstractDriveInfo CreateInstance(string type, object value, string name)
        {
            switch (type.ToLowerInvariant())
            {
                case "azurefile":
                    var d = new AzureFileServiceDriveInfo(value as string, name);
                    return d;
                case "azureblob":
                    var b = new AzureBlobServiceDriveInfo(value as string, name);
                    return b;
                case "azuretable":
                    var t = new AzureTableServiceDriveInfo(value as string, name);
                    return t;
                case "azurequeue":
                    var q = new AzureQueueServiceDriveInfo(value as string, name);
                    return q;
                case "local":
                    var l = new LocalDriveInfo(value as string, name);
                    return l;
                default:
                    return null;

            }
        }
    }
}