text:
from __future__ import division
import string, struct, collections
import fsslib, floppytrack

#import floppyinforead
#dsk = floppyinforead.analyzedisc('j:\\Transfer\\CloudKingdom.fss')
##-Take a coffee break...
#print(floppyinforead.printtable(dsk, 5))          #revolution
#image = floppyinforead.extractimage(dsk,80,2,10)  #tracks, sides, sectors, (size=512)
#fid = open('CloudKingdom.data','wb')
#fid.write(image)
#fid.close()

#Create a string type that doesn't fill the screen with data:
class Silentstring(str):
    __repr__ = object.__repr__

class Silentlist(list):
    __repr__ = object.__repr__

Track = collections.namedtuple('Track', ['trtimedata', 'trsynced', 'trmfmdec', 'sectors'])

Sector = collections.namedtuple('Sector', ['metadata', 'data'])

def sorthelper(a):
    try:
        return a[0]
    except TypeError:
        return a

def analyzedisc(fname):
    fid = open(fname, 'rb')
    floppy = fsslib.Reader(fid)
    fid.close()
    retlst = Silentlist()
    for t in xrange(164):
        side = t%2
        track = t//2
        print "------Track:", track, "Side:", side
        retlst.append(analysetrack((side,track), *floppy.gettrack(side, track)))
    return retlst

def analysetrack(sidetrck,timedata, indpuls):
    print indpuls
    bitsout, indexes = floppytrack.syncronize(timedata, indpuls)
    dataout, markers, indxp = floppytrack.mfmdecode(bitsout, indexes)
    markerpairs, unknownmarkers = floppytrack.lookupaddressmarkers(dataout, markers)
    mrkrspairs = floppytrack.revolutionseparate(markerpairs, indxp)
    unknownmrkrs = floppytrack.revolutionseparate(unknownmarkers, indxp)
    trtimedata = {'timedata' : timedata, 'indpuls' : indpuls}
    trsynced = {'rawbits' : bitsout, 'indpuls' : indexes}
    trmfmdec = {'data' : dataout, 'markers' : markers, 'indpuls' : indxp}
    sectors = Silentlist()
    for rev in zip(mrkrspairs, unknownmrkrs):
        #print "---INDEX---"
        sectors.append(analyserevol(sidetrck, dataout, *rev))
    track = Track(trtimedata=trtimedata, trsynced=trsynced, trmfmdec=trmfmdec, sectors=sectors)
    return track

def analyserevol(sidetrck, data, mrkrspairs, unknownmrkrs):
    markers = mrkrspairs + unknownmrkrs
    sortmark = sorted(markers,key=sorthelper)
    retlst = Silentlist()
    for mark in sortmark:
        try:
            if len(mark) == 2:
                retlst.append(analysesector(sidetrck, mark, data))
            else:
                print "Unkown type of marker-tuple received!", mark , sidetrck
        except TypeError:
            retlst.append(analysedudmark(mark, data))
    return retlst

def analysesector(sidetrck, mark, data):
    #If it's a pair the id-field should always exits - but may be faulty
    sectid = floppytrack.addressdecode(mark[0],data)
    data, datainfo = floppytrack.dataextract(mark[1],sectid['size'],data)
    sector = Sector(metadata=dict(sectid.items() + datainfo.items()), data=Silentstring(data))
    return sector

def analysedudmark(mark, data):
    print mark
    print "dudmark", hex(ord(data[mark]))
    themark = data[mark]
    if struct.unpack('B',themark)[0] == 0xFE:
        # If id-field is truncated: sectid = dict()
        sectid = floppytrack.addressdecode(mark,data)
    else:
        sectid = dict()
    sector = Sector(metadata=sectid, data=themark)
    return sector

def getinfo(sector,tracknum,sidenum):
    probstr = ""
    try:
        if sector.metadata['side'] != sidenum or sector.metadata['track'] != tracknum:
            probstr = "*"
        elif len(sector.data) == 1:  #This is id-field with no data (data contains only 0xFE)
            probstr = "?"
        elif len(sector.data) != sector.metadata['size']:
            probstr = "T"
        elif not sector.metadata['datacrcok']:
            probstr = "!"        # CRC error
        elif sector.metadata['sizecode'] != 2:
            probstr = "#"        # Unusual sector size
    except KeyError:
        #Dudmark
        if len(sector.data) != 1:
            raise ValueError('dudmarks should always have data of length 1')
        #Note: This is not a sector number as above - this is hexdata.
        return "D" + "{0:02x}".format(ord(sector.data)).upper()
    return  probstr + str(sector.metadata['sectnum'])

def printtable(disc,rev):
    layoutstr='Detection:' + ' '*16
    for num in range(1,33):
        layoutstr+=string.rjust(str(num),4,' ')
    for track in xrange(len(disc)):
        tracknum = track//2
        sidenum = track%2
        layoutstr+='\n'
        layoutstr+='Layout Track: '
        layoutstr+=string.rjust(str(tracknum),2,'0')
        layoutstr+=' Side: ' + str(sidenum) + ': '
        if rev < len(disc[track].sectors):
            for sectnum in xrange(len(disc[track].sectors[rev])):
                layoutstr+=string.rjust(getinfo(disc[track].sectors[rev][sectnum],tracknum,sidenum),4,' ')
    layoutstr+='\n'
    layoutstr+='\n\n'
    layoutstr+='#=Non 512 bytes sectors, !=CRC-Error,  ?=Unknown/faulty mark'
    layoutstr+='\n'
    layoutstr+='*=Track/side numbering is wrong, TI=Truncated ID,  TD=Truncated Data'
    layoutstr+='\n'
    layoutstr+='Only one is shown - increasing priority # -> ! -> * -> ?/TD/TI.'
    layoutstr+='\n'
    return layoutstr

def extractsector(sector, ntrack, nsides, sectorsize):
    data = sector.data
    tracknum = ntrack//nsides
    sidenum = ntrack%nsides
    bad = False
    try:
        if sector.metadata['track'] != tracknum:
            bad = True
        if sector.metadata['side'] != sidenum:
            bad = True
        if not sector.metadata['idcrcok']:
            bad = True
        if not sector.metadata['datacrcok']:
            bad = True
        if sector.metadata['size'] != sectorsize:
            bad = True
            if sector.metadata['size'] > sectorsiz:
                data = data[:sectorsiz]
            else:
                data += '\0'*(sectorsiz - len(data))
    except KeyError:
        return 0, True, ''
    return sector.metadata['sectnum'], bad, data

def extractimage(discstruct,ntracks,nsides,nsectors,sectorsize=512):
    disc = discstruct.sectors
    ntracksides = ntracks * nsides
    validsectors = set(range(1,nsectors + 1))
    imagelst = []
    badlst = []
    missinglst = []
    for ntrack in xrange(ntracksides):
        imagelst.append([])
        badlst.append([])
        missinglst.append([])
        for nsector in xrange(nsectors):
            imagelst[ntrack].append(['\0']*sectorsize)
            badlst[ntrack].append(True)
            missinglst[ntrack].append(True)
    for ntrack, track in enumerate(disc):
        for nrev, rev in enumerate(track.sectors):
            for nsector, sector in enumerate(rev):
                sectnum, bad, data = extractsector(sector, ntrack, nsides, sectorsize)
                if not sectnum in validsectors:
                    continue
                if bad:
                    print 'Bad sector in in-image:',
                    print 'Track:', ntrack//nsides,
                    print ' Side:', ntrack%nsides,
                    print ' Num:', sectnum,
                    print ' Rev:', nrev
                if badlst[ntrack][sectnum - 1]:
                    imagelst[ntrack][sectnum - 1] = disc[ntrack].sectors[nrev][nsector].data
                    if type(imagelst[ntrack][sectnum - 1]).__name__ != 'Silentstring':
                        print "ntrack, sectnum", ntrack, sectnum
                        print type(imagelst[ntrack][sectnum - 1]).__name__
                        return imagelst[ntrack][sectnum - 1]
                    badlst[ntrack][sectnum - 1] = bad
                    missinglst[ntrack][sectnum - 1] = False
                #imagelst[ntrack*nsides + nside][ntrack]
    image = Silentstring()
    badsectors = []
    missingsectors = []
    for ntrack in xrange(ntracksides):
        for nsector in xrange(nsectors):
            try:
                image += imagelst[ntrack][nsector]
            except:
                print "ntrack, nsector", ntrack, nsector
                return imagelst[ntrack][nsector]
            if missinglst[ntrack][sectnum]:
                print 'Missing sector in out-image:',
                print 'Track:', ntrack//nsides,
                print ' Side:', ntrack%nsides,
                print ' Num:', nsector+1
            elif badlst[ntrack][nsector]:
                print 'Bad sector in out-image:',
                print 'Track:', ntrack//nsides,
                print ' Side:', ntrack%nsides,
                print ' Num:', nsector+1
    return image

def savetascsv(disc,track, fname):
    floppytrack.savetascsv(disc[track].trtimedata['timedata'], fname)


text:
#ifndef LOAD_PNG_HPP
#define LOAD_PNG_HPP

#include <cat/AllFramework.hpp>
#include <string>
using namespace std;
#include "zlib-1.2.4/zlib.h"

namespace cat {

#include "CRC32.hpp"

#ifdef CAT_PRAGMA_PACK
#pragma pack(push)
#pragma pack(1)
#endif

	typedef struct
	{
		u32 length;
		char type[4];
	} CAT_PACKED SectionHeader;

	typedef struct
	{
		u32 length;
		char type[4];
		u32 crc;
	} CAT_PACKED EmptySection;

	typedef struct
	{
		u32 width, height;
		u8 bitDepth, colorType, compressionMethod, filterMethod, interlaceMethod;
	} CAT_PACKED PNG_IHDR;

	typedef struct
	{
		u8 r, g, b;
	} CAT_PACKED PLTE_Entry8;

	typedef struct
	{
		PLTE_Entry8 table[256];
	} CAT_PACKED PNG_PLTE;

#ifdef CAT_PRAGMA_PACK
#pragma pack(pop)
#endif

	class PNGSkeletonTokenizer
	{
	protected:
		MMapFile mmf;
		CRC32Calculator calculator;
		string path;

		// Split this from the ctor, so virtual overloads are in place by the time we start reading
		bool read(const u8 signature[8]); // Returns false on failure

	public:
		PNGSkeletonTokenizer(const string &path, u32 CRC32polynomial);
		virtual ~PNGSkeletonTokenizer() {}

	protected:
		// return true only if section is valid (no exceptions please)
		virtual bool onSection(char type[4], u8 data[], u32 len) = 0;
	};

	class PNGTokenizer : public PNGSkeletonTokenizer
	{
	protected:
		z_stream zstream;
		u8 *obuf;
		u32 olen;
		int lastZlibResult;

		bool requirePOTS;

		PNG_IHDR header;
		u16 bpp;
		u32 palette[256];
		u8 trans_red, trans_green, trans_blue;

		void rasterizeImage(u8 *image);

	public:
		PNGTokenizer(const string &path, bool requirePOTS);
		virtual ~PNGTokenizer();

	protected:
		bool onSection(char type[4], u8 data[], u32 len);

	protected:
		// Rasterized image in R8G8B8A8 format, new dimensions are powers of two
		virtual void onImage(u32 *image, u32 newWidth, u32 newHeight);

	protected:
		// Important sections
		void onIHDR(PNG_IHDR *infohdr);
		void onPLTE(PNG_PLTE *c_palette);
		void onIDAT(u8 *data, u32 len);
		void onIEND();

		// Transparency info
		void onTRNS_Color2(u16 red, u16 green, u16 blue);
		void onTRNS_Color3(u8 trans[256], u16 len);

		// Color space information (all unimplemented)
		void onGAMA();
		void onCHRM();
		void onSRGB();
		void onICCP();

		// Textual information (all unimplemented)
		void onTEXT();
		void onZTXT();
		void onITXT();

		// Other non-essential info (all unimplemented)
		void onBKGD();
		void onPHYS();
		void onSBIT();
		void onSPLT();
		void onHIST();
		void onTIME();
	};

} // namespace cat

#endif // LOAD_PNG_HPP

redpajama_set_name: RedPajamaGithub


text:
package generate

import (
	"crypto/rand"
	"encoding/base64"
	"io"
	"time"

	"code.gitea.io/gitea/modules/util"
	"github.com/dgrijalva/jwt-go"
)

// NewInternalToken generate a new value intended to be used by INTERNAL_TOKEN.
func NewInternalToken() (string, error) {
	secretBytes := make([]byte, 32)
	_, err := io.ReadFull(rand.Reader, secretBytes)
	if err != nil {
		return "", err
	}

	secretKey := base64.RawURLEncoding.EncodeToString(secretBytes)

	now := time.Now()

	var internalToken string
	internalToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"nbf": now.Unix(),
	}).SignedString([]byte(secretKey))
	if err != nil {
		return "", err
	}

	return internalToken, nil
}

// NewJwtSecret generate a new value intended to be used by LFS_JWT_SECRET.
func NewJwtSecret() (string, error) {
	JWTSecretBytes := make([]byte, 32)
	_, err := io.ReadFull(rand.Reader, JWTSecretBytes)
	if err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(JWTSecretBytes), nil
}

// NewSecretKey generate a new value intended to be used by SECRET_KEY.
func NewSecretKey() (string, error) {
	secretKey, err := util.RandomString(64)
	if err != nil {
		return "", err
	}

	return secretKey, nil
}


text:
package cn.moo.trainingcollege.servicetest;

import cn.moo.trainingcollege.BaseTest;
import cn.moo.trainingcollege.entity.CourseEntity;
import cn.moo.trainingcollege.service.CourseService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by 小春 on 2017/2/21.
 */
public class CourseTest extends BaseTest {
    @Autowired
    CourseService courseService;

    @Test
    public void getJoinedCourseListTest(){
        List<CourseEntity> list = courseService.getJoinedCourseList("S000002");
        System.out.println(list.size());
    }

    @Test
    public void getListTest(){
//        System.out.println(courseService.getJoinedStudent(1).size());
        System.out.println(courseService.getOrganCourseList("O000002").get(0).getName());
    }

    @Test
    public void getUnclosedCourseListTest(){
        System.out.println(courseService.getUnclosedCourseList("tes").size());
    }

    @Test
    public void getOrganCourseList() {
        System.out.println(courseService.getOrganOverCourseList("O000001"));
    }
}


text:
package org.yeastrc.xlink.www.searcher_via_cached_data.return_objects_from_searchers_for_cached_data;

import java.util.List;

import org.yeastrc.xlink.dto.SearchLinkerDTO;

public class SearchLinkerDTO_ForSearchId_Response {

	private List<SearchLinkerDTO> searchLinkerDTOList;

	public List<SearchLinkerDTO> getSearchLinkerDTOList() {
		return searchLinkerDTOList;
	}
	public void setSearchLinkerDTOList(List<SearchLinkerDTO> searchLinkerDTOList) {
		this.searchLinkerDTOList = searchLinkerDTOList;
	}

}


text:
package com.moac.android.interceptordemo.injection.module;

import android.content.Context;
import android.content.SharedPreferences;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module(complete = false, library = true)
public class PersistenceModule {

    @Singleton
    @Provides
    SharedPreferences provideSharedPreferences(@AppModule.ForApplication Context context) {
        return context.getSharedPreferences("config", Context.MODE_PRIVATE);
    }
}


text:
<?php

namespace FTFS\AssetBundle\Controller;

use FTFS\CrudBundle\Controller\CrudController as BaseController;

class AssetController extends BaseController
{
    public function __construct()
    {
        parent::__construct(array(
            'model' => "FTFS/AssetBundle/Asset"
        ));
    }

    public function deviceAddAction(\FTFS\AssetBundle\Entity\Asset $asset)
    {
        $entity = new \FTFS\AssetBundle\Entity\Device;
        $form = $this->createForm(new \FTFS\AssetBundle\Form\DeviceType, $entity);
        /*
        $form = $this->createFormBuilder($entity)
                ->add('serial')
                ->add('product')
                ->add('installed_at', null, array(
                    'widget' => 'single_text',
                ))
                ->add('observation')
                ->getForm()
                ;
         */

        if($this->getRequest()->getMethod() === 'POST') {
            $form->bindRequest($this->getRequest());
            if($form->isValid()) {
                $entity->setAsset($asset);
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($entity);
                $em->flush();
            }
            return $this->redirect($this->generateUrl($this->getRoutingPrefix().'_show', array(
                'id' => $asset->getId(),
            )));
        }

        return $this->render($this->getViewPath().'Device:entry_add_form.html.twig', array(
            'id' => $asset->getId(),
            'prefix' => $this->getRoutingPrefix(),
            'entry_add_form' => $form->createView(),
            'action' => $this->generateUrl($this->getRoutingPrefix().'_device_add', array('id' => $asset->getId())),
        ));
    }

    public function deviceEditAction($device_id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $device = $em->getRepository('FTFSAssetBundle:Device')->find($device_id);
        //throw new \Exception($device_id);
        if(!$device) {
            throw $this->createNotFoundException('device not found');
        }
        $asset = $device->getAsset();

        $form = $this->createForm(new \FTFS\AssetBundle\Form\DeviceType, $device);
        /*
        $form = $this->createFormBuilder($device)
                ->add('serial')
                ->add('product')
                ->add('installed_at', null, array(
                    'widget' => 'single_text',
                ))
                ->add('observation')
                ->getForm()
                ;
         */

        if($this->getRequest()->getMethod() === 'POST') {
            $form->bindRequest($this->getRequest());
            if($form->isValid()) {
                $em->flush();
            }
            return $this->redirect($this->generateUrl($this->getRoutingPrefix().'_show', array(
                'id' => $asset->getId(),
            )));
        }

        return $this->render($this->getViewPath().'Device:entry_add_form.html.twig', array(
            'id' => $asset->getId(),
            'prefix' => $this->getRoutingPrefix(),
            'entry_add_form' => $form->createView(),
            'action' => $this->generateUrl($this->getRoutingPrefix().'_device_edit', array('device_id' => $device_id)),
        ));
    }
    public function deviceDeleteAction($device_id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $device = $em->getRepository('FTFSAssetBundle:Device')->find($device_id);
        //throw new \Exception($device_id);
        if(!$device) {
            throw $this->createNotFoundException('device not found');
        }
        $id = $device->getAsset()->getId();
        $em->remove($device);
        $em->flush();

        return $this->redirect($this->generateUrl($this->getRoutingPrefix().'_show', array(
            'id' => $id,
        )));
    }
}


text:
package edu.utah.further.core.data.hibernate.page;

import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;

import java.util.List;

import org.junit.Test;
import org.springframework.transaction.annotation.Transactional;

import edu.utah.further.core.api.data.PersistentEntity;
import edu.utah.further.core.data.domain.ComplexPersonEntity;
import edu.utah.further.core.data.fixture.CoreDataFixture;
import edu.utah.further.core.data.hibernate.adapter.GenericCriteria;
import edu.utah.further.core.query.domain.MatchType;
import edu.utah.further.core.query.domain.SearchCriteria;
import edu.utah.further.core.query.domain.SearchQuery;
import edu.utah.further.core.query.domain.SearchType;
import edu.utah.further.core.util.collections.page.PagerUtil;

/**
 * Unit test for testing scrollable results distinct_root_entity implementation
 *

 * -----------------------------------------------------------------------------------

 * (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah

 * Contact: {@code <further@utah.edu>}

 * Biomedical Informatics, 26 South 2000 East

 * Room 5775 HSEB, Salt Lake City, UT 84112

 * Day Phone: 1-801-581-4080

 * -----------------------------------------------------------------------------------
 *
 * @author N. Dustin Schultz {@code <dustin.schultz@utah.edu>}
 * @version Oct 6, 2010
 */
public class UTestScrollableResultsTransformer extends CoreDataFixture
{
	/**
	 * Tests that associations are populated
	 */
	@Test
	@Transactional
	@SuppressWarnings("boxing")
	public void testAssociations()
	{
		final GenericCriteria hibernateCriteria = createLikeCriteria();

		final List<List<? extends PersistentEntity<Long>>> allPages = PagerUtil
				.getAllPages(newPager(1, hibernateCriteria.scroll()));
		for (final List<? extends PersistentEntity<Long>> pages : allPages)
		{
			for (final PersistentEntity<Long> page : pages)
			{
				assertThat(page, instanceOf(ComplexPersonEntity.class));
				final ComplexPersonEntity personEntity = (ComplexPersonEntity) page;
				assertThat(personEntity.getEvents(), notNullValue());
				assertThat(personEntity.getEvents().size(), is(greaterThan(0)));
			}
		}

	}

	/**
	 * Creates a LIKE 'Event' query to retrieve all of the events.
	 *
	 * @return
	 */
	private GenericCriteria createLikeCriteria()
	{
		final SearchQuery searchQuery = SearchCriteria
				.queryBuilder(
						SearchCriteria.stringExpression(SearchType.LIKE,
								"Event.eventName", "Event", MatchType.CONTAINS))
				.addAlias("Event", "Event", "events")
				.setRootObject("ComplexPerson")
				.build();

		final GenericCriteria hibernateCriteria = personCriteriaBuilder()
				.setQuery(searchQuery)
				.distinct(true)
				.build();
		return hibernateCriteria;
	}
}


text:
class CreateGoals < ActiveRecord::Migration
  def change
    create_table :goals do |t|
      t.references :student, index: true, foreign_key: true

      t.string :title
      t.text :description
      t.date :start
      t.date :end

      t.integer :parent_id, :null => true, :index => true
      t.integer :lft, :null => false, :index => true
      t.integer :rgt, :null => false, :index => true

      # optional fields
      t.integer :depth, :null => false, :default => 0
      t.integer :children_count, :null => false, :default => 0

      t.timestamps null: false
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:drawable="@drawable/main_add_expense_quickly_new_normal" />
    <item android:state_pressed="true" android:drawable="@drawable/main_add_expense_quickly_new_selected" />
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/main_add_expense_quickly_new_selected" />
    <item android:drawable="@drawable/main_add_expense_quickly_new_normal" />
</selector>


text:
using Fabrikam.Infrastructure.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Fabrikam.Command.Repository.DapperHelpers
{
    public static class GetSqlQuery
    {

        public static string Insert(object parameters, string tableName)
        {
            var colums = new List<string>();
            foreach (var colum in parameters.GetType().GetProperties())
            {
                var add = true;

                var keys = GetPrimaryKey(parameters);

                if (keys.Contains(colum.Name))
                {
                    add = false;
                }
                foreach (var attr in colum.CustomAttributes)
                {
                    if (attr.AttributeType == typeof(IgnoredAttribute))
                    {
                        add = false;
                    }
                }
                if (add) colums.Add(colum.Name);
            }

            var sql = "INSERT INTO [" + tableName + "] ({0}) VALUES(@{1});SELECT CAST(SCOPE_IDENTITY() AS INT);";
            var frmsql = String.Format(sql, String.Join(",", colums), String.Join(",@", colums));
            return frmsql;
        }

        public static string Update(object parameters, string tableName)
        {
            var colums = new List<string>();
            var keys = GetPrimaryKey(parameters);
            foreach (var colum in parameters.GetType().GetProperties())
            {
                var add = true;

                if (keys.Contains(colum.Name))
                {
                    add = false;
                }
                foreach (var attr in colum.CustomAttributes)
                {
                    if (attr.AttributeType == typeof(IgnoredAttribute))
                    {
                        add = false;
                    }
                }
                if (add) colums.Add(colum.Name);
            }
            var sb = new StringBuilder();
            sb.Append("UPDATE [" + tableName + "]  SET ");
            for (var i = 0; i < colums.Count(); i++)
            {
                sb.AppendFormat("[{0}]=@{1}", colums[i], colums[i]);
                //while not last element
                if (i < colums.Count() - 1)
                {
                    sb.Append(", ");
                }
            }

            sb.Append(" WHERE [" + keys.First() + "]= @" + keys.First());
            if (keys.Length > 1)
            {
                sb.Append(" AND " + string.Join(" AND ", keys.Skip(1).Select(x => string.Format("{0}=@{1}", x, x).ToArray())));
            }

            sb.Append("SELECT * FROM [" + tableName + "]");
            sb.Append(" WHERE [" + keys.First() + "]= @" + keys.First());
            if (keys.Length > 1)
            {
                sb.Append(" AND " + string.Join(" AND ", keys.Skip(1).Select(x => string.Format("{0}=@{1}", x, x).ToArray())));
            }

            return sb.ToString();
        }

        public static string Select(string tableName)
        {
            var sql = "SELECT * FROM [" + tableName + "]";
            return sql;
        }

        public static string DeleteById(string tableName)
        {
            var sql = "DELETE FROM [" + tableName + "] WHERE " + tableName + "Id=@Id";
            return sql;
        }

        public static string Find(object parameters, string tableName)
        {

            throw new Exception();
        }

        public static string[] GetPrimaryKey(object parameter)
        {
            Type type = parameter.GetType();
            var attribs = (PrimaryKeyAttribute[])type.GetCustomAttributes(typeof(PrimaryKeyAttribute), false);
            var retVal = attribs.Select(x => x.ColumnName);
            return retVal.ToArray();
        }

    }
}


text:
import numpy as np
import unittest

import chainer
from chainer import testing

from chainercv.experimental.links import PSPNetResNet101
from chainercv.experimental.links import PSPNetResNet50
from chainercv.utils import assert_is_semantic_segmentation_link
from chainercv.utils.testing import attr

@testing.parameterize(
    {'model': PSPNetResNet101},
    {'model': PSPNetResNet50},
)
class TestPSPNetResNet(unittest.TestCase):

    def setUp(self):
        self.n_class = 10
        self.input_size = (120, 160)
        self.link = self.model(
            n_class=self.n_class, input_size=self.input_size)

    def check_call(self):
        xp = self.link.xp
        x = chainer.Variable(xp.random.uniform(
            low=-1, high=1, size=(2, 3) + self.input_size).astype(np.float32))
        y = self.link(x)

        self.assertIsInstance(y, chainer.Variable)
        self.assertIsInstance(y.data, xp.ndarray)
        self.assertEqual(y.shape, (2, self.n_class, 120, 160))

    @attr.slow
    @attr.pfnci_skip
    def test_call_cpu(self):
        self.check_call()

    @attr.gpu
    @attr.slow
    def test_call_gpu(self):
        self.link.to_gpu()
        self.check_call()

    @attr.slow
    @attr.pfnci_skip
    def test_predict_cpu(self):
        assert_is_semantic_segmentation_link(self.link, self.n_class)

    @attr.gpu
    @attr.slow
    def test_predict_gpu(self):
        self.link.to_gpu()
        assert_is_semantic_segmentation_link(self.link, self.n_class)

@testing.parameterize(*testing.product({
    'model': [PSPNetResNet50, PSPNetResNet101],
    'pretrained_model': ['cityscapes', 'ade20k', 'imagenet'],
    'n_class': [None, 19, 150],
}))
class TestPSPNetResNetPretrained(unittest.TestCase):

    @attr.slow
    def test_pretrained(self):
        kwargs = {
            'n_class': self.n_class,
            'pretrained_model': self.pretrained_model,
        }

        if self.pretrained_model == 'cityscapes':
            valid = self.n_class in {None, 19}
        elif self.pretrained_model == 'ade20k':
            valid = self.n_class in {None, 150}
        elif self.pretrained_model == 'imagenet':
            valid = self.n_class is not None

        if valid:
            self.model(**kwargs)
        else:
            with self.assertRaises(ValueError):
                self.model(**kwargs)

testing.run_module(__name__, __file__)


text:
const express = require('express');
const next = require('next')

const bodyParser = require('body-parser');
const session = require('express-session');

const pathMatch = require('path-match');
const { parse } = require('url');

const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);
const promisify = require('es6-promisify');

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler();

// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });

mongoose.connect(process.env.DATABASE, {
  useNewUrlParser: true,
  reconnectTries: Number.MAX_VALUE
});
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises

var db = mongoose.connection;
db.on('error', console.error.bind(console, '🚫 🚫 🚫 🚫 → connection error:'));
db.once('open', function() {
  console.log(`✅  Mongo DB Connected`);
});

require('./models/Journal');
require('./models/Project');

const authController = require('./controllers/authController');
const apiRoutes = require('./router/apiRoutes');
const { setProjectPage, onAuthorisedProject } = require('./router/projectRoutes');

app.prepare()
.then(() => {
  const server = express();

  server.use(bodyParser.json());
  server.use(
    session({
      secret: process.env.SECRET,
      resave: false,
      saveUninitialized: false,
      cookie: { maxAge: 60000 },
      store: new MongoStore({ mongooseConnection: mongoose.connection })
    })
  );

  server.use('/api', apiRoutes);

  // Server-side route handling
  const route = pathMatch();

  server.get('/journal', (req, res) => {
    return app.render(req, res, '/journal', req.query);
  });

  server.get('/journal/:id', (req, res) => {
    const params = route('/journal/:id')(parse(req.url).pathname);
    return app.render(req, res, '/journalDetail', params);
  });

  server.get('/work/:id', onAuthorisedProject, (req, res) => {
    const projPage = setProjectPage(req.params.id);
    const params = route('/work/:id')(parse(req.url).pathname);
    return app.render(req, res, `/work/${projPage}`, params);
  });

  server.get('/add/journal', authController.isLoggedIn, (req, res) => {
    const params = route('/add/journal')(parse(req.url).pathname);
    return app.render(req, res, '/journalAdd', params);
  });

  server.get('/add/work', authController.isLoggedIn, (req, res) => {
    const params = route('/add/work')(parse(req.url).pathname);
    return app.render(req, res, '/workAdd', params);
  });

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  const port = process.env.PORT || 3000;
  server.listen(port, (err) => {
    if (err) throw err
    console.log(`🌍 Express running → PORT ${port}`);
  })
})


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Pedicularis elevatogaleata T.Yamaz.

### Remarks
null


text:
import {
  camelizeKeys,
  // hyphenateKeys,
  extend,
  extendTruthy,
  trimComment,
  normalizeStyle,
  autoPrefix,
  isArray,
  getParentScroller,
  supportSticky,
  appendCss
} from '../utils'
import { tagBegin, tagEnd } from '../utils/perf'
/* istanbul ignore next */

let pseudoId = 0
/**
 * get scoped class style map from stylesheets in <head>.
 */
export function getHeadStyleMap () {
  if (process.env.NODE_ENV === 'development') {
    tagBegin('getHeadStyleMap')
  }
  const needToRemoveStyleSheetNodes = []
  const styleSheetsArr = Array.from(document.styleSheets || []).filter(function (styleSheet) {
    return styleSheet.ownerNode.getAttribute('weex-scanned') !== '1'
  })

  const res = Array.from(styleSheetsArr)
    .reduce((pre, styleSheet) => {
      styleSheet.ownerNode.setAttribute('weex-scanned', 1)
      /**
       * why not using styleSheet.rules || styleSheet.cssRules to get css rules ?
       * because weex's components defined non-standard style attributes, which is
       * auto ignored when access rule.cssText.
       * another reason not to use cssRules directy:
       * @issue: https://stackoverflow.com/questions/21642277/security-error-the-operation-is-insecure-in-firefox-document-stylesheets
       */
      if (
        // css in a link. just ignore this. probably a link stylesheet.
        (styleSheet.ownerNode.tagName.toLowerCase() === 'link')
        || !styleSheet.ownerNode.textContent
        // pseudo class styleSheet node is generated by weex. just ignore it.
        || styleSheet.ownerNode.id.match(/weex-pseudo-\d+/)) {
        return pre
      }
      /**
       * start to analyze it's content.
       */
      const strArr = trimComment(styleSheet.ownerNode.textContent.trim()).split(/}/)
      const len = strArr.length
      const rules = []
      for (let i = 0; i < len; i++) {
        const str = strArr[i]
        if (!str || str.match(/^\s*$/)) {
          continue
        }
        /**
         * should match these cases:
         * .a[data-v-xxx] { color: red; }
         * .a[data-v-xxx]:active { color: green; }
         * .a[data-v-xxx], .b[data-v-xxx] { color: red; }
         *
         * should not match these cases:
         * .a { color: red; }
         * etc.
         */
        const match = str.match(/((?:,?\s*\.[\w-]+\[data-v-\w+\](?::\w+)?)+)\s*({[^}]+)/)
        if (!match) {
          // not the vue static class styles map. so acquire no rules for this styleSheet.
          // just jump through this styleSheet and go to analyzing next.
          return pre
        }
        const clsNms = match[1].split(',').map(n => n.trim())
        const cssText = match[2].replace(/[{}]/g, '').trim()
        let clsNmsIdx = 0
        const clsNmsLen = clsNms.length
        while (clsNmsIdx < clsNmsLen) {
          rules.push({
            selectorText: clsNms[clsNmsIdx],
            cssText
          })
          clsNmsIdx++
        }
      }
      Array.from(rules).forEach(rule => {
        const selector = rule.selectorText || ''
        let isPseudo = false
        if (selector.match(/:(?:active|focus|enabled|disabled)/)) {
          isPseudo = true
        }
        const styleObj = trimComment(rule.cssText).split(';')
          .reduce((styleObj, statement) => {
            statement = statement.trim()
            if (statement && statement.indexOf('/*') <= -1) {
              const resArr = statement.split(':').map((part) => part.trim())
              styleObj[resArr[0]] = resArr[1]
            }
            return styleObj
          }, {})
        if (isPseudo) {
          const txt = Object.keys(styleObj).reduce(function (pre, cur) {
            return pre + `${cur}:${styleObj[cur]}!important;`
          }, '')
          appendCss(`${selector}{${txt}}`, `weex-pseudo-${pseudoId++}`)
        }
        const objMap = !isPseudo ? pre : pre.pseudo
        const res = objMap[selector]
        if (!res) {
          objMap[selector] = styleObj
        }
        else {
          extend(objMap[selector], styleObj)
        }
      })
      /**
       * remove this styleSheet node since it's in the styleMap already. And this style
       * should only be fetched and used from styleMap to generate the final combined
       * component style, not from the stylesheet itself.
       */
      needToRemoveStyleSheetNodes.push(styleSheet.ownerNode)
      return pre
    }, { pseudo: {}})
  if (!window._no_remove_style_sheets) {
    needToRemoveStyleSheetNodes.forEach(function (node) {
      node.parentNode.removeChild(node)
    })
  }
  else if (process.env.NODE_ENV === 'development') {
    console.warn(`[vue-render] you've defined '_no_remove_style_sheets' and the v-data-xx stylesheets will not be removed.`)
  }
  if (process.env.NODE_ENV === 'development') {
    tagEnd('getHeadStyleMap')
  }
  return res
}

// export function getScopeIds (context) {
//   const arr = []
//   let ctx = context
//   let scopeId
//   while (ctx) {
//     scopeId = ctx.$options._scopeId
//     scopeId && arr.push(scopeId)
//     ctx = ctx.$options.parent
//   }
//   return arr
// }

export function getScopeId (vnode) {
  return vnode.context.$options._scopeId
}

/**
 * get style in <style scoped> tags for this component.
 */
export function getScopeStyle (vnode, classNames) {
  const scopeId = getScopeId(vnode)
  const style = {}
  const styleMap = weex._styleMap || {}
  let clsNmsIdx = 0
  const clsNmsLen = classNames.length
  while (clsNmsIdx < clsNmsLen) {
    const cls = `.${classNames[clsNmsIdx]}[${scopeId}]`
    const map = styleMap[cls]
    map && extendTruthy(style, map)
    clsNmsIdx++
  }
  return camelizeKeys(style)
}

function getStyle (vnode, extract) {
  const data = vnode.data || {}
  const staticClassNames = (typeof data.staticClass === 'string') ? data.staticClass.split(' ') : (data.staticClass || [])
  const classNames = (typeof data.class === 'string') ? data.class.split(' ') : (data.class || [])
  const clsNms = staticClassNames.concat(classNames)
  const style = normalizeStyle(getScopeStyle(vnode, clsNms))
  /**
   * cache static style and bind style.
   * cached staticStyle (including style and staticStyle) has already been normalized
   * in $processStyle. So there's no need to normalize it again.
   */
  if (!data.cached) {
    // cache staticStyle once in the beginning.
    data.cached = extendTruthy({}, data.staticStyle)
  }
  // cache binding style every time since the binding style is variable.
  extendTruthy(data.cached, data.style)
  extend(style, data.cached)
  data.staticStyle = style
  if (extract) {
    delete data.staticStyle
    delete data.style
  }
  return style
}

/**
 * get style merged with static styles, binding styles, and scoped class styles,
 * with keys in camelcase.
 */
export function getComponentStyle (context, extract) {
  if (!context.$vnode) {
    if (process.env.NODE_ENV === 'development') {
      return console.error('[vue-render] getComponentStyle failed: no $vnode in context.')
    }
    return {}
  }
  const style = {}
  let vnode = context.$vnode
  while (vnode) {
    extend(style, getStyle(vnode, extract))
    vnode = vnode.parent
  }
  const prefixedStyle = autoPrefix(style)
  /**
   * when prefixed value is a array, it should be applied to element
   * during the next tick.
   * e.g.
   *  background-image:  linear-gradient(to top,#f5fefd,#ffffff);
   *  will generate:
   *  {
   *    backgroundImage: [
   *      "-webkit-linear-gradient(to top,#f5fefd,#ffffff)",
   *      "-moz-linear-gradient(to top,#f5fefd,#ffffff)",
   *      "linear-gradient(to top,#f5fefd,#ffffff)"]
   *  }
   */
  for (const k in prefixedStyle) {
    if (Array.isArray(prefixedStyle[k])) {
      const vals = prefixedStyle[k]
      context.$nextTick(function () {
        const el = context.$el
        if (el) {
          for (let i = 0; i < vals.length; i++) {
            el.style[k] = vals[i]
          }
        }
      })
      if (k !== 'position') {
        /**
         * Should not delete prefixedStyle[k] directly. Otherwise will
         * trigger issue: https://issues.apache.org/jira/projects/WEEX/issues/WEEX-97
         */
        prefixedStyle[k] = style[k]
      }
    }
  }

  /**
   * If position is 'sticky', then add it to the stickyChildren of the parent scroller.
   */
  const pos = prefixedStyle.position
  const reg = /sticky$/
  if (pos === 'fixed') {
    context.$nextTick(function () {
      const el = context.$el
      if (el) {
        el.classList.add('weex-fixed')
      }
    })
  }
  else if (isArray(pos) && pos[0].match(reg) || (pos + '').match(reg)) {
    delete prefixedStyle.position
    // use native sticky.
    if (supportSticky()) {
      context.$nextTick(function () {
        const el = context.$el
        if (el) {
          el.classList.add('weex-ios-sticky')
        }
      })
    }
    // use re-implementation of sticky.
    else if (!context._stickyAdded) {
      const uid = context._uid
      const scroller = getParentScroller(context)
      if (scroller) {
        context._stickyAdded = true
        if (!scroller._stickyChildren) {
          scroller._stickyChildren = {}
        }
        scroller._stickyChildren[uid] = context
      }
      context.$nextTick(function () {
        const el = context.$el
        if (el) {
          context._initOffsetTop = el.offsetTop
        }
      })
    }
  }

  return prefixedStyle
}

export function extractComponentStyle (context) {
  return getComponentStyle(context, true)
}


text:
REPO="https://github.com/emberjs/guides.emberjs.com.git"
ROOT=$HOME/build/emberjs/guides
BUILT_FILES=$ROOT/build
DEPLOY=$ROOT/deploy
WEBSITE_FILES=$DEPLOY/guides.emberjs.com

# setup a temp folder to run things out of
mkdir $DEPLOY
cd $DEPLOY

echo "Installing Firebase tools for deploys"
npm install firebase-tools@^2.1 -g

git clone $REPO

# get latest version so we can copy our files to the right snapshot dir
cd guides.emberjs.com/snapshots
a=(*/)
tmp=${a[@]: -1} # has a trailing slash we remove below
latestVersion=${tmp%/}

LATEST_VERSION=$WEBSITE_FILES/snapshots/$latestVersion

cd $DEPLOY

rm -rf $LATEST_VERSION
cp -r $BUILT_FILES $LATEST_VERSION

cd $WEBSITE_FILES

# clean up versions in our built files
node tasks/update-versions.js

# do the deploy to production
firebase deploy


text:
package cs.karibu.helloworld.stage2;

/** The project code to identify the example
 * data type.
 *
 * @author Henrik Baerbak Christensen, Aarhus University
 *
 */
public class ExampleCodes {

  public static final String EXAMPLE_PRODUCER_CODE = "EXMXX001";
  public static final String EXAMPLE_TOPIC = "exampleproject.reading.store";

}


text:
<?php

namespace Google\Service\YouTube;

class VideoSuggestions extends \Google\Collection
{
  protected $collection_key = 'tagSuggestions';
  /**
   * @var string[]
   */
  public $editorSuggestions;
  /**
   * @var string[]
   */
  public $processingErrors;
  /**
   * @var string[]
   */
  public $processingHints;
  /**
   * @var string[]
   */
  public $processingWarnings;
  protected $tagSuggestionsType = VideoSuggestionsTagSuggestion::class;
  protected $tagSuggestionsDataType = 'array';

  /**
   * @param string[]
   */
  public function setEditorSuggestions($editorSuggestions)
  {
    $this->editorSuggestions = $editorSuggestions;
  }
  /**
   * @return string[]
   */
  public function getEditorSuggestions()
  {
    return $this->editorSuggestions;
  }
  /**
   * @param string[]
   */
  public function setProcessingErrors($processingErrors)
  {
    $this->processingErrors = $processingErrors;
  }
  /**
   * @return string[]
   */
  public function getProcessingErrors()
  {
    return $this->processingErrors;
  }
  /**
   * @param string[]
   */
  public function setProcessingHints($processingHints)
  {
    $this->processingHints = $processingHints;
  }
  /**
   * @return string[]
   */
  public function getProcessingHints()
  {
    return $this->processingHints;
  }
  /**
   * @param string[]
   */
  public function setProcessingWarnings($processingWarnings)
  {
    $this->processingWarnings = $processingWarnings;
  }
  /**
   * @return string[]
   */
  public function getProcessingWarnings()
  {
    return $this->processingWarnings;
  }
  /**
   * @param VideoSuggestionsTagSuggestion[]
   */
  public function setTagSuggestions($tagSuggestions)
  {
    $this->tagSuggestions = $tagSuggestions;
  }
  /**
   * @return VideoSuggestionsTagSuggestion[]
   */
  public function getTagSuggestions()
  {
    return $this->tagSuggestions;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(VideoSuggestions::class, 'Google_Service_YouTube_VideoSuggestions');


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace UniplatServiceWCF
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    /// <summary>
    /// Контракт для работы партнеров с системой UniplatService
    /// </summary>
    [ServiceContract]
    public interface IUniplatService
    {
        [OperationContract]
        //[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml,
        //    ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/GetDebitState")]
        Resp DebitMoney(ReqDebit request);

        [OperationContract]
        //[WebGet(BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml,
        //    ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/GetDebitState")]
        Resp GetDebitState(ReqState request);
    }

    [DataContract]
    public class ReqDebit
    {
        private string _MSISDN;
        private string _paymentId;
        private string _operatorCode;
        private string _comment;
        private string _serviceId;
        private string _partnerCode;
        private int _amount;
        private string _hash;
        private string _paymentNumber;

        /// <summary>
        /// Номер телефона абонента для списания
        /// </summary>
        [DataMember]
        public string MSISDN
        {
            get { return _MSISDN; }
            set { _MSISDN = value; }
        }

        /// <summary>
        /// Уникальный идентификатор платежа
        /// </summary>
        [DataMember]
        public string PaymentId
        {
            get { return _paymentId; }
            set { _paymentId = value; }
        }

        /// <summary>
        /// Код оператора (см справочник Операторы)
        /// </summary>
        [DataMember]
        public string OperatorCode
        {
            get { return _operatorCode; }
            set { _operatorCode = value; }
        }

        /// <summary>
        /// Oписание услуги (заказа), который оплачивает клиент (будет передано в SMS-сообщении) максимальная длина 15 символов.
        /// </summary>
        [DataMember]
        public string Comment
        {
            get { return _comment; }
            set { _comment = value; }
        }

        /// <summary>
        /// Код сервиса по которому происходит списание (см справочник Сервисы)
        /// </summary>
        [DataMember]
        public string ServiceId
        {
            get { return _serviceId; }
            set { _serviceId = value; }
        }

        /// <summary>
        /// Код партнера, переданный при регистрации
        /// </summary>
        [DataMember]
        public string PartnerCode
        {
            get { return _partnerCode; }
            set { _partnerCode = value; }
        }

        /// <summary>
        /// Сумма списания в копейках
        /// </summary>
        [DataMember]
        public int Amount
        {
            get { return _amount; }
            set { _amount = value; }
        }

        /// <summary>
        /// md5 хеш конкатенации следующих параметров:
        /// PaymentId + PartnerCode + ServiceId + MSISDN + PaymentNumber + Amount + Password
        /// Где Password – секретный пароль Партнера, полученный при регистрации партнера в Системе.
        /// </summary>
        [DataMember]
        public string Hash
        {
            get { return _hash; }
            set { _hash = value; }
        }

        /// <summary>
        /// уникальный номер списания (будет передан абоненту в SMS )
        /// Первые три символа – код партнера, остальные 7 символов – номер платежа (уникальный за последние 30 дней), например «0031234567»
        /// </summary>
        [DataMember]
        public string PaymentNumber
        {
            get { return _paymentNumber; }
            set { _paymentNumber = value; }
        }

        private static Regex _paymentIdRegex = new Regex(@"^.*$", RegexOptions.Compiled),
                             _partnerCodeRegex = new Regex(@"^.{1,3}$", RegexOptions.Compiled),
                             _serviceIdRegex = new Regex(@"^\d+$", RegexOptions.Compiled),
                             _msisdnRegex = new Regex(@"^\d{10}$", RegexOptions.Compiled),
                             _paymentNumberRegex = new Regex(@"^.{10}$", RegexOptions.Compiled),
                             _amountRegex = new Regex(@"^\d+$", RegexOptions.Compiled);

        internal bool CheckParametersRegex(out string wrongParameters)
        {
            var list = new List<string>();
            if (!_paymentIdRegex.IsMatch(PaymentId ?? ""))
                list.Add("PaymentId");
            if (!_partnerCodeRegex.IsMatch(PartnerCode ?? ""))
                list.Add("PartnerCode");
            if (!_serviceIdRegex.IsMatch(ServiceId ?? ""))
               list.Add("ServiceId");
            if (!_msisdnRegex.IsMatch(MSISDN ?? ""))
                list.Add("MSISDN");
            if (!_paymentNumberRegex.IsMatch(PaymentNumber ?? ""))
                list.Add("PaymentNumber");
            if (!_amountRegex.IsMatch(Amount.ToString()))
                list.Add("Amount");

            if (list.Count == 0)
            {
                wrongParameters = "";
                return true;
            }

            wrongParameters = list.Aggregate((cur, i) => cur + ", " + i);
            return false;
        }

        internal bool CheckHashCode(string password)
        {
            var checkingValue = PaymentId + PartnerCode + ServiceId + MSISDN + PaymentNumber + Amount + password;
            var data = Encoding.GetEncoding(1251).GetBytes(checkingValue);
            var md5 = MD5.Create();

            var hash = Convert.ToBase64String(md5.ComputeHash(data));

            return Hash == hash;
        }
    }

    [DataContract]
    public class ReqState
    {
        private string _paymentId;
        private string _partnerCode;
        private string _hash;

        /// <summary>
        /// Идентификатор транзакции, заданный Партнером.
        /// </summary>
        [DataMember]
        public string PaymentId
        {
            get { return _paymentId; }
            set { _paymentId = value; }
        }

        /// <summary>
        /// Код партнера, переданный при регистрации
        /// </summary>
        [DataMember]
        public string PartnerCode
        {
            get { return _partnerCode; }
            set { _partnerCode = value; }
        }

        /// <summary>
        /// md5 хеш конкатенации следующих параметров:
        /// PaymentId + PartnerCode + Password
        /// Где Password – секретный пароль Партнера, полученный при регистрации партнера в Системе.
        /// </summary>
        [DataMember]
        public string Hash
        {
            get { return _hash; }
            set { _hash = value; }
        }

        private static Regex _paymentIdRegex = new Regex(@"^.*$", RegexOptions.Compiled),
                             _partnerCodeRegex = new Regex(@"^.{1,3}$", RegexOptions.Compiled);

        internal bool CheckParametersRegex(out string wrongParameters)
        {
            var list = new List<string>();
            if (!_paymentIdRegex.IsMatch(PaymentId ?? ""))
                list.Add("PaymentId");
            if (!_partnerCodeRegex.IsMatch(PartnerCode ?? ""))
                list.Add("PartnerCode");
            if (list.Count == 0)
            {
                wrongParameters = "";
                return true;
            }
            wrongParameters = list.Aggregate((cur, i) => cur + ", " + i);
            return false;
        }

        internal bool CheckHashCode(string password)
        {
            var checkingValue = PaymentId + PartnerCode + password;
            var data = Encoding.GetEncoding(1251).GetBytes(checkingValue);
            var md5 = MD5.Create();

            var hash = Convert.ToBase64String(md5.ComputeHash(data));

            return Hash == hash;
        }
    }

    [DataContract]
    public class Resp
    {
        private string _paymentId;
        private int _resultCode;
        private string _resultcoment;

        /// <summary>
        /// Идентификатор транзакции, заданный Партнером.
        /// </summary>
        [DataMember]
        public string PaymentId
        {
            get { return _paymentId; }
            set { _paymentId = value; }
        }

        /// <summary>
        /// Код результата обработки запроса. Это основное значение, на которое необходимо ориентироваться, выстраивая бизнес-логику приложения. Возможные коды ошибок обработки на этом этапе:
        /// •	0 — запрос принят в обработку,
        /// •	2 — нарушен формат параметра,
        /// •	3 — указаны ошибочные идентификаторы поставщика услуги,
        /// •	4 — ошибка в hash-значении,
        /// •	5 — сервер временно не принимает запросы в связи с высокой нагрузкой. Повторите попытку позже,
        /// •	6 — номер мобильного телефона не опознан, неизвестный провайдер,
        /// •	9 — категория не найдена,
        /// •	11 — ошибка связи с Провайдером.
        /// </summary>
        [DataMember]
        public int ResultCode
        {
            get { return _resultCode; }
            set { _resultCode = value; }
        }

        /// <summary>
        /// Комментарий к результату обработки в произвольном текстовом формате.
        /// </summary>
        [DataMember]
        public string Resultcoment
        {
            get { return _resultcoment; }
            set { _resultcoment = value; }
        }
    }

}


text:
#include "./vpx_config.h"
#include "./vp8_rtcd.h"

#include "third_party/googletest/src/include/gtest/gtest.h"

#include "test/buffer.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "vpx/vpx_integer.h"

typedef void (*IdctFunc)(int16_t *input, unsigned char *pred_ptr,
                         int pred_stride, unsigned char *dst_ptr,
                         int dst_stride);
namespace {

using libvpx_test::Buffer;

class IDCTTest : public ::testing::TestWithParam<IdctFunc> {
 protected:
  virtual void SetUp() {
    UUT = GetParam();

    input = new Buffer<int16_t>(4, 4, 0);
    ASSERT_TRUE(input != NULL);
    ASSERT_TRUE(input->Init());
    predict = new Buffer<uint8_t>(4, 4, 3);
    ASSERT_TRUE(predict != NULL);
    ASSERT_TRUE(predict->Init());
    output = new Buffer<uint8_t>(4, 4, 3);
    ASSERT_TRUE(output != NULL);
    ASSERT_TRUE(output->Init());
  }

  virtual void TearDown() {
    delete input;
    delete predict;
    delete output;
    libvpx_test::ClearSystemState();
  }

  IdctFunc UUT;
  Buffer<int16_t> *input;
  Buffer<uint8_t> *predict;
  Buffer<uint8_t> *output;
};

TEST_P(IDCTTest, TestAllZeros) {
  // When the input is '0' the output will be '0'.
  input->Set(0);
  predict->Set(0);
  output->Set(0);

  ASM_REGISTER_STATE_CHECK(UUT(input->TopLeftPixel(), predict->TopLeftPixel(),
                               predict->stride(), output->TopLeftPixel(),
                               output->stride()));

  ASSERT_TRUE(input->CheckValues(0));
  ASSERT_TRUE(input->CheckPadding());
  ASSERT_TRUE(output->CheckValues(0));
  ASSERT_TRUE(output->CheckPadding());
}

TEST_P(IDCTTest, TestAllOnes) {
  input->Set(0);
  ASSERT_TRUE(input->TopLeftPixel() != NULL);
  // When the first element is '4' it will fill the output buffer with '1'.
  input->TopLeftPixel()[0] = 4;
  predict->Set(0);
  output->Set(0);

  ASM_REGISTER_STATE_CHECK(UUT(input->TopLeftPixel(), predict->TopLeftPixel(),
                               predict->stride(), output->TopLeftPixel(),
                               output->stride()));

  ASSERT_TRUE(output->CheckValues(1));
  ASSERT_TRUE(output->CheckPadding());
}

TEST_P(IDCTTest, TestAddOne) {
  // Set the transform output to '1' and make sure it gets added to the
  // prediction buffer.
  input->Set(0);
  ASSERT_TRUE(input->TopLeftPixel() != NULL);
  input->TopLeftPixel()[0] = 4;
  output->Set(0);

  uint8_t *pred = predict->TopLeftPixel();
  for (int y = 0; y < 4; ++y) {
    for (int x = 0; x < 4; ++x) {
      pred[y * predict->stride() + x] = y * 4 + x;
    }
  }

  ASM_REGISTER_STATE_CHECK(UUT(input->TopLeftPixel(), predict->TopLeftPixel(),
                               predict->stride(), output->TopLeftPixel(),
                               output->stride()));

  uint8_t const *out = output->TopLeftPixel();
  for (int y = 0; y < 4; ++y) {
    for (int x = 0; x < 4; ++x) {
      EXPECT_EQ(1 + y * 4 + x, out[y * output->stride() + x]);
    }
  }

  if (HasFailure()) {
    output->DumpBuffer();
  }

  ASSERT_TRUE(output->CheckPadding());
}

TEST_P(IDCTTest, TestWithData) {
  // Test a single known input.
  predict->Set(0);

  int16_t *in = input->TopLeftPixel();
  for (int y = 0; y < 4; ++y) {
    for (int x = 0; x < 4; ++x) {
      in[y * input->stride() + x] = y * 4 + x;
    }
  }

  ASM_REGISTER_STATE_CHECK(UUT(input->TopLeftPixel(), predict->TopLeftPixel(),
                               predict->stride(), output->TopLeftPixel(),
                               output->stride()));

  uint8_t *out = output->TopLeftPixel();
  for (int y = 0; y < 4; ++y) {
    for (int x = 0; x < 4; ++x) {
      switch (y * 4 + x) {
        case 0: EXPECT_EQ(11, out[y * output->stride() + x]); break;
        case 2:
        case 5:
        case 8: EXPECT_EQ(3, out[y * output->stride() + x]); break;
        case 10: EXPECT_EQ(1, out[y * output->stride() + x]); break;
        default: EXPECT_EQ(0, out[y * output->stride() + x]);
      }
    }
  }

  if (HasFailure()) {
    output->DumpBuffer();
  }

  ASSERT_TRUE(output->CheckPadding());
}

INSTANTIATE_TEST_CASE_P(C, IDCTTest, ::testing::Values(vp8_short_idct4x4llm_c));

#if HAVE_NEON
INSTANTIATE_TEST_CASE_P(NEON, IDCTTest,
                        ::testing::Values(vp8_short_idct4x4llm_neon));
#endif  // HAVE_NEON

#if HAVE_MMX
INSTANTIATE_TEST_CASE_P(MMX, IDCTTest,
                        ::testing::Values(vp8_short_idct4x4llm_mmx));
#endif  // HAVE_MMX

#if HAVE_MSA
INSTANTIATE_TEST_CASE_P(MSA, IDCTTest,
                        ::testing::Values(vp8_short_idct4x4llm_msa));
#endif  // HAVE_MSA

#if HAVE_MMI
INSTANTIATE_TEST_CASE_P(MMI, IDCTTest,
                        ::testing::Values(vp8_short_idct4x4llm_mmi));
#endif  // HAVE_MMI
}  // namespace


text:
function map = metis_to_matlab(AdjacencyMatrix, n_subdom, contiguous)
%METIS_TO_MATLAB wrapper to Metis multiway partition
%
%   map = METIS_TO_MATLAB(AdjacencyMatrix, n_subdom, contiguous)
%
%   Requires the adjacency matrix of the graph and the number of desired
%   subdomains. If contiguous = 1, metis returns a contiguous partition.
%
%   See also geometric_domain_decomposition
%
%   Inspired by metisdice (part of MESHPART toolbox) by John Gilbert
%
%   Requires metis 5.0 and metismex interface.
%   To compile metismex see the link below:
%   http://dgleich.wordpress.com/2012/05/22/want-to-use-metis-5-0-with-matlab-try-the-new-metismex/

%   This file is part of redbKIT.
%   Copyright (c) 2016, Ecole Polytechnique Federale de Lausanne (EPFL)
%   Author: Federico Negri <federico.negri at epfl.ch>

if nargin == 2 || isempty(contiguous) || ~contiguous

      map = metismex('PartGraphKway', AdjacencyMatrix, n_subdom);

elseif nargin == 3

      wtflag.contig = 1;
      map = metismex('PartGraphKway', AdjacencyMatrix, n_subdom, wtflag);

end


text:
from lettuce import before, after, world, step
import datetime
import os
from contextlib import closing

from journal import connect_db
from journal import DB_SCHEMA
from journal import INSERT_ENTRY

from pyramid import testing

TEST_DSN = 'dbname=test_learning_journal user=jakeanderson'
settings = {'db': TEST_DSN}
INPUT_BTN = '<input class="btn" type="submit" value="Share" name="Share"/>'

@world.absorb
def make_an_entry(app):
    entry_data = {
        'title': 'Hello there',
        'text': '''##This is a post
```python
    def func(x):
        return x
```''',
    }
    response = app.post('/add', params=entry_data, status='3*')
    return response

@world.absorb
def login_helper(username, password, app):
    """encapsulate app login for reuse in tests
    Accept all status codes so that we can make assertions in tests
    """
    login_data = {'username': username, 'password': password}
    return app.post('/login', params=login_data, status='*')

@before.all
def init_db():
    with closing(connect_db(settings)) as db:
        db.cursor().execute(DB_SCHEMA)
        db.commit()

@after.all
def clear_db(total):
    with closing(connect_db(settings)) as db:
        db.cursor().execute("DROP TABLE entries")
        db.commit()

@after.each_feature
def clear_entries(scenario):
    with closing(connect_db(settings)) as db:
        db.cursor().execute("DELETE FROM entries")
        db.commit()

@before.each_scenario
def app(scenario):
    from journal import main
    from webtest import TestApp
    os.environ['DATABASE_URL'] = TEST_DSN
    app = main()
    world.app = TestApp(app)

@step('a journal home page')
def get_home_page(step):
    response = world.app.get('/')
    assert response.status_code == 200
    actual = response.body
    expected = 'No entries here so far'
    assert expected in actual

@step('I click on the entry link')
def click_on_the_entry_link(step):
    login_helper('admin', 'secret', world.app)
    world.make_an_entry(world.app)
    response = world.app.get('/')
    response.click(href='detail/1')
    assert response.status_code == 200

@step('I get the detail page for that entry')
def get_detail_page(step):
    response = world.app.get('/detail/1')
    assert response.status_code == 200
    assert 'This is a post' in response.body

@step('a logged in user')
def a_logged_in_user(step):
    redirect = login_helper('admin', 'secret', world.app)
    assert redirect.status_code == 302
    response = redirect.follow()
    assert response.status_code == 200
    actual = response.body
    assert INPUT_BTN in actual

@step('a journal detail page')
def journal_detail_page(step):
    response = world.app.get('/detail/1')
    assert response.status_code == 200
    assert 'This is a post' in response.body

@step('I click on the edit button')
def click_on_the_edit_button(step):
    login_helper('admin', 'secret', world.app)
    world.make_an_entry(world.app)
    response = world.app.get('/detail/1')
    assert response.status_code == 200
    response.click(href='/edit/1')
    assert response.status_code == 200

@step('I am taken to the edit page for that entry')
def journal_edit_page(step):
    login_helper('admin', 'secret', world.app)
    response = world.app.get('/edit/1')
    assert response.status_code == 200
    actual = response.body
    assert INPUT_BTN in actual

@step('a journal edit form')
def journal_edit_form(step):
    login_helper('admin', 'secret', world.app)
    world.make_an_entry(world.app)
    response = world.app.get('/')
    response.click(href='/detail/1')
    assert response.status_code == 200

@step('I type in the edit box')
def type_edit_box(step):
    login_helper('admin', 'secret', world.app)
    world.make_an_entry(world.app)
    response = world.app.get('/edit/1')
    assert response.form

@step('I can use Markdown to format my post')
def get_md_page(step):
    login_helper('admin', 'secret', world.app)
    world.make_an_entry(world.app)
    response = world.app.get('/detail/1')
    assert response.status_code == 200
    assert '
This is a post
' in response.body

@step('I look at a post')
def look_at_a_post(step):
    response = world.app.get('/detail/1')
    assert response.status_code == 200
    assert 'This is a post' in response.body

@step('I can see colorized code samples')
def get_colorized_code(step):
    response = world.app.get('/detail/1')
    assert response.status_code == 200
    assert 'class="codehilite"' in response.body


text:
- Support diagnostics (done)

### How to use it

if you have installed vundle, just add

```Plugin 'Chilledheart/vim-wdc'```

in your vimrc file, and run

```~/.vim/bundle/vim-wdc/bootstrap```

#### Requirement
- OS X or Linux
- cmake 3.0 or later
- llvm 3.7 or later


text:
package cloud_controller_clock
/*
* File Generated by enaml generator
* !!! Please do not edit this file !!!
*/
type CloudControllerClockJob struct {

	/*Version - Descr: 'version' attribute in the /v2/info endpoint Default: 0
*/
	Version interface{} `yaml:"version,omitempty"`

	/*SystemDomain - Descr: Domain reserved for CF operator, base URL where the login, uaa, and other non-user apps listen Default: <nil>
*/
	SystemDomain interface{} `yaml:"system_domain,omitempty"`

	/*Build - Descr: 'build' attribute in the /v2/info endpoint Default:
*/
	Build interface{} `yaml:"build,omitempty"`

	/*Name - Descr: 'name' attribute in the /v2/info endpoint Default:
*/
	Name interface{} `yaml:"name,omitempty"`

	/*Hm9000 - Descr: URL of the hm9000 server Default: <nil>
*/
	Hm9000 *Hm9000 `yaml:"hm9000,omitempty"`

	/*LoggerEndpoint - Descr: Whether to use ssl for logger endpoint listed at /v2/info Default: true
*/
	LoggerEndpoint *LoggerEndpoint `yaml:"logger_endpoint,omitempty"`

	/*MetronEndpoint - Descr: The host used to emit messages to the Metron agent Default: 127.0.0.1
*/
	MetronEndpoint *MetronEndpoint `yaml:"metron_endpoint,omitempty"`

	/*Ccdb - Descr: The timeout for Sequel pooled connections Default: 10
*/
	Ccdb *Ccdb `yaml:"ccdb,omitempty"`

	/*AppDomains - Descr: Array of domains for user apps (example: 'user.app.space.foo', a user app called 'neat' will listen at 'http://neat.user.app.space.foo') Default: <nil>
*/
	AppDomains interface{} `yaml:"app_domains,omitempty"`

	/*Login - Descr: whether use login as the authorization endpoint or not Default: true
*/
	Login *Login `yaml:"login,omitempty"`

	/*SupportAddress - Descr: 'support' attribute in the /v2/info endpoint Default:
*/
	SupportAddress interface{} `yaml:"support_address,omitempty"`

	/*SystemDomainOrganization - Descr: An organization that will be created as part of the seeding process. When the system_domain is not shared with (in the list of) app_domains, this is required as the system_domain will be created as a PrivateDomain in this organization. Default:
*/
	SystemDomainOrganization interface{} `yaml:"system_domain_organization,omitempty"`

	/*Uaa - Descr: URL of the UAA server Default: <nil>
*/
	Uaa *Uaa `yaml:"uaa,omitempty"`

	/*Ssl - Descr: specifies that the job is allowed to skip ssl cert verification Default: false
*/
	Ssl *Ssl `yaml:"ssl,omitempty"`

	/*Nats - Descr: Password for cc client to connect to NATS Default: <nil>
*/
	Nats *Nats `yaml:"nats,omitempty"`

	/*Domain - Descr: Deprecated in favor of system_domain. Domain where cloud_controller will listen (api.domain) Default: <nil>
*/
	Domain interface{} `yaml:"domain,omitempty"`

	/*DeaNext - Descr: Disk limit in mb for staging tasks Default: 6144
*/
	DeaNext *DeaNext `yaml:"dea_next,omitempty"`

	/*RequestTimeoutInSeconds - Descr: Timeout for requests in seconds. Default: 900
*/
	RequestTimeoutInSeconds interface{} `yaml:"request_timeout_in_seconds,omitempty"`

	/*Description - Descr: 'description' attribute in the /v2/info endpoint Default:
*/
	Description interface{} `yaml:"description,omitempty"`

	/*Cc - Descr: The type of blobstore backing to use. Valid values: ['fog', 'webdav'] Default: fog
*/
	Cc *Cc `yaml:"cc,omitempty"`

}


text:
#include "sonLib.h"
#include "cactus.h"
#include "adjacencyTraversal.h"

bool getTerminalAdjacencyLength_ignoreAdjacencies = 0;

char *getTerminalAdjacencySubString(Cap *cap) {
    if(getTerminalAdjacencyLength_ignoreAdjacencies) {
        return stString_copy("");
    }
    cap = getTerminalCap(cap);
    cap = cap_getStrand(cap) ? cap : cap_getReverse(cap); //This ensures the asserts are as expected.
    Cap *adjacentCap = cap_getAdjacency(cap);
    int64_t i = cap_getCoordinate(cap) - cap_getCoordinate(adjacentCap);
    assert(i != 0);
    if (i > 0) {
        assert(cap_getSide(cap));
        assert(!cap_getSide(adjacentCap));
        return sequence_getString(cap_getSequence(cap),
                cap_getCoordinate(adjacentCap) + 1, i - 1, 1);
    } else {
        assert(cap_getSide(adjacentCap));
        assert(!cap_getSide(cap));
        return sequence_getString(cap_getSequence(cap), cap_getCoordinate(cap) + 1, -i - 1, 1);
    }
}

int64_t getTerminalAdjacencyLength(Cap *cap) {
    if(getTerminalAdjacencyLength_ignoreAdjacencies) {
        return 0;
    }
    char *cA = getTerminalAdjacencySubString(cap);
    int64_t i = strlen(cA);
    free(cA);
    return i;
}

Cap *getTerminalCap(Cap *cap) {
    Flower *nestedFlower = group_getNestedFlower(end_getGroup(cap_getEnd(cap)));
    if (nestedFlower != NULL) {
        Cap *nestedCap = flower_getCap(nestedFlower, cap_getName(cap));
        assert(nestedCap != NULL);
        return getTerminalCap(cap_getOrientation(cap) ? nestedCap : cap_getReverse(nestedCap));
    }
    return cap;
}

Segment *getCapsSegment(Cap *cap) {
    if (cap_getSegment(cap) != NULL) {
        return cap_getSegment(cap);
    }
    assert(!end_isBlockEnd(cap_getEnd(cap)));
    assert(end_isStubEnd(cap_getEnd(cap)));
    //Walk up to get the next adjacency.
    Group *parentGroup = flower_getParentGroup(end_getFlower(cap_getEnd(cap)));
    if (parentGroup != NULL) {
        Cap *parentCap = flower_getCap(group_getFlower(parentGroup), cap_getName(cap));
        if (parentCap != NULL) {
            assert(cap_getOrientation(parentCap));
            if (!cap_getOrientation(cap)) {
                parentCap = cap_getReverse(parentCap);
            }
            return getCapsSegment(parentCap);
        } else { //Cap must be a free stub end.
            assert(0); //Not in the current alignments.
            assert(end_isFree(cap_getEnd(cap)));
        }
    }
    return NULL;
}

Segment *getAdjacentCapsSegment(Cap *cap) {
    cap = getTerminalCap(cap);
    cap = cap_getAdjacency(cap);
    assert(cap != NULL);
    return getCapsSegment(cap);
}

static bool capHasGivenEvents(Cap *cap, stList *eventStrings) {
    const char *headerSeq = event_getHeader(cap_getEvent(cap));
    for (int64_t i = 0; i < stList_length(eventStrings); i++) {
        if (strcmp(headerSeq, stList_get(eventStrings, i)) == 0) {
            return 1;
        }
    }
    return 0;
}

bool trueAdjacency(Cap *cap, stList *eventStrings) {
	if(getTerminalAdjacencyLength(cap) > 0) {
        return 0;
    }
	cap = getTerminalCap(cap);
    assert(cap != NULL);
    Cap *otherCap = cap_getAdjacency(cap);
    assert(otherCap != NULL);
    assert(cap_getAdjacency(otherCap) == cap);
    //So is the adjacency present in one of the haplotypes? That's what we're going to answer..
    End *otherEnd = end_getPositiveOrientation(cap_getEnd(otherCap));
    End_InstanceIterator *endInstanceIt = end_getInstanceIterator(cap_getEnd(cap));
    Cap *cap2;
    while ((cap2 = end_getNext(endInstanceIt)) != NULL) {
        Cap *otherCap2 = cap_getAdjacency(cap2);
        assert(otherCap2 != NULL);
        if (otherEnd == end_getPositiveOrientation(cap_getEnd(otherCap2))) {
            //const char *eventName = event_getHeader(cap_getEvent(cap2));
            assert(event_getHeader(cap_getEvent(cap2)) == event_getHeader(
                            cap_getEvent(otherCap2)));
            if (capHasGivenEvents(cap2, eventStrings)) { //strcmp(eventName, "hapA1") == 0 || strcmp(eventName, "hapA2") == 0) {
                if(getTerminalAdjacencyLength(cap2) == 0) {
                    end_destructInstanceIterator(endInstanceIt);
                    return 1;
                }
            }
        }
    }
    end_destructInstanceIterator(endInstanceIt);
    return 0;
}

bool hasCapInEvent(End *end, const char *eventString) {
    Cap *cap;
    End_InstanceIterator *instanceIt = end_getInstanceIterator(end);
    while ((cap = end_getNext(instanceIt)) != NULL) {
        if (strcmp(event_getHeader(cap_getEvent(cap)), eventString) == 0) {
            end_destructInstanceIterator(instanceIt);
            return 1;
        }
    }
    end_destructInstanceIterator(instanceIt);
    return 0;
}

bool hasCapNotInEvent(End *end, const char *eventString) {
    Cap *cap;
    End_InstanceIterator *instanceIt = end_getInstanceIterator(end);
    while ((cap = end_getNext(instanceIt)) != NULL) {
        if (strcmp(event_getHeader(cap_getEvent(cap)), eventString) != 0) {
            end_destructInstanceIterator(instanceIt);
            return 1;
        }
    }
    end_destructInstanceIterator(instanceIt);
    return 0;
}

bool hasCapInEvents(End *end, stList *eventStrings) {
    for(int64_t i=0; i<stList_length(eventStrings); i++) {
        if(hasCapInEvent(end, stList_get(eventStrings, i))) {
            return 1;
        }
    }
    return 0;
}

bool endsAreConnected(End *end1, End *end2, stList *eventStrings) {
    if (end_getName(end1) == end_getName(end2)) { //Then the ends are the same and are part of the same chromosome by definition.
        End_InstanceIterator *instanceIterator = end_getInstanceIterator(end1);
        Cap *cap1;
        while ((cap1 = end_getNext(instanceIterator)) != NULL) {
            if (capHasGivenEvents(cap1, eventStrings)) {
                end_destructInstanceIterator(instanceIterator);
                return 1;
            }
        }
        return 0;
    }
    End_InstanceIterator *instanceIterator = end_getInstanceIterator(end1);
    Cap *cap1;
    while ((cap1 = end_getNext(instanceIterator)) != NULL) {
        if (capHasGivenEvents(cap1, eventStrings)) {
            End_InstanceIterator *instanceIterator2 = end_getInstanceIterator(end2);
            Cap *cap2;
            while ((cap2 = end_getNext(instanceIterator2)) != NULL) {
                assert(cap_getName(cap2) != cap_getName(cap1)); //This could only happen if end1 == end2
                if (sequence_getMetaSequence(cap_getSequence(cap1)) == sequence_getMetaSequence(cap_getSequence(cap2))) {
                    assert(strcmp(event_getHeader(cap_getEvent(cap1)),
                                    event_getHeader(cap_getEvent(cap2))) == 0);
                    assert(cap_getPositiveOrientation(cap1)
                            != cap_getPositiveOrientation(cap2));
                    assert(cap_getName(cap1) != cap_getName(cap2));
                    //they could have the same coordinate if they represent two ends of a block of length 1.

                    end_destructInstanceIterator(instanceIterator);
                    end_destructInstanceIterator(instanceIterator2);
                    return 1;
                }
            }
            end_destructInstanceIterator(instanceIterator2);
        }
    }
    end_destructInstanceIterator(instanceIterator);
    return 0;
}

bool capsAreAdjacent(Cap *cap1, Cap *cap2, int64_t *separationDistance) {
    if (cap_getName(cap2) != cap_getName(cap1) && cap_getCoordinate(cap1) != cap_getCoordinate(cap2)) { //This can happen if end1 == end2
        if (sequence_getMetaSequence(cap_getSequence(cap1)) == sequence_getMetaSequence(cap_getSequence(cap2))) {
            assert(strcmp(event_getHeader(cap_getEvent(cap1)), event_getHeader(
                                    cap_getEvent(cap2))) == 0);
            assert(cap_getPositiveOrientation(cap1)
                    != cap_getPositiveOrientation(cap2));
            assert(cap_getName(cap1) != cap_getName(cap2));
            assert(sequence_getMetaSequence(cap_getSequence(cap1))
                                == sequence_getMetaSequence(cap_getSequence(cap2)));

            if (!cap_getStrand(cap1)) {
                cap1 = cap_getReverse(cap1);
            }
            if (!cap_getStrand(cap2)) {
                cap2 = cap_getReverse(cap2);
            }
            assert(cap_getStrand(cap1));
            assert(cap_getStrand(cap2));
            if (cap_getCoordinate(cap1) < cap_getCoordinate(cap2)) {
                if (!cap_getSide(cap1) && cap_getSide(cap2)) {
                    *separationDistance = cap_getCoordinate(cap2) - cap_getCoordinate(cap1) - 1; //The minus 1, to give the length of the sequence between the two caps.
                    return 1;
                }
            } else {
                if (cap_getSide(cap1) && !cap_getSide(cap2)) {
                    *separationDistance = cap_getCoordinate(cap1) - cap_getCoordinate(cap2) - 1;
                    return 1;
                }
            }
        }
    }
    return 0;
}

bool endsAreAdjacent2(End *end1, End *end2, Cap **returnCap1, Cap **returnCap2, int64_t *minimumDistanceBetweenHaplotypeCaps, stList *eventStrings) {
    End_InstanceIterator *instanceIterator = end_getInstanceIterator(end1);
    Cap *cap1;
    *returnCap1 = NULL;
    *returnCap2 = NULL;
    *minimumDistanceBetweenHaplotypeCaps = INT64_MAX;
    bool areAdjacent = 0;
    while ((cap1 = end_getNext(instanceIterator)) != NULL) {
        if (capHasGivenEvents(cap1, eventStrings)) {
            End_InstanceIterator *instanceIterator2 = end_getInstanceIterator(end2);
            Cap *cap2;
            while ((cap2 = end_getNext(instanceIterator2)) != NULL) {
                int64_t i;
                if (capsAreAdjacent(cap1, cap2, &i)) {
                    areAdjacent = 1;
                    if (i < *minimumDistanceBetweenHaplotypeCaps) {
                        *minimumDistanceBetweenHaplotypeCaps = i;
                        *returnCap1 = cap1;
                        *returnCap2 = cap2;
                    }
                }
            }
            end_destructInstanceIterator(instanceIterator2);
        }
    }
    end_destructInstanceIterator(instanceIterator);
    return areAdjacent;
}

bool endsAreAdjacent(End *end1, End *end2, int64_t *minimumDistanceBetweenHaplotypeCaps, stList *eventStrings) {
    Cap *cap1 = NULL, *cap2 = NULL;
    return endsAreAdjacent2(end1, end2, &cap1, &cap2, minimumDistanceBetweenHaplotypeCaps, eventStrings);
}


text:
namespace v8 {
namespace internal {
namespace compiler {

BytecodeLiveness::BytecodeLiveness(int register_count, Zone* zone)
    : in(zone->New<BytecodeLivenessState>(register_count, zone)),
      out(zone->New<BytecodeLivenessState>(register_count, zone)) {}

BytecodeLivenessMap::BytecodeLivenessMap(int bytecode_size, Zone* zone)
    : liveness_map_(base::bits::RoundUpToPowerOfTwo32(bytecode_size / 4 + 1),
                    base::KeyEqualityMatcher<int>(),
                    ZoneAllocationPolicy(zone)) {}

uint32_t OffsetHash(int offset) { return offset; }

BytecodeLiveness& BytecodeLivenessMap::InitializeLiveness(int offset,
                                                          int register_count,
                                                          Zone* zone) {
  return liveness_map_
      .LookupOrInsert(offset, OffsetHash(offset),
                      [&]() { return BytecodeLiveness(register_count, zone); })
      ->value;
}

BytecodeLiveness& BytecodeLivenessMap::GetLiveness(int offset) {
  return liveness_map_.Lookup(offset, OffsetHash(offset))->value;
}

const BytecodeLiveness& BytecodeLivenessMap::GetLiveness(int offset) const {
  return liveness_map_.Lookup(offset, OffsetHash(offset))->value;
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8


text:
package com.maxiee.heartbeat.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.maxiee.heartbeat.R;
import com.maxiee.heartbeat.common.TimeUtils;
import com.maxiee.heartbeat.model.Thoughts;
import com.maxiee.heartbeat.ui.AddEditThoughtActivity;
import com.maxiee.heartbeat.ui.GalleryActivity;

/**
 * Created by maxiee on 15-6-13.
 */
public class ThoughtTimeaxisAdapter extends RecyclerView.Adapter<ThoughtTimeaxisAdapter.ViewHolder> {

    private Thoughts mThoughtList;

    public ThoughtTimeaxisAdapter(Thoughts thoughtList) {
        mThoughtList = thoughtList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_thought_timeaxis, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        String order;
        if (holder.sortingType.equals("0")) {
            switch (position) {
                case 0:
                    order = holder.mContext.getString(R.string.firtime);
                    break;
                case 1:
                    order = holder.mContext.getString(R.string.sectime);
                    break;
                default:
                    order = String.valueOf(position + 1) + ".";
                    break;
            }
        } else {
            if (position == mThoughtList.length() - 1) {
                order = holder.mContext.getString(R.string.firtime);
            } else if (position == mThoughtList.length() - 2) {
                order = holder.mContext.getString(R.string.sectime);
            } else {
                order = String.valueOf(mThoughtList.length() - position) + ".";
            }
        }
        holder.tvOrder.setText(order);

        long time = mThoughtList.get(position).getTimeStamp();
        holder.tvThought.setText(mThoughtList.get(position).getThought());
        holder.tvTime.setText(TimeUtils.parseTime(holder.mContext, time));

        if (mThoughtList.get(position).hasImage()) {
            holder.mImage.setVisibility(View.VISIBLE);
            Glide.with(holder.mContext).load(mThoughtList.get(position).getPath()).into(holder.mImage);
            holder.mImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(holder.mContext, GalleryActivity.class);
                    i.putExtra(GalleryActivity.PATH, mThoughtList.get(position).getPath());
                    holder.mContext.startActivity(i);
                }
            });
        } else {
            holder.mImage.setVisibility(View.GONE);
        }

        holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent i = new Intent(holder.mContext, AddEditThoughtActivity.class);
                i.putExtra(AddEditThoughtActivity.MODE, AddEditThoughtActivity.MODE_EDIT);
                i.putExtra(AddEditThoughtActivity.THOUGHT_ID, mThoughtList.get(position).getKey());
                i.putExtra(AddEditThoughtActivity.THOUGHT, mThoughtList.get(position).getThought());
                i.putExtra(Thoughts.Thought.THOUGHT_RES, mThoughtList.get(position).getResType());
                i.putExtra(Thoughts.Thought.THOUGHT_PATH, mThoughtList.get(position).getPath());
                holder.mContext.startActivity(i);
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        return mThoughtList.length();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tvOrder, tvThought, tvTime;
        public ImageView mImage;
        public final View mView;
        public Context mContext;
        public String sortingType;

        public ViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
            mContext = itemView.getContext();
            tvOrder = (TextView) itemView.findViewById(R.id.tv_order);
            tvThought = (TextView) itemView.findViewById(R.id.tv_thought);
            tvTime = (TextView) itemView.findViewById(R.id.tv_time);
            mImage = (ImageView) itemView.findViewById(R.id.image_thought);
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
            sortingType = sp.getString("time_axis_sorting", "0");
        }
    }
}


text:
package com.sunny.template.service;

import com.sunny.component.MailComponent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.mail.MessagingException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-config.xml"})
public class MailComponentTest {

    @Autowired
    private MailComponent mailComponent;

    @Test
    public void send() throws MessagingException {
//        mailComponent.send(new String[]{"10000@qq.com"}, null, null, "hello", "hello");
    }

}


text:
import {bind} from "classnames/bind";
import {MithrilViewComponent} from "jsx/mithril-component";
import m from "mithril";
import Stream from "mithril/stream";
import {MaterialRevision, Modification, PipelineRunInfo} from "models/pipeline_activity/pipeline_activity";
import {Dropdown, DropdownAttrs} from "views/components/buttons";
import * as Icons from "views/components/icons";
import styles from "./index.scss";

const classnames = bind(styles);

interface Attrs {
  pipelineRunInfo: PipelineRunInfo;
  showBuildCaseFor: Stream<string>;
}

export class BuildCauseWidget extends Dropdown<Attrs> {
  toggleDropdown(vnode: m.Vnode<DropdownAttrs & Attrs>, e: MouseEvent) {
    super.toggleDropdown(vnode, e);
    if (vnode.attrs.show()) {
      vnode.attrs.showBuildCaseFor(vnode.attrs.pipelineRunInfo.counterOrLabel());
    } else {
      vnode.attrs.showBuildCaseFor("");
    }
  }

  protected doRenderButton(vnode: m.Vnode<DropdownAttrs & Attrs>): m.Children {
    if (!vnode.attrs.pipelineRunInfo.revision()) {
      return;
    }

    return
      {vnode.attrs.pipelineRunInfo.buildCauseBy()}
    ;
  }

  protected doRenderDropdownContent(vnode: m.Vnode<DropdownAttrs & Attrs>) {
    if (!vnode.attrs.show()) {
      return;
    }

    return

        <Icons.Close data-test-id="build-details-close-btn" onclick={this.toggleDropdown.bind(this, vnode)}/>

      {vnode.attrs.pipelineRunInfo.materialRevisions().map((rev, index) => {
        return <MaterialRevisionWidget data-test-id={`material-revision-${index}`}
                                       materialRevision={rev}
                                       show={vnode.attrs.show}/>;
      })}

;
  }
}

interface MaterialRevisionAttrs {
  materialRevision: MaterialRevision;
  show: Stream<boolean>;
}

class MaterialRevisionWidget extends MithrilViewComponent<MaterialRevisionAttrs> {
  view(vnode: m.Vnode<MaterialRevisionAttrs, this>): m.Children {
    const materialRevision = vnode.attrs.materialRevision;
    return

        {materialRevision.scmType()} - {materialRevision.location()}

      <div class={classnames(styles.modifications, {[styles.changed]: materialRevision.changed()})}
           data-test-id={`revisions-${materialRevision.revision()}`}>
        {materialRevision.modifications().map((modification) => {
          return <ModificationWidget modification={modification}/>;
        })}

;
  }
}

interface ModificationAttrs {
  modification: Modification;
}

class ModificationWidget extends MithrilViewComponent<ModificationAttrs> {
  view(vnode: m.Vnode<ModificationAttrs, this>): m.Children {
    const modification = vnode.attrs.modification;
    return <div class={styles.modification} data-test-id={`modification-${modification.revision()}`}>
      {modification.user()}
      {m.trust(modification.comment())}
      {modification.revision()}

;
  }
}


text:
using System;
using System.Drawing;
using System.Collections.ObjectModel;

#endregion Using Directives

namespace ScintillaNET.Configuration
{
    public class IndicatorConfig
    {
        #region Fields

        private Color _color;
        private bool? _inherit;
        private bool? _isDrawnUnder;
        private int _number;
        private IndicatorStyle? _style;

        #endregion Fields

        #region Properties

        public Color Color
        {
            get
            {
                return _color;
            }
            set
            {
                _color = value;
            }
        }

        public bool? Inherit
        {
            get
            {
                return _inherit;
            }
            set
            {
                _inherit = value;
            }
        }

        public bool? IsDrawnUnder
        {
            get
            {
                return _isDrawnUnder;
            }
            set
            {
                _isDrawnUnder = value;
            }
        }

        public int Number
        {
            get
            {
                return _number;
            }
            set
            {
                _number = value;
            }
        }

        public IndicatorStyle? Style
        {
            get
            {
                return _style;
            }
            set
            {
                _style = value;
            }
        }

        #endregion Properties
    }
}


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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Open SCAP Library: elements.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Open SCAP Library

Main Page

Related Pages

Modules

Data Structures

Files

File List

Globals

src

common

common/elements.h

    1

    5

   26

   27 #ifndef OSCAP_ELEMENTS_H_

   28 #define OSCAP_ELEMENTS_H_

   29

   30 #include <libxml/xmlreader.h>

   31 #include <libxml/xmlwriter.h>

   32 #include <stdbool.h>

   33 #include <time.h>

   34 #include "public/oscap.h"

   35 #include "util.h"

   36

   37 #define OSCAP_XMLNS_XSI BAD_CAST "http://www.w3.org/2001/XMLSchema-instance"

   38

   40 extern const struct oscap_string_map OSCAP_BOOL_MAP[];

   41

   42 typedef void (*oscap_xml_value_consumer) (char *, void *);

   43 int oscap_parser_text_value(xmlTextReaderPtr reader, oscap_xml_value_consumer consumer, void *user);

   44 void oscap_text_consumer(char *text, void *user);

   45

   47 bool oscap_to_start_element(xmlTextReaderPtr reader, int depth);

   49 char *oscap_element_string_copy(xmlTextReaderPtr reader);

   51 const char *oscap_element_string_get(xmlTextReaderPtr reader);

   53 int oscap_element_depth(xmlTextReaderPtr reader);

   55 char *oscap_get_xml(xmlTextReaderPtr reader);

   57 time_t oscap_get_date(const char *date);

   59 time_t oscap_get_datetime(const char *date);

   61 xmlNode *oscap_xmlstr_to_dom(xmlNode *parent, const char *elname, const char *content);

   62

   69 int oscap_xml_save_filename(const char *filename, xmlDocPtr doc);

   70

   77 int oscap_xml_save_filename_free(const char *filename, xmlDocPtr doc);

   78

   79 xmlNs *lookup_xsi_ns(xmlDoc *doc);

   80

   81 #endif

oscap.h

General OpenScap functions and types.

oscap_string_map

Define mapping between symbolic constant and its string representation.

Definition: util.h:309

<address class="footer">
Generated by

 1.8.6
</address>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Holm & Nannfeldt, Thunbergia 11: 7, no. 3367 (1990)

#### Original name
Hysteropezizella holmii Svrcek

### Remarks
null


text:
package javasmmr.zoosome.models.animals;

public enum WaterType {
	SALTWATER, FRESHWATER;
}


text:
package com.acg12.service.impl;

import com.acg12.entity.po.Acg12PersonDetailEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.acg12.dao.Acg12PersonDetailDao;
import com.acg12.service.Acg12PersonDetailService;
import java.util.List;
/**
 * SERVICE - Acg12PersonDetail(personDetail)
 *
 * @author kcj
 * @version 2.0
 */
@Service
public class Acg12PersonDetailServiceImpl extends GenericServiceImpl<Acg12PersonDetailEntity, Long> implements Acg12PersonDetailService {

	@Autowired
	private Acg12PersonDetailDao acg12PersonDetailDao;

	@Autowired
	public void setGenericDao() {
		super.setGenericDao(acg12PersonDetailDao);
	}

	public List<Acg12PersonDetailEntity> findListByPage(Object parameter){
		return acg12PersonDetailDao.findListByPage(parameter);
	}

	public List<Acg12PersonDetailEntity> findListNewByPage(Object parameter) {
		return acg12PersonDetailDao.findListNewByPage(parameter);
	}

	public Long deletes(Object parameter){
		return acg12PersonDetailDao.deletes( parameter);
	}

}


text:
DEPS = [
  'build',
  'infra',
  'recipe_engine/context',
  'recipe_engine/file',
  'recipe_engine/path',
  'recipe_engine/properties',
  'recipe_engine/python',
  'recipe_engine/raw_io',
  'recipe_engine/step',
  'checkout',
  'flavor',
  'run',
  'vars',
]

def RunSteps(api):
  # Checkout, compile, etc.
  api.vars.setup()
  checkout_root = api.checkout.default_checkout_root
  api.checkout.bot_update(checkout_root=checkout_root)
  api.file.ensure_directory('makedirs tmp_dir', api.vars.tmp_dir)
  api.flavor.setup()

  cwd = api.path['checkout']

  with api.context(cwd=cwd):
    # Get a baseline diff. This should be empty, but we want to be flexible for
    # cases where we have local diffs on purpose.
    diff1 = api.run(
        api.step,
        'git diff #1',
        cmd=['git', 'diff', '--no-ext-diff'],
        stdout=api.m.raw_io.output()).stdout

    with api.context(env=api.infra.go_env):
      api.step('generate gl interfaces',
               cmd=['make', '-C', 'tools/gpu/gl/interface', 'generate'])

    # Touch all .fp files so that the generated files are rebuilt.
    api.run(
        api.python.inline,
        'touch fp files',
        program="""import os
import subprocess

for r, d, files in os.walk('%s'):
  for f in files:
    if f.endswith('.fp'):
      path = os.path.join(r, f)
      print 'touch %%s' %% path
      subprocess.check_call(['touch', path])
""" % cwd)

    # Regenerate the SKSL files.
    api.build(checkout_root=checkout_root,
              out_dir=api.vars.build_dir.join('out', 'Release'))

    # Get a second diff. If this doesn't match the first, then there have been
    # modifications to the generated files.
    diff2 = api.run(
        api.step,
        'git diff #2',
        cmd=['git', 'diff', '--no-ext-diff'],
        stdout=api.m.raw_io.output()).stdout

    api.run(
        api.python.inline,
        'compare diffs',
        program="""
diff1 = '''%s'''

diff2 = '''%s'''

if diff1 != diff2:
  print 'Generated files have been edited!'
  exit(1)
""" % (diff1, diff2))

def GenTests(api):
  yield (
      api.test('Housekeeper-PerCommit-CheckGeneratedFiles') +
      api.properties(buildername='Housekeeper-PerCommit-CheckGeneratedFiles',
                     repository='https://skia.googlesource.com/skia.git',
                     revision='abc123',
                     path_config='kitchen',
                     swarm_out_dir='[SWARM_OUT_DIR]') +
      api.path.exists(api.path['start_dir'])
  )


text:
#ifndef sstmac_hardware_network_topology_routing_VALIANT_ROUTER_H
#define sstmac_hardware_network_topology_routing_VALIANT_ROUTER_H

#include <sstmac/hardware/router/minimal_routing.h>

namespace sstmac {
namespace hw {

/**
 * @brief The valiant_router class
 * Enacpsulates a router that performs oblivious, global routing according to
 * "A Scheme for Fast Parallel Computation" by Valiant.
 */
class valiant_router : public minimal_router
{
  FactoryRegister("valiant", router, valiant_router,
              "router implementing valiant routing")
 public:
  valiant_router(sprockit::sim_parameters* params,
                 topology* top, network_switch* netsw,
                 routing::algorithm_t algo = routing::valiant);

  virtual ~valiant_router() { }

  virtual void route(packet* pkt) override;

  virtual std::string to_string() const override {
    return "valiant";
  }

  /**
    The topology object specifies a virtual channel based purely on geometry.
    However, the final virtual channel depends on both geometry and
    routing algorithm.  In this case, we need a separate set of
    virtual channels depending on whether we are in the first
    stage (routing to the intermediate switch) or the second stage
    (routing to the final switch).
    @param topology_vc The geometry-specific virtual channel
    @return The first stage virtual channel
  */
  virtual int first_stage_vc(int topology_vc) const {
    return 2*topology_vc;
  }

  /**
    The topology object specifies a virtual channel based purely on geometry.
    However, the final virtual channel depends on both geometry and
    routing algorithm.  In this case, we need a separate set of
    virtual channels depending on whether we are in the first
    stage (routing to the intermediate switch) or the second stage
    (routing to the final switch).
    @param topology_vc The geometry-specific virtual channel
    @return The second stage virtual channel
  */
  virtual int second_stage_vc(int topology_vc) const {
    return 2*topology_vc + 1;
  }

 protected:
  typedef enum {
    eject,
    minimal,
    intermediate_switch,
    final_node
  } next_action_t;

  /**
   * @brief intermediate_step
   * @param rtbl  The routing interface with path information
   * @param pkt   The packet corresponding to the structured_routable
   * @return The next action to take. It may be intermediate_switch or
   * final_node depending on whether the intermediate switch has been
   * reached or not.
   */
  next_action_t intermediate_step(routable* rtbl, packet* pkt);

  /**
   Different for pure valiant and UGAL.
   */
  virtual next_action_t initial_step(routable* rtbl, packet* pkt);

  /**
   * @brief next_routing_stage
   * Figure out which action is required for the packet
   * @param pkt The packet being routed
   * @return It may be intermediate_switch or
   * final_node depending on whether the intermediate switch has been
   * reached or not. Or it may be minimal if the packet is still on
   * the minimal path and has not switched to Valiant.
   */
  next_action_t next_routing_stage(packet* pkt);

  /**
   * @brief configure_intermediate_path
   * Once the packet has switched to Valiant, compute a path to the
   * chosen intermediate switch
   * @param path
   */
  void configure_intermediate_path(routable::path& path);

  /**
   * @brief configure_final_path
   * Once the packet has switched to Valiant and reached the intermediate switch,
   * compute a path to the final ejection switch
   * @param path
   */
  void configure_final_path(routable::path& path);

  /**
   * @brief route_valiant
   * Figure out if in intermediate or final stage and make appropriate routing computation
   * @param pkt
   */
  void route_valiant(packet* pkt);

};

}
}

#endif // VALIANT_ROUTER_H