text:
module like

    use params
    use gputils, only: gp_n_planet_pars
    use utils1, only: logSumExp
!     use Nested, only: MPI_COMM_WORLD

    !use lib_matrix, only: inverse, determinant
    implicit none

    real(kind=8), parameter :: pi = 3.1415926535897932384626433832795029d0
    real(kind=8), parameter :: twopi = 2.d0 * pi
    real(kind=8), parameter :: lntwopi = log(twopi)
    real(kind=8), parameter :: lnstwopi = log(sqrt(twopi))

contains

    subroutine likelihood_init(N)
    ! Initialize variables that depend on the data dimensions
        integer, intent(in) :: N ! total size of data-set
        allocate(ss(N), alpha(N), tau(N))
        allocate(observ(N))
        allocate(times(N), rvs(N), errors(N))
        allocate(train_var(N))
        allocate(vel(N), r(N), sigma(N))
        !allocate(vel_oversampled(5*N), times_oversampled(5*N))
        !allocate(last_vel_oversampled(5*N, 3))
        !allocate(covmat(N,N), inv_covmat(N,N))
    end subroutine likelihood_init

    subroutine likelihood_finish()
    ! deallocate memory
        deallocate(ss, alpha, tau)
        deallocate(observ)
        deallocate(times, rvs, errors)
        deallocate(vel, r, sigma)
        !deallocate(last_vel_oversampled, vel_oversampled, times_oversampled)
        !deallocate(covmat, inv_covmat)
    end subroutine likelihood_finish

    subroutine slikelihood(Cube,slhood,context)
    ! Likelihood subroutine
    ! This is called by getLogLike in nestwrap.f90 which does the parameter rescaling.
    ! Cube(1:nPar) has already physical parameters.
    ! The log-likelihood is returned in slhood
        implicit none

        real(kind=8), intent(in) :: Cube(nest_nPar)
        real(kind=8), intent(out) :: slhood
        integer, intent(in) :: context
        real(kind=8) :: lhood, lhood_test(1,1), det, jitter, var
        integer :: i, n, ierr, iendpar
        character(len=100) :: fmt

        ! times, rvs and errors are defined in params and initialized/read in main
!         ss = 0.d0
!         alpha = 1.d0
!         tau = 1.d0

        n = size(times)
        slhood=-huge(1.d0)*epsilon(1.d0)

!         write(*,'(f10.3, i3)') (rvs(i), observ(i), i=1,n)
        iendpar = nest_nPar-nextra
        if (using_jitter) iendpar = iendpar+1
!             iendpar = iendpar-1

        do i=1,nobserv
            where(observ == i) vel = Cube(iendpar+i)
        end do

        if (trend) then
!             print *, Cube
!             print *, Cube(iendpar+i+1)
            vel = vel + Cube(iendpar+i+1)*(times-mean_time)
        end if

        ! get the radial velocity model with these parameters (in vel)
        if (nplanets > 0) then
            call get_rvN(times, &
                         Cube(1:5*nplanets:5), & ! periods for all planets
                         Cube(2:5*nplanets:5), & ! K for all planets
                         Cube(3:5*nplanets:5), & ! ecc for all planets
                         Cube(4:5*nplanets:5), & ! omega for all planets
                         Cube(5:5*nplanets:5), & ! t0 for all planets
                         0.d0, & ! systematic velocity
                         vel, n, nplanets)

            ! this works from more than one observatory using OPEN/ext/get_rvN_MultiSite.f90
            ! well not just yet
!             call get_rvN(times, &
!                          Cube(1:iendpar:5), & ! periods for all planets
!                          Cube(2:iendpar:5), & ! K for all planets
!                          Cube(3:iendpar:5), & ! ecc for all planets
!                          Cube(4:iendpar:5), & ! omega for all planets
!                          Cube(5:iendpar:5), & ! t0 for all planets
!                          Cube(iendpar+1:), & ! systematic velocity(ies)
!                          observ, & ! array with observatory indices
!                          vel, n, nplanets, nobserv)

        end if

        ! residuals: what is left when the planets (or just vsys) is subtracted from the data
        r = rvs - vel

!             call MPI_COMM_RANK(MPI_COMM_WORLD, i, ierr)
!             if (i==0) then
!                 print *, 'r = ', r
!                write(fmt,'(a,i2,a)')  '(',nest_nPar,'f13.4)'
!                write(*, fmt) Cube(:)
! !                write(*, fmt) Cube(:gp_n_planet_pars)
! !                write(*, fmt) Cube(gp_n_planet_pars)
! !                write(*, fmt) Cube(gp_n_planet_pars+2)
! !                write(*, fmt) Cube(gp_n_planet_pars+3)
! !                write(*, fmt) Cube(gp_n_planet_pars+4:gp_n_planet_pars+5)
!             end if
!             call MPI_BARRIER(MPI_COMM_WORLD, ierr)
!             STOP 1

        if (using_gp) then
            ! gp1 is an object of type GP (class is defined in gp_utils.f90)
            ! its hierarchy is quite complex:
            !   gp1%gp_kernel%pars    holds the parameters of the kernel's sum, i.e,
            !                         the multiplying constants behind the 2 kernels
            !
            !   gp1%sub_kernel1       is the first sub kernel (a product of kernels)
            !   gp1%sub_kernel1%pars  holds the parameters of the kernels' product, i.e.,
            !                         the multiplying constants - do not change these
            !   parameters of the two kernels being multiplied can be accessed and changed by
            !   gp1%sub_kernel1%get_kernel_pars(k)
            !   gp1%sub_kernel1%set_kernel_pars(k, new_pars)
            !   where k=1 corresponds to the ExpSquared kernel (with 1 parameter)
            !         k=2 corresponds to the ExpSineSquared kernel (with 2 parameters)
            !
            !   gp%sub_kernel2        is the second sub kernel (a simple DiagonalKernel)
            !   gp1%sub_kernel1%pars  holds the DiagonalKernel parameter (the jitter value)

            !! update the hyperparameters

            ! amplitude of the quasi-periodic component
            gp1%gp_kernel%pars(1) = Cube(gp_n_planet_pars+1)
            ! jitter
            gp1%sub_kernel2%pars(1) = Cube(gp_n_planet_pars+2)
            ! timescale for growth / decay of active regions (d)
            call gp1%sub_kernel1%set_kernel_pars(1, (/Cube(gp_n_planet_pars+3)/) )
            ! periodicity (recurrence) timescale -> rotation period of the star
            ! correlation scale
            call gp1%sub_kernel1%set_kernel_pars(2, Cube(gp_n_planet_pars+4:))

            !! log likelihood of the residuals
            ! mean_fun is 0. because vsys is already taken care of
            lhood = gp1%get_lnlikelihood(times, r, (/0.d0/), yerr=errors)

        else if (using_jitter) then
            jitter = Cube(nest_nPar-nextra+1)
            do i=1,n
                var = errors(i)*errors(i) + jitter*jitter
                lhood = lhood - 0.5*lntwopi - 0.5*log(var) - 0.5*(r(i)**2)/var
            end do

!             sigma(:) = errors(:)**2 + jitter**2
            !lhood = - n*lnstwopi - sum(log(sqrt(sigma)) + 0.5d0 * r**2 / sigma)
!             lhood = -0.5d0*n*lntwopi - n*sum(log(sqrt(sigma))) -0.5d0*sum(r**2 / sigma)
!             print *, lhood
            ! lhood = - 0.5d0*log(twopi**n * product(sqrt(sigma))) -0.5d0 * sum(r**2 / sigma)
        else
            do i=1,n
                var = errors(i)*errors(i)
                lhood = lhood - 0.5*lntwopi - 0.5*log(var) - 0.5*(r(i)**2)/var
            end do
            ! lhood = -0.5d0*n*lntwopi - n*sum(log(errors)) -0.5d0*sum(r**2 / errors**2)
            ! lhood = - 0.5d0*log(twopi**n * product(errors)) -0.5d0 * sum(r**2 / errors**2)
        end if

        slhood = logSumExp(slhood,lhood)
!         stop
        if (doing_debug) write(*,'(f8.3)', advance='no') slhood

    end subroutine slikelihood

!    subroutine get_covmat(times, sigma, observ, ss, alpha, tau, covmat, det, inv_covmat)
!    ! Calculates the covariance matrix of the observations and returns its
!    ! determinant and inverse.
!        ! vectors with times and uncertainties
!        real(kind=8), intent(in), dimension(:) :: times, sigma
!        ! vector with flags for points comming from each observatory
!        integer, intent(in), dimension(:) :: observ
!        ! nuisance parameters for each observatory
!        real(kind=8), intent(in), dimension(:) :: ss, alpha, tau
!        ! on output, the covariance matrix of the observations and its inverse
!        real(kind=8), intent(out), dimension(:,:) :: covmat, inv_covmat
!        real(kind=8), intent(out) :: det ! determinant of covmat
!
!        ! local variables
!        integer :: i, j, nt
!
!        covmat = 0.d0; inv_covmat = 0.d0
!        nt = size(sigma)
!        do i=1,nt
!            do j=1,nt
!                ! Kronecker delta on the times
!                if (i==j) covmat(i,j) = (sigma(j)/alpha(j))**2
!                ! Kronecker delta on the observatories
!                if (observ(i)==observ(j)) then
!                    covmat(i,j) = covmat(i,j) + ss(j)**2 * exp(-abs(times(i)-times(j))/tau(j))
!                endif
!            end do
!        end do
!        det = determinant(covmat)
!        call inverse(covmat, inv_covmat)
!    end subroutine get_covmat

end module like


text:
package operations

import (
	"github.com/omise/omise-go/internal"
)

// Example:
//
//	refunds, list := &omise.RefundList{}, &ListRefunds{"chrg_333"}
//	if e := client.Do(refunds, list); e != nil {
//		panic(e)
//	}
//
//	fmt.Println("refunded on chrg_333:", refunds.Data[0].Amount)
//
type ListRefunds struct {
	ChargeID string
	List
}

func (req *ListRefunds) Describe() *internal.Description {
	return &internal.Description{
		Endpoint:    internal.API,
		Method:      "GET",
		Path:        "/charges/" + req.ChargeID + "/refunds",
		ContentType: "application/json",
	}
}

// Example:
//
//	refund, create := &omise.Refund{}, &CreateRefund{
//		ChargeID: charge.ID,
//		Amount:   charge.Amount >> 1, // half
//	}
//	if e := client.Do(refund, create); e != nil {
//		panic(e)
//	}
//
//	fmt.Println("refunded half of charge with:", refund.ID)
//
type CreateRefund struct {
	ChargeID string                 `json:"-"`
	Amount   int64                  `json:"amount"`
	Void     bool                   `json:"void,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

func (req *CreateRefund) Describe() *internal.Description {
	return &internal.Description{
		Endpoint:    internal.API,
		Method:      "POST",
		Path:        "/charges/" + req.ChargeID + "/refunds",
		ContentType: "application/json",
	}
}

// Example:
//
//	refund, retrieve := &omise.Refund{}, &RetrieveRefund{
//		ChargeID: "chrg_123",
//		RefundID: "rfnd_777",
//	}
//	if e := client.Do(refund, retrieve); e != nil {
//		panic(e)
//	}
//
//	fmt.Printf("refund #777: %#v\n", refund)
//
type RetrieveRefund struct {
	ChargeID string `json:"-"`
	RefundID string `json:"-"`
}

func (req *RetrieveRefund) Describe() *internal.Description {
	return &internal.Description{
		Endpoint:    internal.API,
		Method:      "GET",
		Path:        "/charges/" + req.ChargeID + "/refunds/" + req.RefundID,
		ContentType: "application/json",
	}
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * This utility method will manage the execution of the right reducer based
 * on the triggered action.
 *
 * @param {object} actionHandlers redux actions/reducers
 */
export function createActionHandlers(actionHandlers, initialState = {}) {
  return function (state = initialState, action) {
    if (!action) return state;
    const { type, payload } = action;
    const hndlr = actionHandlers[type];
    return hndlr ? hndlr(state, payload, action) : state;
  };
}


text:
#ifndef __MEM_RUBY_NETWORK_GARNET_FLEXIBLE_PIPELINE_NETWORK_LINK_HH__
#define __MEM_RUBY_NETWORK_GARNET_FLEXIBLE_PIPELINE_NETWORK_LINK_HH__

#include <iostream>
#include <vector>

#include "mem/ruby/common/NetDest.hh"
#include "mem/ruby/network/garnet/flexible-pipeline/FlexibleConsumer.hh"
#include "mem/ruby/network/garnet/flexible-pipeline/flitBuffer.hh"
#include "mem/ruby/network/garnet/NetworkHeader.hh"
#include "params/NetworkLink.hh"
#include "sim/clocked_object.hh"

class GarnetNetwork;

class NetworkLink : public ClockedObject, public FlexibleConsumer
{
  public:
    typedef NetworkLinkParams Params;
    NetworkLink(const Params *p);
    ~NetworkLink();

    void setLinkConsumer(FlexibleConsumer *consumer);
    void setSourceQueue(flitBuffer *srcQueue);
    flit *peekLink();
    flit *consumeLink();

    void print(std::ostream& out) const {}

    bool is_vc_ready(flit *t_flit);

    int get_id() const { return m_id; }
    void setInPort(int port);
    void setOutPort(int port);
    void wakeup();
    bool isReady();
    void grant_vc_link(int vc, Cycles grant_time);
    void release_vc_link(int vc, Cycles release_time);
    void request_vc_link(int vc, NetDest destination, Cycles request_time);
    bool isBufferNotFull_link(int vc);
    void setSource(FlexibleConsumer *source);
    void init_net_ptr(GarnetNetwork* net_ptr) { m_net_ptr = net_ptr; }

    unsigned int getLinkUtilization() const { return m_link_utilized; }
    const std::vector<unsigned int> & getVcLoad() const { return m_vc_load; }

    bool functionalRead(Packet *);
    uint32_t functionalWrite(Packet *);

  private:
    int m_id;
    Cycles m_latency;
    int m_in_port, m_out_port;
    GarnetNetwork *m_net_ptr;

    flitBuffer *linkBuffer;
    FlexibleConsumer *link_consumer;
    FlexibleConsumer *link_source;
    flitBuffer *link_srcQueue;

    // Statistical variables
    unsigned int m_link_utilized;
    std::vector<unsigned int> m_vc_load;
};

#endif // __MEM_RUBY_NETWORK_GARNET_FLEXIBLE_PIPELINE_NETWORK_LINK_HH__


text:
package openmods.inventory;

import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import net.minecraft.item.ItemStack;
import openmods.inventory.comparator.EqualComponents;
import openmods.inventory.comparator.EqualComponents.IItemStackTester;

public class StackEqualityTesterBuilder {

	@FunctionalInterface
	public interface IEqualityTester {
		public boolean isEqual(Object left, Object right);
	}

	private boolean usedItem;
	private boolean usedItemId;
	private boolean usedDamage;
	private boolean usedSize;
	private boolean usedNBT;

	private IItemStackTester tester = null;

	private void compose(IItemStackTester newTerm) {
		if (tester == null) {
			tester = newTerm;
		} else {
			final IItemStackTester current = tester;
			tester = (left, right) -> newTerm.isEqual(left, right) && current.isEqual(left, right);
		}
	}

	public StackEqualityTesterBuilder useItem() {
		Preconditions.checkState(!usedItem);
		usedItem = true;
		compose(EqualComponents.ITEM_TESTER);
		return this;
	}

	public StackEqualityTesterBuilder useItemId() {
		Preconditions.checkState(!usedItemId);
		usedItemId = true;
		compose(EqualComponents.ITEM_ID_TESTER);
		return this;
	}

	public StackEqualityTesterBuilder useDamage() {
		Preconditions.checkState(!usedDamage);
		usedDamage = true;
		compose(EqualComponents.DAMAGE_TESTER);
		return this;
	}

	public StackEqualityTesterBuilder useSize() {
		Preconditions.checkState(!usedSize);
		usedSize = true;
		compose(EqualComponents.SIZE_TESTER);
		return this;
	}

	public StackEqualityTesterBuilder useNBT() {
		Preconditions.checkState(!usedNBT);
		usedNBT = true;
		compose(EqualComponents.NBT_TESTER);
		return this;
	}

	public IEqualityTester build() {
		final IItemStackTester tester = this.tester != null? this.tester : (left, right) -> true;

		return (left, right) -> {
			if (left == right) return true;
			if ((left instanceof ItemStack) && (right instanceof ItemStack)) { return tester.isEqual((ItemStack)left, (ItemStack)right); }
			return false;
		};
	}

	public Predicate<ItemStack> buildPredicate(ItemStack template) {
		final ItemStack copy = template.copy();
		final IEqualityTester tester = build();
		return input -> tester.isEqual(copy, input);
	}

}


text: 1 Use BFS & DFS to search a subView of specified ClassName from superView


text:
<?php

namespace mirocow\eav\interfaces;

interface HanlerInterface {

    public function getValueModel();

    public function load();

    public function save();

    public function getTextValue();

}


text:
<?php

namespace ZendTest\Barcode\Object\TestAsset;

/**
 * @category   Zend
 * @package    Zend_Barcode
 * @subpackage UnitTests
 * @group      Zend_Barcode
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class BarcodeTest extends \Zend\Barcode\Object\AbstractObject
{

    protected function calculateBarcodeWidth()
    {
        return 1;
    }

    public function validateText($value)
    {}

    protected function prepareBarcode()
    {
        return array();
    }

    protected function checkSpecificParams()
    {}

    public function addTestInstruction(array $instruction)
    {
        $this->addInstruction($instruction);
    }

    public function addTestPolygon(array $points, $color = null, $filled = true)
    {
        $this->addPolygon($points, $color, $filled);
    }

    public function addTestText($text, $size, $position, $font, $color, $alignment = 'center', $orientation = 0)
    {
        $this->addText($text, $size, $position, $font, $color, $alignment, $orientation);
    }
}


text:
(function() {
    var IntersectionsData = function(data) {
        var _this = this;
        this.data = data;
        this.listeners = [];
        var idmap = {};
        for (var i=0; i<this.data.length; i++) {
            idmap[this.data[i]['id']] = i;
            if (!this.data[i].hasOwnProperty('reports')) {
                this.data[i]['reports'] = [];
            }
        }

        this.get = function(intersection_id) {
            if (this.data.hasOwnProperty(idmap[intersection_id])) {
                return this.data[idmap[intersection_id]];
            } else {
                return null;
            }
        };

        this.getLat = function(intersection_id) {
            return this.get(intersection_id)['loc']['coordinates'][1];
        };

        this.getLon = function(intersection_id) {
            return this.get(intersection_id)['loc']['coordinates'][0];
        };

        this.each = function(callback) {
            for (var i=0; i<this.data.length; i++) {
                callback(this.data[i]);
            }
        };

        this.update = function(intersection_id, update) {
            var intersection = _this.get(intersection_id);
            if (intersection != null && update != null) {
                for (var i=0; i<update['reports'].length; i++) {
                    intersection['reports'].push(update['reports'][i]);
                }
                _this._dispatchUpdate(intersection_id);
            }
        };

        this.addUpdateListener = function(f) {
            this.listeners.push(f);
        };

        this._dispatchUpdate = function(intersection_id) {
            for (var i=0; i<this.listeners.length; i++) {
                this.listeners[i](intersection_id);
            }
        };

        this.size = function() {
             return this.data.length;
        };
    };

    if (typeof exports !== 'undefined') {
        module.exports = IntersectionsData;
    } else {
        window.IntersectionsData = IntersectionsData;
    }
})();


text:
class CreateCustomFieldCcHandling < ActiveRecord::Migration
  def self.up
    c = CustomField.new(
      :name => 'cc-handling',
      :editable => true,
      :visible => true,
      :field_format => 'bool')
    c.type = 'ProjectCustomField' # cannot be set by mass assignement!
    c.save
  end

  def self.down
    CustomField.find_by_name('cc-handling').delete
  end
end


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wts.roms.model;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeSupport;
import java.util.*;
import java.util.logging.Logger;

/**
 *
 * @author William.Stockhausen
 */
public class OptionalModelVariablesInfo extends AbstractVariablesInfo {

    /** */
    private static final Logger logger = Logger.getLogger(OptionalModelVariablesInfo.class.getName());

    /** version */
    public static final String version = "1.0";

    /** the singleton instance */
    private static OptionalModelVariablesInfo instance = null;

    /**
     * Static method (creates and) returns the singleton instance of this class.
     *
     * @return - the singleton
     */
    public static OptionalModelVariablesInfo getInstance(){
        if (instance==null) instance = new OptionalModelVariablesInfo();
        return instance;
    }

    private OptionalModelVariablesInfo(){
        super(20);
        propertySupport = new PropertyChangeSupport(this);
    }

    @Override
    public void addVariable(String name,String desc){
        OptionalVariableInfo ovi = new OptionalVariableInfo(name,desc);
        ovi.setNameInROMSDataset(name);//set as default
        ovi.addPropertyChangeListener(this);
        mapAVI.put(name,ovi);
        propertySupport.firePropertyChange(PROP_VARIABLE_ADDED,null,ovi);
    }

    @Override
    public OptionalVariableInfo removeVariable(String name){
        logger.info("Removing ovi "+name);
        return (OptionalVariableInfo) super.removeVariable(name);
    }

    /**
     * Returns the variable information associated with a variable name.
     *
     * @param name = the variable's name
     * @return -
     */
    @Override
    public OptionalVariableInfo getVariableInfo(String name){
        return (OptionalVariableInfo) super.getVariableInfo(name);
    }

    /**
     * Read in stored properties.
     * TODO: probably don't want to do this-->write to a file in the WorkingDirectory.
     *
     * @param p
     */
    @Override
    public void readProperties(Properties p){
        logger.info("reading properties");
        String clazz = this.getClass().getName();
        String version = p.getProperty(clazz+"_version");
        if ((version!=null)&&(version.equals("1.0"))){
            int n = Integer.parseInt(p.getProperty(clazz+"_"+"vars","0"));
            System.out.println("Reading n = "+n);
            for (int i=0;i<n;i++){
                String str = clazz+"_var"+i+".";
                boolean checked = Boolean.parseBoolean(p.getProperty(str+AbstractVariableInfo.PROP_Checked));
                String romsName = p.getProperty(str+AbstractVariableInfo.PROP_NameInROMS);
                String varName  = p.getProperty(str+AbstractVariableInfo.PROP_Name);
                boolean isField   = Boolean.parseBoolean(p.getProperty(str+AbstractVariableInfo.PROP_Field));
                String maskType = p.getProperty(str+AbstractVariableInfo.PROP_MaskType);
                String descr    = p.getProperty(str+AbstractVariableInfo.PROP_Description);
                logger.info("Creating VI "+varName+"; rn = "+romsName+"; mt = "+maskType+"; de = "+descr);
                OptionalVariableInfo ovi = new OptionalVariableInfo(varName, descr);
                ovi.setChecked(checked);
                ovi.setNameInROMSDataset(romsName);
                ovi.setSpatialField(isField);
                ovi.setMaskType(maskType);
                mapAVI.put(varName, ovi);
            }
        }
    }

    /**
     * Writes property values.
     *
     * @param p
     */
    @Override
    public void writeProperties(Properties p){
        logger.info("Writing properties");
        String clazz = this.getClass().getName();
        p.put(clazz+"_version", "1.0");
        Set<String> names = mapAVI.keySet();
        logger.info("Writing "+names.size()+" VIs to properties");
        writeProperties(p, this.getClass(), version);
        logger.info("Done writing properties");
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(OptionalVariableInfo.PROP_Name)){
            //variable name has changed, so need to remove associated vi under the
            //old name and "refile" it under the new name.
            String old = (String) evt.getOldValue();
            AbstractVariableInfo ovi = mapAVI.remove(old);//remove under old name
            mapAVI.put(ovi.getName(),ovi);                //put under new name
            propertySupport.firePropertyChange(PROP_VARIABLE_RENAMED,old,ovi.getName());//propagate event up chain
        }
    }
}


text:
a = range(1,11,2) # returns a list
b = xrange(1,11,2) # creates an xrange object (not a list) << better for long number genration

for i in a:
	print(i)

print("Now with xrange:")
for i in xrange(1,11,2):
	print(i)


text:
<!DOCTYPE html>

  <title>😎 @aberigle - Alejandro Berzosa Iglesias</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="author" content="@aberigle">
  <meta property="og:title" content="Alejandro Berzosa">
  <meta property="og:url" content="http://aberigle.com">
  <meta property="og:image" content="https://avatars3.githubusercontent.com/u/3426238">
  <meta property="twitter:creator" content="@aberigle">
  <meta property="twitter:site" content="http://aberigle.com">
  <meta property="twitter:card" content="summary">
  <meta http-equiv="Content-Language" content="es">
  <meta name="revisit-after" content="1 days">
  <meta name="distribution" content="global">
  <link rel="stylesheet" href="/dependencies/tuktuk/tuktuk.css">
  <link rel="stylesheet" href="/dependencies/tuktuk/tuktuk.icons.css">
  <link rel="stylesheet" href="/static/css/app.css">

made with byuhurus


text:
layout: post
title: Nails This Week - Silver Lining
date: 2013-01-07
permalink: /nails-this-week-silver-lining/
---

Hey everyone! Did you all have a fabulous New Year's? Did you rock some awesome party nails? ;)

Well the holiday season is OFFICIALLY over (unless you're a retailer and already stocking up on Valentine's Day supplies :P ), so we're going back to regular manicures this week.

Since we've had some relatively complicated nail tutorials the last few times, I thought I'd keep things simple. Today, I have your basic French tips that are also accented with a silver tape lining.

![](/images/Nails This Week/silverlining.JPG)

And remember, if you want a quick and easy way to do French tips, check out the tutorial I did [here](/tutorial-rubber-band-french-tips/).

Enjoy everybody! See you next time! <3

**Nail polish used:**

- Sinful Colors Professional in "Snow Me White" (#101)


text:
#include <encode/encode.hpp>
#include <nparse/nparse.hpp>
#include <anta/sas/regex.hpp>
#include "_priority.hpp"
#include "static.hpp"

namespace {

using namespace nparse;

namespace rx = boost;
typedef rx::basic_regex<anta::character<NLG>::type> regex_type;
typedef rx::match_results<anta::iterator<NLG>::type> match_results_type;
typedef rx::sub_match<anta::iterator<NLG>::type> sub_match_type;

class Acceptor: public IAcceptor, public anta::Acceptor<NLG>
{
public:
	Acceptor (const string_t& a_pattern):
		m_regex (a_pattern, boost::regex_constants::save_subexpression_location)
	{
		const regex_type::size_type
#if BOOST_VERSION >= 105600
		i0 = 0, di = 1;
#else
		i0 = 1, di = 0;
#endif
		for (regex_type::size_type i = i0; i < m_regex. mark_count(); ++ i)
		{
			// NOTE: According to boost::regex documentation, marked groups have
			//		 the following syntax
			//		 (?<name>...)  OR  (?'name'...)
			//		 The iterator range returned by regex::subexpression(i) does
			//		 not include the closing parethesis, therefore the shortest
			//		 possible marked group definition '(?<x>' must contain at
			//		 least five characters.
			std::pair<
				regex_type::const_iterator,
				regex_type::const_iterator> p = m_regex.subexpression(i);
			if (std::distance(p. first, p. second) < 5)
			{
				continue;
			}
			std::advance(p. first, 3);
			switch (*(p. first - 1))
			{
			case L'<':
				p. second = std::find(p. first, p. second, L'>');
				break;
			case L'\'':
				p. second = std::find(p. first, p. second, *(p. first - 1));
				break;
			default:
				continue;
			}
			const IEnvironment::key_type key(string_t(p. first, p. second));
			m_named_groups. push_back(named_groups_t::value_type(key, i + di));
		}
	}

public:
	// Overridden from IAcceptor:
	const anta::Acceptor<NLG>& get () const
	{
		return *this;
	}

	// Overridden from Acceptor<NLG>:
	void accept (const anta::range<NLG>::type& C,
			const anta::range<NLG>::type& E, anta::spectrum<NLG>::type& S) const
	{
		match_results_type m;
		if (! rx::regex_search(E. second, C. second, m, m_regex,
					rx::match_continuous))
		{
			return;
		}
		else if (m. empty())
		{
			S. push(m[0]. first, m[0]. second);
		}
		else
		{
			anta::State<NLG>* state = S. spawn(m[0]. first, m[0]. second);
			if (state != NULL)
			{
				for (named_groups_t::const_iterator g = m_named_groups. begin();
						g != m_named_groups. end(); ++ g)
				{
					const sub_match_type& sub = m[g -> second];
					state -> ref(g -> first, S, true) = IEnvironment::value_type(
							sub. first, sub. second);
				}
				S. push(state);
			}
		}
	}

private:
	regex_type m_regex;

	typedef std::vector<std::pair<IEnvironment::key_type, regex_type::size_type
		> > named_groups_t;
	named_groups_t m_named_groups;

};

class AcceptorFactory: public IAcceptorFactory
{
public:
	// Overridden from IPrioritized:
	int priority () const
	{
		return PRIORITY_REGEX;
	}

	// Overridden from IAcceptorFactory:
	bool create (const string_t& a_definition, const IAcceptor*& a_instance,
			const std::string&/* a_path*/)
	{
		if (a_definition. size() > 1 && *a_definition. begin() == '^')
		{
			a_instance = new Acceptor(a_definition);
			return true;
		}
		else if (a_definition. size() > 3 && *a_definition. begin() == '/' &&
				*a_definition. rbegin() == '/')
		{
			a_instance = new Acceptor(
					a_definition. substr(1, a_definition. size() - 2));
			return true;
		}
		else
		{
			return false;
		}
	}

};

} // namespace

PLUGIN(AcceptorFactory, acceptor_regex, nparse.acceptors.RegEx)


text:
class PrefService;
class TestingBrowserProcess;
class TokenService;

namespace net {
class URLRequestContextGetter;
}

namespace policy {

class CloudPolicySubsystem;
class ConfigurationPolicyProvider;
class DevicePolicyIdentityStrategy;

// Manages the lifecycle of browser-global policy infrastructure, such as the
// platform policy providers.
class BrowserPolicyConnector {
 public:
  static BrowserPolicyConnector* Create();
  ~BrowserPolicyConnector();

  ConfigurationPolicyProvider* GetManagedPlatformProvider() const;
  ConfigurationPolicyProvider* GetManagedCloudProvider() const;
  ConfigurationPolicyProvider* GetRecommendedPlatformProvider() const;
  ConfigurationPolicyProvider* GetRecommendedCloudProvider() const;

  // Returns a weak pointer to the CloudPolicySubsystem managed by this
  // policy connector, or NULL if no such subsystem exists (i.e. when running
  // outside ChromeOS).
  CloudPolicySubsystem* cloud_policy_subsystem() {
    return cloud_policy_subsystem_.get();
  }

  // Used to set the credentials stored in the identity strategy associated
  // with this policy connector.
  void SetCredentials(const std::string& owner_email,
                      const std::string& gaia_token);

  // Returns true if this device is managed by an enterprise (as opposed to
  // a local owner).
  bool IsEnterpriseManaged();

  // Locks the device to an enterprise domain.
  EnterpriseInstallAttributes::LockResult LockDevice(const std::string& user);

  // Returns the enterprise domain if device is managed.
  std::string GetEnterpriseDomain();

  // Exposes the StopAutoRetry() method of the CloudPolicySubsystem managed
  // by this connector, which can be used to disable automatic
  // retrying behavior.
  void StopAutoRetry();

  // Initiates a policy fetch after a successful device registration.
  void FetchPolicy();

 private:
  friend class ::TestingBrowserProcess;

  BrowserPolicyConnector();

  static ConfigurationPolicyProvider* CreateManagedPlatformProvider();
  static ConfigurationPolicyProvider* CreateRecommendedPlatformProvider();

  // Constructor for tests that allows tests to use fake platform policy
  // providers instead of using the actual ones.
  BrowserPolicyConnector(
      ConfigurationPolicyProvider* managed_platform_provider,
      ConfigurationPolicyProvider* recommended_platform_provider);

  // Activates the cloud policy subsystem.
  void Initialize();

  scoped_ptr<ConfigurationPolicyProvider> managed_platform_provider_;
  scoped_ptr<ConfigurationPolicyProvider> recommended_platform_provider_;

#if defined(OS_CHROMEOS)
  scoped_ptr<DevicePolicyIdentityStrategy> identity_strategy_;
  scoped_ptr<EnterpriseInstallAttributes> install_attributes_;
#endif
  scoped_ptr<CloudPolicySubsystem> cloud_policy_subsystem_;

  ScopedRunnableMethodFactory<BrowserPolicyConnector> method_factory_;

  DISALLOW_COPY_AND_ASSIGN(BrowserPolicyConnector);
};

}  // namespace policy

#endif  // CHROME_BROWSER_POLICY_BROWSER_POLICY_CONNECTOR_H_


text:
Rate Limit
===
[![NPM version][npm-image]][npm-url] [![Build Status][build-image]][build-url] [![Coverage Status][coverage-image]][coverage-url] [![Dependencies][dependencies-image]][dependencies-url]

> Get a user's [rate limit][github-rate-limit] status.

## Installation

``` bash
$ npm install github-user-rate-limit
```

## Usage

``` javascript
var ratelimit = require( 'github-user-rate-limit' );
```

#### ratelimit( opts, clbk )

Gets a user's [rate limit][github-rate-limit] status.

``` javascript
var opts = {
	'token': 'tkjorjk34ek3nj4!'
};

ratelimit( opts, clbk );

function clbk( error, status ) {
	if ( error ) {
		throw new Error( error.message );
	}
	console.dir( status );
	/*
		{
			"core": {
				"limit": 5000,
				"remaining": 4999,
				"reset": 1372700873 // UTC seconds
			},
			"search": {
				"limit": 30,
				"remaining": 18,
				"reset": 1372697452 // UTC seconds
			}
		}
	*/
}
```

The `function` accepts the following `options`:
*	__token__: Github [access token][github-token] (*required*).
*	__useragent__: [user agent][github-user-agent] `string`.

To [authenticate][github-oauth2] with Github, set the [`token`][github-token] option.

``` javascript
var opts = {
	'token': 'tkjorjk34ek3nj4!'
};

ratelimit( opts, clbk );
```

To specify a [user agent][github-user-agent], set the `useragent` option.

``` javascript
var opts = {
	'token': 'tkjorjk34ek3nj4!',
	'useragent': 'hello-github!'
};

ratelimit( opts, clbk );
```

#### ratelimit.factory( options, clbk )

Creates a reusable `function`.

``` javascript
var opts = {
	'token': 'tkjorjk34ek3nj4!',
	'useragent': 'hello-github!'
};

var get = ratelimit.factory( opts, clbk );

get();
get();
get();
// ...
```

The factory method accepts the same `options` as [`ratelimit()`](#ratelimit).

---
## Examples

``` javascript
var ratelimit = require( 'github-user-rate-limit' );

var opts = {
	'token': 'tkjorjk34ek3nj4!',
	'useragent': 'beep-boop-bop'
};

ratelimit( opts, clbk );

function clbk( error, status ) {
	if ( error ) {
		throw new Error( error.message );
	}
	console.dir( status );
}
```

To run the example code from the top-level application directory,

``` bash
$ node ./examples/index.js
```

__Note__: in order to run the example, you will need to obtain an access [token][github-token] and modify the `token` option accordingly.

---
## CLI

### Installation

To use the module as a general utility, install the module globally

``` bash
$ npm install -g github-user-rate-limit
```

### Usage

``` bash
Usage: ghratelimit [options]

Options:

  -h,  --help               Print this message.
  -V,  --version            Print the package version.
       --token token        Github access token.
  -ua, --useragent ua       User agent.
       --pretty             Pretty format.
```

### Notes

*	In addition to the [`token`][github-token] option, the [token][github-token] may also be specified by a [`GITHUB_TOKEN`][github-token] environment variable. The command-line option __always__ takes precedence.
*	[Rate limit][github-rate-limit] information is written to `stdout`.

### Examples

Setting the access [token][github-token] using the command-line option:

``` bash
$ DEBUG=* ghratelimit --token <token>
# => {"core":{...},"search":{...}}
```

Setting the access [token][github-token] using an environment variable:

``` bash
$ DEBUG=* GITHUB_TOKEN=<token> ghratelimit
# => {"core":{...},"search":{...}}
```

For local installations, modify the command to point to the local installation directory; e.g.,

``` bash
$ DEBUG=* ./node_modules/.bin/ghratelimit --token <token>
# => {"core":{...},"search":{...}}
```

Or, if you have cloned this repository and run `npm install`, modify the command to point to the executable; e.g.,

``` bash
$ DEBUG=* node ./bin/cli --token <token>
# => {"core":{...},"search":{...}}
```

To pretty format the [rate limit][github-rate-limit] status, set the `pretty` option.

``` bash
$ DEBUG=* ghratelimit --token <token> --pretty
#
# core
#   limit: 5000
#   remaining: 4999
#   reset: 2016-02-12T02:11:34.000Z
#
# search
#   limit: 30
#   remaining: 30
#   reset: 2016-02-12T01:25:28.000Z
#
```

---
## Tests

### Unit

This repository uses [tape][tape] for unit tests. To run the tests, execute the following command in the top-level application directory:

``` bash
$ make test
```

All new feature development should have corresponding unit tests to validate correct functionality.

### Test Coverage

This repository uses [Istanbul][istanbul] as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:

``` bash
$ make test-cov
```

Istanbul creates a `./reports/coverage` directory. To access an HTML version of the report,

``` bash
$ make view-cov
```

### Browser Support

This repository uses [Testling][testling] for browser testing. To run the tests in a (headless) local web browser, execute the following command in the top-level application directory:

``` bash
$ make test-browsers
```

To view the tests in a local web browser,

``` bash
$ make view-browser-tests
```

---
## License

[MIT license](http://opensource.org/licenses/MIT).

## Copyright

Copyright © 2016. Athan Reines.

[npm-image]: http://img.shields.io/npm/v/github-user-rate-limit.svg
[npm-url]: https://npmjs.org/package/github-user-rate-limit

[build-image]: http://img.shields.io/travis/kgryte/github-user-rate-limit/master.svg
[build-url]: https://travis-ci.org/kgryte/github-user-rate-limit

[coverage-image]: https://img.shields.io/codecov/c/github/kgryte/github-user-rate-limit/master.svg
[coverage-url]: https://codecov.io/github/kgryte/github-user-rate-limit?branch=master

[dependencies-image]: http://img.shields.io/david/kgryte/github-user-rate-limit.svg
[dependencies-url]: https://david-dm.org/kgryte/github-user-rate-limit

[dev-dependencies-image]: http://img.shields.io/david/dev/kgryte/github-user-rate-limit.svg
[dev-dependencies-url]: https://david-dm.org/dev/kgryte/github-user-rate-limit

[github-issues-image]: http://img.shields.io/github/issues/kgryte/github-user-rate-limit.svg
[github-issues-url]: https://github.com/kgryte/github-user-rate-limit/issues

[tape]: https://github.com/substack/tape
[istanbul]: https://github.com/gotwarlost/istanbul
[testling]: https://ci.testling.com

[unix-time]: http://en.wikipedia.org/wiki/Unix_time

[github-get]: https://github.com/kgryte/github-get
[github-api]: https://developer.github.com/v3/
[github-token]: https://github.com/settings/tokens/new
[github-oauth2]: https://developer.github.com/v3/#oauth2-token-sent-in-a-header
[github-user-agent]: https://developer.github.com/v3/#user-agent-required
[github-rate-limit]: https://developer.github.com/v3/rate_limit/


text:
use strict;
use lib "../../../lib";
use utf8;

use Data::Uniqid qw(uniqid);

use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201809::AdGroup;
use Google::Ads::AdWords::v201809::AdGroupAd;
use Google::Ads::AdWords::v201809::AdGroupAdOperation;
use Google::Ads::AdWords::v201809::AdGroupCriterionOperation;
use Google::Ads::AdWords::v201809::AdGroupOperation;
use Google::Ads::AdWords::v201809::BiddableAdGroupCriterion;
use Google::Ads::AdWords::v201809::BiddingStrategyConfiguration;
use Google::Ads::AdWords::v201809::Budget;
use Google::Ads::AdWords::v201809::Campaign;
use Google::Ads::AdWords::v201809::CampaignOperation;
use Google::Ads::AdWords::v201809::CpcBid;
use Google::Ads::AdWords::v201809::ProductAd;
use Google::Ads::AdWords::v201809::ProductPartition;
use Google::Ads::AdWords::v201809::ShoppingSetting;

use Cwd qw(abs_path);

# Replace with valid values of your account.
my $budget_id   = "INSERT_BUDGET_ID_HERE";
my $merchant_id = "INSERT_MERCHANT_CENTER_ID_HERE";
# If set to true (1), a default partition will be created. If running the
# add_product_partition_tree.pl example right after this example,
# make sure this stays set to false (0).
my $create_default_partition = 0;

# Example main subroutine.
sub add_shopping_campaign {
  my ($client, $budget_id, $merchant_id, $create_default_partition) = @_;

  my $campaign = Google::Ads::AdWords::v201809::Campaign->new({
      name => "Shopping campaign #" . uniqid(),
      # The advertisingChannelType is what makes this a Shopping campaign
      advertisingChannelType => "SHOPPING",
      # Recommendation: Set the campaign to PAUSED when creating it to stop
      # the ads from immediately serving. Set to ENABLED once you've added
      # targeting and the ads are ready to serve.
      status => "PAUSED",
      # Set budget (required)
      budget =>
        Google::Ads::AdWords::v201809::Budget->new({budgetId => $budget_id}),
      # Set bidding strategy (required)
      biddingStrategyConfiguration =>
        Google::Ads::AdWords::v201809::BiddingStrategyConfiguration->new(
        {biddingStrategyType => "MANUAL_CPC"}
        ),
      # Set shopping setting (required)
      settings => [
        # All Shopping campaigns need a ShoppingSetting
        Google::Ads::AdWords::v201809::ShoppingSetting->new({
            salesCountry     => "US",
            campaignPriority => 0,
            merchantId       => $merchant_id,
            # By setting enableLocal to true (1) below, you will enable Local
            # Inventory Ads in your campaign. Set this to false (0) if you want
            # to disable this feature in your campaign.
            enableLocal => 1
          })]});

  # Create operation
  my $operation = Google::Ads::AdWords::v201809::CampaignOperation->new({
    operand  => $campaign,
    operator => "ADD"
  });

  # Make the mutate request
  my $result = $client->CampaignService()->mutate({operations => [$operation]});

  # Display result
  $campaign = $result->get_value()->[0];
  printf "Campaign name '%s' and ID %d was added.\n",
    $campaign->get_name(),
    $campaign->get_id();

  # Create ad group
  my $ad_group = Google::Ads::AdWords::v201809::AdGroup->new({
      campaignId => $campaign->get_id(),
      name       => "Ad Group #" . uniqid()});

  # Create operation
  $operation = Google::Ads::AdWords::v201809::AdGroupOperation->new({
    operand  => $ad_group,
    operator => "ADD"
  });

  # Make the mutate request
  $result = $client->AdGroupService()->mutate({operations => [$operation]});

  # Display result
  $ad_group = $result->get_value()->[0];
  printf "Ad group with name '%s' and ID %d was added.\n",
    $ad_group->get_name(),
    $ad_group->get_id();

  # Create product ad
  my $product_ad = Google::Ads::AdWords::v201809::ProductAd->new();

  # Create ad group ad
  my $ad_group_ad = Google::Ads::AdWords::v201809::AdGroupAd->new({
    adGroupId => $ad_group->get_id(),
    ad        => $product_ad
  });

  # Create operation
  $operation = Google::Ads::AdWords::v201809::AdGroupAdOperation->new({
    operand  => $ad_group_ad,
    operator => "ADD"
  });

  # Make the mutate request
  $result = $client->AdGroupAdService()->mutate({operations => [$operation]});

  # Display result
  $ad_group_ad = $result->get_value()->[0];
  printf "Product ad with ID %d was added.\n", $ad_group_ad->get_ad()->get_id();

  if ($create_default_partition) {
    # Create an ad group criterion for 'All products'.
    my $product_partition =
      Google::Ads::AdWords::v201809::ProductPartition->new({
        partitionType => 'UNIT',
        # Make sure the caseValue is null and the parentCriterionId is null.
        caseValue         => undef,
        parentCriterionId => undef
      });

    my $ad_group_criterion =
      Google::Ads::AdWords::v201809::BiddableAdGroupCriterion->new({
        adGroupId => $ad_group->get_id(),
        criterion => $product_partition,
        biddingStrategyConfiguration =>
          Google::Ads::AdWords::v201809::BiddingStrategyConfiguration->new({
            bids => [
              Google::Ads::AdWords::v201809::CpcBid->new({
                  bid => Google::Ads::AdWords::v201809::Money->new(
                    {microAmount => 500000})}
              ),
            ]})});

    # Create operation.
    $operation = Google::Ads::AdWords::v201809::AdGroupCriterionOperation->new({
      operator => "ADD",
      operand  => $ad_group_criterion
    });

    # Make the mutate request
    $result =
      $client->AdGroupCriterionService()->mutate({operations => [$operation]});

    # Display result
    $ad_group_criterion = $result->get_value()->[0];
    printf "Ad group criterion with ID %d in ad group with ID %d was added.\n",
      $ad_group_criterion->get_criterion()->get_id(),
      $ad_group_criterion->get_adGroupId();
  }

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();

# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201809"});

# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);

# Call the example
add_shopping_campaign($client, $budget_id, $merchant_id,
  $create_default_partition);


text:
template< typename T >
class DeviceArray1D
{
public:

    DeviceArray1D() = default;
    DeviceArray1D( size_t length );
    DeviceArray1D( const DeviceArray1D< T >& copy );
    DeviceArray1D( DeviceArray1D< T >&& move );
    DeviceArray1D< T >& operator = ( const DeviceArray1D< T >& copy );
    DeviceArray1D< T >& operator = ( DeviceArray1D< T >&& move );
    ~DeviceArray1D();

    bool isNull() const;
    bool notNull() const;

    // The number of elements in this DeviceArray1D.
    size_t length() const;

    // The number of elements in this DeviceArray1D, equivalent to length().
    size_t size() const;

    // The number of elements in this DeviceArray1D, equivalent to length().
    size_t numElements() const;

    // The number of bytes allocated for this DeviceArray1D.
    size_t sizeInBytes() const;

    // This only works if T is a CUDA builtin type such as char, int2, or
    // float4 and packed().
    // TODO: consider using std::enable_if or thrust::enable_if.
    cudaResourceDesc resourceDesc() const;

    // Resize this array, destroying its contents.
    // size.x and size.y must be positive.
    cudaError resize( size_t length );

    // Sets this array to 0 (all bytes to 0).
    cudaError clear();

    // Fills this array with the given value.
    void fill( const T& value );

    // Get an element of the array from the device, returning the value and
    // its status in err.
    // WARNING: probably slow as it incurs a cudaMemcpy.
    T get( int x, cudaError& err ) const;

    // Get an element of the array from the device, without a status code.
    // WARNING: this operation is probably slow as it incurs a cudaMemcpy.
    T operator [] ( int x ) const;

    // Sets an element of the array from the host.
    // WARNING: this operation is probably slow as it incurs a cudaMemcpy.
    cudaError set( int x, const T& value );

    const T* pointer() const;
    T* pointer();

    const T* elementPointer( size_t x ) const;
    T* elementPointer( size_t x );

    KernelArray1D< const T > readView() const;
    KernelArray1D< T > writeView();

private:

    size_t m_length = 0;
    uint8_t* m_devicePointer = nullptr;

    cudaError destroy();
};

// Copy data from src.length() to dst[ dstOffset : dstOffset + src.length() ).
// Assumes:
// - src.packed()
// - dst.notNull()
// - src.length() - dstOffset >= dst.length()
// TODO: once we have Array1DWriteView on device pointers, can get rid of
// dstOffset.
template< typename T >
cudaError copy( Array1DReadView< T > src, DeviceArray1D< T >& dst,
    size_t dstOffset = 0 );

// Copy data from src to dst.
// Assumes:
// - dst.packed()
// - src.notNull()
// src and dst must have the same size.
template< typename T >
cudaError copy( const DeviceArray1D< T >& src, Array1DWriteView< T > dst );

// Copy data from src[ srcOffset : dst.length() ) to dst.
// Assumes:
// - dst.packed()
// - src.notNull()
// - src.length() - srcOffset >= dst.length().
// TODO: once we have Array1DReadView on device pointers, can get rid of
// srcOffset.
template< typename T >
cudaError copy( const DeviceArray1D< T >& src, size_t srcOffset,
    Array1DWriteView< T > dst );

// Copy data from src to dst.
// src and dst must have the same size.
template< typename T >
cudaError copy( const DeviceArray1D< T >& src, DeviceArray1D< T >& dst );

#include "DeviceArray1D.inl"


text:
Prior to setting up a controller with Fermentrack, please read the documentation specific to your controller's hardware. Supported hardware families include:

* [Arduino (and compatible)](../hardware/Arduino.md)
* [ESP8266](../hardware/ESP8266.md)
* [Spark Core](../hardware/Spark.md)
* [Native Python (Fuscus)](../hardware/Native Python.md)

Controllers can be se up to connect via both WiFi and serial. When setting up a controller to connect via serial the selected "port" is incredibly important but is prone to change on reboot or as other devices are connected. Please read the "About Serial Port Autodetection" note below for information on how Fermentrack handles this issue.

## Setting up a controller using Advanced Workflow

1. Connect the controller to the Raspberry Pi
2. Launch guided setup and select "Add New Device (Advanced)"
3. Enter the configuration options associated with the device.

## About Serial Port Autodetection

By default, Linux assigns serial ports to devices like BrewPi controllers based on the order they are connected. If you have multiple devices connected to your Raspberry Pi this can mean that Fermentrack could potentially mistake one device for another. To prevent this, Fermentrack includes a feature which will disregard the specified serial port when connecting to the controller and will instead connect to the device with the USB serial number that matches the device you set up.

If you wish to disable this feature and instead only connect to the specified serial port, uncheck the "Prefer Connecting Via Udev" option in the "Manage Device" screen.

This feature only works on Linux-based operating systems (including Raspbian for Raspberry Pi), and may not work if Fermentrack is installed on a Mac or Windows-based computer.


text:
$Dependencies = "PyYAML XlsxWriter artifacts bencode certifi cffi chardet cryptography dateutil defusedxml dfdatetime dfvfs dfwinreg dtfabric elasticsearch-py fakeredis future idna libbde libcreg libesedb libevt libevtx libewf libfsapfs libfsext libfshfs libfsntfs libfsxfs libfvde libfwnt libfwsi liblnk libluksde libmodi libmsiecf libolecf libqcow libregf libscca libsigscan libsmdev libsmraw libvhdi libvmdk libvsgpt libvshadow libvslvm lz4 mock pbr pefile psutil pyparsing pytsk3 pytz pyzmq redis requests six sortedcontainers urllib3 yara-python"
$Dependencies = ${Dependencies} -split " "

$Output = Invoke-Expression -Command "git clone https://github.com/log2timeline/l2tdevtools.git ..\l2tdevtools 2>&1"
Write-Host (${Output} | Out-String)

If ($env:APPVEYOR_REPO_BRANCH -eq "main")
{
	$Track = "stable"
}
Else
{
	$Track = $env:APPVEYOR_REPO_BRANCH
}
New-Item -ItemType "directory" -Name "dependencies"

$env:PYTHONPATH = "..\l2tdevtools"

$Output = Invoke-Expression -Command "& '${env:PYTHON}\python.exe' ..\l2tdevtools\tools\update.py --download-directory dependencies --machine-type ${env:MACHINE_TYPE} --msi-targetdir ${env:PYTHON} --track ${env:L2TBINARIES_TRACK} ${Dependencies} 2>&1"
Write-Host (${Output} | Out-String)


text:
package it.frech.jhealth.gc;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;

public class GCEventThread extends Thread {

	private static final String DOMAIN_START_SIGN = "$";

	private static final String DOMAIN_REGEX = "\\" + DOMAIN_START_SIGN + "(.+?)\\{(.+?\\}{0,})(\\})*\\}";

	private static final String DOMAIN_TIME = "TIME";
	private static final String DOMAIN_SYSPROP = "SYSPROP";
	private static final String DOMAIN_JHEALTH_YOUNG_GC = "jhealth:type=YoungGC";
	private static final String DOMAIN_JHEALTH_TENURED_GC = "jhealth:type=TenuredGC";

	private static final String SUB_DOMAIN_TIMEZONE = "TIMEZONE";

	private static final String VALUE_NOT_AVAILABLE = "[n/a]";

	private Deque<AtomicLong> youngGcCounter = new ConcurrentLinkedDeque<AtomicLong>();
	private Deque<AtomicLong> tenuredGcCounter = new ConcurrentLinkedDeque<AtomicLong>();

	private long initialDelay;
	private boolean running = true;
	private String path;
	private long lastException;
	private String format;

	public GCEventThread(long initialDelay, String path, String format) {
		super("JHealthAgent - GC Event Thread");
		this.initialDelay = initialDelay;
		this.path = path;
		this.format = format;

		for (int i = 0; i < 10; i++) {
			youngGcCounter.add(new AtomicLong(0));
			tenuredGcCounter.add(new AtomicLong(0));
		}
	}

	@Override
	public void run() {

		// touch the output file
		if (path != null) {
			try {
				FileWriter fileWriter = new FileWriter(path, true);
				fileWriter.close();
			} catch (IOException e) {
				logException(e);
			}
		}

		// wait to make sure early construction of the MBean server does not
		// interfere with other software
		try {
			Thread.sleep(initialDelay);
		} catch (InterruptedException e) {
		}

		// loop through all garbage collectors and register to their event
		MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
		List<GarbageCollectorMXBean> gcMxBeans = ManagementFactory.getGarbageCollectorMXBeans();

		for (GarbageCollectorMXBean gcMxBean : gcMxBeans) {
			String gcName = gcMxBean.getName();
			GarbageCollector gc = GarbageCollector.getByName(gcName);
			if (gc == null) {
				System.err.println("Garbage Collector '" + gcName + "' unknown so far, ignoring it!");
				continue;
			}

			// register the code to increase the counter on the MBean
			ObjectName objectName = gcMxBean.getObjectName();
			NotificationListener listener = new GCEventListener();
			Deque<AtomicLong> counterList = gc.isOld() ? tenuredGcCounter : youngGcCounter;
			try {
				mBeanServer.addNotificationListener(objectName, listener, null, counterList);
			} catch (InstanceNotFoundException e) {
				e.printStackTrace(System.err);
			}
		}

		// from now on remove the last counter at the end and add a new one at the front
		while (running) {
			try {
				Thread.sleep(60 * 1000);
			} catch (InterruptedException e) {
			}

			if (path != null) {
				try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(path, true)))) {
				    Matcher matcher = createDomainMatcher(this.format);
					StringBuffer sb = new StringBuffer();
					while(matcher.find()) {
						String domain = matcher.group(1);
						String attribute = matcher.group(2);
						String replacement = VALUE_NOT_AVAILABLE;
						switch (domain) {
							case DOMAIN_TIME:
								replacement = getTime(attribute);
								break;
							case DOMAIN_SYSPROP:
								replacement = System.getProperty(attribute);
								break;
							case DOMAIN_JHEALTH_YOUNG_GC:
								replacement = getJHealthDomain(youngGcCounter,attribute);
								break;
							case DOMAIN_JHEALTH_TENURED_GC:
								replacement = getJHealthDomain(tenuredGcCounter,attribute);
								break;
							default:
								// other MBean
								Object value;
								try {
									value = mBeanServer.getAttribute(new ObjectName(domain), attribute);
									replacement = value.toString();
								} catch (AttributeNotFoundException | InstanceNotFoundException
										| MalformedObjectNameException | MBeanException | ReflectionException e) {
									logException(e);
									replacement = VALUE_NOT_AVAILABLE;
								}
								break;
						}
						matcher.appendReplacement(sb,replacement);
					}
					matcher.appendTail(sb);

					out.println(sb.toString());
				} catch (IOException e) {
					logException(e);
				}
			}

			// String s = "Young ";
			// for (Iterator<AtomicLong> iter = youngGcCounter.iterator(); iter.hasNext();) {
			// s += "[" + iter.next().toString() + "]";
			// }
			// s += "\nTenured ";
			// for (Iterator<AtomicLong> iter = tenuredGcCounter.iterator(); iter.hasNext();) {
			// s += "[" + iter.next().toString() + "]";
			// }
			// System.err.println(s);

			youngGcCounter.removeLast();
			youngGcCounter.addFirst(new AtomicLong(0));
			tenuredGcCounter.removeLast();
			tenuredGcCounter.addFirst(new AtomicLong(0));
		}
	}

	private Matcher createDomainMatcher(String searchBase){
		Pattern pattern = Pattern.compile(DOMAIN_REGEX);
		return pattern.matcher(searchBase);
	}

	private String getTime(String attributeForTime){
		Matcher subDomainMatcher = createDomainMatcher(attributeForTime);
		String formattedTime = VALUE_NOT_AVAILABLE;

		try{
			SimpleDateFormat sdf = null;

			if( subDomainMatcher.find() ){
				String subDomainName = subDomainMatcher.group(1);
				String attribute = subDomainMatcher.group(2);
				if( SUB_DOMAIN_TIMEZONE.equals( subDomainName )){
				    // remove the timezone-part from the original incoming value
				    // NOTE: we intentionally invoke trim() here so that we can use blank between value and sub-domain
				    // for better readability
				    // e.g. given: $TIME{dd.MM.yyyy HH:mm:ss $TIMEZONE{Europe/Berlin}}
				    // => blank between '...:ss $TIMEZONE{...'
					attributeForTime = subDomainMatcher.replaceFirst("").trim();
					sdf = new SimpleDateFormat(attributeForTime);
					sdf.setTimeZone(TimeZone.getTimeZone(attribute));
				}
			} else {
			    sdf = new SimpleDateFormat(attributeForTime);
			}

			formattedTime = sdf.format(new Date());
		} catch( Exception e ){
			logException(e);
		}

		return formattedTime;
	}

	private String getJHealthDomain(Deque<AtomicLong> gcCounter, String attribute) {
		if (attribute.startsWith("count-")) {
			int count = Integer.parseInt(attribute.substring(6));
			long sum = 0;
			Iterator<AtomicLong> iter = gcCounter.iterator();
			for (int i = 0; i < count; i++) {
				sum += iter.next().longValue();
			}
			return Long.toString(sum);
		}
		return VALUE_NOT_AVAILABLE;

	}

	private void logException(Exception e) {
		long millis = System.currentTimeMillis();
		if (millis - lastException > 1000 * 60 * 60) { // once each hour
			lastException = millis;
			e.printStackTrace(System.err);
		}
	}

	public void stopThread() {
		running = false;
	}
}


text:
/* You can add global styles to this file, and also import other style files */

/* NOTE: CodeMirror's styles for displaying a code properly */

@import "~codemirror/lib/codemirror.css";
@import "~codemirror/theme/material.css";

/* NOTE: JsonEditor style for displaying json as tree  */
@import "~jsoneditor/dist/jsoneditor.min.css";

/* NOTE: Custom fonts */
@import "~bootstrap/dist/css/bootstrap.css";
@import "~font-awesome/css/font-awesome.css";


text:
#ifndef __ahci_mgmt_IF_H
#define __ahci_mgmt_IF_H 1

#include <flounder/flounder.h>

/*
 * Concrete type definitions
 */
typedef uint64_t ahci_mgmt_genpaddr_t;
typedef uint64_t ahci_mgmt_genvaddr_t;
typedef uint32_t ahci_mgmt_rsrcid_t;
typedef uint64_t ahci_mgmt_errval_t;
typedef uint64_t ahci_mgmt_cycles_t;
typedef uint32_t ahci_mgmt_iref_t;
typedef uint8_t ahci_mgmt_coreid_t;
typedef uint32_t ahci_mgmt_domainid_t;

/*
 * Forward declaration of binding type
 */
struct ahci_mgmt_binding;

/*
 * Contination (callback) and control function types
 */
typedef  void ahci_mgmt_bind_continuation_fn(void *st, errval_t err, struct ahci_mgmt_binding *_binding);
typedef  bool ahci_mgmt_can_send_fn(struct ahci_mgmt_binding *_binding);
typedef  errval_t ahci_mgmt_register_send_fn(struct ahci_mgmt_binding *_binding, struct waitset *ws, struct event_closure _continuation);
typedef  errval_t ahci_mgmt_change_waitset_fn(struct ahci_mgmt_binding *_binding, struct waitset *ws);
typedef  errval_t ahci_mgmt_control_fn(struct ahci_mgmt_binding *_binding, idc_control_t control);
typedef  void ahci_mgmt_error_handler_fn(struct ahci_mgmt_binding *_binding, errval_t err);

/*
 * Enumeration for message numbers
 */
typedef enum ahci_mgmt_msg_enum {
    ahci_mgmt___dummy__msgnum = 0,
    ahci_mgmt___bind__msgnum = 1,
    ahci_mgmt___bind_reply__msgnum = 2,
    ahci_mgmt_list_call__msgnum = 3,
    ahci_mgmt_list_response__msgnum = 4,
    ahci_mgmt_identify_call__msgnum = 5,
    ahci_mgmt_identify_response__msgnum = 6,
    ahci_mgmt_open_call__msgnum = 7,
    ahci_mgmt_open_response__msgnum = 8,
    ahci_mgmt_close_call__msgnum = 9,
    ahci_mgmt_close_response__msgnum = 10,
    ahci_mgmt_command_completed__msgnum = 11
} ahci_mgmt_msg_enum;

/*
 * Message type signatures (transmit)
 */
typedef  errval_t ahci_mgmt_list_call__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation);
typedef  errval_t ahci_mgmt_list_response__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, const uint8_t *port_ids, size_t len);
typedef  errval_t ahci_mgmt_identify_call__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id);
typedef  errval_t ahci_mgmt_identify_response__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, const uint8_t *identify_data, size_t data_len);
typedef  errval_t ahci_mgmt_open_call__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id);
typedef  errval_t ahci_mgmt_open_response__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, ahci_mgmt_errval_t status, struct capref controller_mem, uint64_t offset, uint32_t capabilities);
typedef  errval_t ahci_mgmt_close_call__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id);
typedef  errval_t ahci_mgmt_close_response__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, ahci_mgmt_errval_t status);
typedef  errval_t ahci_mgmt_command_completed__tx_method_fn(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id, uint32_t interrupt_status);

/*
 * Message type signatures (receive)
 */
typedef  void ahci_mgmt_list_call__rx_method_fn(struct ahci_mgmt_binding *_binding);
typedef  void ahci_mgmt_list_response__rx_method_fn(struct ahci_mgmt_binding *_binding, uint8_t *port_ids, size_t len);
typedef  void ahci_mgmt_identify_call__rx_method_fn(struct ahci_mgmt_binding *_binding, uint8_t port_id);
typedef  void ahci_mgmt_identify_response__rx_method_fn(struct ahci_mgmt_binding *_binding, uint8_t *identify_data, size_t data_len);
typedef  void ahci_mgmt_open_call__rx_method_fn(struct ahci_mgmt_binding *_binding, uint8_t port_id);
typedef  void ahci_mgmt_open_response__rx_method_fn(struct ahci_mgmt_binding *_binding, ahci_mgmt_errval_t status, struct capref controller_mem, uint64_t offset, uint32_t capabilities);
typedef  void ahci_mgmt_close_call__rx_method_fn(struct ahci_mgmt_binding *_binding, uint8_t port_id);
typedef  void ahci_mgmt_close_response__rx_method_fn(struct ahci_mgmt_binding *_binding, ahci_mgmt_errval_t status);
typedef  void ahci_mgmt_command_completed__rx_method_fn(struct ahci_mgmt_binding *_binding, uint8_t port_id, uint32_t interrupt_status);

/*
 * Struct type for holding the args for each msg
 */
struct ahci_mgmt_list_response__args {
    uint8_t *port_ids;
    size_t len;
};
struct ahci_mgmt_identify_call__args {
    uint8_t port_id;
};
struct ahci_mgmt_identify_response__args {
    uint8_t *identify_data;
    size_t data_len;
};
struct ahci_mgmt_open_call__args {
    uint8_t port_id;
};
struct ahci_mgmt_open_response__args {
    ahci_mgmt_errval_t status;
    struct capref controller_mem;
    uint64_t offset;
    uint32_t capabilities;
};
struct ahci_mgmt_close_call__args {
    uint8_t port_id;
};
struct ahci_mgmt_close_response__args {
    ahci_mgmt_errval_t status;
};
struct ahci_mgmt_command_completed__args {
    uint8_t port_id;
    uint32_t interrupt_status;
};

/*
 * Union type for all message arguments
 */
union ahci_mgmt_arg_union {
    struct ahci_mgmt_list_response__args list_response;
    struct ahci_mgmt_identify_call__args identify_call;
    struct ahci_mgmt_identify_response__args identify_response;
    struct ahci_mgmt_open_call__args open_call;
    struct ahci_mgmt_open_response__args open_response;
    struct ahci_mgmt_close_call__args close_call;
    struct ahci_mgmt_close_response__args close_response;
    struct ahci_mgmt_command_completed__args command_completed;
};

/*
 * VTable struct definition for the interface (transmit)
 */
struct ahci_mgmt_tx_vtbl {
    ahci_mgmt_list_call__tx_method_fn *list_call;
    ahci_mgmt_list_response__tx_method_fn *list_response;
    ahci_mgmt_identify_call__tx_method_fn *identify_call;
    ahci_mgmt_identify_response__tx_method_fn *identify_response;
    ahci_mgmt_open_call__tx_method_fn *open_call;
    ahci_mgmt_open_response__tx_method_fn *open_response;
    ahci_mgmt_close_call__tx_method_fn *close_call;
    ahci_mgmt_close_response__tx_method_fn *close_response;
    ahci_mgmt_command_completed__tx_method_fn *command_completed;
};

/*
 * VTable struct definition for the interface (receive)
 */
struct ahci_mgmt_rx_vtbl {
    ahci_mgmt_list_call__rx_method_fn *list_call;
    ahci_mgmt_list_response__rx_method_fn *list_response;
    ahci_mgmt_identify_call__rx_method_fn *identify_call;
    ahci_mgmt_identify_response__rx_method_fn *identify_response;
    ahci_mgmt_open_call__rx_method_fn *open_call;
    ahci_mgmt_open_response__rx_method_fn *open_response;
    ahci_mgmt_close_call__rx_method_fn *close_call;
    ahci_mgmt_close_response__rx_method_fn *close_response;
    ahci_mgmt_command_completed__rx_method_fn *command_completed;
};

/*
 * Incoming connect callback type
 */
typedef  errval_t ahci_mgmt_connect_fn(void *st, struct ahci_mgmt_binding *binding);

/*
 * Export state struct
 */
struct ahci_mgmt_export {
    struct idc_export common;
    ahci_mgmt_connect_fn *connect_cb;
    struct waitset *waitset;
    void *st;
};

/*
 * Export function
 */
extern  errval_t ahci_mgmt_export(void *st, idc_export_callback_fn *export_cb, ahci_mgmt_connect_fn *connect_cb, struct waitset *ws, idc_export_flags_t flags);

/*
 * The message buffer structure (for accept/connect)
 */
struct ahci_mgmt_frameinfo {
    /* Physical address of send buffer */
    lpaddr_t sendbase;

    /* Pointer to incoming message buffer */
    void *inbuf;

    /* Size of the incoming buffer in bytes */
    size_t inbufsize;

    /* Pointer to outgoing message buffer */
    void *outbuf;

    /* Size of the outgoing buffer in bytes */
    size_t outbufsize;

};

/*
 * Accept function over already shared frame
 */
extern  errval_t ahci_mgmt_accept(struct ahci_mgmt_frameinfo *_frameinfo, void *st, ahci_mgmt_bind_continuation_fn *_continuation, struct waitset *ws, idc_export_flags_t flags);

/*
 * The Binding structure
 */
struct ahci_mgmt_binding {
    /* Arbitrary user state pointer */
    void *st;

    /* Waitset used for receive handlers and send continuations */
    struct waitset *waitset;

    /* Mutex for the use of user code. */
    /* Must be held before any operation where there is a possibility of */
    /* concurrent access to the same binding (eg. multiple threads, or */
    /* asynchronous event handlers that use the same binding object). */
    struct event_mutex mutex;

    /* returns true iff a message could currently be accepted by the binding */
    ahci_mgmt_can_send_fn *can_send;

    /* register an event for when a message is likely to be able to be sent */
    ahci_mgmt_register_send_fn *register_send;

    /* change the waitset used by a binding */
    ahci_mgmt_change_waitset_fn *change_waitset;

    /* perform control operations */
    ahci_mgmt_control_fn *control;

    /* error handler for any async errors associated with this binding */
    /* must be filled-in by user */
    ahci_mgmt_error_handler_fn *error_handler;

    /* Message send functions (filled in by binding) */
    struct ahci_mgmt_tx_vtbl tx_vtbl;

    /* Incoming message handlers (filled in by user) */
    struct ahci_mgmt_rx_vtbl rx_vtbl;

    /* Private state belonging to the binding implementation */
    union ahci_mgmt_arg_union tx_union;
    union ahci_mgmt_arg_union rx_union;
    struct waitset_chanstate register_chanstate;
    struct waitset_chanstate tx_cont_chanstate;
    enum ahci_mgmt_msg_enum tx_msgnum;
    enum ahci_mgmt_msg_enum rx_msgnum;
    int tx_msg_fragment;
    int rx_msg_fragment;
    size_t tx_str_pos;
    size_t rx_str_pos;
    size_t tx_str_len;
    size_t rx_str_len;
    struct event_queue_node event_qnode;
    ahci_mgmt_bind_continuation_fn *bind_cont;
};

/*
 * Generic bind function
 */
extern  errval_t ahci_mgmt_bind(iref_t i, ahci_mgmt_bind_continuation_fn *_continuation, void *st, struct waitset *waitset, idc_bind_flags_t flags);

/*
 * Generic connect function over already shared frame
 */
extern  errval_t ahci_mgmt_connect(struct ahci_mgmt_frameinfo *_frameinfo, ahci_mgmt_bind_continuation_fn *_continuation, void *st, struct waitset *ws, idc_bind_flags_t flags);

/*
 * Send wrappers
 */
static inline errval_t ahci_mgmt_list_call__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_list_call__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation)
{
    return(((_binding->tx_vtbl).list_call)(_binding, _continuation));
}

static inline errval_t ahci_mgmt_list_response__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, const uint8_t *port_ids, size_t len) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_list_response__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, const uint8_t *port_ids, size_t len)
{
    return(((_binding->tx_vtbl).list_response)(_binding, _continuation, port_ids, len));
}

static inline errval_t ahci_mgmt_identify_call__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_identify_call__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id)
{
    return(((_binding->tx_vtbl).identify_call)(_binding, _continuation, port_id));
}

static inline errval_t ahci_mgmt_identify_response__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, const uint8_t *identify_data, size_t data_len) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_identify_response__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, const uint8_t *identify_data, size_t data_len)
{
    return(((_binding->tx_vtbl).identify_response)(_binding, _continuation, identify_data, data_len));
}

static inline errval_t ahci_mgmt_open_call__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_open_call__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id)
{
    return(((_binding->tx_vtbl).open_call)(_binding, _continuation, port_id));
}

static inline errval_t ahci_mgmt_open_response__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, ahci_mgmt_errval_t status, struct capref controller_mem, uint64_t offset, uint32_t capabilities) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_open_response__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, ahci_mgmt_errval_t status, struct capref controller_mem, uint64_t offset, uint32_t capabilities)
{
    return(((_binding->tx_vtbl).open_response)(_binding, _continuation, status, controller_mem, offset, capabilities));
}

static inline errval_t ahci_mgmt_close_call__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_close_call__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id)
{
    return(((_binding->tx_vtbl).close_call)(_binding, _continuation, port_id));
}

static inline errval_t ahci_mgmt_close_response__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, ahci_mgmt_errval_t status) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_close_response__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, ahci_mgmt_errval_t status)
{
    return(((_binding->tx_vtbl).close_response)(_binding, _continuation, status));
}

static inline errval_t ahci_mgmt_command_completed__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id, uint32_t interrupt_status) __attribute__ ((always_inline));
static inline errval_t ahci_mgmt_command_completed__tx(struct ahci_mgmt_binding *_binding, struct event_closure _continuation, uint8_t port_id, uint32_t interrupt_status)
{
    return(((_binding->tx_vtbl).command_completed)(_binding, _continuation, port_id, interrupt_status));
}

/*
 * Backend-specific includes
 */
#ifdef CONFIG_FLOUNDER_BACKEND_LMP
#include <if/ahci_mgmt_lmp_defs.h>
#endif // CONFIG_FLOUNDER_BACKEND_LMP
#ifdef CONFIG_FLOUNDER_BACKEND_UMP
#include <if/ahci_mgmt_ump_defs.h>
#endif // CONFIG_FLOUNDER_BACKEND_UMP
#ifdef CONFIG_FLOUNDER_BACKEND_UMP_IPI
#include <if/ahci_mgmt_ump_ipi_defs.h>
#endif // CONFIG_FLOUNDER_BACKEND_UMP_IPI
#ifdef CONFIG_FLOUNDER_BACKEND_MULTIHOP
#include <if/ahci_mgmt_multihop_defs.h>
#endif // CONFIG_FLOUNDER_BACKEND_MULTIHOP
/*
 * And we're done
 */
#endif // __ahci_mgmt_IF_H


text:
var fs = require("fs"),
	express = require("express"),
	app = express(),
	marked = require("marked"),
	mustache = require("mustache"),
	months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
	archives,
	drafts,
	get_config = function () {
		var config;
		try {
			config = fs.readFileSync("config.json", { "encoding": "utf-8" });
		} catch (e) {
			console.log("ERROR", "Could not find `config.json`. Please run `setup.js`.")
		}
		return config ? JSON.parse(config) : {};
	},
	get_context = function () {
		var context;
		try {
			context = fs.readFileSync("context.json", { "encoding": "utf-8" });
		} catch (e) {
			console.log("ERROR", "Could not find `context.json`. Please run `setup.js`.")
		}
		return context ? JSON.parse(context) : {};
	},
	tripled_variables = ["css", "content", "profile_image"],
	config = get_config(),
	context = get_context(),
	template = context.theme
		? fs.readFileSync("./themes/" + context.theme + "/main.html", { "encoding": "utf-8" })
		: "";

// Alert if template has not been read.
if (!template) {
	console.log("Template could not be found. Check theme referenced in `context.json` is valid has corresponding folder and `main.html` under `themes` folder.")
}

// By inserting a space in each triplet of braces, this prevents an error with the CSS and Mustache template.
template = template.replace(/\}\}\}/g, "}} }");

// Because Scriptogram only ever uses double-braced variables, replace these with triple-braced.
tripled_variables.forEach(function (v, i, a) {
	template = template.replace(new RegExp("\{\{(" + v + ")\}\}", "g"), "{{{$1}}}");
});

app.use("/themes", express.static('themes'));

app.use(function (req, res, next) {

	var archive_location = config.archives || "";

	fs.readdir(archive_location, function (err, files) {

		var vanilla_fn = function(v, i, a) {
				var current_post = {},
					post_file = "",
					post_title,
					post_tags,
					post_date,
					post_slug;

				console.log("Running vanilla Scriptogram preview.");

				try {
					post_file = fs.readFileSync(archive_location + v, { "encoding": "utf-8" });
				} catch (e) {
					console.log("Could not find `" + v + "`. May be an issue with the `archives` property in `config.json`.")
				}

				post_title = post_file.match(/Title\:[\ \t]*(.*?)[\n\r]/) || "";
				current_post["title"] =  post_title[1] || "";
				post_file = post_title[0] ? post_file.replace(post_title[0], "") : post_file;

				current_post["tags"] = [];
				post_tags = post_file.match(/Tags\:[\ \t]*([^\n\r]*?)[\n\r]/) || ["", ""];
				post_tags[1].split(/\,/g).forEach(function (v, i, a) {
					current_post.tags.push({ "name": v });
				});
				current_post["if_tags"] = current_post.tags.length;
				post_file = post_tags[0] ? post_file.replace(post_tags[0], "") : post_file;

				post_date = post_file.match(/Date\:[\ \t]*(.*?)[\n\r]/) || ["", ""];
				current_post["date"] = new Date(post_date[1].substr(0,4), post_date[1].substr(5,2) - 1, post_date[1].substr(8,2), post_date[1].substr(11,2) + 1, post_date[1].substr(14,2), 0);
				current_post["prettydate"] = months[current_post["date"].getMonth()] + " " + (+(post_date[1].substr(8,2))) + ", " + post_date[1].substr(0,4);
				post_file = post_date[0] ? post_file.replace(post_date[0], "") : post_file;

				post_slug = post_file.match(/Slug\:[\ \t]*(.*?)[\n\r]/) || ["", ""];
				post_file = post_slug[0] ? post_file.replace(post_slug[0], "") : post_file;

				current_post["content"] = marked(post_file);

				if (context.hasOwnProperty("posts")) {
					context.posts.push(current_post);
				}

			},
			ahem_fn = function(v, i, a) {
				var current_post = {},
					post_file = "",
					tags_file = "",
					date_file = "",
					post_title = "";

				console.log("Running Scriptogram preview with `ahem` workflow.");

				try {
					post_file = fs.readFileSync(archive_location + v + "/" + v + ".md", { "encoding": "utf-8" });
					tags_file = fs.readFileSync(archive_location + v + "/" + "tags.txt", { "encoding": "utf-8" });
					date_file = fs.readFileSync(archive_location + v + "/" + "date.txt", { "encoding": "utf-8"});
				} catch (e) {
					console.log("Could not find `" + v + ".md`. May be an issue with the `archives` property in `config.json`.")
				}

				post_title = post_file.match(/^[\s\n\r\t]*\#[\s\t]*([^\n]*)\n*/) || "";
				current_post["title"] =  post_title[1] || "";
				current_post["content"] = marked(post_title[0] ? post_file.replace(post_title[0], "") : "");

				current_post["tags"] = [];
				tags_file.split(/\n/g).forEach(function (v, i, a) {
					current_post.tags.push({ "name": v });
				});
				current_post["if_tags"] = current_post.tags.length;

				current_post["date"] = new Date(date_file.substr(0,4), date_file.substr(5,2) - 1, date_file.substr(8,2), date_file.substr(11,2) + 1, date_file.substr(14,2), 0);
				current_post["prettydate"] = months[current_post["date"].getMonth()] + " " + (+(date_file.substr(8,2))) + ", " + date_file.substr(0,4);

				if (context.hasOwnProperty("posts")) {
					context.posts.push(current_post);
				}

			};

		if (err) {
			res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
		} else {
			archives = files.filter(function (e, i, a) {
				return (e.match(/^\d{12}/));
			});
			context = get_context();
			archives.forEach(config.ahem ? ahem_fn : vanilla_fn);

			context.posts.sort(function (a, b) {
				return b.date - a.date;
			});

			// TODO: sort out synchronicity
			next();
		}
	});
});

app.use("/draft", function (req, res, next) {
	fs.readdir(config.drafts || "", function (err, files) {
		if (err) {
			res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
		} else {
			drafts = files.filter(function (e, i, a) {
				return true;
			});
			next();
		}
	});
});

app.get("/", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(JSON.stringify(archives, null, "\t"));
	next();
});

app.use("/preview", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(mustache.render(template, context));
	next();
});

app.get("/draft", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(JSON.stringify(archives, null, "\t"));
	res.write(JSON.stringify(drafts, null, "\t") || " ");
	next();
});

app.use(function (req, res, next) {
	res.end();
});

app.listen(1337);


text:
                  MELD project

               Tweets by MELD_project


text:
<!--
Description: feed tagline contains iframe
Expect:      not bozo and feed['tagline'] == 'safe description'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<tagline type="text/html" mode="escaped">safe<iframe src="http://example.com/"></iframe> description</tagline>
</feed>


text:
/* Packet Table wrapper classes
 *
 * Wraps the H5PT Packet Table C functions in C++ objects
 *
 * Nat Furrer and James Laird
 * February 2004
 */

/* High-level library internal header file */
#include "H5HLprivate2.h"

#include "H5PacketTable.h"

    /********************************/
    /* PacketTable superclass       */
    /********************************/

    /* "Open" Constructor
     * Opens an existing packet table, which can contain either fixed-length or
     * variable-length packets.
     */
    PacketTable::PacketTable(hid_t fileID, char* name)
    {
        table_id = H5PTopen( fileID, name);
    }

    /* Destructor
     * Cleans up the packet table
     */
    PacketTable::~PacketTable()
    {
        H5PTclose( table_id);
    }

    /* IsValid
     * Returns true if this packet table is valid, false otherwise.
     * Use this after the constructor to ensure HDF did not have
     * any trouble making or opening the packet table.
     */
    bool PacketTable::IsValid()
    {
        if (H5PTis_valid(table_id) == 0)
            return true;
        else
            return false;
    }

#ifdef VLPT_REMOVED
    /* IsVariableLength
     * Return 1 if this packet table is a Variable Length packet table,
     * return 0 if it is Fixed Length.  Returns -1 if the table is
     * invalid (not open).
     */
    int PacketTable::IsVariableLength()
    {
        return H5PTis_varlen(table_id);
    }
#endif /* VLPT_REMOVED */

    /* ResetIndex
     * Sets the index to point to the first packet in the packet table
     */
    void PacketTable::ResetIndex()
    {
        H5PTcreate_index(table_id);
    }

    /* SetIndex
     * Sets the index to point to the packet specified by index.
     * Returns 0 on success, negative on failure (if index is out of bounds)
     */
    int PacketTable::SetIndex(hsize_t index)
    {
        return H5PTset_index(table_id, index);
    }

    /* SetIndex
     * Sets the index to point to the packet specified by index.
     * Returns 0 on success, negative on failure (if index is out of bounds)
     */
    hsize_t PacketTable::GetIndex(int &error)
    {
        hsize_t index;

        error = H5PTget_index(table_id, &index);
        if(error < 0)
           return 0;
        else
           return index;
    }

    /* GetPacketCount
     * Returns the number of packets in the packet table.  Error
     * is set to 0 on success.  On failure, returns 0 and
     * error is set to negative.
     */
    hsize_t PacketTable::GetPacketCount(int& error)
    {
        hsize_t npackets;

        error = H5PTget_num_packets( table_id, (hsize_t *)&npackets);
        return npackets;
    }

    /********************************/
    /* Fixed-Length Packet Table    */
    /********************************/

    /* Constructor
     * Creates a packet table in which to store fixed length packets.
     * Takes the ID of the file the packet table will be created in, the name of
     * the packet table, the ID of the datatype of the set, and the size
     * of a memory chunk used in chunking.
     */
    FL_PacketTable::FL_PacketTable(hid_t fileID, char* name, hid_t dtypeID, hsize_t chunkSize, int compression)
    {
        table_id = H5PTcreate_fl ( fileID, name, dtypeID, chunkSize, compression);
    }

    /* "Open" Constructor
     * Opens an existing fixed-length packet table.
     * Fails if the packet table specified is variable-length.
     */
    FL_PacketTable::FL_PacketTable(hid_t fileID, char* name) : PacketTable(fileID, name)
    {
#ifdef VLPT_REMOVED
        if( H5PTis_varlen(table_id) != 0 )    // If this is not a fixed-length table
        {
            H5PTclose(table_id);
            table_id = -1;
        }
#endif /* VLPT_REMOVED */
    }

    /* AppendPacket
     * Adds a single packet to the packet table.  Takes a pointer
     * to the location of the data in memory.
     * Returns 0 on success, negative on failure
     */
    int FL_PacketTable::AppendPacket(void * data)
    {
        return H5PTappend(table_id, 1, data);
    }

    /* AppendPackets (multiple packets)
     * Adds multiple packets to the packet table.  Takes the number of packets
     * to be added and a pointer to their location in memory.
     * Returns 0 on success, -1 on failure.
     */
    int FL_PacketTable::AppendPackets(size_t numPackets, void * data)
    {
        return H5PTappend(table_id, numPackets, data);
    }

    /* GetPacket (indexed)
     * Gets a single packet from the packet table.  Takes the index
     * of the packet (with 0 being the first packet) and a pointer
     * to memory where the data should be stored.
     * Returns 0 on success, negative on failure
     */
    int FL_PacketTable::GetPacket(hsize_t index, void * data)
    {
        return H5PTread_packets(table_id, index, 1, data);
    }

    /* GetPackets (multiple packets)
     * Gets multiple packets at once, all packets between
     * startIndex and endIndex inclusive.  Also takes a pointer to
     * the memory where these packets should be stored.
     * Returns 0 on success, negative on failure.
     */
    int FL_PacketTable::GetPackets(hsize_t startIndex, hsize_t endIndex, void * data)
    {
        // Make sure the range of indexes is valid
        if (startIndex > endIndex)
            return -1;

        return  H5PTread_packets(table_id, startIndex, (size_t)(endIndex-startIndex+1), data);
    }

    /* GetNextPacket (single packet)
     * Gets the next packet in the packet table.  Takes a pointer to
     * memory where the packet should be stored.
     * Returns 0 on success, negative on failure.  Index
     * is not advanced to the next packet on failure.
     */
    int FL_PacketTable::GetNextPacket(void * data)
    {
        return H5PTget_next(table_id, 1, data);
    }

    /* GetNextPackets (multiple packets)
     * Gets the next numPackets packets in the packet table.  Takes a
     * pointer to memory where these packets should be stored.
     * Returns 0 on success, negative on failure.  Index
     * is not advanced on failure.
     */
    int FL_PacketTable::GetNextPackets(size_t numPackets, void * data)
    {
        return H5PTget_next(table_id, numPackets, data);
    }

#ifdef VLPT_REMOVED
    /********************************/
    /* Variable-Length Packet Table */
    /********************************/

    /* Constructor
     * Creates a packet table in which to store variable length packets.
     * Takes the ID of the file the packet table will be created in, the name of
     * the packet table, and the size of a memory chunk used in chunking.
     */
    VL_PacketTable::VL_PacketTable(hid_t fileID, char* name, hsize_t chunkSize)
    {
        table_id = H5PTcreate_vl ( fileID, name, chunkSize);
    }

    /* "Open" Constructor
     * Opens an existing variable-length packet table.
     * Fails if the packet table specified is fixed-length.
     */
    VL_PacketTable::VL_PacketTable(hid_t fileID, char* name) : PacketTable(fileID, name)
    {
        if( H5PTis_varlen(table_id) != 1 )    // If this is not a variable-length table
        {
            H5PTclose(table_id);
            table_id = -1;
        }
    }

    /* AppendPacket (variable-length)
     * Adds a single variable-length packet to the packet table.
     * Takes a pointer to the location of the data in memory and the length of the data
     * in bytes.
     * Returns 0 on success, negative on failure.
     */
       int VL_PacketTable::AppendPacket(void * data, size_t length)
    {
        hvl_t packet;

        packet.len = length;
        packet.p = data;

        return H5PTappend(table_id, 1, &packet);
    }

    /* AppendPackets (multiple packets)
     * Adds multiple variable-length packets to the packet table.  Takes the
     * number of
     * packets to be added and a pointer to an array of hvl_t structs in memory.
     * Returns 0 on success, negative on failure.
     */
    int VL_PacketTable::AppendPackets(size_t numPackets, hvl_t * data)
    {
        return H5PTappend(table_id, numPackets, data);
    }

    /* GetPacket (indexed)
     * Gets a single variable-length packet from the packet table.  Takes the
     * index of the packet (with 0 being the first packet) and a pointer
     * to a hvl_t struct in which to store the packet's size and location.
     * Returns 0 on success, negative on failure.
     */
    int VL_PacketTable::GetPacket(hsize_t index, hvl_t * data)
    {
        return H5PTread_packets(table_id, index, 1, data);
    }

    /* GetPackets (multiple packets)
     * Gets multiple variable-length packets at once, all packets between
     * startIndex and endIndex inclusive.  Takes a pointer to an array
     * of hvl_t structs in memory in which to store pointers to the packets.
     * Returns 0 on success, negative on failure.
     */
    int VL_PacketTable::GetPackets(hsize_t startIndex, hsize_t endIndex, hvl_t * data)
    {
        // Make sure the range of indexes is valid
        if (startIndex > endIndex)
            return -1;

        return  H5PTread_packets(table_id, startIndex, endIndex-startIndex+1, data);
    }

    /* GetNextPacket (single packet)
     * Gets the next packet in the packet table.  Takes a pointer to
     * an hvl_t struct where the packet should be stored.
     * Returns 0 on success, negative on failure.  Index
     * is not advanced to the next packet on failure.
     */
    int VL_PacketTable::GetNextPacket(hvl_t * data)
    {
        return H5PTget_next(table_id, 1, data);
    }

    /* GetNextPackets (multiple packets)
     * Gets the next numPackets packets in the packet table.  Takes a
     * pointer to an array of hvl_t structs where pointers to the packets
     * should be stored.
     * Returns 0 on success, negative on failure.  Index
     * is not advanced on failure.
     */
    int VL_PacketTable::GetNextPackets(size_t numPackets, hvl_t * data)
    {
        return H5PTget_next(table_id, numPackets, data);
    }

    /* FreeReadbuff
     * Frees the buffers created when variable-length packets are read.
     * Takes the number of hvl_t structs to be freed and a pointer to their
     * location in memory.
     * Returns 0 on success, negative on error.
     */
    int VL_PacketTable::FreeReadbuff(size_t numStructs, hvl_t * buffer)
    {
        return H5PTfree_vlen_readbuff( table_id, numStructs, buffer);
    }
#endif /* VLPT_REMOVED */


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>CMAKE_ARGV0 — CMake 3.7.1 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="top" title="CMake 3.7.1 Documentation" href="../index.html" />
    <link rel="up" title="cmake-variables(7)" href="../manual/cmake-variables.7.html" />
    <link rel="next" title="CMAKE_AR" href="CMAKE_AR.html" />
    <link rel="prev" title="CMAKE_ARGC" href="CMAKE_ARGC.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.7.1 Documentation »

cmake-variables(7) »

CMAKE_ARGV0¶

Command line argument passed to CMake in script mode.

When run in -P script mode, CMake sets this variable to
the first command line argument.  It then also sets CMAKE_ARGV1,
CMAKE_ARGV2, ... and so on, up to the number of command line arguments
given.  See also CMAKE_ARGC.

Previous topic

CMAKE_ARGC

Next topic

CMAKE_AR

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

    CMake »

    3.7.1 Documentation »

cmake-variables(7) »

        © Copyright 2000-2016 Kitware, Inc. and Contributors.
      Created using Sphinx 1.4a0+.


text:
package stroom.pipeline.stepping;

import stroom.pipeline.shared.SharedElementData;
import stroom.pipeline.shared.SourceLocation;
import stroom.pipeline.shared.stepping.SharedStepData;

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

public class StepData {

    private final Map<String, ElementData> elementMap = new HashMap<>();
    private SourceLocation sourceLocation;

    public SourceLocation getSourceLocation() {
        return sourceLocation;
    }

    public void setSourceLocation(final SourceLocation sourceLocation) {
        this.sourceLocation = sourceLocation;
    }

    public Map<String, ElementData> getElementMap() {
        return elementMap;
    }

    public SharedStepData convertToShared() {
        final Map<String, SharedElementData> map = new HashMap<>();
        for (final Entry<String, ElementData> entry : elementMap.entrySet()) {
            map.put(entry.getKey(), entry.getValue().convertToShared());
        }

        return new SharedStepData(sourceLocation, map);
    }
}


text:
<?php
/**
 * Import question : success
 */
?>

<div class='side-body <?php echo getSideBodyClass(false); ?>'>

<?php eT("Import Question") ?>

<?php eT("Success") ?>

<?php eT("Question import summary") ?>

<?php echo gT("Questions") . ": " . $aImportResults['questions'] ?>

<?php echo gT("Subquestions") . ": " . $aImportResults['subquestions'] ?>

<?php echo gT("Answers") . ": " . $aImportResults['answers'] ?>

                        <?php if (strtolower($sExtension) == 'csv'):?>

<?php echo gT("Label sets") . ": " . $aImportResults['labelsets'] . " (" . $aImportResults['labels'] ?>)

                        <?php endif;?>

<?php echo gT("Question attributes:") . $aImportResults['question_attributes'] ?>

                <?php if (!empty($aImportResults['importwarnings'])): ?>

<?php eT("Warnings");?>:

                        <?php
                            foreach ($aImportResults['importwarnings'] as $warning)
                            { ?>

<?php echo $warning; ?>

                            <?php
                        } ?>

                <?php endif; ?>

<?php eT("Question import is complete.") ?>

                    <a href="<?php echo $this->createUrl('admin/questions/sa/view/surveyid/' . $surveyid . '/gid/' . $gid . '/qid/' . $aImportResults['newqid']) ?>"  class="btn btn-default btn-lg" /><?php eT("Go to question") ?>


text:
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using Telegram.Bot.Types;

namespace Telegram.Bot.Mvc.Framework {
    public class ChatSession {

        public ChatSession(long chatId) {
            ChatId = chatId;
            Clear();
        }
        public long ChatId { get; set; }

        public void Clear()
        {
            _bag = new Dictionary<string, object>();
        }

        public override bool Equals(object obj) {
            if (obj as ChatSession == null) return false;
            return (obj as ChatSession).ChatId == ChatId;
        }

        public override int GetHashCode() {
            return ChatId.GetHashCode();
        }

        private IDictionary<string, object> _bag;

        public object this[string key]
        {
            get
            {
                _bag.TryGetValue(key, out object result);
                return result;
            }
            set
            {
                _bag[key] = value;
            }
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier;
using Microsoft.VisualStudio.Shell;

namespace Microsoft.SSHDebugPS.SSH
{
    internal class SSHPort : AD7Port, IDebugGdbServerAttach
    {
        public SSHPort(AD7PortSupplier portSupplier, string name, bool isInAddPort)
            : base(portSupplier, name, isInAddPort) { }

        protected override Connection GetConnectionInternal()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            return ConnectionManager.GetSSHConnection(Name);
        }

        public string GdbServerAttachProcess(int id, string preAttachCommand)
        {
            return ((SSHConnection)GetConnection()).AttachToProcess(id, preAttachCommand);
        }
    }
}