text:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QtWebEngine/QtWebEngine"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
//    r1("/vrpn_client_node/RigidBody1/pose"),
//    x(1),y(1)
      ,x(10),y(10)
{
     ui->setupUi(this);
     this->setWindowTitle("plottest");

    getRosTopics(topic_list);
    for(ros::master::V_TopicInfo::iterator it=topic_list.begin();it!=topic_list.end();it++)
    {
      ros::master::TopicInfo& info = *it;
      if(info.name.compare(0,5,"/vrpn")==0)
      {
        rigidbody_list.push_back(info.name);
      }
    }
    for(int i=0;i<rigidbody_list.size();i++)
    {
      rigidbody_group.push_back(new rigidbody(rigidbody_list[i]));
    }
    /*

    ui->customplot->graph(0)->setLineStyle(QCPGraph::LineStyle::lsNone);
    ui->customplot->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle);
    */
   //ui->customplot->addGraph();

    for(int i=0;i<10;i++)
    {
      ui->customplot->addGraph();
    }

    ui->customplot->xAxis->setLabel("x");
    ui->customplot->yAxis->setLabel("y");

    // set axes ranges, so we see all data:
    ui->customplot->xAxis->setRange(-3, 3);
    ui->customplot->yAxis->setRange(-3, 3);

    for(int i=0;i<50;i++)
    {
      ros::spinOnce();
    }

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()),this, SLOT(sub_loop()));
    //looprate
    timer->start(10);

}

MainWindow::~MainWindow()
{
    delete ui;
  delete timer;

}
void MainWindow::sub_loop()
{
  //count++;
  if(ros::ok())
  {

     ros::spinOnce();
     ui->customplot->graph(0)->setPen(QPen(Qt::red));
     ui->customplot->graph(1)->setPen(QPen(Qt::black));
     ui->customplot->graph(2)->setPen(QPen(Qt::blue));
     ui->customplot->graph(3)->setPen(QPen(Qt::darkGreen));

     for(int i=0;i<rigidbody_group.size();i++)
     {
         x[i].push_back(rigidbody_group[i]->data.x);
         y[i].push_back(rigidbody_group[i]->data.y);
         ui->customplot->graph(i)->setLineStyle(QCPGraph::LineStyle::lsNone);
         ui->customplot->graph(i)->setScatterStyle(QCPScatterStyle::ssCircle);
         ui->customplot->graph(i)->setData(x[i], y[i]);

     }
     if(x[0].size()>400)
     {
       for(int i=0;i<rigidbody_group.size();i++)
       {
//           x[i].push_back(rigidbody_group[i]->data.x);
//           y[i].push_back(rigidbody_group[i]->data.y);
         x[i].pop_front();
         y[i].pop_front();
       }
     }

    ui->customplot->xAxis->setLabel("x");
    ui->customplot->yAxis->setLabel("y");
    ui->customplot->replot();
  }
  else
  {
     QApplication::quit();
  }
}

bool MainWindow::getRosTopics(ros::master::V_TopicInfo& topics){
    XmlRpc::XmlRpcValue args, result, payload;
    args[0] = ros::this_node::getName();
    std::string str;
    if (!ros::master::execute("getTopicTypes", args, result, payload, true)){
        std::cout << "Failed!" << std::endl;
        return false;
    }

    topics.clear();
    for (int i = 0; i < payload.size(); ++i)
        topics.push_back(ros::master::TopicInfo(std::string(payload[i][0]), std::string(payload[i][1])));
    return true;
}

redpajama_set_name: RedPajamaGithub


text:
package com.jesson.android.internet.core.json;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *
 * JsonCreator, in order to declare constructor that use @JsonProperty as
 * parameters.
 *
 * Java Bean with multiple JsonCreators, the last one will be used.
 *
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.CONSTRUCTOR })
public @interface JsonCreator {
	// No value
}


text:
// Copyright (c) Intel Corporation 2008.
// Copyright (c) 2008-2012 Simonson Lucanus.
// Copyright (c) 2012-2012 Andrii Sydorchuk.

// See http://www.boost.org for updates, documentation, and revision history.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_POLYGON_SEGMENT_DATA_HPP
#define BOOST_POLYGON_SEGMENT_DATA_HPP

#include "isotropy.hpp"
#include "segment_concept.hpp"

namespace boost {
namespace polygon {

template <typename T>
class segment_data {
 public:
  typedef T coordinate_type;
  typedef point_data<T> point_type;

  segment_data()
#ifndef BOOST_POLYGON_MSVC
    : points_()
#endif
  {}

  segment_data(const point_type& low, const point_type& high) {
    points_[LOW] = low;
    points_[HIGH] = high;
  }

  segment_data(const segment_data& that) {
    points_[0] = that.points_[0];
    points_[1] = that.points_[1];
  }

  segment_data& operator=(const segment_data& that) {
    points_[0] = that.points_[0];
    points_[1] = that.points_[1];
    return *this;
  }

  template <typename SegmentType>
  segment_data& operator=(const SegmentType& that) {
    assign(*this, that);
    return *this;
  }

  point_type get(direction_1d dir) const {
    return points_[dir.to_int()];
  }

  void set(direction_1d dir, const point_type& point) {
    points_[dir.to_int()] = point;
  }

  point_type low() const {
    return points_[LOW];
  }

  segment_data& low(const point_type& point) {
    points_[LOW] = point;
    return *this;
  }

  point_type high() const {
    return points_[HIGH];
  }

  segment_data& high(const point_type& point) {
    points_[HIGH] = point;
    return *this;
  }

  bool operator==(const segment_data& that) const {
    return (points_[0] == that.points_[0]) &&
           (points_[1] == that.points_[1]);
  }

  bool operator!=(const segment_data& that) const {
    return (points_[0] != that.points_[0]) ||
           (points_[1] != that.points_[1]);
  }

  bool operator<(const segment_data& that) const {
    if (points_[0] != that.points_[0]) {
      points_[0] < that.points_[0];
    }
    return points_[1] < that.points_[1];
  }

  bool operator<=(const segment_data& that) const {
    return !(that < *this);
  }

  bool operator>(const segment_data& that) const {
    return that < *this;
  }

  bool operator>=(const segment_data& that) const {
    return !((*this) < that);
  }

 private:
  point_type points_[2];
};

template <typename CType>
struct geometry_concept<segment_data<CType> > {
  typedef segment_concept type;
};
}  // polygon
}  // boost

#endif  // BOOST_POLYGON_SEGMENT_DATA_HPP


text:
package org.apache.karaf.scheduler.core;

import java.util.Date;

import org.apache.karaf.scheduler.Job;
import org.apache.karaf.scheduler.Scheduler;
import org.apache.karaf.scheduler.command.Schedule;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The quartz based implementation of the scheduler.
 *
 */
public class WhiteboardHandler {

    /** Default logger. */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private Scheduler scheduler;

    private ServiceTracker<?,?> serviceTracker;

    public WhiteboardHandler(final BundleContext context, Scheduler scheduler) throws InvalidSyntaxException {
        this.scheduler = scheduler;
        this.serviceTracker = new ServiceTracker<>(context,
                context.createFilter("(|(" + Constants.OBJECTCLASS + "=" + Runnable.class.getName() + ")" +
                        "(" + Constants.OBJECTCLASS + "=" + Job.class.getName() + "))"),
                new ServiceTrackerCustomizer<Object,Object>() {

                    public synchronized void  removedService(final ServiceReference reference, final Object service) {
                        context.ungetService(reference);
                        unregister(reference, service);
                    }

                    public synchronized void modifiedService(final ServiceReference reference, final Object service) {
                        unregister(reference, service);
                        register(reference, service);
                    }

                    public synchronized Object addingService(final ServiceReference reference) {
                        final Object obj = context.getService(reference);
                        if ( obj != null ) {
                            register(reference, obj);
                        }
                        return obj;
                    }
                });
        this.serviceTracker.open();
    }

    /**
     * Deactivate this component.
     */
    public void deactivate() {
        this.serviceTracker.close();
    }

    /**
     * Create unique identifier
     */
    private String getServiceIdentifier(final ServiceReference ref) {
        String name = (String) ref.getProperty(Scheduler.PROPERTY_SCHEDULER_NAME);
        if ( name == null ) {
            name = (String) ref.getProperty(Constants.SERVICE_PID);
            if ( name == null ) {
                name = "Registered Service";
            }
        }
        // now append service id to create a unique identifier
        name = name + "." + ref.getProperty(Constants.SERVICE_ID);
        return name;
    }

    /**
     * Register a job or task
     */
    private void register(final ServiceReference ref, final Object job) {
        final String name = getServiceIdentifier(ref);
        Boolean concurrent = true;
        if (ref.getProperty(Scheduler.PROPERTY_SCHEDULER_CONCURRENT) != null) {
            if (ref.getProperty(Scheduler.PROPERTY_SCHEDULER_CONCURRENT) instanceof Boolean) {
                concurrent = (Boolean) ref.getProperty(Scheduler.PROPERTY_SCHEDULER_CONCURRENT);
            } else {
                concurrent = new Boolean((String) ref.getProperty(Scheduler.PROPERTY_SCHEDULER_CONCURRENT));
            }
        }
        final String expression = (String) ref.getProperty(Scheduler.PROPERTY_SCHEDULER_EXPRESSION);
        try {
            if (expression != null) {
                this.scheduler.schedule(job, this.scheduler.EXPR(expression)
                        .name(name)
                        .canRunConcurrently(concurrent));
            } else {
                Integer times = -1;
                {
                    final Object v = ref.getProperty(Scheduler.PROPERTY_SCHEDULER_TIMES);
                    if (null != v) {
                        if (v instanceof Integer) {
                            times = (Integer) v;
                        } else if (v instanceof Long) {
                            times = ((Long) v).intValue();
                        } else if (v instanceof Number) {
                            times = ((Number) v).intValue();
                        } else {
                            times = new Integer(v.toString());
                        }
                    }
                }

                Long period = null;
                if (ref.getProperty(Scheduler.PROPERTY_SCHEDULER_PERIOD) != null) {
                    if (ref.getProperty(Scheduler.PROPERTY_SCHEDULER_PERIOD) instanceof Long) {
                        period = (Long) ref.getProperty(Scheduler.PROPERTY_SCHEDULER_PERIOD);
                    } else {
                        period = new Long((String) ref.getProperty(Scheduler.PROPERTY_SCHEDULER_PERIOD));
                    }
                    if (period < 1) {
                        this.logger.debug("Ignoring service {} : scheduler period is less than 1.", ref);
                    } else if (times < -1) {
                        this.logger.debug("Ignoring service {} : scheduler times is defined but is less than -1.", ref);
                    } else {
                        boolean immediate = false;
                        if (ref.getProperty(Scheduler.PROPERTY_SCHEDULER_IMMEDIATE) != null) {
                            if (ref.getProperty(Scheduler.PROPERTY_SCHEDULER_IMMEDIATE) instanceof Boolean) {
                                immediate = (Boolean) ref.getProperty(Scheduler.PROPERTY_SCHEDULER_IMMEDIATE);
                            } else {
                                immediate = new Boolean((String) ref.getProperty(Scheduler.PROPERTY_SCHEDULER_IMMEDIATE));
                            }
                        }
                        final Date date = new Date();
                        if (!immediate) {
                            date.setTime(System.currentTimeMillis() + period * 1000);
                        }
                        this.scheduler.schedule(job, this.scheduler.AT(date, times, period)
                                .name(name)
                                .canRunConcurrently((concurrent != null ? concurrent : true)));
                    }
                } else {
                    this.logger.debug("Ignoring service {} : no scheduling property found.", ref);
                }
            }
        } catch (Exception e) {
            logger.warn("Error scheduling job", e);
        }
    }

    /**
     * Unregister a service.
     */
    private void unregister(final ServiceReference reference, final Object service) {
        final String name = getServiceIdentifier(reference);
        this.scheduler.unschedule(name);
    }
}


text:
var _ = require('underscore');

module.exports = function(robot){

	robot.annoy = {
		greeting: 'Hey, want to hear the most annoying sound in the world?',
		salutation: 'Alright... alright.  I\'m done.',
		sessions: {},
		restrictedChannels: [ 'general', 'random', 'boc-events', 'boc-women' ], // Channels we don't ever want annoyed
		sound: {
			chars: ['A', 'E', 'I', 'G', 'H', 'E'],  // Characters that comprise the sound text
			charOccurrenceRates: [
				{ char: 'A', min: 10, max: 15 },
				{ char: 'E', min: 15, max: 20 },
				{ char: 'I', min: 8, max: 12 },
				{ char: 'G', min: 3, max: 9 },
				{ char: 'H', min: 10, max: 15 }
			]
		},
		timeUnitMsMap: {
			hour: 3600000,
			minute: 60000,
			second: 1000
		},

		makeSound: function(){
			var sound = '';
			_.each(this.sound.chars, function(char){
				var rate = _.where(robot.annoy.sound.charOccurrenceRates, { char: char })[0];
				var random = Math.floor(Math.random() * (rate.max - rate.min)) + rate.min;

				for (var i = 0; i < random; i++){
					sound += char;
				}
			});
			return sound;
		},

		start: function(room, annoyer, intervalMs, durationMs){
			var self = this,
				intervalLength = intervalMs || 2500,	  // 2.5 seconds if interval isn't specified
				durationLength = durationMs || 1000 * 45; // 45 Seconds if duration is not specified

			if (_.contains(this.restrictedChannels, room))
				return;

			// Send greeting
			robot.messageRoom(room, this.greeting);

			// Start annoying
			var interval = setInterval(function(){
				robot.messageRoom(room, self.makeSound());
			}, intervalLength);

			// Create annoy session
			var session = {
				interval: interval,
				annoyer: annoyer
			};

			// Save annoy session so we can clear it later
			this.sessions[room] = session;

			// Set clearInterval to execute and clear the annoy session at the appropriate time
			setTimeout(function(){
				var session = robot.annoy.sessions[room];
				clearInterval(session.interval);
				delete robot.annoy.sessions[room];
				robot.messageRoom(room, robot.annoy.salutation);
			}, durationLength);
		},

		stop: function(room, requester){
			var session = this.sessions[room];

			var isUserCurrentlyBeingAnnoyed = room === requester.room;
			// If the person requesting stop is the person who started the annoy session or an admin,
			// clear the session
			if (isUserCurrentlyBeingAnnoyed || robot.auth.isAdmin(requester) || requester.name === session.annoyer){
				clearInterval(session.interval);
				delete this.sessions[room];
			}
		},

		stopAll: function(){
			// Loop through all the current annoy sessions and clear them
			_.each(robot.annoy.sessions, function(session){
				clearInterval(session.interval);
			});
			this.sessions = {};
		}
	};

	// This function tries its best to match all common language scheduling syntaxes
	// For example:
	//	annoy me
	// 	annoy me for 10 minutes
	// 	annoy me every 10 minutes
	// 	annoy me every minute for 30 minutes
	// 	annoy me every 10 minutes for 2 hours
	// 	annoy me every minute for an hour
	// 	annoy me every 10 minutes for an hour
	// 	annoy me every minute for an hour
	// 	annoy me every second for a minute
	robot.respond(/annoy me( every (\d+)?( )?(second(s)?|minute(s)?|hour(s)?))?( for (a|an|\d+)? (second(s)?|minute(s)?|hour(s)?)+)?/i, function(res){
		var intervalTime = res.match[2] || '',
			intervalUnit = res.match[4] || '',
			intervalIsPlural = res.match[5] || res.match[6] || res.match[7],
			durationTime = res.match[9] || '',
			durationUnit = res.match[10] || '',
			durationIsPlural = res.match[11] || res.match[12] || res.match[13],
			intervalMs,
			durationMs;

		// Figure out interval time in milliseconds
		if (intervalTime && intervalUnit){
			var timeFactor = robot.annoy.timeUnitMsMap[intervalUnit.toLowerCase()];

			if (/a/i.test(intervalTime)) // 'a' or 'an' so we assume 1 unit
				intervalMs = timeFactor;
			else
				intervalMs = timeFactor * intervalTime;
		}

		// Figure out duration time in milliseconds
		if (durationTime && durationUnit){
			var timeFactor = robot.annoy.timeUnitMsMap[durationUnit.toLowerCase()];
			if (/a/i.test(durationTime))
				durationMs = timeFactor;
			else
				durationMs = timeFactor * durationTime;
		}

		// Start annoying
		robot.annoy.start(res.message.user.name, intervalMs, durationMs, res.message.user.name);
	});

	robot.respond(/annoy (.*)/i, function(res){
		var user = res.match[1];
		if (!user)
			res.reply('You must specify a user or channel');
		else{
			user = user.trim();
			if (user[0] === '@' || user[0] === '#')
				user = user.substring(1);
		}

		robot.annoy.start(user, res.message.user.name);
	});

	robot.respond(/stop annoying (.*)/i, function(res){
		var room = res.match[1];
		if (!room)
			res.reply('You must specify a room');
		else{
			room = room.trim();
			if (room === 'me')
				room = res.message.user.name;
			if (room[0] === '#' || room[0] === '@')
				room = room.substring(1);
		}

		robot.annoy.stop(room, res.message.user);
	});

	robot.respond(/stop all annoyances/i, function(res){
		if (!robot.auth.isAdmin(res.message.user))
			return;

		robot.annoy.stopAll();
	});

	robot.respond(/current annoyances/i, function(res){
		var ret = [];
		_.each(robot.annoy.sessions, function(value, key){
			ret.push(key + ' is being annoyed by ' + value.annoyer);
		});

		if (ret.length > 0)
			res.send(ret.join('\n'));
		else
			res.send('I am not annoying anyone at this time');
	});
}


text:
using Globals;
using Softv.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace SoftvWCFService.Contracts
{
    [ServiceContract]
    public interface IPregunta
    {
        [OperationContract]
        PreguntaEntity GetPregunta(int? IdPregunta);
        [OperationContract]
        PreguntaEntity GetDeepPregunta(int? IdPregunta);
        [OperationContract]
        IEnumerable<PreguntaEntity> GetPreguntaList();
        [OperationContract]
        SoftvList<PreguntaEntity> GetPreguntaPagedList(int page, int pageSize);
        [OperationContract]
        SoftvList<PreguntaEntity> GetPreguntaPagedListXml(int page, int pageSize, String xml);
        //[OperationContract]
        //int AddPregunta(PreguntaEntity objPregunta);
        [OperationContract]
        int UpdatePregunta(string xml);
        [OperationContract]
        int DeletePregunta(int? IdPregunta);

        [OperationContract]
        int AddPregunta(string data);

    }
}


text:
package githttp

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path"
	"strings"
)

const (
	uploadPack  = "upload-pack"
	receivePack = "receive-pack"
)

// GitHTTP is an http.Handler that knows how to serve the git protocol over HTTP
type GitHTTP struct {
	// Root directory to serve repos from
	ProjectRoot string

	// Path to git binary
	GitBinPath string

	// Access rules
	UploadPack  bool
	ReceivePack bool

	// Event handling functions
	EventHandler func(ev Event)

	// FillRepo is called when a repository is not found. This function has the chance to get it from somewhere else.
	// If this returns an error or is nil, then the git operation will fail
	FillRepo func(string) error
}

// Implement the http.Handler interface
func (g *GitHTTP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	requestHandler(g, w, r)
	return
}

// New is the shorthand constructor for most common scenario
func New(root string) *GitHTTP {
	return &GitHTTP{
		ProjectRoot: root,
		GitBinPath:  "/usr/bin/git",
		UploadPack:  true,
		ReceivePack: true,
	}
}

// Init builds the root directory if doesn't exist
func (g *GitHTTP) Init() (*GitHTTP, error) {
	if err := os.MkdirAll(g.ProjectRoot, os.ModePerm); err != nil {
		return nil, err
	}
	return g, nil
}

// Publish event if EventHandler is set
func (g *GitHTTP) event(e Event) {
	if g.EventHandler != nil {
		g.EventHandler(e)
	}
}

// Actual command handling functions

func (g *GitHTTP) serviceRPC(hr HandlerReq) error {
	access, err := g.hasAccess(hr.r, hr.Dir, hr.RPC, true)
	if err != nil {
		return err
	}

	if access == false {
		return &ErrorNoAccess{hr.Dir}
	}

	// Reader that decompresses if necessary
	reader, err := requestReader(hr.r)
	if err != nil {
		return err
	}
	defer reader.Close()

	// Reader that scans for events
	rpcReader := &RpcReader{
		Reader: reader,
		Rpc:    hr.RPC,
	}

	// Set content type
	hr.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", hr.RPC))

	args := []string{hr.RPC, "--stateless-rpc", "."}
	cmd := exec.Command(g.GitBinPath, args...)
	cmd.Dir = hr.Dir
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return err
	}
	defer stdin.Close()

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}
	defer stdout.Close()

	err = cmd.Start()
	if err != nil {
		return err
	}

	// Scan's git command's output for errors
	gitReader := &GitReader{
		Reader: stdout,
	}

	// Copy input to git binary
	io.Copy(stdin, rpcReader)

	// Write git binary's output to http response
	io.Copy(hr.w, gitReader)

	// Wait till command has completed
	mainError := cmd.Wait()

	if mainError == nil {
		mainError = gitReader.GitError
	}

	// Fire events
	for _, e := range rpcReader.Events {
		// Set directory to current repo
		e.Dir = hr.Dir
		e.Request = hr.r
		e.Error = mainError

		// Fire event
		g.event(e)
	}

	// May be nil if all is good
	return mainError
}

func (g *GitHTTP) getInfoRefs(hr HandlerReq) error {
	serviceName := getServiceType(hr.r)
	access, err := g.hasAccess(hr.r, hr.Dir, serviceName, false)
	if err != nil {
		return err
	}

	if !access {
		g.updateServerInfo(hr.Dir)
		hdrNocache(hr.w)
		return sendFile("text/plain; charset=utf-8", hr)
	}

	refs, err := g.gitCommand(hr.Dir, serviceName, "--stateless-rpc", "--advertise-refs", hr.Dir)
	if err != nil {
		return err
	}

	hdrNocache(hr.w)
	hr.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", serviceName))
	hr.w.WriteHeader(http.StatusOK)
	hr.w.Write(packetWrite("# service=git-" + serviceName + "\n"))
	hr.w.Write(packetFlush())
	hr.w.Write(refs)

	return nil
}

func (g *GitHTTP) getInfoPacks(hr HandlerReq) error {
	hdrCacheForever(hr.w)
	return sendFile("text/plain; charset=utf-8", hr)
}

func (g *GitHTTP) getLooseObject(hr HandlerReq) error {
	hdrCacheForever(hr.w)
	return sendFile("application/x-git-loose-object", hr)
}

func (g *GitHTTP) getPackFile(hr HandlerReq) error {
	hdrCacheForever(hr.w)
	return sendFile("application/x-git-packed-objects", hr)
}

func (g *GitHTTP) getIdxFile(hr HandlerReq) error {
	hdrCacheForever(hr.w)
	return sendFile("application/x-git-packed-objects-toc", hr)
}

func (g *GitHTTP) getTextFile(hr HandlerReq) error {
	hdrNocache(hr.w)
	return sendFile("text/plain", hr)
}

// Logic helping functions

func sendFile(contentType string, hr HandlerReq) error {
	w, r := hr.w, hr.r
	reqFile := path.Join(hr.Dir, hr.File)

	f, err := os.Stat(reqFile)
	if err != nil {
		return err
	}

	w.Header().Set("Content-Type", contentType)
	w.Header().Set("Content-Length", fmt.Sprintf("%d", f.Size()))
	w.Header().Set("Last-Modified", f.ModTime().Format(http.TimeFormat))
	http.ServeFile(w, r, reqFile)

	return nil
}

func (g *GitHTTP) getGitDir(filePath string) (string, error) {
	root := g.ProjectRoot

	if root == "" {
		cwd, err := os.Getwd()

		if err != nil {
			return "", err
		}

		root = cwd
	}

	f := path.Join(root, filePath)
	_, statErr := os.Stat(f)
	if statErr != nil && !os.IsNotExist(statErr) {
		return "", statErr
	}
	if statErr != nil && g.FillRepo == nil {
		return "", statErr
	}
	if statErr != nil {
		if err := g.FillRepo(f); err != nil {
			return "", err
		}
	}
	return f, nil
}

func (g *GitHTTP) hasAccess(r *http.Request, dir string, rpc string, checkContentType bool) (bool, error) {
	if checkContentType {
		if r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", rpc) {
			return false, nil
		}
	}

	if !(rpc == uploadPack || rpc == receivePack) {
		return false, nil
	}
	if rpc == receivePack {
		return g.ReceivePack, nil
	}
	if rpc == uploadPack {
		return g.UploadPack, nil
	}

	return g.getConfigSetting(rpc, dir)
}

func (g *GitHTTP) getConfigSetting(service_name string, dir string) (bool, error) {
	service_name = strings.Replace(service_name, "-", "", -1)
	setting, err := g.getGitConfig("http."+service_name, dir)
	if err != nil {
		return false, nil
	}

	if service_name == "uploadpack" {
		return setting != "false", nil
	}

	return setting == "true", nil
}

func (g *GitHTTP) getGitConfig(configName string, dir string) (string, error) {
	args := []string{"config", configName}
	out, err := g.gitCommand(dir, args...)
	if err != nil {
		return "", err
	}
	return string(out)[0 : len(out)-1], nil
}

func (g *GitHTTP) updateServerInfo(dir string) ([]byte, error) {
	args := []string{"update-server-info"}
	return g.gitCommand(dir, args...)
}

func (g *GitHTTP) gitCommand(dir string, args ...string) ([]byte, error) {
	command := exec.Command(g.GitBinPath, args...)
	command.Dir = dir
	out, err := command.CombinedOutput()
	if err != nil {
		return nil, newCmdErr(command, out, err)
	}
	return out, nil
}


text:
/*
Query the list of CITY names from STATION that either do not start with vowels or do not end with vowels.
Your result cannot contain duplicates.
*/

select distinct city from station
where lower(substr(CITY,length(CITY),1)) not in ('a','e','i','o','u')
and lower(substr(CITY, 1, 1)) not in ('a', 'e', 'i', 'o', 'u');


text:
"""Event timezone

Revision ID: 55097480a655
Revises: 3a6b2ab00e3e
Create Date: 2013-11-09 15:53:48.318340

"""

# revision identifiers, used by Alembic.
revision = '55097480a655'
down_revision = '3a6b2ab00e3e'

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('proposal_space', sa.Column('timezone', sa.Unicode(length=40), nullable=False, server_default=u'UTC'))
    op.alter_column('proposal_space', 'timezone', server_default=None)

def downgrade():
    op.drop_column('proposal_space', 'timezone')


text:
import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const postSchema = new Schema({
  cuid: { type: 'String', required: true },
  uid: { type: 'String', required: true },
  name: { type: 'String', required: true },
  title: { type: 'String', required: true },
  content: { type: 'String', required: true },
  slug: { type: 'String', required: true },
  dateAdded: { type: 'Date', default: Date.now, required: true },
});

export default mongoose.model('Posts', postSchema);


text:
redis
=====

This role helps to deploy a Redis master or replication server on target host.
This roles sets several default values for Redis configuration which can be
overrriden by the user.

Requirements
------------

This role requires Ansible 1.4 or higher, and platform requirements are listed
in the metadata file.

Role Variables
--------------

The variables that can be passed to this role and a brief description about
them are as follows. See the documentation for Redis for details:

	redis_bind_address                # The network address for redis to bind to
        redis_port: 6379                  # Port for redis server
	redis_syslog_enabled: "yes"       # enable_syslog
	redis_databases: 16               # Set number of databases
	redis_database_save_times:        # Save the DB on disk (seconds changes)
	  - [900, 1]
	  - [300, 10]
	  - [60, 10000]
	redis_dbfilename: dump.rdb        # Filename for the db
	redis_db_dir: /var/lib/redis      # DB directory
	redis_role: master                # The role for this redis deployment (master/slave)
	redis_requirepass: false          # If password is required for querying
	redis_pass: None                  # Password if require_pass is enabled
	redis_max_clients: 128
	redis_max_memory: 512mb
	redis_maxmemory_policy: volatile-lru
	redis_appendfsync: everysec       # How often to sync the filesystem

	# If redis_role is "slave", set these values too
	redis_master_ip: 1.1.1.1          # The master's IP
	redis_master_port: 6379           # master port
	redis_master_auth: None           # master auth

Examples
--------

The following example sets up a master Redis server.

	- hosts: all
	  sudo: true
	  roles:
	  - {role: bennojoy.redis, redis_port: 11244}

The following example sets up a slave Redis server.

	- hosts: all
	  sudo: true
	  roles:
	  - {role: bennojoy.redis,
	     redis_role: 'slave',
	     master_ip: '192.168.2.10',
	     master_auth: 'foobar'}

Dependencies
------------

None

License
-------

BSD

Author Information
------------------

Benno Joy


text:
function init()
dofile("mqtt_aclm.lua")
end

tmr.create():alarm(5000, tmr.ALARM_SINGLE, init)


text:
package gov.nih.nci.clinicalconnector.service.globus;

import gov.nih.nci.clinicalconnector.service.ClinicalConnectorImpl;

import java.rmi.RemoteException;

import org.springframework.web.context.support.XmlWebApplicationContext;

/**
 * DO NOT EDIT:  This class is autogenerated!
 *
 * This class implements each method in the portType of the service.  Each method call represented
 * in the port type will be then mapped into the unwrapped implementation which the user provides
 * in the ClinicalConnectorImpl class.  This class handles the boxing and unboxing of each method call
 * so that it can be correclty mapped in the unboxed interface that the developer has designed and
 * has implemented.  Authorization callbacks are automatically made for each method based
 * on each methods authorization requirements.
 *
 * @created by Introduce Toolkit version 1.3
 *
 */
public class ClinicalConnectorProviderImpl{

	ClinicalConnectorImpl impl;

	public ClinicalConnectorProviderImpl() throws RemoteException {
		XmlWebApplicationContext c = new XmlWebApplicationContext();
		c.setConfigLocation("classpath:applicationContext.xml");
		c.refresh();
		impl = (ClinicalConnectorImpl) c.getBean("clinicalConnectorService");
	}

    public gov.nih.nci.clinicalconnector.stubs.LoadLabsResponse loadLabs(gov.nih.nci.clinicalconnector.stubs.LoadLabsRequest params) throws RemoteException {
    gov.nih.nci.clinicalconnector.stubs.LoadLabsResponse boxedResult = new gov.nih.nci.clinicalconnector.stubs.LoadLabsResponse();
    boxedResult.setLoadLabsResponse(impl.loadLabs(params.getLoadLabsRequest().getLoadLabsRequest()));
    return boxedResult;
  }

    public gov.nih.nci.clinicalconnector.stubs.RegisterSubjectResponse registerSubject(gov.nih.nci.clinicalconnector.stubs.RegisterSubjectRequest params) throws RemoteException {
    gov.nih.nci.clinicalconnector.stubs.RegisterSubjectResponse boxedResult = new gov.nih.nci.clinicalconnector.stubs.RegisterSubjectResponse();
    boxedResult.setRegisterSubjectResponse(impl.registerSubject(params.getRegisterSubjectRequest().getRegisterSubjectRequest()));
    return boxedResult;
  }

}


text:
package mil.tatrc.physiology.biogears.engine;

import java.io.File;
import java.io.IOException;
import java.util.*;

import mil.tatrc.physiology.datamodel.bind.EnumAnatomy;
import mil.tatrc.physiology.datamodel.bind.EnumAnesthesiaMachine;
import mil.tatrc.physiology.datamodel.bind.EnumAnesthesiaMachineEvent;
import mil.tatrc.physiology.datamodel.bind.EnumInhaler;
import mil.tatrc.physiology.datamodel.bind.EnumPatientEvent;
import mil.tatrc.physiology.datamodel.compartment.*;
import mil.tatrc.physiology.datamodel.compartment.anatomy.SEAnatomyCompartments;
import mil.tatrc.physiology.datamodel.compartment.anesthesia.SEAnesthesiaMachineCompartments;
import mil.tatrc.physiology.datamodel.compartment.inhaler.SEInhalerCompartments;
import mil.tatrc.physiology.datamodel.patient.SEPatient;
import mil.tatrc.physiology.datamodel.patient.nutrition.SENutrition;
import mil.tatrc.physiology.datamodel.properties.*;
import mil.tatrc.physiology.datamodel.properties.CommonUnits.TimeUnit;
import mil.tatrc.physiology.datamodel.scenario.datarequests.*;
import mil.tatrc.physiology.datamodel.substance.SESubstance;
import mil.tatrc.physiology.datamodel.substance.SESubstanceCompartmentEffect;
import mil.tatrc.physiology.datamodel.substance.SESubstanceManager;
import mil.tatrc.physiology.datamodel.system.SESystem;
import mil.tatrc.physiology.datamodel.system.environment.*;
import mil.tatrc.physiology.datamodel.system.equipment.anesthesia.*;
import mil.tatrc.physiology.datamodel.system.equipment.electrocardiogram.*;
import mil.tatrc.physiology.datamodel.system.equipment.inhaler.*;
import mil.tatrc.physiology.datamodel.system.physiology.*;
import mil.tatrc.physiology.datamodel.utilities.SEEventHandler;
import mil.tatrc.physiology.utilities.FileUtils;
import mil.tatrc.physiology.utilities.Log;
import mil.tatrc.physiology.utilities.LogListener;
import mil.tatrc.physiology.utilities.Pair;
import mil.tatrc.physiology.utilities.UnitConverter;

public class BioGears
{
  public SEScalarTime                     timeStep = new SEScalarTime();
  public SEScalarTime                     currentTime = new SEScalarTime();

  public SESubstanceManager               substanceManager = new SESubstanceManager();
  public SEPatient                        patient = new SEPatient();
  // Physiology systems
  public SEBloodChemistrySystem           bloodChemistry = new SEBloodChemistrySystem();
  public SECardiovascularSystem           cardiovascular = new SECardiovascularSystem();
  public SEEndocrineSystem                endocrine = new SEEndocrineSystem();
  public SEEnergySystem                   energy = new SEEnergySystem();
  public SEGastrointestinalSystem         gastrointestinal = new SEGastrointestinalSystem();
  public SERenalSystem                    renal = new SERenalSystem();
  public SENervousSystem                  nervous = new SENervousSystem();
  public SERespiratorySystem              respiratory = new SERespiratorySystem();
  public SEDrugSystem                     drug = new SEDrugSystem();
  // Physiology compartments
  public SEAnatomyCompartments            anatomyCompartments = new SEAnatomyCompartments();
  // Environment
  public SEEnvironment                    environment = new SEEnvironment();
  // Anesthesia
  public SEAnesthesiaMachine              anesthesiaMachine = new SEAnesthesiaMachine();
  public SEAnesthesiaMachineCompartments  anesthesiaMachineCompartments = new SEAnesthesiaMachineCompartments();
  // ECG
  public SEElectroCardioGram              ecg = new SEElectroCardioGram();
  // Inhaler
  public SEInhaler                        inhaler = new SEInhaler();
  public SEInhalerCompartments            inhalerCompartments = new SEInhalerCompartments();

  protected CDMUpdatedCallback            cdmCallback;
  protected LogListener                   listener;
  protected SEEventHandler                eventHandler;

  protected long nativeObj;
  protected native long nativeAllocate(String logFile);
  protected native void nativeDelete(long nativeObj);

  protected List<Pair<SEDataRequest,SEScalar>> dataRequests = new ArrayList<Pair<SEDataRequest,SEScalar>>();

  public BioGears()
  {
    this.nativeObj=0;
    this.reset();

    // We need to copy engine files from user.dir to user.home because on mac
    // The working directory can the home directory depending on how you kick off the app
    // At that point, BioGears will not be able to find the files it needs
    // So we temporarily copy them, we will remove them when things are cleaned up
    try
    {
      FileUtils.copy(new File(System.getProperty("user.dir")  + "/config/"),
          new File(System.getProperty("user.home") + "/config/"));

      FileUtils.copy(new File(System.getProperty("user.dir")  + "/ecg/"),
          new File(System.getProperty("user.home") + "/ecg/"));

      FileUtils.copy(new File(System.getProperty("user.dir")  + "/patients/"),
          new File(System.getProperty("user.home") + "/patients/"));

      FileUtils.copy(new File(System.getProperty("user.dir")  + "/environments/"),
          new File(System.getProperty("user.home") + "/environments/"));

      FileUtils.copy(new File(System.getProperty("user.dir")  + "/xsd/"),
          new File(System.getProperty("user.home") + "/xsd/"));

      FileUtils.copy(new File(System.getProperty("user.dir")  + "/BioGearsConfiguration.xml"),
          new File(System.getProperty("user.home") + "/BioGearsConfiguration.xml"));
    }
    catch (IOException ex)
    {
      Log.warn("Could not copy BioGears files to user.home, BioGears may not execute propertly",ex);
    }

    List<String> files = FileUtils.findFiles(System.getProperty("user.dir"), "BioGearsEngineJNI", true);
    if(files.size()!=1)// Attempt to load and hope for the best...
      System.loadLibrary("BioGearsEngineJNI");
    else
      System.load(files.get(0));

    UnitConverter.initialize(System.getProperty("user.dir"));
  }

  public void finalize()
  {
    this.cleanUp();
  }

  public void reset()
  {
    currentTime.invalidate();
    substanceManager.loadSubstanceDirectory();
    patient.reset();
    bloodChemistry.reset();
    cardiovascular.reset();
    endocrine.reset();
    energy.reset();
    gastrointestinal.reset();
    renal.reset();
    nervous.reset();
    respiratory.reset();
    drug.reset();
    anatomyCompartments.reset();
    environment.reset();
    anesthesiaMachine.reset();
    anesthesiaMachineCompartments.reset();
    ecg.reset();
    inhaler.reset();
    inhalerCompartments.reset();
    cdmCallback=null;
    listener = null;
    eventHandler = null;
  }

  public void cleanUp()
  {
    this.reset();
    if(this.nativeObj!=0)
    {
      nativeDelete(this.nativeObj);
      this.nativeObj=0;
    }
    this.listener = null;
    FileUtils.delete(new File(System.getProperty("user.home") + "/config/"));
    FileUtils.delete(new File(System.getProperty("user.home") + "/ecg/"));
    FileUtils.delete(new File(System.getProperty("user.home") + "/patients/"));
    FileUtils.delete(new File(System.getProperty("user.home") + "/environments/"));
    FileUtils.delete(new File(System.getProperty("user.home") + "/xsd/"));
    FileUtils.delete(new File(System.getProperty("user.home") + "/BioGearsConfiguration.xml"));
  }

  public void setListener(LogListener listener)
  {
    this.listener = listener;
  }

  public void setEventHandler(SEEventHandler handler)
  {
    eventHandler = handler;
  }
  /**
   * C++ will call this method
   * @param type 0 = patient, 1 = anesthesia machine
   * @param event enumeration index
   * @param active if it's on or off
   */
  protected void handleEvent(int type, int event, boolean active, double time_s)
  {
    switch(type)
    {
      case 0:
        if(eventHandler!=null)
          eventHandler.handlePatientEvent(EnumPatientEvent.values()[event],active,new SEScalarTime(time_s,TimeUnit.s));
        this.patient.setEvent(EnumPatientEvent.values()[event],active);
        break;
      case 1:
        if(eventHandler!=null)
          eventHandler.handleAnesthesiaMachineEvent(EnumAnesthesiaMachineEvent.values()[event],active,new SEScalarTime(time_s,TimeUnit.s));
        this.anesthesiaMachine.setEvent(EnumAnesthesiaMachineEvent.values()[event],active);
        break;
      default:
          Log.error("Unsupported event type "+type);
    }
  }

  public List<Pair<SEDataRequest,SEScalar>> getDataRequestPairs()
  {
    return Collections.unmodifiableList(this.dataRequests);
  }

  protected void updateCDM(double time_s, double[] data)
  {
    int i=0;
    currentTime.setValue(time_s,TimeUnit.s);
    for(Pair<SEDataRequest,SEScalar> e : dataRequests)
    {
      e.getR().setValue(data[i++],e.getL().getUnit());
    }
    if(this.cdmCallback!=null)
      cdmCallback.update(time_s);
  }

  /**
   * You can provided a data request with out a unit
   * And the engine will update the request with what
   * ever it calculated the requested value in.
   * The method will be called to inform us what
   * unit the data given to updateCDM. If the data
   * request had a unit specified in the first place,
   * this will be the same, but if no unit was specified
   * in the data request, this information is needed
   * when putting the received value into is associated scalar.
   * @param units
   */
  protected void setCDMHeadings(String[] units)
  {
    int i=0;
    for(Pair<SEDataRequest,SEScalar> e : dataRequests)
    {
      // Rip out the units from the headings
      String unit = units[i++];
      int idx = unit.indexOf('(');
      if(idx > -1)
      {
        unit = unit.substring(idx+1, unit.length()-1);
        unit = unit.replace("_", " ");
        e.getL().setUnit(unit);
      }
      else
        e.getL().setUnit("");// Unitless
    }
  }

  // Process all the data requests, and map them to CDM scalars
  protected boolean requestData(List<SEDataRequest> drs)
  {
    // Gather our systems up into a list to make things easier
    List<SESystem> systems = new ArrayList<SESystem>();
    systems.add(bloodChemistry);
    systems.add(cardiovascular);
    systems.add(endocrine);
    systems.add(energy);
    systems.add(gastrointestinal);
    systems.add(renal);
    systems.add(nervous);
    systems.add(respiratory);
    systems.add(drug);
    systems.add(energy);

    List<SESystem> equipment = new ArrayList<SESystem>();
    equipment.add(anesthesiaMachine);
    equipment.add(ecg);
    equipment.add(inhaler);

    for(SEDataRequest dr : drs)
    {
      if(dr instanceof SEPhysiologySystemDataRequest)
      {
        SEScalar scalar = null;
        for (SESystem sys : systems)
        {
          scalar = SEScalar.getScalar(sys,dr.getName());
          if (scalar != null)
          {
            dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,scalar));
            break;
          }

          if (sys instanceof SEGastrointestinalSystem && dr.getName().startsWith("Stomach"))
          {
            String scalarNameWithoutStomach = dr.getName().substring(7);
            SENutrition nutrition = ((SEGastrointestinalSystem)sys).getNutrientsInStomach();

            scalar = SEScalar.getScalar(nutrition, scalarNameWithoutStomach);
            if (scalar != null)
            {
              dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,scalar));
              break;
            }
          }
        }
        if(scalar!=null)
          continue;
        Log.error("Unable to find system property " + dr.getName());
        return false;
      }
      else if(dr instanceof SEAnatomyCompartmentDataRequest)
      {
        SEAnatomyCompartmentDataRequest adr = (SEAnatomyCompartmentDataRequest)dr;
        SECompartment<EnumAnatomy> cmpt = anatomyCompartments.GetCompartment(adr.getCompartment(), adr.getType());
        if(adr.hasSubstance())
        {
          switch(adr.getType())
          {
            case CHYME:
              dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,SEScalar.getScalar(((SELiquidCompartment<EnumAnatomy>)cmpt).getSubstanceQuantity(adr.getSubstance()), dr.getName())));
              continue;
            case PULMONARY:
              dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,SEScalar.getScalar(((SEGasCompartment<EnumAnatomy>)cmpt).getSubstanceQuantity(adr.getSubstance()), dr.getName())));
              continue;
            case TISSUE:
              dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,SEScalar.getScalar(((SETissueCompartment<EnumAnatomy>)cmpt).getSubstanceQuantity(adr.getSubstance()), dr.getName())));
              continue;
            case URINE:
              dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,SEScalar.getScalar(((SELiquidCompartment<EnumAnatomy>)cmpt).getSubstanceQuantity(adr.getSubstance()), dr.getName())));
              continue;
            case VASCULAR:
              dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,SEScalar.getScalar(((SELiquidCompartment<EnumAnatomy>)cmpt).getSubstanceQuantity(adr.getSubstance()), dr.getName())));
              continue;
             default:
               Log.error("Unsupported substance data request for a compartment type " + adr.getType());
          }
        }
        else
        {
          dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,SEScalar.getScalar(cmpt, dr.getName())));
          continue;
        }
        Log.error("Unable to find anatomy property " + dr.getName());
        return false;
      }
      else if(dr instanceof SEPatientDataRequest)
      {
        String name = dr.getName();
        if(dr.getName().startsWith("Patient"))
          name = dr.getName().substring(7);
        SEScalar scalar = SEScalar.getScalar(this.patient, name);
        if (scalar != null)
        {
          dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,scalar));
          continue;
        }
        Log.error("Unable to find patient property " + dr.getName());
        return false;
      }
      else if(dr instanceof SESubstanceDataRequest)
      {
        SESubstanceDataRequest sdr = (SESubstanceDataRequest)dr;
        SESubstance sub = this.substanceManager.getSubstance(sdr.getSubstance().getName());
        if(sdr.hasCompartment())
        {
          SESubstanceCompartmentEffect subFX = sub.getAnatomyEffect(sdr.getCompartment());
          SEScalar scalar = SEScalar.getScalar(subFX, dr.getName());
          if (scalar != null)
          {
            dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,scalar));
            continue;
          }
        }
        else
        {
          SEScalar scalar = SEScalar.getScalar(sub, dr.getName());
          if (scalar != null)
          {
            dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,scalar));
            continue;
          }
        }
        Log.error("Unable to find substance property " + dr.getName());
        return false;
      }
      else if(dr instanceof SEEquipmentSystemDataRequest)
      {
        SEScalar scalar = null;
        for(SESystem equip : equipment)
        {
          scalar = SEScalar.getScalar(equip, dr.getName());
          if (scalar != null)
          {
            dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,scalar));
            break;
          }
        }
        if(scalar!=null)
          continue;
        Log.error("Unable to find equipment property " + dr.getName());
        return false;
      }
      else if(dr instanceof SEAnesthesiaMachineCompartmentDataRequest)
      {
        SEAnesthesiaMachineCompartmentDataRequest adr = (SEAnesthesiaMachineCompartmentDataRequest)dr;
        SEGasCompartment<EnumAnesthesiaMachine> cmpt = this.anesthesiaMachineCompartments.GetCompartment(adr.getCompartment());
        if(adr.hasSubstance())
        {
          dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,SEScalar.getScalar(cmpt.getSubstanceQuantity(adr.getSubstance()), dr.getName())));
          continue;
        }
        else
        {
          SEScalar scalar = SEScalar.getScalar(cmpt, dr.getName());
          if (scalar != null)
          {
            dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,scalar));
            continue;
          }
        }
        Log.error("Unable to find anesthesia machine compartment property " + dr.getName());
        return false;
      }
      else if(dr instanceof SEInhalerCompartmentDataRequest)
      {
        SEInhalerCompartmentDataRequest idr = (SEInhalerCompartmentDataRequest)dr;
        SEGasCompartment<EnumInhaler> cmpt = this.inhalerCompartments.GetCompartment(idr.getCompartment());
        if(idr.hasSubstance())
        {
          dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,SEScalar.getScalar(cmpt.getSubstanceQuantity(idr.getSubstance()), dr.getName())));
          continue;
        }
        else
        {
          SEScalar scalar = SEScalar.getScalar(cmpt, dr.getName());
          if (scalar != null)
          {
            dataRequests.add(new Pair<SEDataRequest,SEScalar>(dr,scalar));
            continue;
          }
        }
        Log.error("Unable to find inhaler compartment property " + dr.getName());
        return false;
      }
      else
      {
        Log.error("Unsupported data request type");
        return false;
      }
    }

    // Make sure nothing is mapped to null
    for(Pair<SEDataRequest,SEScalar> p : dataRequests)
    {
      if(p.getL()==null || p.getR()==null)
      {
        Log.error("We have an invalid data request pair");
        return false;
      }
    }
    return true;
  }

//TODO I could make origin, the Scenario/engine name we are running
 protected void LogDebug(String msg, String origin)
 {
   if(this.listener!=null)
     this.listener.handleDebug(msg, origin);
 }
 protected void LogInfo(String msg, String origin)
 {
   if(this.listener!=null)
     this.listener.handleInfo(msg, origin);
 }
 protected void LogWarning(String msg, String origin)
 {
   if(this.listener!=null)
     this.listener.handleWarn(msg, origin);
 }
 protected void LogError(String msg, String origin)
 {
   if(this.listener!=null)
     this.listener.handleError(msg, origin);
 }
 protected void LogFatal(String msg, String origin)
 {
   if(this.listener!=null)
     this.listener.handleFatal(msg, origin);
 }
}


text:
/*
 * PivotMDS.h
 *
 *  Created on: Jul 7, 2016
 *      Author: Michael Wegner (michael.wegner@student.kit.edu)
 */

#ifndef NETWORKIT_CPP_VIZ_PIVOTMDS_H_
#define NETWORKIT_CPP_VIZ_PIVOTMDS_H_

#include "GraphLayoutAlgorithm.h"

#include "../algebraic/CSRMatrix.h"
#include "../algebraic/Vector.h"

#include "../graph/Graph.h"

namespace NetworKit {

/**
 * @ingroup viz
 *
 * Implementation of PivotMDS proposed by Brandes and Pich.
 */
class PivotMDS : public GraphLayoutAlgorithm<double> {
public:
	/**
	 * Constructs a PivotMDS object for the given @a graph. The algorithm should embed the graph in @a dim dimensions
	 * using @a numPivots pivots.
	 * @param graph
	 * @param dim
	 * @param numPivots
	 */
	PivotMDS(const Graph& graph, count dim, count numPivots);

	/*
	 * Default destructor
	 */
	virtual ~PivotMDS() = default;

	/**
	 * Runs the PivotMDS algorithm.
	 */
	void run() override;

private:
	count dim;
	count numPivots;

	/**
	 *  Randomly picks the pivots for the algorithm
	 */
	std::vector<node> computePivots();

	/**
	 * Power method to compute the largest eigenvector and eigenvalue that are stored in @a eigenvector and
	 * @a eigenvalue.
	 */
	void powerMethod(const CSRMatrix& mat, const count n, Vector& eigenvector, double& eigenvalue);
};

} /* namespace NetworKit */

#endif /* NETWORKIT_CPP_VIZ_PIVOTMDS_H_ */


text:
ENV['RACK_ENV'] = 'test'
require 'minitest/autorun'
require 'rack/test'

require_relative File.expand_path '../../mailer.rb', __FILE__


text:
namespace malmo
{
    MissionRecord::MissionRecord(const MissionRecordSpec& spec)
        : spec(spec)
    {
        this->is_closed = false;
        if (spec.is_recording) {
            boost::filesystem::create_directories(this->spec.temp_dir);
        }
    }

    MissionRecord::~MissionRecord()
    {
        try {
            if (!this->is_closed) {
                this->close();
            }

        }
        catch (const std::exception& e) {
            // we don't really want to assume that is safe to write to cout but can't have destructors throwing exceptions
            std::cout << "Exception in closing of MissionRecord: " << e.what() << std::endl;
        }
        catch(...) {
            // we don't really want to assume that is safe to write to cout but can't have destructors throwing exceptions
            std::cout << "Unknown exception in closing of MissionRecord." << std::endl;
        }
    }

    MissionRecord::MissionRecord(MissionRecord&& record)
        : is_closed(record.is_closed)
        , spec(record.spec)
    {
        record.spec = MissionRecordSpec();
    }

    MissionRecord& MissionRecord::operator=(MissionRecord&& record)
    {
        if (this != &record){
            this->is_closed = record.is_closed;
            this->spec = record.spec;

            record.spec = MissionRecordSpec();
        }

        return *this;
    }

    void MissionRecord::close()
    {
        if (!this->spec.is_recording || this->is_closed){
            return;
        }

        // create zip file, push to destination
        std::vector<boost::filesystem::path> fileList;
        this->addFiles(fileList, this->spec.temp_dir);

        if (fileList.size() > 0){
            std::stringstream out("tempfile");
            lindenb::io::Tar tarball(out);

            for (auto file : fileList){
                try{
                    this->addFile(tarball, file);
                }
                catch (const std::exception& e){
                    std::cout << "[warning] Unable to archive " << file.string() << ": " << e.what() << std::endl;
                }
            }

            tarball.finish();
            {
                std::ofstream file(this->spec.destination, std::ofstream::binary);
                if (file.fail()) {
                    std::cout << "[warning] Unable to write recording to output file " << this->spec.destination << std::endl;
                }
                else {
                    boost::iostreams::filtering_streambuf< boost::iostreams::input> in;
                    in.push(boost::iostreams::gzip_compressor());
                    in.push(out);
                    boost::iostreams::copy(in, file);
                }
            }
        }

        boost::filesystem::remove_all(this->spec.temp_dir);

        this->is_closed = true;
    }

    void MissionRecord::addFiles(std::vector<boost::filesystem::path> &fileList, boost::filesystem::path directory)
    {
        if (!boost::filesystem::exists(directory))
        {
            throw std::runtime_error("Attempt to write to non-existent directory: " + directory.string());
        }
        boost::filesystem::directory_iterator dirIter(directory);
        boost::filesystem::directory_iterator dirIterEnd;

        while (dirIter != dirIterEnd)
        {
            if (boost::filesystem::exists(*dirIter))
            {
                if (boost::filesystem::is_directory(*dirIter)){
                    this->addFiles(fileList, *dirIter);
                }
                else
                {
                    fileList.push_back((*dirIter));
                }
            }

            ++dirIter;
        }
    }

    void MissionRecord::addFile(lindenb::io::Tar& archive, boost::filesystem::path path)
    {
        std::string file_name_in_archive = path.relative_path().normalize().string();
        std::replace(file_name_in_archive.begin(), file_name_in_archive.end(), '\\', '/');
        file_name_in_archive = file_name_in_archive.substr(2, file_name_in_archive.size());
        archive.putFile(path.string().c_str(), file_name_in_archive.c_str());
    }

    bool MissionRecord::isRecording() const
    {
        return this->spec.is_recording;
    }

    bool MissionRecord::isRecordingMP4() const
    {
        return this->spec.is_recording_mp4;
    }

    bool MissionRecord::isRecordingObservations() const
    {
        return this->spec.is_recording_observations;
    }

    bool MissionRecord::isRecordingRewards() const
    {
        return this->spec.is_recording_rewards;
    }

    bool MissionRecord::isRecordingCommands() const
    {
        return this->spec.is_recording_commands;
    }

    std::string MissionRecord::getMP4Path() const
    {
        return this->spec.mp4_path;
    }

    int64_t MissionRecord::getMP4BitRate() const
    {
        return this->spec.mp4_bit_rate;
    }

    int MissionRecord::getMP4FramesPerSecond() const
    {
        return this->spec.mp4_fps;
    }

    std::string MissionRecord::getObservationsPath() const
    {
        return this->spec.observations_path;
    }

    std::string MissionRecord::getRewardsPath() const
    {
        return this->spec.rewards_path;
    }

    std::string MissionRecord::getCommandsPath() const
    {
        return this->spec.commands_path;
    }

    std::string MissionRecord::getMissionInitPath() const
    {
        return this->spec.mission_init_path;
    }
}


text:
colector
========

creacion de un repositorio ejemplo github


text:
layout: post
title: TypeScript-Interface
categories:
tags:
  - typescript
---


text:
var Node = function() {
    var value = undefined;
    var address = undefined;
    this.setValue = function(val) {
        value = val;
    }
    this.getValue = function() {
        return value;
    }
    this.setAddress = function(val) {
        address = val;
    }
    this.getAddress = function() {
        return address;
    }
}
var LinkedList = function() {
    var first = undefined;
    var buf = undefined;
    var tmp = undefined;
    this.add = function(value) {
        if (first === undefined) {
            first = new Node();
            first.setValue(value);
            buf = first;
        } else {
            var b = new Node();
            b.setValue(value);
            buf.setAddress(b);
            buf = buf.getAddress();
        }
    }

    this.print = function() {
        traversalCallBack(first);
    }
    var traversalCallBack = function(node) {
        console.log(node.getValue());
        if (node.getAddress() === undefined) {
            console.log("On the Buttom.");
            return;
        }
        traversalCallBack(node.getAddress());
    }
    this.isEmpty = function() {
        if (first === undefined) {
            return true;
        }
        return false;
    }

    this.insert = function(index, data) {
        var node = undefined;
        if (index === 0) {
            data.setAddress(first);
            first = data;
            return;
        }

        for (var i = 0; i <= index; i++) {
            if (node === undefined) {
                node = first;
            } else {
                if (node.getAddress() === undefined) {
                    console.log("LinkedList length is less then " + index);
                    return;
                }
                node = node.getAddress();
            }
            console.log(node.getValue());
        };
        var bufAddress = node.getAddress();

        data.setAddress(bufAddress);
        node.setAddress(data);
    }
    this.deleteNode = function(index) {
        if (index === 0) {
            first = first.getAddress();
            return;
        }
        var node = undefined;
        var parent = undefined;
        for (var i = 0; i < index; i++) {
            if (node === undefined) {
                parent = first;
                node = parent.getAddress();
            } else {
                if (node.getAddress() === undefined) {
                    console.log("LinkedList length is less then " + index);
                    return;
                }
                parent = node;
                node = node.getAddress();

            }
        };

        if (node.getAddress() === undefined) {
            parent.setAddress(undefined);
            node = undefined;
            return;
        };
        var chrildNode = node.getAddress();
        parent.setAddress(chrildNode);
        node = undefined;
    }
    this.reverse = function() {
        var container = [];
        var node = first;
        container.push(node.getValue());
        while (node.getAddress() !== undefined) {
            node = node.getAddress();
            container.push(node.getValue());
        }
        var length = container.length;
        var tmpFirst = undefined;
        var tmpNode = undefined;
        for (var i = length - 1; i >= 0; i--) {
            if (tmpFirst === undefined) {
                tmpFirst = new Node();
                tmpFirst.setValue(container[i]);
                tmpNode = tmpFirst;
            } else {
                var b = new Node();
                b.setValue(container[i]);
                tmpNode.setAddress(b);
                tmpNode = tmpNode.getAddress();
            }
        };
        first = tmpFirst;
    }
    this.concatenation = function(linkedList) {
        var last = undefined;
        var node = first;
        while (node.getAddress() !== undefined) {
            node = node.getAddress();
        }
        node.setAddress(linkedList.getFirstNode());
    }
    this.getFirstNode = function() {
        return first;
    }
}

/* Test Code
    var b = new LinkedList();
    for (var i = 0; i <100; i++) {
        b.add(i.toString());
    };

    var b = new LinkedList();
    for (var i = 1; i < 4; i++) {
        b.add(i.toString());
    };
    var r = new Node();
    r.setValue("2.5");
    b.insert(2,r);
*/


text:
from k5test import *

realm = K5Realm(create_kdb=False)

keyctl = which('keyctl')
out = realm.run([klist, '-c', 'KEYRING:process:abcd'], expected_code=1)
test_keyring = (keyctl is not None and
                'Unknown credential cache type' not in out)
if not test_keyring:
    skipped('keyring collection tests', 'keyring support not built')

# Run the collection test program against each collection-enabled type.
realm.run(['./t_cccol', 'DIR:' + os.path.join(realm.testdir, 'cc')])
if test_keyring:
    def cleanup_keyring(anchor, name):
        out = realm.run(['keyctl', 'list', anchor])
        if ('keyring: ' + name + '\n') in out:
            keyid = realm.run(['keyctl', 'search', anchor, 'keyring', name])
            realm.run(['keyctl', 'unlink', keyid.strip(), anchor])

    # Use the test directory as the collection name to avoid colliding
    # with other build trees.
    cname = realm.testdir
    col_ringname = '_krb_' + cname

    # Remove any keys left behind by previous failed test runs.
    cleanup_keyring('@s', cname)
    cleanup_keyring('@s', col_ringname)
    cleanup_keyring('@u', col_ringname)

    # Run test program over each subtype, cleaning up as we go.  Don't
    # test the persistent subtype, since it supports only one
    # collection and might be in actual use.
    realm.run(['./t_cccol', 'KEYRING:' + cname])
    cleanup_keyring('@s', col_ringname)
    realm.run(['./t_cccol', 'KEYRING:legacy:' + cname])
    cleanup_keyring('@s', col_ringname)
    realm.run(['./t_cccol', 'KEYRING:session:' + cname])
    cleanup_keyring('@s', col_ringname)
    realm.run(['./t_cccol', 'KEYRING:user:' + cname])
    cleanup_keyring('@u', col_ringname)
    realm.run(['./t_cccol', 'KEYRING:process:abcd'])
    realm.run(['./t_cccol', 'KEYRING:thread:abcd'])

realm.stop()

# Test cursor semantics using real ccaches.
realm = K5Realm(create_host=False)

realm.addprinc('alice', password('alice'))
realm.addprinc('bob', password('bob'))

ccdir = os.path.join(realm.testdir, 'cc')
dccname = 'DIR:%s' % ccdir
duser = 'DIR::%s/tkt1' % ccdir
dalice = 'DIR::%s/tkt2' % ccdir
dbob = 'DIR::%s/tkt3' % ccdir
dnoent = 'DIR::%s/noent' % ccdir
realm.kinit('user', password('user'), flags=['-c', duser])
realm.kinit('alice', password('alice'), flags=['-c', dalice])
realm.kinit('bob', password('bob'), flags=['-c', dbob])

if test_keyring:
    cleanup_keyring('@s', col_ringname)
    krccname = 'KEYRING:session:' + cname
    kruser = '%s:tkt1' % krccname
    kralice = '%s:tkt2' % krccname
    krbob = '%s:tkt3' % krccname
    krnoent = '%s:noent' % krccname
    realm.kinit('user', password('user'), flags=['-c', kruser])
    realm.kinit('alice', password('alice'), flags=['-c', kralice])
    realm.kinit('bob', password('bob'), flags=['-c', krbob])

def cursor_test(testname, args, expected):
    outlines = realm.run(['./t_cccursor'] + args).splitlines()
    outlines.sort()
    expected.sort()
    if outlines != expected:
        fail('Output not expected for %s\n' % testname +
             'Expected output:\n\n' + '\n'.join(expected) + '\n\n' +
             'Actual output:\n\n' + '\n'.join(outlines))

fccname = 'FILE:%s' % realm.ccache
cursor_test('file-default', [], [fccname])
cursor_test('file-default2', [realm.ccache], [fccname])
cursor_test('file-default3', [fccname], [fccname])

cursor_test('dir', [dccname], [duser, dalice, dbob])
cursor_test('dir-subsidiary', [duser], [duser])
cursor_test('dir-nofile', [dnoent], [])

if test_keyring:
    cursor_test('keyring', [krccname], [kruser, kralice, krbob])
    cursor_test('keyring-subsidiary', [kruser], [kruser])
    cursor_test('keyring-noent', [krnoent], [])

mfoo = 'MEMORY:foo'
mbar = 'MEMORY:bar'
cursor_test('filemem', [fccname, mfoo, mbar], [fccname, mfoo, mbar])
cursor_test('dirmem', [dccname, mfoo], [duser, dalice, dbob, mfoo])
if test_keyring:
    cursor_test('keyringmem', [krccname, mfoo], [kruser, kralice, krbob, mfoo])

# Test krb5_cccol_have_content.
realm.run(['./t_cccursor', dccname, 'CONTENT'])
realm.run(['./t_cccursor', fccname, 'CONTENT'])
realm.run(['./t_cccursor', realm.ccache, 'CONTENT'])
realm.run(['./t_cccursor', mfoo, 'CONTENT'], expected_code=1)
if test_keyring:
    realm.run(['./t_cccursor', krccname, 'CONTENT'])
    cleanup_keyring('@s', col_ringname)

# Make sure FILE doesn't yield a nonexistent default cache.
realm.run([kdestroy])
cursor_test('noexist', [], [])
realm.run(['./t_cccursor', fccname, 'CONTENT'], expected_code=1)

success('Renewing credentials')


text:
tempfile module
===============

.. automodule:: tempfile
    :members:
    :undoc-members:
    :show-inheritance:


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rltvlyot_rowmain"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/transparent" >

    <RelativeLayout
       	android:layout_width="match_parent"
       	android:layout_height="fill_parent"
    	android:clickable="true"
		android:background="?attr/selectableItemBackground" >

	    <ImageView
	        android:id="@+id/rowIcon"
	        android:layout_width="35dp"
	        android:layout_height="wrap_content"
	        android:layout_alignParentLeft="true"
	        android:layout_alignParentStart="true"
	        android:layout_marginLeft="16dp"
	        android:layout_marginRight="16dp"
	        android:contentDescription="@string/app_name"
	        android:src="@drawable/ic_launcher"
	        android:layout_centerVertical="true" />

	    <TextView
	        android:id="@+id/rowText"
	        android:layout_width="wrap_content"
	        android:layout_height="match_parent"
	        android:layout_toRightOf="@id/rowIcon"
	        android:layout_toEndOf="@id/rowIcon"
	        android:minHeight="?android:attr/listPreferredItemHeightSmall"
	        android:textAppearance="?android:attr/textAppearanceListItemSmall"
	        android:textColor="@color/list_item_title"
	        android:gravity="center_vertical"
	        android:paddingRight="35dp" />

    </RelativeLayout>

</RelativeLayout>


text:
package org.springframework.boot.test.context;

import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link SpringBootTest} configured with {@link WebEnvironment#RANDOM_PORT}.
 *
 * @author Phillip Webb
 * @author Andy Wilkinson
 */
@RunWith(SpringRunner.class)
@DirtiesContext
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = { "value=123" })
public class SpringBootTestTestRestTemplateDefinedByUser
		extends AbstractSpringBootTestEmbeddedWebEnvironmentTests {

	@Test
	public void restTemplateIsUserDefined() throws Exception {
		assertThat(getContext().getBean("testRestTemplate"))
				.isInstanceOf(RestTemplate.class);
	}

	// gh-7711

	@Configuration
	@EnableWebMvc
	@RestController
	protected static class Config extends AbstractConfig {

		@Bean
		public RestTemplate testRestTemplate() {
			return new RestTemplate();
		}

	}

}


text:
from typing import Any, Callable, Dict, Optional, TypeVar

from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat

from ... import models as _models
from ..._vendor import _convert_request
from ...operations._configuration_profile_hci_assignments_operations import build_create_or_update_request, build_delete_request, build_get_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]

class ConfigurationProfileHCIAssignmentsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.automanage.aio.AutomanageClient`'s
        :attr:`configuration_profile_hci_assignments` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace_async
    async def create_or_update(
        self,
        resource_group_name: str,
        cluster_name: str,
        configuration_profile_assignment_name: str,
        parameters: _models.ConfigurationProfileAssignment,
        **kwargs: Any
    ) -> _models.ConfigurationProfileAssignment:
        """Creates an association between a AzureStackHCI cluster and Automanage configuration profile.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
        :type resource_group_name: str
        :param cluster_name: The name of the Arc machine.
        :type cluster_name: str
        :param configuration_profile_assignment_name: Name of the configuration profile assignment.
         Only default is supported.
        :type configuration_profile_assignment_name: str
        :param parameters: Parameters supplied to the create or update configuration profile
         assignment.
        :type parameters: ~azure.mgmt.automanage.models.ConfigurationProfileAssignment
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: ConfigurationProfileAssignment, or the result of cls(response)
        :rtype: ~azure.mgmt.automanage.models.ConfigurationProfileAssignment
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-05-04"))  # type: str
        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.ConfigurationProfileAssignment]

        _json = self._serialize.body(parameters, 'ConfigurationProfileAssignment')

        request = build_create_or_update_request(
            subscription_id=self._config.subscription_id,
            resource_group_name=resource_group_name,
            cluster_name=cluster_name,
            configuration_profile_assignment_name=configuration_profile_assignment_name,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            template_url=self.create_or_update.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if response.status_code == 200:
            deserialized = self._deserialize('ConfigurationProfileAssignment', pipeline_response)

        if response.status_code == 201:
            deserialized = self._deserialize('ConfigurationProfileAssignment', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    create_or_update.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureStackHci/clusters/{clusterName}/providers/Microsoft.Automanage/configurationProfileAssignments/{configurationProfileAssignmentName}"}  # type: ignore

    @distributed_trace_async
    async def get(
        self,
        resource_group_name: str,
        cluster_name: str,
        configuration_profile_assignment_name: str,
        **kwargs: Any
    ) -> _models.ConfigurationProfileAssignment:
        """Get information about a configuration profile assignment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
        :type resource_group_name: str
        :param cluster_name: The name of the Arc machine.
        :type cluster_name: str
        :param configuration_profile_assignment_name: The configuration profile assignment name.
        :type configuration_profile_assignment_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: ConfigurationProfileAssignment, or the result of cls(response)
        :rtype: ~azure.mgmt.automanage.models.ConfigurationProfileAssignment
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-05-04"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.ConfigurationProfileAssignment]

        request = build_get_request(
            resource_group_name=resource_group_name,
            subscription_id=self._config.subscription_id,
            cluster_name=cluster_name,
            configuration_profile_assignment_name=configuration_profile_assignment_name,
            api_version=api_version,
            template_url=self.get.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize('ConfigurationProfileAssignment', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureStackHci/clusters/{clusterName}/providers/Microsoft.Automanage/configurationProfileAssignments/{configurationProfileAssignmentName}"}  # type: ignore

    @distributed_trace_async
    async def delete(  # pylint: disable=inconsistent-return-statements
        self,
        resource_group_name: str,
        cluster_name: str,
        configuration_profile_assignment_name: str,
        **kwargs: Any
    ) -> None:
        """Delete a configuration profile assignment.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
        :type resource_group_name: str
        :param cluster_name: The name of the Arc machine.
        :type cluster_name: str
        :param configuration_profile_assignment_name: Name of the configuration profile assignment.
        :type configuration_profile_assignment_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-05-04"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        request = build_delete_request(
            subscription_id=self._config.subscription_id,
            resource_group_name=resource_group_name,
            cluster_name=cluster_name,
            configuration_profile_assignment_name=configuration_profile_assignment_name,
            api_version=api_version,
            template_url=self.delete.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if cls:
            return cls(pipeline_response, None, {})

    delete.metadata = {'url': "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureStackHci/clusters/{clusterName}/providers/Microsoft.Automanage/configurationProfileAssignments/{configurationProfileAssignmentName}"}  # type: ignore


text:
"""
    sockjs.tornado.transports.websocket
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Websocket transport implementation
"""
import logging
import socket

from sockjs.tornado import proto, websocket
from sockjs.tornado.transports import base
from sockjs.tornado.util import bytes_to_str

LOG = logging.getLogger("tornado.general")

class WebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin):
    """Websocket transport"""
    name = 'websocket'

    def initialize(self, server):
        self.server = server
        self.session = None
        self.active = True

    def open(self, session_id):
        # Stats
        self.server.stats.on_conn_opened()

        # Disable nagle
        if self.server.settings['disable_nagle']:
            self.stream.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)

        # Handle session
        self.session = self.server.create_session(session_id, register=False)

        if not self.session.set_handler(self):
            self.close()
            return

        self.session.verify_state()

        if self.session:
            self.session.flush()

    def _detach(self):
        if self.session is not None:
            self.session.remove_handler(self)
            self.session = None

    def on_message(self, message):
        # SockJS requires that empty messages should be ignored
        if not message or not self.session:
            return

        try:
            msg = proto.json_decode(bytes_to_str(message))

            if isinstance(msg, list):
                self.session.on_messages(msg)
            else:
                self.session.on_messages((msg,))
        except Exception:
            LOG.exception('WebSocket')

            # Close session on exception
            #self.session.close()

            # Close running connection
            self.abort_connection()

    def on_close(self):
        # Close session if websocket connection was closed
        if self.session is not None:
            # Stats
            self.server.stats.on_conn_closed()

            # Detach before closing session
            session = self.session
            self._detach()
            session.close()

    def send_pack(self, message, binary=False):
        # Send message
        try:
            self.write_message(message, binary)
        except IOError:
            self.server.io_loop.add_callback(self.on_close)

    def session_closed(self):
        # If session was closed by the application, terminate websocket
        # connection as well.
        try:
            self.close()
        except IOError:
            pass
        finally:
            self._detach()

    # Websocket overrides
    def allow_draft76(self):
        return True

    def auto_decode(self):
        return False


text:
struct sNode{
	int value;
	sNode* pLeft;
	sNode* pRight;
};

class cBSTree
{
public:
	cBSTree();
	~cBSTree();

	//void removeRoot();
	bool insert(int n);

	sNode* deleteByValue(int n);

	bool contains(int n);

	void print();
	void deleteMin();

	void clear(sNode* node);
private:
	bool insertRec(int n, sNode* cur);
	sNode* getNodebyValue(int n, sNode* cur);

	// get address of the min
	sNode* Min(sNode* cur);

	// delete the min
	sNode* deleteMin(sNode* cur);
	sNode* deleteByValue(int n, sNode* cur);

	void printRecursiveHelper(sNode* cur);
	sNode* m_pRoot;
	int m_nSize = 0;
};


text:
//
//  ZKCGUtilities.h
//  ZKCategories(https://github.com/kaiser143/ZKCategories.git)
//
//  Created by Kaiser on 2018/8/17.
//  Copyright © 2018年 Kaiser. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

NS_ASSUME_NONNULL_BEGIN

/// Create an `ARGB` Bitmap context. Returns NULL if an error occurs.
///
/// @discussion The function is same as UIGraphicsBeginImageContextWithOptions(),
/// but it doesn't push the context to UIGraphic, so you can retain the context for reuse.
CGContextRef _Nullable ZKCGContextCreateARGBBitmapContext(CGSize size, BOOL opaque, CGFloat scale);

/// Create a `DeviceGray` Bitmap context. Returns NULL if an error occurs.
CGContextRef _Nullable ZKCGContextCreateGrayBitmapContext(CGSize size, CGFloat scale);

/// Get main screen's scale.
CGFloat ZKScreenScale(void);

/// Get main screen's size. Height is always larger than width.
CGSize ZKScreenSize(void);

/// Convert degrees to radians.
static inline CGFloat DegreesToRadians(CGFloat degrees) {
    return degrees * M_PI / 180;
}

/// Convert radians to degrees.
static inline CGFloat RadiansToDegrees(CGFloat radians) {
    return radians * 180 / M_PI;
}

/// Get the transform rotation.
/// @return the rotation in radians [-PI,PI] ([-180°,180°])
static inline CGFloat CGAffineTransformGetRotation(CGAffineTransform transform) {
    return atan2(transform.b, transform.a);
}

/// Get the transform's scale.x
static inline CGFloat CGAffineTransformGetScaleX(CGAffineTransform transform) {
    return  sqrt(transform.a * transform.a + transform.c * transform.c);
}

/// Get the transform's scale.y
static inline CGFloat CGAffineTransformGetScaleY(CGAffineTransform transform) {
    return sqrt(transform.b * transform.b + transform.d * transform.d);
}

/// Get the transform's translate.x
static inline CGFloat CGAffineTransformGetTranslateX(CGAffineTransform transform) {
    return transform.tx;
}

/// Get the transform's translate.y
static inline CGFloat CGAffineTransformGetTranslateY(CGAffineTransform transform) {
    return transform.ty;
}

/**
 If you have 3 pair of points transformed by a same CGAffineTransform:
     p1 (transform->) q1
     p2 (transform->) q2
     p3 (transform->) q3
 This method returns the original transform matrix from these 3 pair of points.

 @see http://stackoverflow.com/questions/13291796/calculate-values-for-a-cgaffinetransform-from-three-points-in-each-of-two-uiview
 */
CGAffineTransform ZKCGAffineTransformGetFromPoints(CGPoint before[_Nullable 3], CGPoint after[_Nullable 3]);

/// Get the transform which can converts a point from the coordinate system of a given view to another.
CGAffineTransform ZKCGAffineTransformGetFromViews(UIView *from, UIView *to);

/// Create a skew transform.
static inline CGAffineTransform CGAffineTransformMakeSkew(CGFloat x, CGFloat y){
    CGAffineTransform transform = CGAffineTransformIdentity;
    transform.c = -x;
    transform.b = y;
    return transform;
}

/// Negates/inverts a UIEdgeInsets.
static inline UIEdgeInsets UIEdgeInsetsInvert(UIEdgeInsets insets) {
    return UIEdgeInsetsMake(-insets.top, -insets.left, -insets.bottom, -insets.right);
}

/// Convert CALayer's gravity string to UIViewContentMode.
UIViewContentMode ZKCAGravityToUIViewContentMode(NSString *gravity);

/// Convert UIViewContentMode to CALayer's gravity string.
NSString *ZKUIViewContentModeToCAGravity(UIViewContentMode contentMode);

/**
 Returns a rectangle to fit the @param rect with specified content mode.

 @param \rect The constrant rect
 @param size The content size
 @param mode The content mode
 @return A rectangle for the given content mode.
 @discussion UIViewContentModeRedraw is same as UIViewContentModeScaleToFill.
 */
CGRect ZKCGRectFitWithContentMode(CGRect rect, CGSize size, UIViewContentMode mode);

/// Returns the center for the rectangle.
static inline CGPoint CGRectGetCenter(CGRect rect) {
    return CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
}

/// Returns the area of the rectangle.
static inline CGFloat CGRectGetArea(CGRect rect) {
    if (CGRectIsNull(rect)) return 0;
    rect = CGRectStandardize(rect);
    return rect.size.width * rect.size.height;
}

/// Returns the distance between two points.
static inline CGFloat CGPointGetDistanceToPoint(CGPoint p1, CGPoint p2) {
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

/// Returns the minmium distance between a point to a rectangle.
static inline CGFloat CGPointGetDistanceToRect(CGPoint p, CGRect r) {
    r = CGRectStandardize(r);
    if (CGRectContainsPoint(r, p)) return 0;
    CGFloat distV, distH;
    if (CGRectGetMinY(r) <= p.y && p.y <= CGRectGetMaxY(r)) {
        distV = 0;
    } else {
        distV = p.y < CGRectGetMinY(r) ? CGRectGetMinY(r) - p.y : p.y - CGRectGetMaxY(r);
    }
    if (CGRectGetMinX(r) <= p.x && p.x <= CGRectGetMaxX(r)) {
        distH = 0;
    } else {
        distH = p.x < CGRectGetMinX(r) ? CGRectGetMinX(r) - p.x : p.x - CGRectGetMaxX(r);
    }
    return MAX(distV, distH);
}

/// Convert point to pixel.
static inline CGFloat CGFloatToPixel(CGFloat value) {
    return value * ZKScreenScale();
}

/// Convert pixel to point.
static inline CGFloat CGFloatFromPixel(CGFloat value) {
    return value / ZKScreenScale();
}

/// floor point value for pixel-aligned
static inline CGFloat CGFloatPixelFloor(CGFloat value) {
    CGFloat scale = ZKScreenScale();
    return floor(value * scale) / scale;
}

/// round point value for pixel-aligned
static inline CGFloat CGFloatPixelRound(CGFloat value) {
    CGFloat scale = ZKScreenScale();
    return round(value * scale) / scale;
}

/// ceil point value for pixel-aligned
static inline CGFloat CGFloatPixelCeil(CGFloat value) {
    CGFloat scale = ZKScreenScale();
    return ceil(value * scale) / scale;
}

/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
static inline CGFloat CGFloatPixelHalf(CGFloat value) {
    CGFloat scale = ZKScreenScale();
    return (floor(value * scale) + 0.5) / scale;
}

/// floor point value for pixel-aligned
static inline CGPoint CGPointPixelFloor(CGPoint point) {
    CGFloat scale = ZKScreenScale();
    return CGPointMake(floor(point.x * scale) / scale,
                       floor(point.y * scale) / scale);
}

/// round point value for pixel-aligned
static inline CGPoint CGPointPixelRound(CGPoint point) {
    CGFloat scale = ZKScreenScale();
    return CGPointMake(round(point.x * scale) / scale,
                       round(point.y * scale) / scale);
}

/// ceil point value for pixel-aligned
static inline CGPoint CGPointPixelCeil(CGPoint point) {
    CGFloat scale = ZKScreenScale();
    return CGPointMake(ceil(point.x * scale) / scale,
                       ceil(point.y * scale) / scale);
}

/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
static inline CGPoint CGPointPixelHalf(CGPoint point) {
    CGFloat scale = ZKScreenScale();
    return CGPointMake((floor(point.x * scale) + 0.5) / scale,
                       (floor(point.y * scale) + 0.5) / scale);
}

/// floor point value for pixel-aligned
static inline CGSize CGSizePixelFloor(CGSize size) {
    CGFloat scale = ZKScreenScale();
    return CGSizeMake(floor(size.width * scale) / scale,
                      floor(size.height * scale) / scale);
}

/// round point value for pixel-aligned
static inline CGSize CGSizePixelRound(CGSize size) {
    CGFloat scale = ZKScreenScale();
    return CGSizeMake(round(size.width * scale) / scale,
                      round(size.height * scale) / scale);
}

/// ceil point value for pixel-aligned
static inline CGSize CGSizePixelCeil(CGSize size) {
    CGFloat scale = ZKScreenScale();
    return CGSizeMake(ceil(size.width * scale) / scale,
                      ceil(size.height * scale) / scale);
}

/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
static inline CGSize CGSizePixelHalf(CGSize size) {
    CGFloat scale = ZKScreenScale();
    return CGSizeMake((floor(size.width * scale) + 0.5) / scale,
                       (floor(size.height * scale) + 0.5) / scale);
}

/// floor point value for pixel-aligned
static inline CGRect CGRectPixelFloor(CGRect rect) {
    CGPoint origin = CGPointPixelCeil(rect.origin);
    CGPoint corner = CGPointPixelFloor(CGPointMake(rect.origin.x + rect.size.width,
                                                   rect.origin.y + rect.size.height));
    CGRect ret = CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
    if (ret.size.width < 0) ret.size.width = 0;
    if (ret.size.height < 0) ret.size.height = 0;
    return ret;
}

/// round point value for pixel-aligned
static inline CGRect CGRectPixelRound(CGRect rect) {
    CGPoint origin = CGPointPixelRound(rect.origin);
    CGPoint corner = CGPointPixelRound(CGPointMake(rect.origin.x + rect.size.width,
                                                  rect.origin.y + rect.size.height));
    return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
}

/// ceil point value for pixel-aligned
static inline CGRect CGRectPixelCeil(CGRect rect) {
    CGPoint origin = CGPointPixelFloor(rect.origin);
    CGPoint corner = CGPointPixelCeil(CGPointMake(rect.origin.x + rect.size.width,
                                                   rect.origin.y + rect.size.height));
    return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
}

/// round point value to .5 pixel for path stroke (odd pixel line width pixel-aligned)
static inline CGRect CGRectPixelHalf(CGRect rect) {
    CGPoint origin = CGPointPixelHalf(rect.origin);
    CGPoint corner = CGPointPixelHalf(CGPointMake(rect.origin.x + rect.size.width,
                                                  rect.origin.y + rect.size.height));
    return CGRectMake(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y);
}

/// floor UIEdgeInset for pixel-aligned
static inline UIEdgeInsets UIEdgeInsetPixelFloor(UIEdgeInsets insets) {
    insets.top = CGFloatPixelFloor(insets.top);
    insets.left = CGFloatPixelFloor(insets.left);
    insets.bottom = CGFloatPixelFloor(insets.bottom);
    insets.right = CGFloatPixelFloor(insets.right);
    return insets;
}

/// ceil UIEdgeInset for pixel-aligned
static inline UIEdgeInsets UIEdgeInsetPixelCeil(UIEdgeInsets insets) {
    insets.top = CGFloatPixelCeil(insets.top);
    insets.left = CGFloatPixelCeil(insets.left);
    insets.bottom = CGFloatPixelCeil(insets.bottom);
    insets.right = CGFloatPixelCeil(insets.right);
    return insets;
}

/** 设置投影 **/
static inline void kai_view_shadow(UIView *view, UIColor *color, CGSize offset, CGFloat opacity, CGFloat radius) {
    view.layer.shadowColor = color.CGColor;
    view.layer.shadowOffset = offset;
    view.layer.shadowOpacity = opacity;
    view.layer.shadowRadius = radius;
}

/** view 圆角 */
static inline void kai_view_radius(UIView *view, CGFloat radius) {
    [view.layer setCornerRadius:radius];
    [view.layer setMasksToBounds:YES];
}

/** view 边框 */
static inline void kai_view_border(UIView *view, CGFloat width, UIColor *color) {
    [view.layer setBorderWidth:(width)];
    [view.layer setBorderColor:[color CGColor]];
}

/** view 圆角 边框 */
static inline void kai_view_border_radius(UIView *view, CGFloat radius, CGFloat width, UIColor *color) {
    kai_view_radius(view, radius);
    kai_view_border(view, width, color);
}

/**
 view 单个圆角

 @param view 试图
 @param angle 某个圆角
 * UIRectCornerTopLeft
 * UIRectCornerTopRight
 * UIRectCornerBottomLeft
 * UIRectCornerBottomRight
 * UIRectCornerAllCorners
 @param radius 圆角度
 */
static inline void kai_view_singleFillet(UIView *view, UIRectCorner angle, CGFloat radius) {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds
                                                   byRoundingCorners:angle
                                                         cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

// main screen's scale
#ifndef kScreenScale
#define kScreenScale ZKScreenScale()
#endif

// main screen's size (portrait)
#ifndef kScreenSize
#define kScreenSize ZKScreenSize()
#endif

// main screen's width (portrait)
#ifndef kScreenWidth
#define kScreenWidth ZKScreenSize().width
#endif

// main screen's height (portrait)
#ifndef kScreenHeight
#define kScreenHeight ZKScreenSize().height
#endif

NS_ASSUME_NONNULL_END