text:
package util;

public class Range<T extends Comparable<T>> {
	private T min;
	private T max;
	private boolean useMin;
	private boolean useMax;

	public Range(T min, T max) {
		this.min = min;
		this.max = max;
		useMin = true;
		useMax = true;
	}

	@Override
	public String toString() {
		String result = "{Range: ";
		result += useMin ? (min + " <= ")  : "";
		result += "x";
		result += useMax ? (" <= " + max) : "";
		result += "}";
		return result;
	}

	/**
	 * @return true if other is within this range
	 */
	public boolean includes(T other) {
		boolean result = true;
		if (useMin) {
			result = result && (min.compareTo(other) <= 0);
		}
		if (useMax) {
			result = result && (other.compareTo(max) <= 0);
		}
		return result;
	}

	public T getMin() {
		return min;
	}

	public void setMin(T min) {
		this.min = min;
	}

	public T getMax() {
		return max;
	}

	public void setMax(T max) {
		this.max = max;
	}

	/**
	 * @return the closest thing to other that is in the range
	 */
	public T closestInRangeTo(T other) {
		if (includes(other)) {
			return other;
		} else if (min.compareTo(other) > 0) {
			// less than min
			return min;
		} else if (other.compareTo(max) > 0) {
			// more than max
			return max;
		} else {
			System.err.println("Range: TSNH!");
			return null;
		}
	}

	/**
	 * Tells this range which of its boundaries, if any, to apply.
	 *
	 * @param min
	 *            true if you want to enforce the lower bound
	 * @param max
	 *            true if you want to enforce the upper bound
	 */
	public void useBoundaries(boolean min, boolean max) {
		useMin = min;
		useMax = max;
	}
}


text:
package org.jboss.weld.tests.contexts.conversation.timeout.concurrent;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import jakarta.enterprise.context.Conversation;
import jakarta.inject.Inject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.jboss.weld.test.util.Timer;

@WebServlet(value = "/inspect", urlPatterns = "/*")
public class InspectServlet extends HttpServlet {

    private static final Logger logger = Logger.getLogger(InspectServlet.class.getName());

    public static final String MODE_INIT = "init";
    public static final String MODE_LONG_TASK = "long";
    public static final String MODE_BUSY_REQUEST = "busy";

    @Inject
    Conversation conversation;

    @Inject
    StateHolder stateHolder;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/plain");
        String mode = req.getParameter("mode");

        if (MODE_INIT.equals(mode)) {
            conversation.begin();
            stateHolder.reset();
            resp.getWriter().write(conversation.getId() + "::" + req.getSession().getId());
        } else if (MODE_LONG_TASK.equals(mode)) {
            if (conversation.isTransient()) {
                resp.sendError(500, "No long running conversation");
            } else {
                long start = System.currentTimeMillis();
                try {
                    new Timer().setSleepInterval(100l).setDelay(2, TimeUnit.SECONDS).addStopCondition(new Timer.StopCondition() {
                        @Override
                        public boolean isSatisfied() {
                            return stateHolder.isBusyAttemptMade();
                        }
                    }).start();
                } catch (InterruptedException e1) {
                    throw new IllegalStateException();
                }
                logger.info("Long task finished [isBusyAttemptMade: " + stateHolder.isBusyAttemptMade() + ", time: " + String
                        .valueOf(System.currentTimeMillis() - start));
                resp.getWriter().write("OK");
            }
        } else if (MODE_BUSY_REQUEST.equals(mode)) {
            resp.getWriter().write("Conversation locked");
        } else {
            throw new ServletException("Unknown test mode");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface YXCommentView ()<YXBottomInputViewDelegate, UITableViewDelegate>
@property (nonatomic, strong) MASConstraint *bottomInputViewBotConstarint;
@end

@implementation YXCommentView

- (instancetype)init {
    //初始化,frame不为 CGRectZero,就不会报约束冲突了
    self = [super initWithFrame:CGRectMake(0, 0, 100, 100)];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self addSubviews];
        [self addConstarinsForSubviews];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}

- (void)addSubviews {
    YXCommentTableView *commentTableView = [[YXCommentTableView alloc] init];
    commentTableView.delegate = self;
    [self addSubview:commentTableView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapCommentTableView)];
    [commentTableView addGestureRecognizer:tap];
    self.commentTableView = commentTableView;

    YXBottomInputView *bottomInputView = [[YXBottomInputView alloc] init];
    bottomInputView.delegate = self;
    [self addSubview:bottomInputView];
    self.bottomInputView = bottomInputView;
}

- (void)addConstarinsForSubviews {
    [self.commentTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self);
        make.left.right.equalTo(self);
        make.bottom.equalTo(self).offset(-49);
    }];

    [self.bottomInputView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
        make.height.equalTo(@49);
        self.bottomInputViewBotConstarint = make.bottom.equalTo(self);
    }];
}

- (void)sendRequest:(NSString *)urlStr para:(NSDictionary *)para {
    [YXNetWorking postUrlString:urlStr paramater:para success:^(id obj, NSURLResponse *response) {
        if ([urlStr isEqualToString:YXSave_Comment]) {

        }

    } fail:^(NSError *error, NSString *errorMessage) {
        NSLog(@"errorMessage:%@", errorMessage);
    }];
}

//收到键盘Frame发生改变的通知后执行
- (void)keyboardWillChangeFrame:(NSNotification *)noti {
    NSTimeInterval duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardFrame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (keyboardFrame.origin.y != [UIScreen mainScreen].bounds.size.height) {
        [UIView animateWithDuration:duration animations:^{
            self.bottomInputViewBotConstarint.offset = -keyboardFrame.size.height;
            [self layoutIfNeeded];
        } completion:^(BOOL finished) {

        }];
    } else {
        [UIView animateWithDuration:duration animations:^{
            self.bottomInputViewBotConstarint.offset = 0;
            [self layoutIfNeeded];
        }];
    }
}

- (void)didTapCommentTableView {
    [self resignTextviewFirstResponder];
    [UIMenuController sharedMenuController].menuVisible = NO;
}

- (void)resignTextviewFirstResponder {
    if (self.bottomInputView.textView.isFirstResponder) {
        [self.bottomInputView.textView resignFirstResponder];
    }
}

#pragma mark TableViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self resignTextviewFirstResponder];
    [UIMenuController sharedMenuController].menuVisible = NO;
}

#pragma mark BottomInputViewDelegate
- (void)bottomInputView:(YXBottomInputView *)bottomInputView sendMessage:(NSString *)message {
    //当按下回车,发送评论的时候,会执行该代理方法。
    //YXTODO:在这里传入用户名,用户ID,用户头像
    NSString *username = @"";
    NSString *userId = @"";//用户ID后添加"-sdk",如:@"0001-sdk"
    NSString *avatar = @"";//用户头像图片地址
    [self sendRequest:YXSave_Comment
                 para:@{
                        @"lsId":self.streamId,
                        @"userId":userId,
                        @"username":username,
                        @"avatar":avatar,
                        @"content":message}];
}
@end


text:
-- =============================================
-- Author:		Mark Entingh
-- Create date: 10/13/2011 11:33 AM
-- Description:	Adds a user to the platform
-- =============================================
CREATE PROCEDURE [dbo].[User_Create]
	@email nvarchar(75) = '',
	@password nvarchar(100) = '',
	@displayname nvarchar(25) = '',
	@photo int = 0,
	@status int = 1,
	@signupip nvarchar(15) = '',
	@referrer nvarchar(250) = '',
	@activation nchar(20) = '',
	@deleted bit = 0
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @date datetime = GETDATE(),
	@id int = NEXT VALUE FOR SequenceUsers

    INSERT INTO Users (userId, email, [password], displayname, photo,
    lastlogin, dateCreated, [status],
    signupip, referrer, [activation], deleted)
    VALUES
    (@id, @email, @password, @displayname, @photo,
	@date, @date, @status,
    @signupip, @referrer, @activation, @deleted)

    SELECT @id
END


text:
module.exports = {
  role: 'database',
  model: 'credit_transfer'
};


text:
/*!	\file string.h
	\brief standard string function declarations
	This file contains all the common string function declaration.
*/
#ifndef STRING_H
#define STRING_H

#include <stdlib.h>

#ifdef __cplusplus
    extern "C" {
#endif

void * memchr(const void *s, int c, size_t n);
int memcmp(const void *s1, const void *s2, size_t n);
void* memcpy(void *dest, const void *src, size_t n);
void* memmove(void *dest, void *src, size_t n);
void* memset(void *s, int c, size_t n);

int str_total_characters(char * src, char ch);
int str_total_tokens(char * src, char ch);
char * str_get_token_info(char * src, unsigned int token_no, char token_separator, unsigned int * token_len);
char * str_get_token(char * src, unsigned int token_no, char token_separator, char * buf, int buf_size );
void str_replace(char * src, char oldch, char newch);
char* str_ltrim(char * src);
char* str_rtrim(char * src);
char* str_atrim(char * src);
char* str_toupper(char * src);
char* str_tolower(char * src);
int str_pattern_search(const char * src, const char * pattern);
char* strcat(char *s, const char *append);
char* strchr(const char *s, int c);
char * strrchr ( const char *s, int c );
int strcmp(const char *s1, const char *s2);
int strcoll(const char *s1, const char *s2);
char* strcpy(char *dest, const char *src);
char* strncpy(char *dst, const char *src, size_t n);
size_t strspn(const char *s, const char *accept);
size_t strcspn(const char *s, const char *reject);
char* strerror(int errnum);
int stricmp(const char *s1, const char *s2);
size_t strlen(const char *str);
char* strncat(char *dest, const char *src, size_t n);
char *strnchr(const char *str, char c, size_t count);
int strncmp(const char *s1, const char *s2, size_t n);
char* strpbrk(const char *s1, const char *s2);
char* strstr(const char *s, const char *find);
char* strtok(char *s, const char *delim);
size_t strxfrm(char *dst, char *src, size_t n);

long strtol(const char *src, char **endptr, int base);
unsigned long strtoul(const char *src, char **endptr, int base);

#ifdef __cplusplus
	}
#endif

#endif


text:
namespace mesos {
namespace internal {

bool operator==(const Task& left, const Task& right);

std::ostream& operator<<(std::ostream& stream, const StatusUpdate& update);

std::ostream& operator<<(
    std::ostream& stream,
    const StatusUpdateRecord::Type& type);

} // namespace internal {
} // namespace mesos {

#endif // __MESSAGES_HPP__


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>fouti</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="The Canonical Csound Reference Manual" />
    <link rel="up" href="OpcodesTop.html" title="Orchestra Opcodes and Operators" />
    <link rel="prev" href="fout.html" title="fout" />
    <link rel="next" href="foutir.html" title="foutir" />

          fouti

          Prev
          Orchestra Opcodes and Operators
           Next

          fouti

fouti —
      Outputs i-rate signals of an arbitrary number of channels to a specified file.

Description

      fouti output N i-rate signals to a specified file of N channels.

Syntax

fouti ihandle, iformat, iflag, iout1 [, iout2, iout3,....,ioutN]

Initialization

      ihandle -- a number which specifies this file.

      iformat -- a flag to choose output file format:

0 - floating point in text format

1 - 32-bit floating point in binary format

      iflag -- choose the mode of writing to the ASCII file (valid only in ASCII mode; in binary mode iflag has no meaning, but it must be present anyway). iflag can be a value chosen among the following:

0 - line of text without instrument prefix

1 - line of text with instrument prefix (see below)

2 - reset the time of instrument prefixes to zero (to be used only in some particular cases. See below)

      iout,..., ioutN -- values to be written to the file

Performance

      fouti and foutir write i-rate values to a file. The main use of these opcodes is to generate a score file during a realtime session. For this purpose, the user should set iformat to 0 (text file output) and iflag to 1, which enable the output of a prefix consisting of the strings inum, actiontime, and duration, before the values of iout1...ioutN arguments. The arguments in the prefix refer to instrument number, action time and duration of current note.

      Notice that fout and foutk can use either a string containing a file pathname, or a handle-number generated by fiopen. Whereas, with fouti and foutir, the target file can be only specified by means of a handle-number.

Examples

      Here is an example of the fouti opcode. It uses the file fouti.csd.

            Example 334. Example of the fouti opcode.

See the sections Real-time Audio and Command Line Flags for more information on using command line flags.

<CsoundSynthesizer>
<CsOptions>

; Select audio/midi flags here according to platform
-odac     ;;;realtime audio out
;-iadc    ;;;uncomment -iadc if realtime audio input is needed too
; For Non-realtime ouput leave only the line below:
; -o fouti.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

gihand fiopen "test.txt", 0

instr 1

ires  random  0, 10
      fouti gihand, 0, 1, ires
      ficlose gihand

endin
</CsInstruments>
<CsScore>

i 1 0 1

e
</CsScore>
</CsoundSynthesizer>

See Also

      fiopen,
      fout,
      foutir,
      foutk

Credits

            Author: Gabriel Maldonado

            Italy

            1999

New in Csound version 3.56

          Prev

            Up

           Next

          fout

            Home

           foutir


text:
Allow parsing of the `function.sent` meta property.

## Installation

```sh
npm install --save-dev babel-plugin-syntax-function-sent
```

## Usage

### Via `.babelrc` (Recommended)

**.babelrc**

```json
{
  "plugins": ["syntax-function-sent"]
}
```

### Via CLI

```sh
babel --plugins syntax-function-sent script.js
```

### Via Node API

```javascript
require("babel-core").transform("code", {
  plugins: ["syntax-function-sent"]
});
```


text:
<?php

use Illuminate\Support\Facades\URL;

class Platform extends Eloquent {

    public function __toString()
    {
        return $this->title;
    }

    public function getBySlug($slug)
    {
        return $this->where('slug', '=', $slug)->first();
    }

    public function games()
    {
        return $this->hasMany('Game');
    }

    public function url()
    {
        return '/platforms/' . $this->slug;
    }

    public function hasImage()
    {
        return !empty($this->image);
    }
}


text:
using namespace ofxPixelPusher;

Strip::Strip(short stripNumber, int length) {
	mPixels.reserve(length);
	for (int i = 0; i < length; i++) {
		mPixels.push_back(std::shared_ptr<Pixel>(new Pixel()));
	}

	mPixelData.reserve(3 * length);
	for (int i = 0; i < 3 * length; i++) {
		mPixelData.push_back(0);
	}

	mStripNumber = stripNumber;
	mTouched = false;
	mIsRGBOW = false;

	mPowerScale = 1.0;
	mID = NULL;
	mStripType = STRIP;

	resetTexture();
}

Strip::~Strip() {
}

int Strip::getLength() {
	return mPixels.size();
}

bool Strip::isTouched() {
	return mTouched;
}

short Strip::getStripNumber() {
	return mStripNumber;
}

void Strip::setPixels(unsigned char r, unsigned char g, unsigned char b) {
	for (int i = 0; i < mPixels.size(); i++) {
		mPixels[i]->setColor(r, g, b);
	}
	mTouched = true;
}

void Strip::setPixelsHSB(float hue, float saturation, float brightness) {
	for (int i = 0; i < mPixels.size(); i++) {
		mPixels[i]->setColorHSB(hue, saturation, brightness);
	}
	mTouched = true;
}

void Strip::setPixels(std::vector<std::shared_ptr<Pixel> > pixels) {
	mPixels = pixels;
	mTouched = true;
}

void Strip::setPixel(int position, unsigned char r, unsigned char g, unsigned char b) {
	if (position < mPixels.size()) {
		mPixels[position]->setColor(r, g, b);
		mTouched = true;
	}
	else {
		std::printf("Strip::setPixel ERROR -- Invalid pixel number %d.\n", position);
	}
}

void Strip::setPixelHSB(int position, float hue, float saturation, float brightness) {
	if (position < mPixels.size()) {
		mPixels[position]->setColorHSB(hue, saturation, brightness);
		mTouched = true;
	}
	else {
		std::printf("Strip::setPixelHSB ERROR -- Invalid pixel number %d.\n", position);
	}
}

void Strip::setPixel(int position, std::shared_ptr<Pixel> pixel) {
	if (position < mPixels.size()) {
		mPixels[position] = pixel;
		mTouched = true;
	}
	else {
		std::printf("Strip::setPixel ERROR -- Invalid pixel number %d.\n", position);
	}
}

void Strip::setPixelsFromTex() {
	if (mTexSrc != nullptr) {
		if (mUseTexCoords) {

			unsigned char* subTexSrc = new unsigned char[mSubTexWidth*mSubTexHeight*mTexDepth];

			if (mSubTexWidth * mSubTexHeight < mPixels.size()) {
				std::printf("Strip::setPixelsFromTex ERROR -- not enough pixels in subtexture to map to physical pixels.  Please set new texture coordinates.\n");
				return;
			}

			for (int y = 0; y < mSubTexHeight; y++) {
				for (int x = 0; x < mSubTexWidth; x++) {
					for (int d = 0; d < mTexDepth; d++) {
						if (y % 2 == 0) {
							// even row
							subTexSrc[y*mSubTexWidth*mTexDepth + x*mTexDepth + d] = mTexSrc[(mSubTexY + y)*mTexWidth*mTexDepth + (mSubTexX + x)*mTexDepth + d];
						}
						else {
							// even row
							subTexSrc[y*mSubTexWidth*mTexDepth + (mSubTexWidth - x)*mTexDepth + d] = mTexSrc[(mSubTexY + y)*mTexWidth*mTexDepth + (mSubTexX + x)*mTexDepth + d];
						}
					}
				}
			}

			scrapeTexture(subTexSrc, mSubTexWidth, mSubTexHeight, mTexDepth);

			//do I need to free(subTexSrc)? or delete?
			delete[] subTexSrc;
		}
		else {
			scrapeTexture(mTexSrc, mTexWidth, mTexHeight, mTexDepth);
		}
		mTouched = true;
	}

	else {
		std::printf("Strip::setPixelsFromTex ERROR -- no texture assigned!  Please assign a texture to this strip.\n");
	}
}

std::vector<std::shared_ptr<Pixel> > Strip::getPixels() {
	return mPixels;
}

int Strip::getNumberOfPixels() {
	return mPixels.size();
}

void Strip::setPowerScale(double powerscale) {
	if (powerscale <= 1.0 && powerscale > 0.0) {
		mPowerScale = powerscale;
	}
	else {
		std::printf("Strip::setPowerScale -- power scale set out of bounds (0, 1).  Please set the power scale between 0 and 1!\n");
	}
}

void Strip::setTint(unsigned char red, unsigned char green, unsigned char blue) {
	for (auto pixel : mPixels) {
		pixel->setManualCorrection(red / 255.0, green / 255.0, blue / 255.0);
	}

}

void Strip::setTint(float red, float green, float blue) {
	for (auto pixel : mPixels) {
		pixel->setManualCorrection(red, green, blue);
	}

}

void Strip::setColorTemperature(Pixel::ColorTemperature temperature) {
	for (auto pixel : mPixels) {
		pixel->setColorTemperature(temperature);
	}
}

void Strip::setColorCorrection(Pixel::ColorCorrection correction) {
	for (auto pixel : mPixels) {
		pixel->setColorCorrection(correction);
	}
}

void Strip::serialize() {
	for (int i = 0; i < mPixels.size(); i++) {
		mPixelData[3 * i + 0] = (unsigned char)(mPixels[i]->mRed * mPowerScale);
		mPixelData[3 * i + 1] = (unsigned char)(mPixels[i]->mGreen * mPowerScale);
		mPixelData[3 * i + 2] = (unsigned char)(mPixels[i]->mBlue * mPowerScale);
	}
	mTouched = false;
}

std::vector<unsigned char>::iterator Strip::begin() {
	return mPixelData.begin();
}

std::vector<unsigned char>::iterator Strip::end() {
	return mPixelData.end();
}

void Strip::setID(int id) {
	mID = id;
}

int Strip::getID() {
	return mID;
}

void Strip::setStripType(StripType type) {
	if (type == StripType::TWENTYSQUARED && mPixels.size() < 400) {
		std::printf("Strip::setStriPType ERROR -- not enough pixels for this strip to be set as a TwentySquared tile.  Please check your PixelPusher's pixel.rc file.\n");
	}
	mStripType = type;
}

StripType Strip::getStripType() {
	return mStripType;
}

void Strip::setTexture(unsigned char* source, int width, int height, int depth) {
	if (width * height < mPixels.size()) {
		std::printf("Strip::setTexture ERROR -- not enough pixels in texture to map to physical pixels.  Please use a larger texture.\n");
		return;
	}
	mTexSrc = source;
	mTexWidth = width;
	mTexHeight = height;
	mTexDepth = depth;
}

void Strip::resetTexture() {
	mTexSrc = nullptr;
	mTexWidth = 0;
	mTexHeight = 0;
	mTexDepth = 0;
	mUseTexCoords = false;
	mSubTexX = 0.0;
	mSubTexY = 0.0;
	mSubTexWidth = 0.0;
	mSubTexHeight = 0.0;
}

void Strip::setTexCoords(float lower_x, float lower_y, float upper_x, float upper_y) {
	if (lower_x > upper_x || lower_y > upper_y) {
		std::printf("Strip::setTexCoords ERROR -- lower bounds greater than upper bounds.\n");
		return;
	}
	if (lower_x < 0 || upper_x < 0 || lower_y < 0 || upper_y < 0) {
		std::printf("Strip::setTexCoords ERROR -- texture coordinates must be greater than zero.\n");
		return;
	}

	mSubTexX = lower_x*mTexWidth;
	mSubTexY = lower_y*mTexHeight;
	mSubTexWidth = (upper_x - lower_x)*mTexWidth + 1;
	mSubTexHeight = (upper_y - lower_y)*mTexHeight + 1;

	if (mSubTexWidth*mSubTexHeight < mPixels.size()) {
		std::printf("Strip::setTexCoords ERROR -- not enough pixels in subtexture to map to physical pixels.  Please set new texture coordinates.\n");
		return;
	}

	mUseTexCoords = true;
}

void Strip::scrapeTexture(unsigned char* source, int width, int height, int depth) {
	int stride_x;
	int stride_y;

	switch(mStripType) {
	case STRIP:
		//evenly distribute pixels along length of strip
		stride_x = (width*height) / (float)mPixels.size();
		for (int i = 0; i < mPixels.size(); i++) {
			mPixels[i]->setColor(source[stride_x*i*depth + 0], source[stride_x*i*depth + 1], source[stride_x*i*depth + 2]);
		}
		break;
	case TWENTYSQUARED:
		//evenly distribute pixels across x and y
		stride_x = int(width / 20.0);
		stride_y = int(height / 20.0);
		for (int j = 0; j < 20; j++) {
			for (int i = 0; i < 20; i++) {
				if (j % 2 == 0) {
					//even row
					int index = i + 20 * j;
					int source_pixel = i*stride_x + j*stride_y*width;
					setPixel(index, source[source_pixel*depth + 0], source[source_pixel*depth + 1], source[source_pixel*depth + 2]);
				}
				else {
					//odd row
					// FIX THIS
					int index = 20 * (j+1) - (i+1);
					int source_pixel = i*stride_x + j*stride_y*width;
					setPixel(index, source[source_pixel*depth + 0], source[source_pixel*depth + 1], source[source_pixel*depth + 2]);
				}
			}
		}
		break;
	}

}


text:
<#
.SYNOPSIS
Microsoft.PowerShell_profile.ps1 - My Custom PowerShell profile

.DESCRIPTION
Customizes the PowerShell console

.NOTES
Author: Nicolas PRIGENT
Source: https://www.red-gate.com/simple-talk/sysadmin/powershell/powershell-day-to-day-sysadmin-tasks-securing-scripts/
#>

#PART 1

if ($host.name -eq 'ConsoleHost')
{
$Shell=$Host.UI.RawUI
$size=$Shell.BufferSize
$size.width=120
$size.height=3000
$Shell.BufferSize=$size
$size=$Shell.WindowSize
$size.width=120
$size.height=30
$Shell.WindowSize=$size
$Shell.BackgroundColor="Black"
$Shell.ForegroundColor="White"
$Shell.CursorSize=10
$Shell.WindowTitle="Console PowerShell - By Nicolas"
}

#PART 2

function Get-Uptime {

 $os = Get-WmiObject win32_operatingsystem
 $uptime = (Get-Date) - ($os.ConvertToDateTime($os.lastbootuptime))
 $Display = "" + $Uptime.Days + "days / " + $Uptime.Hours + "hours / " + $Uptime.Minutes + "minutes"
 Write-Output $Display
}

function Get-Time {return $(Get-Date | ForEach {$_.ToLongTimeString()})}

function prompt
{
 Write-Host "[" -noNewLine
 Write-Host $(Get-Time) -ForegroundColor DarkYellow -noNewLine
 Write-Host "] " -noNewLine
 Write-Host $($(Get-Location).Path.replace($home,"~")) -ForegroundColor DarkGreen -noNewLine
 Write-Host $(if ($nestedpromptlevel -ge 1) { '>>' }) -noNewLine
 return "> "
}

function rdp ($IPAddr) {
 Start-Process -FilePath mstsc -ArgumentList "/admin /w:1024 /h:768 /v:$IPAddr"
}

#PART 3

Set-Location C:\

$MaximumHistoryCount=1024
$IPAddress=@(Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DefaultIpGateway})[0].IPAddress[0]
$IPGateway=@(Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object {$_.DefaultIpGateway})[0].DefaultIPGateway[0]
$PSExecPolicy=Get-ExecutionPolicy
$PSVersion=$PSVersionTable.PSVersion.Major

#PART 4

Clear-Host
Write-Host " -------------------------------------------------------------------------------------------------------" -ForegroundColor Green
Write-Host " ¦`tComputerName:`t`t" -nonewline -ForegroundColor Green;Write-Host $($env:COMPUTERNAME)"`t`t`t`t" -nonewline -ForegroundColor Cyan;Write-Host "UserName:`t" -nonewline -ForegroundColor Green;Write-Host $env:UserDomain\$env:UserName"`t`t" -nonewline -ForegroundColor Cyan;Write-Host " ¦" -ForegroundColor Green
Write-Host " ¦`tLogon Server:`t`t" -nonewline -ForegroundColor Green;Write-Host $($env:LOGONSERVER)"`t`t`t`t" -nonewline -ForegroundColor Cyan;Write-Host "IP Address:`t" -nonewline -ForegroundColor Green;Write-Host $IPAddress"`t`t" -nonewline -ForegroundColor Cyan;Write-Host " ¦" -ForegroundColor Green
Write-Host " ¦`tPS Execution Policy:`t" -nonewline -ForegroundColor Green;Write-Host $($PSExecPolicy)"`t`t`t" -nonewline -ForegroundColor Cyan;Write-Host "PS Version:`t" -nonewline -ForegroundColor Green;Write-Host $PSVersion"`t`t`t" -nonewline -ForegroundColor Cyan;Write-Host " ¦" -ForegroundColor Green
Write-Host " ¦`tUptime:`t`t`t" -nonewline -ForegroundColor Green;Write-Host $(Get-Uptime)"`t`t`t`t`t`t" -nonewline -ForegroundColor Cyan;Write-Host " ¦" -ForegroundColor Green
Write-Host " -------------------------------------------------------------------------------------------------------`n" -ForegroundColor Green
Write-Host "Customs functions : Get-Uptime / Get-Time / RDP <IPAddr>`n" -ForegroundColor


text:
exports.config = {
  allScriptsTimeout: 11000,

  specs: [
    'e2e/*.js'
  ],

  capabilities: {
    'browserName': 'chrome'
  },

  baseUrl: 'http://localhost:8000/app/angular',

  framework: 'jasmine',

  jasmineNodeOpts: {
    defaultTimeoutInterval: 30000
  }
};


text:
package com.mongodb.internal.operation;

import com.mongodb.Function;
import com.mongodb.MongoException;
import com.mongodb.MongoExecutionTimeoutException;
import com.mongodb.MongoNodeIsRecoveringException;
import com.mongodb.MongoNotPrimaryException;
import com.mongodb.MongoSocketException;
import com.mongodb.MongoTimeoutException;
import com.mongodb.MongoWriteConcernException;
import com.mongodb.WriteConcern;
import com.mongodb.connection.ConnectionDescription;
import com.mongodb.connection.ServerDescription;
import com.mongodb.internal.async.SingleResultCallback;
import com.mongodb.internal.binding.AsyncWriteBinding;
import com.mongodb.internal.binding.WriteBinding;
import com.mongodb.internal.operation.CommandOperationHelper.CommandCreator;
import com.mongodb.lang.Nullable;
import org.bson.BsonDocument;
import org.bson.BsonInt32;
import org.bson.BsonInt64;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL;
import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.internal.operation.CommandOperationHelper.RETRYABLE_WRITE_ERROR_LABEL;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * An operation that commits a transaction.
 *
 *
This class is not part of the public API and may be removed or changed at any time

 */
public class CommitTransactionOperation extends TransactionOperation {
    private final boolean alreadyCommitted;
    private BsonDocument recoveryToken;
    private Long maxCommitTimeMS;

    public CommitTransactionOperation(final WriteConcern writeConcern) {
        this(writeConcern, false);
    }

    public CommitTransactionOperation(final WriteConcern writeConcern, final boolean alreadyCommitted) {
        super(writeConcern);
        this.alreadyCommitted = alreadyCommitted;
    }

    public CommitTransactionOperation recoveryToken(final BsonDocument recoveryToken) {
        this.recoveryToken = recoveryToken;
        return this;
    }

    public CommitTransactionOperation maxCommitTime(@Nullable final Long maxCommitTime, final TimeUnit timeUnit) {
        if (maxCommitTime == null) {
            this.maxCommitTimeMS = null;
        } else {
            notNull("timeUnit", timeUnit);
            isTrueArgument("maxCommitTime > 0", maxCommitTime > 0);
            this.maxCommitTimeMS = MILLISECONDS.convert(maxCommitTime, timeUnit);
        }
        return this;
    }

    @Nullable
    public Long getMaxCommitTime(final TimeUnit timeUnit) {
        notNull("timeUnit", timeUnit);
        if (maxCommitTimeMS == null) {
            return null;
        }
        return timeUnit.convert(maxCommitTimeMS, MILLISECONDS);
    }

    @Override
    public Void execute(final WriteBinding binding) {
        try {
            return super.execute(binding);
        } catch (MongoException e) {
            addErrorLabels(e);
            throw e;
        }
    }

    @Override
    public void executeAsync(final AsyncWriteBinding binding, final SingleResultCallback<Void> callback) {
        super.executeAsync(binding, new SingleResultCallback<Void>() {
            @Override
            public void onResult(final Void result, final Throwable t) {
                 if (t instanceof MongoException) {
                     addErrorLabels((MongoException) t);
                 }
                 callback.onResult(result, t);
            }
        });
    }

    private void addErrorLabels(final MongoException e) {
        if (shouldAddUnknownTransactionCommitResultLabel(e)) {
            e.addLabel(UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL);
        }
    }

    private static final List<Integer> NON_RETRYABLE_WRITE_CONCERN_ERROR_CODES = asList(79, 100);

    private static boolean shouldAddUnknownTransactionCommitResultLabel(final MongoException e) {

        if (e instanceof MongoSocketException || e instanceof MongoTimeoutException
                || e instanceof MongoNotPrimaryException || e instanceof MongoNodeIsRecoveringException
                || e instanceof MongoExecutionTimeoutException) {
            return true;
        }

        if (e.hasErrorLabel(RETRYABLE_WRITE_ERROR_LABEL)) {
            return true;
        }

        if (e instanceof MongoWriteConcernException) {
            return !NON_RETRYABLE_WRITE_CONCERN_ERROR_CODES.contains(e.getCode());
        }

        return false;
    }

    @Override
    protected String getCommandName() {
        return "commitTransaction";
    }

    @Override
    CommandCreator getCommandCreator() {
        final CommandCreator creator = new CommandCreator() {
            @Override
            public BsonDocument create(final ServerDescription serverDescription, final ConnectionDescription connectionDescription) {
                BsonDocument command = CommitTransactionOperation.super.getCommandCreator().create(serverDescription,
                        connectionDescription);
                if (maxCommitTimeMS != null) {
                    command.append("maxTimeMS",
                            maxCommitTimeMS > Integer.MAX_VALUE
                            ? new BsonInt64(maxCommitTimeMS) : new BsonInt32(maxCommitTimeMS.intValue()));
                }
                return command;
            }
        };
        if (alreadyCommitted) {
            return new CommandCreator() {
                @Override
                public BsonDocument create(final ServerDescription serverDescription, final ConnectionDescription connectionDescription) {
                    return getRetryCommandModifier().apply(creator.create(serverDescription, connectionDescription));
                }
            };
        } else if (recoveryToken != null) {
                return new CommandCreator() {
                    @Override
                    public BsonDocument create(final ServerDescription serverDescription,
                                               final ConnectionDescription connectionDescription) {
                        return creator.create(serverDescription, connectionDescription).append("recoveryToken", recoveryToken);
                    }
                };
        }
        return creator;
    }

    @Override
    protected Function<BsonDocument, BsonDocument> getRetryCommandModifier() {
        return new Function<BsonDocument, BsonDocument>() {
            @Override
            public BsonDocument apply(final BsonDocument command) {
                WriteConcern retryWriteConcern = getWriteConcern().withW("majority");
                if (retryWriteConcern.getWTimeout(TimeUnit.MILLISECONDS) == null) {
                    retryWriteConcern = retryWriteConcern.withWTimeout(10000, TimeUnit.MILLISECONDS);
                }
                command.put("writeConcern", retryWriteConcern.asDocument());
                if (recoveryToken != null) {
                    command.put("recoveryToken", recoveryToken);
                }
                return command;
            }
        };
    }
}


text:
The material embodied in this software is provided to you "as-is" and without
warranty of any kind, express, implied or otherwise, including without
limitation, any warranty of fitness for a particular purpose. In no event shall
the Centers for Disease Control and Prevention (CDC) or the United States (U.S.)
government be liable to you or anyone else for any direct, special, incidental,
indirect or consequential damages of any kind, or any damages whatsoever,
including without limitation, loss of profit, loss of use, savings or revenue,
or the claims of third parties, whether or not CDC or the U.S. government has
been advised of the possibility of such loss, however caused and on any theory
of liability, arising out of or in connection with the possession, use or
performance of this software.


text:
require "chef/knife"
require "chef/knife/key_create"
require "chef/knife/key_create_base"

class Chef
  class Knife
    # Implements knife user key create using Chef::Knife::KeyCreate
    # as a service class.
    #
    # @author Tyler Cloke
    #
    # @attr_reader [String] actor the name of the client that this key is for
    class ClientKeyCreate < Knife
      include Chef::Knife::KeyCreateBase

      banner "knife client key create CLIENT (options)"

      attr_reader :actor

      def initialize(argv = [])
        super(argv)
        @service_object = nil
      end

      def run
        apply_params!(@name_args)
        service_object.run
      end

      def actor_field_name
        "client"
      end

      def service_object
        @service_object ||= Chef::Knife::KeyCreate.new(@actor, actor_field_name, ui, config)
      end

      def actor_missing_error
        "You must specify a client name"
      end

      def apply_params!(params)
        @actor = params[0]
        if @actor.nil?
          show_usage
          ui.fatal(actor_missing_error)
          exit 1
        end
      end
    end
  end
end


text:
package TAD_PILA;

import ListaDoble.Doble;

public class Pila<T> implements IPila<T>{

	protected Doble<T> pila;
	private int top;
	private int capacidad;
	private Pila<T> parteSuperior;

	public Pila(){
		pila = new Doble<T>();
		top=-1;
		capacidad = pila.darLongitud();

	}

	public int getCapacidad() {
		return capacidad;
	}

	@Override
	public void empuje(T elemento) {
		// TODO Auto-generated method stub
		try {
			pila.agregar(0, elemento);
			top++;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Pila<T> getParteSuperior() {
		return parteSuperior;
	}

	@Override
	public void pop() {
		// TODO Auto-generated method stub
		pila.eliminar(0);
		top--;
	}

	@Override
	public boolean estaVacia() {
		// TODO Auto-generated method stub
		boolean vacio = false;
		if(getTop()==-1){
			vacio = true;
		}
		return vacio;
	}

	@Override
	public T darElementoParteSuperior() {
		// TODO Auto-generated method stub
		T elemento = null;
		try {
			elemento = pila.darElemento(0);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return elemento;
	}

	public int getTop() {
		// TODO Auto-generated method stub
		return top;
	}

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<methodResponse>
<params>
<param>
<value><struct>
<member>
<name>date_updated</name>
<value><dateTime.iso8601>20110324T15:49:50</dateTime.iso8601></value>
</member>
<member>
<name>last_error</name>
<value><string></string></value>
</member>
<member>
<name>date_start</name>
<value><string></string></value>
</member>
<member>
<name>source</name>
<value><string>AB3917-GANDI</string></value>
</member>
<member>
<name>step</name>
<value><string>DONE</string></value>
</member>
<member>
<name>eta</name>
<value><int>39</int></value>
</member>
<member>
<name>date_created</name>
<value><dateTime.iso8601>20110324T15:49:32</dateTime.iso8601></value>
</member>
<member>
<name>type</name>
<value><string>vm_delete</string></value>
</member>
<member>
<name>id</name>
<value><int>637366</int></value>
</member>
</struct></value>
</param>
</params>
</methodResponse>


text:
<?php

namespace s9e\TextFormatter\Tests\Configurator\Traits;

use s9e\TextFormatter\Tests\Test;
use s9e\TextFormatter\Configurator\Collections\NormalizedCollection;
use s9e\TextFormatter\Configurator\Traits\Configurable;

/**
* @covers s9e\TextFormatter\Configurator\Traits\Configurable
*/
class ConfigurableTest extends Test
{
	/**
	* @testdox __get('foo') calls getFoo() if it exists
	*/
	public function testMagicGetMethod()
	{
		$dummy = new ConfigurableTestDummy;

		$this->assertSame('foobar', $dummy->foo);
	}

	/**
	* @testdox __get($k) returns the property if it exists
	*/
	public function testMagicGet()
	{
		$dummy = new ConfigurableTestDummy;

		$this->assertSame(42, $dummy->int);
	}

	/**
	* @testdox __get() throws a RuntimeException if the property does not exist
	* @expectedException RuntimeException
	* @expectedExceptionMessage Property 'inexistent' does not exist
	*/
	public function testMagicGetInexistent()
	{
		$dummy = new ConfigurableTestDummy;
		$dummy->inexistent;
	}

	/**
	* @testdox __get($k) returns null if the property is null
	*/
	public function testMagicGetNull()
	{
		$dummy = new ConfigurableTestDummy;

		$this->assertNull($dummy->null);
	}

	/**
	* @testdox __set('foo', 'bar') calls setFoo('bar') if it exists
	*/
	public function testMagicSetMethod()
	{
		$dummy = new ConfigurableTestDummy;
		$dummy->foo = 'bar';

		$this->assertSame('foobar', $dummy->foo);
	}

	/**
	* @testdox __set() can create new properties
	*/
	public function testMagicSetNew()
	{
		$dummy = new ConfigurableTestDummy;
		$dummy->inexistent = 'foo';

		$this->assertSame('foo', $dummy->inexistent);
	}

	/**
	* @testdox __set() can replace an instance of Foo with another instance of Foo
	*/
	public function testMagicSetSameObject()
	{
		$dummy = new ConfigurableTestDummy;

		$foo = new Foo;
		$dummy->fooObject = $foo;

		$this->assertSame($foo, $dummy->fooObject);
	}

	/**
	* @testdox __set() can replace an instance of Foo with an instance of FooPlus, which extends Foo
	*/
	public function testMagicSetChildObject()
	{
		$dummy = new ConfigurableTestDummy;

		$foo = new FooPlus;
		$dummy->fooObject = $foo;

		$this->assertSame($foo, $dummy->fooObject);
	}

	/**
	* @testdox __set() throws an exception if an instance of Foo would be replaced by an instance of Bar
	* @expectedException InvalidArgumentException
	* @expectedExceptionMessage Cannot replace property 'fooObject' of class 's9e\TextFormatter\Tests\Configurator\Traits\Foo' with instance of 's9e\TextFormatter\Tests\Configurator\Traits\Bar'
	*/
	public function testMagicSetDifferentObject()
	{
		$dummy = new ConfigurableTestDummy;

		$bar = new Bar;
		$dummy->fooObject = $bar;
	}

	/**
	* @testdox __set() can replace a scalar value with a value of the same type
	*/
	public function testMagicSetSameType()
	{
		$dummy = new ConfigurableTestDummy;
		$dummy->int = 55;

		$this->assertSame(55, $dummy->int);
	}

	/**
	* @testdox __set() can replace a scalar value with another scalar value if it can be losslessly cast to the same type
	*/
	public function testMagicSetCompatibleType()
	{
		$dummy = new ConfigurableTestDummy;
		$dummy->int = '55';

		$this->assertSame(55, $dummy->int);
	}

	/**
	* @testdox __set() throws an exception if a scalar value would be overwritten by a scalar value that cannot be losslessly cast to the same type
	* @expectedException InvalidArgumentException
	* @expectedExceptionMessage Cannot replace property 'int' of type integer with value of type string
	*/
	public function testMagicSetIncompatibleType()
	{
		$dummy = new ConfigurableTestDummy;

		$dummy->int = "55!";
	}

	/**
	* @testdox __set() will clear and repopulate a NormalizedCollection rather than overwrite it
	*/
	public function testMagicSetNormalizedCollection()
	{
		$dummy = new ConfigurableTestDummy;

		$dummy->collection->set('old', 'old');

		$values = array('foo' => 'bar', 'baz' => 'quux');
		$dummy->collection = $values;

		$this->assertInstanceOf(
			's9e\\TextFormatter\\Configurator\\Collections\\NormalizedCollection',
			$dummy->collection
		);

		$this->assertSame($values, iterator_to_array($dummy->collection));
	}

	/**
	* @testdox __set() throws an exception if a NormalizedCollection would be overwritten by a non-array, non-Traversable value
	* @expectedException InvalidArgumentException
	* @expectedExceptionMessage Property 'collection' expects an array or a traversable object to be passed
	*/
	public function testMagicSetNonTraversable()
	{
		$dummy = new ConfigurableTestDummy;

		$dummy->collection = 1;
	}

	/**
	* @testdox __isset($k) returns true if the property exists
	*/
	public function testMagicIsset()
	{
		$dummy = new ConfigurableTestDummy;

		$this->assertTrue(isset($dummy->int));
	}
}

class Foo {}
class FooPlus extends Foo {}
class Bar {}

class ConfigurableTestDummy
{
	use Configurable;

	protected $int = 42;
	protected $null = null;
	protected $collection;
	protected $fooObject;

	public function __construct()
	{
		$this->collection = new NormalizedCollection;
		$this->fooObject  = new Foo;
	}

	protected function getFoo()
	{
		return 'foobar';
	}

	protected function setFoo($str)
	{
		$this->foo = 'foo' . $str;
	}
}


text:
import logging
import urllib

from flask import redirect, g, abort
from flask import Blueprint
from google.appengine.api import urlfetch

from sparkprs import app
from sparkprs.models import Issue

jenkins = Blueprint('jenkins', __name__)

@jenkins.route("/trigger-jenkins/<int:number>", methods=['GET', 'POST'])
def test_pr(number):
    """
    Triggers a parametrized Jenkins build for testing Spark pull requests.
    """
    if not (g.user and g.user.has_capability("jenkins")):
        return abort(403)
    pr = Issue.get_or_create(number)
    commit = pr.pr_json["head"]["sha"]
    target_branch = pr.pr_json["base"]["ref"]
    # The parameter names here were chosen to match the ones used by Jenkins' GitHub pull request
    # builder plugin: https://wiki.jenkins-ci.org/display/JENKINS/Github+pull+request+builder+plugin
    # In the Spark repo, the https://github.com/apache/spark/blob/master/dev/run-tests-jenkins
    # script reads these variables when posting pull request feedback.
    query = {
        'token': app.config['JENKINS_PRB_TOKEN'],
        'ghprbPullId': number,
        'ghprbActualCommit': commit,
        'ghprbTargetBranch': target_branch,
        'ghprbPullTitle': pr.raw_title.encode('utf-8'),
        # This matches the Jenkins plugin's logic; see
        # https://github.com/jenkinsci/ghprb-plugin/blob/master/src/main/java/org/jenkinsci/plugins/ghprb/GhprbTrigger.java#L146
        #
        # It looks like origin/pr/*/merge ref points to the last successful test merge commit that
        # GitHub generates when it checks for mergeability.  This API technically isn't documented,
        # but enough plugins seem to rely on it that it seems unlikely to change anytime soon
        # (if it does, we can always upgrade our tests to perform the merge ourselves).
        #
        # See also: https://developer.github.com/changes/2013-04-25-deprecating-merge-commit-sha/
        'sha1': ("origin/pr/%i/merge" % number) if pr.is_mergeable else commit,
    }
    trigger_url = "%sbuildWithParameters?%s" % (app.config["JENKINS_PRB_JOB_URL"],
                                                urllib.urlencode(query))
    logging.debug("Triggering Jenkins with url %s" % trigger_url)
    response = urlfetch.fetch(trigger_url, method="POST")
    if response.status_code not in (200, 201):
        logging.error("Jenkins responded with status code %i" % response.status_code)
        return response.content
    else:
        return redirect(app.config["JENKINS_PRB_JOB_URL"])


text:
// License Terms
//
// Copyright (c) 2008, California Institute of Technology ("Caltech").
// U.S. Government sponsorship acknowledged.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Caltech nor its operating division, the Jet Propulsion
// Laboratory, nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER  OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
/**
 * Test program
 *
 * This program displays one image in mono or two image as stereo pair
 * Mono or Left image is put in a custom viewport that allows to "scroll"
 * it independently from "right" image.
 * To scroll both images: use scrollbars.  To scroll left image with respect
 * to right image use slider bars.
 *
 * Requires J2SE runtime environment, JAI, JOGL and JadeDisplay
 *  * To run it:
 * % Jadis_disparity_test left_image right_image(optional)
 * Note that not all Look and Feels are fully supported, if encounter problems add
 * -Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel as a VM argument
 * on a command line.
 * Created on April 14, 2008, 10:52 AM
 * @author Oleg Pariser
 */
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

import javax.media.jai.*;

import jpl.mipl.jade.*;
import jpl.mipl.jade.jadis.Jadis;
import jpl.mipl.jade.jadis.StereoJPanel;
import jpl.mipl.jade.jadis.StereoJFrame;

public class Jadis_disparity_test {

	JSlider _hdispSlider, _vdispSlider;
	JViewportImage _vp_disp_left;
    /** Creates a new instance */
    public Jadis_disparity_test(String argv[]) {
        super();

        PlanarImage image_left = null;
        PlanarImage _image_right = null;
        boolean _is_stereo_pair = false;

        // Load the images specified as command line args
        if (argv.length == 0) {
        	System.out.println("Usage: Jadis_disparity_test left_image right_image(optional)");
            System.exit(0);
        }
        else {
        	image_left = JAI.create("fileload", argv[0]);
        }
        if (argv.length > 1) {
        	_image_right = JAI.create("fileload", argv[1]);

            _is_stereo_pair = true;
        }

        // Add left and right view to the panel that can display them simultaneously
        StereoJPanel stereoPanel = new StereoJPanel();

        JadeDisplay jd_left  = new JadeDisplay(image_left);
        // for this sample program only left image component is put in a viewport to control
        // For the "real" program, most useful scenario likely would be both "left" and "right" image
        // display components put in "viewport within viewport"
        _vp_disp_left = new JViewportImage();
        _vp_disp_left.setView(jd_left);
        if (_is_stereo_pair) {
        	JadeDisplay jd_right = new JadeDisplay(_image_right);
        	stereoPanel.add(_vp_disp_left, "Left");
        	stereoPanel.add(jd_right, "Right");
        }
        else {
        	stereoPanel.add(jd_left);
        }

        // Manage the panel using Scrollpane
        // this is optional
        JViewportImage viewport = new JViewportImage();
        viewport.setView(stereoPanel);
        JScrollPane sp = new JScrollPane();
        sp.setViewport(viewport);

        // create new custom JFrame capable of displaying stereo
        StereoJFrame myFrame = new StereoJFrame();
        //JFrame myFrame = new JFrame();
        myFrame.getContentPane().add(sp);
        // set the stereo mode, anaglyph is the default
        //myFrame.setStereoMode(Jadis.STEREO_ANAGLYPH);

        // disable double buffering
        RepaintManager currentManager = RepaintManager.currentManager(myFrame);
        currentManager.setDoubleBufferingEnabled(false);

        // set the size of the window and make it visible
        myFrame.getContentPane().setPreferredSize(new Dimension(500, 600));
        myFrame.pack();
        myFrame.setVisible(true);

    	JFrame f3 = new JFrame("controls");
        f3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container w3 = f3.getContentPane();
        w3.setLayout(new BoxLayout(w3, BoxLayout.Y_AXIS));

    	_hdispSlider = new JSlider(-700, 700, 0);
       	_vdispSlider = new JSlider(-500, 500, 0);
    	_hdispSlider.addChangeListener(new ChangeListener() {
    		public void stateChanged(ChangeEvent e) {
			int off_x = _hdispSlider.getValue();
			int off_y = _vdispSlider.getValue();
			    _vp_disp_left.setViewPosition(new Point(off_x, off_y));
			    //System.out.println("changing offset to " + off_x + " " + off_y);
		    }
		});
       	_vdispSlider.addChangeListener(new ChangeListener() {
    		public void stateChanged(ChangeEvent e) {
			int off_x = _hdispSlider.getValue();
			int off_y = _vdispSlider.getValue();
			    _vp_disp_left.setViewPosition(new Point(off_x, off_y));
			    //System.out.println("changing offset to " + off_x + " " + off_y);
		    }
		});
		w3.add(new JLabel("disparity"));
		w3.add(_hdispSlider);
		w3.add(_vdispSlider);

    	f3.pack();
    	f3.setVisible(true);
     }

    public static void main(String argv[]){

    	new Jadis_disparity_test(argv);

    }
}


text:
/*

Azure Media Services REST API v2 Function

This function prepares the asset for indexing with Video Indexer v2. It delete all the non mp4 files from the asset & blob container

Input:
{
    "assetId" : "the Id of the asset"
}
Output:
{
    "mp4FileName":"" // name of the mp4 file
}

*/

using System;
using System.Net;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.MediaServices.Client;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using System.Net.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Linq;
using Microsoft.WindowsAzure.Storage.Blob;

namespace media_functions_for_logic_app
{
    public static class prepare_asset_for_vi
    {
        // Field for service context.
        private static CloudMediaContext _context = null;

        [FunctionName("prepare-asset-for-vi")]
        public static async Task<object> Run([HttpTrigger(WebHookType = "genericJson")]HttpRequestMessage req, TraceWriter log)

        {
            log.Info($"Webhook was triggered!");

            string jsonContent = await req.Content.ReadAsStringAsync();
            dynamic data = JsonConvert.DeserializeObject(jsonContent);
            log.Info("Request : " + jsonContent);

            MediaServicesCredentials amsCredentials = new MediaServicesCredentials();
            log.Info($"Using Azure Media Service Rest API Endpoint : {amsCredentials.AmsRestApiEndpoint}");

            // Validate input objects
            if (data.assetId == null)
                return req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Please pass assetId in the input object" });

            string assetId = data.assetId;

            var attachedstoragecred = KeyHelper.ReturnStorageCredentials();
            string mp4FileName = "";

            IAsset asset = null;
            try
            {

                AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(amsCredentials.AmsAadTenantDomain,
                                             new AzureAdClientSymmetricKey(amsCredentials.AmsClientId, amsCredentials.AmsClientSecret),
                                             AzureEnvironments.AzureCloudEnvironment);

                AzureAdTokenProvider tokenProvider = new AzureAdTokenProvider(tokenCredentials);

                _context = new CloudMediaContext(amsCredentials.AmsRestApiEndpoint, tokenProvider);

                // Find the Asset
                asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault();
                if (asset == null)
                    return req.CreateResponse(HttpStatusCode.BadRequest, new { error = "Asset not found" });

                var files = asset.AssetFiles.ToList().Where(f => !f.Name.EndsWith(".mp4"));

                string storname = amsCredentials.StorageAccountName;
                string storkey = amsCredentials.StorageAccountKey;
                if (asset.StorageAccountName != amsCredentials.StorageAccountName)
                {
                    if (attachedstoragecred.ContainsKey(asset.StorageAccountName)) // asset is using another storage than default but we have the key
                    {
                        storname = asset.StorageAccountName;
                        storkey = attachedstoragecred[storname];
                    }
                    else // we don't have the key for that storage
                    {
                        log.Info($"Face redaction Asset is in {asset.StorageAccountName} and key is not provided in MediaServicesAttachedStorageCredentials application settings");
                        return req.CreateResponse(HttpStatusCode.BadRequest, new
                        {
                            error = "Storage key is missing"
                        });
                    }
                }

                // Setup blob container
                CloudBlobContainer sourceBlobContainer = CopyBlobHelpers.GetCloudBlobContainer(storname, storkey, asset.Uri.Segments[1]);

                foreach (var file in asset.AssetFiles.ToList())
                {
                    if (file.Name.EndsWith(".mp4"))
                    {
                        file.IsPrimary = true;
                        file.Update();
                        mp4FileName = file.Name;
                    }
                    else
                    {

                        file.Delete();
                        CloudBlob sourceBlob = sourceBlobContainer.GetBlockBlobReference(file.Name);
                        sourceBlob.DeleteIfExists();
                        log.Info($"Start copy of file : {file.Name}");
                    }
                }
                asset.Update();
                MediaServicesHelper.SetAFileAsPrimary(asset);

            }
            catch (Exception ex)
            {
                string message = ex.Message + ((ex.InnerException != null) ? Environment.NewLine + MediaServicesHelper.GetErrorMessage(ex) : "");
                log.Info($"ERROR: Exception {message}");
                return req.CreateResponse(HttpStatusCode.InternalServerError, new { error = message });
            }

            return req.CreateResponse(HttpStatusCode.OK, new
            {
                mp4FileName
            });
        }
    }
}


text:
default['openhab']['install_java']   = true
default['openhab']['install_method'] = 'package'
default['openhab']['version']        = '1.8.1'
default['openhab']['plugins']        = []

# Source only options:
default['openhab']['install_dir'] = '/opt'
default['openhab']['user']        = 'root'
default['openhab']['group']       = 'root'

# Init script options:
default['openhab']['http_port']  = '8080'
default['openhab']['https_port'] = '8443'

# my.openHAB options:
default['openhab']['my']['version'] = '1.7.0'

# habmin options:
default['openhab']['habmin']['install_dir']    = '/opt/openhab/webapps/habmin'
default['openhab']['habmin']['git_repository'] = 'https://github.com/cdjackson/HABmin'
default['openhab']['habmin']['git_revision']   = 'e523d77c7a3d73d75ce050a582a3bfe8bc7a1324' # v0.1.3-snapshot
default['openhab']['habmin']['user']           = 'root'
default['openhab']['habmin']['group']          = 'root'