text:
require 'twilio-ruby'

response = Twilio::TwiML::VoiceResponse.new
response.pay do |pay|
  pay.prompt(for: 'expiration-date', attempt: '1') do |prompt|
    prompt
      .say(message: 'Please enter your expiration date, two digits for the month and two digits for the year.')
  end
  pay.prompt(for: 'expiration-date', attempt: '2 3') do |prompt2|
    prompt2
      .say(message: 'Please enter your expiration date, two digits for the month and two digits for the year. For example, if your expiration date is March 2022, then please enter 0 3 2 2')
  end
end

puts response

redpajama_set_name: RedPajamaGithub


text:
/*
	Tournaments Commands
*/

Settings.addPermissions(['tournament']);

exports.commands = {
	tourhelp: function (arg, by, room, cmd) {
		this.restrictReply('Usage: ' + this.cmdToken + this.trad('h'), 'tournament');
	},

	tourstart: 'tourend',
	tourend: function (arg, by, room, cmd) {
		if (this.roomType !== 'chat' || !this.can('tournament')) return;
		if (!Features['tours'].tourData[room]) return this.reply(this.trad('err'));
		if (cmd === 'tourstart' && Features['tours'].tourData[room].isStarted) return false;
		this.reply("/tournament " + (cmd === 'tourend' ? 'end' : 'start'));
	},

	maketour: 'tournament',
	newtour: 'tournament',
	itour: 'tournament',
	tour: 'tournament',
	tournament: function (arg, by, room, cmd) {
		if (this.roomType !== 'chat' || !this.can('tournament')) return;
		if (Features['tours'].tourData[room]) {
			if (toId(arg) === 'end') return this.parse(this.cmdToken + 'tourend');
			if (toId(arg) === 'start') return this.parse(this.cmdToken + 'tourstart');
			return this.reply(this.trad('e2'));
		}
		var details = {
			format: 'ou',
			type: 'elimination',
			maxUsers: null,
			timeToStart: 30 * 1000,
			autodq: 1.5
		};
		if (typeof Config.tourDefault === 'object') {
			for (var i in Config.tourDefault) {
				details[i] = Config.tourDefault[i];
			}
		}
		if (arg && arg.length) {
			var args = arg.split(",");
			var params = {
				format: null,
				type: null,
				maxUsers: null,
				timeToStart: null,
				autodq: null,
				scout: null
			};
			var splArg;
			for (var i = 0; i < args.length; i++) {
				args[i] = args[i].trim();
				if (!args[i]) continue;
				splArg = args[i].split("=");
				if (splArg.length < 2) {
					switch (i) {
						case 0:
							params.format = args[i];
							break;
						case 1:
							params.timeToStart = args[i];
							break;
						case 2:
							params.autodq = args[i];
							break;
						case 3:
							params.maxUsers = args[i];
							break;
						case 4:
							params.type = args[i];
							break;
					}
				} else {
					var idArg = toId(splArg[0]);
					var valueArg = splArg[1].trim();
					switch (idArg) {
						case 'format':
						case 'tier':
							params.format = valueArg;
							break;
						case 'time':
						case 'singups':
						case 'timer':
							params.timeToStart = valueArg;
							break;
						case 'autodq':
						case 'dq':
							params.autodq = valueArg;
							break;
						case 'maxusers':
						case 'users':
							params.maxUsers = valueArg;
							break;
						case 'generator':
						case 'type':
							params.type = valueArg;
							break;
						case 'scouting':
						case 'scout':
						case 'setscout':
						case 'setscouting':
							params.scout = valueArg;
							break;
						default:
							return this.reply(this.trad('param') + ' ' + idArg + ' ' + this.trad('paramhelp') + ": tier, timer, dq, users, type, scout");
					}
				}
			}
			if (params.format) {
				var format = Tools.parseAliases(params.format);
				if (!Formats[format] || !Formats[format].chall) return this.reply(this.trad('e31') + ' ' + format + ' ' + this.trad('e32'));
				details.format = format;
			}
			if (params.timeToStart) {
				if (toId(params.timeToStart) === 'off') {
					details.timeToStart = null;
				} else {
					var time = parseInt(params.timeToStart);
					if (!time || time < 10) return this.reply(this.trad('e4'));
					details.timeToStart = time * 1000;
				}
			}
			if (params.autodq) {
				if (toId(params.autodq) === 'off') {
					details.autodq = false;
				} else {
					var dq = parseFloat(params.autodq);
					if (!dq || dq < 0) return this.reply(this.trad('e5'));
					details.autodq = dq;
				}
			}
			if (params.maxUsers) {
				if (toId(params.maxUsers) === 'off') {
					details.maxUsers = null;
				} else {
					var musers = parseInt(params.maxUsers);
					if (!musers || musers < 4) return this.reply(this.trad('e6'));
					details.maxUsers = musers;
				}
			}
			if (params.type) {
				var type = toId(params.type);
				if (type !== 'elimination' && type !== 'roundrobin') return this.reply(this.trad('e7'));
				details.type = type;
			}
			if (params.scout) {
				var scout = toId(params.scout);
				if (scout in {'yes': 1, 'on': 1, 'true': 1, 'allow': 1, 'allowed': 1})  details.scoutProtect = false;
				else details.scoutProtect = true;
			}
		}
		Features['tours'].newTour(room, details);
		setTimeout(function () {
			if (Features['tours'].tournaments[room] && !Features['tours'].tourData[room]) {
				Bot.say(room, this.trad('notstarted'));
				delete Features['tours'].tournaments[room];
			} else if (cmd !== 'maketour' && (cmd === 'itour' || room === 'espaol')) {
				this.parse(this.cmdToken + 'info torneo');
			}
		}.bind(this), 2500);
	}
};


text:
package info.mornlight.gw2s.android.model.item;

/**
 * Created by alfred on 6/5/13.
 */
public enum Discipline {
    Armorsmith,
    Artificer,
    Chef,
    Huntsman,
    Jeweler,
    Leatherworker,
    Tailor,
    Weaponsmith
}


text:
from collections import Counter

def palindromeRearranging(inputString):
    cnt = Counter(inputString)
    pair = 0
    nb_not_pair = 0
    for k,v in cnt.items():
        if v % 2 == 0:
            pair += 1
        else:
            nb_not_pair += 1
    if pair > 0 and nb_not_pair == 0:
        return True
    if pair % 2 == 0 and nb_not_pair == 1:
        return True
    if nb_not_pair > 1:
        return False
    return False


text:
package fi.vrk.xroad.catalog.persistence;

import fi.vrk.xroad.catalog.persistence.entity.CompanyForm;
import fi.vrk.xroad.catalog.persistence.repository.CompanyFormRepository;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Transactional
@Slf4j
public class CompanyFormRepositoryTest {

    @Autowired
    CompanyFormRepository companyFormRepository;

    @Test
    public void testFindAnyByCompanyId() {
        Optional<List<CompanyForm>> companyForms = companyFormRepository.findAnyByCompanyId(1L);
        assertEquals(true, companyForms.isPresent());
        assertEquals(1, companyForms.get().size());
        assertNotNull(companyForms.get().get(0).getStatusInfo());
        assertEquals("EN", companyForms.get().get(0).getLanguage());
        assertEquals("Public limited company", companyForms.get().get(0).getName());
        assertEquals(1, companyForms.get().get(0).getSource());
        assertEquals(0, companyForms.get().get(0).getType());
        assertEquals(1, companyForms.get().get(0).getVersion());
        assertEquals(LocalDate.of(2017, 10, 19), companyForms.get().get(0).getRegistrationDate().toLocalDate());
        assertNull(companyForms.get().get(0).getEndDate());
    }

}


text:
package org.kuali.rice.core.framework.config.module;

import org.kuali.rice.core.api.config.property.ConfigContext;

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

/**
 * Includes configuration for a web module of Kuali Rice.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class WebModuleConfiguration {

    private final String moduleName;
    private List<String> webSpringFiles;

    public WebModuleConfiguration(String moduleName) {
        this.moduleName = moduleName;
        this.webSpringFiles = new ArrayList<String>();
    }

    public String getWebModuleBaseUrl() {
		return ConfigContext.getCurrentContextConfig().getProperty(getModuleName().toLowerCase() + ".url");
	}

    public String getWebModuleStrutsConfigurationFiles() {
		return ConfigContext.getCurrentContextConfig().getProperty("rice." + getModuleName().toLowerCase() + ".struts.config.files");
	}

    public String getWebModuleStrutsConfigName() {
        return "config/" + getModuleName().toLowerCase();
    }

    public String getModuleName() {
        return moduleName;
    }

    public List<String> getWebSpringFiles() {
        return webSpringFiles;
    }

    public void setWebSpringFiles(List<String> webSpringFiles) {
        this.webSpringFiles = webSpringFiles;
    }

}


text:
package org.gradle.api.internal.provider;

import javax.annotation.Nullable;
import java.util.Collection;

public interface ValueCollector<T> {
    void add(@Nullable T value, Collection<T> dest);

    void addAll(Iterable<? extends T> values, Collection<T> dest);
}


text:
var _init_a, _init_b;
const dec = () => {};
class Foo {}
[_init_a, _init_b] = babelHelpers.applyDecs(Foo, [[dec, 5, "a", function () {
  return babelHelpers.classStaticPrivateFieldSpecGet(this, Foo, _a);
}, function (value) {
  babelHelpers.classStaticPrivateFieldSpecSet(this, Foo, _a, value);
}], [dec, 5, "b", function () {
  return babelHelpers.classStaticPrivateFieldSpecGet(this, Foo, _b);
}, function (value) {
  babelHelpers.classStaticPrivateFieldSpecSet(this, Foo, _b, value);
}]], []);
var _a = {
  writable: true,
  value: _init_a(Foo)
};
var _b = {
  writable: true,
  value: _init_b(Foo, 123)
};


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE126_Buffer_Overread__char_alloca_loop_51b.c
Label Definition File: CWE126_Buffer_Overread.stack.label.xml
Template File: sources-sink-51b.tmpl.c
*/
/*
 * @description
 * CWE: 126 Buffer Over-read
 * BadSource:  Set data pointer to a small buffer
 * GoodSource: Set data pointer to a large buffer
 * Sink: loop
 *    BadSink : Copy data to string using a loop
 * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

void CWE126_Buffer_Overread__char_alloca_loop_51b_badSink(char * data)
{
    {
        size_t i, destLen;
        char dest[100];
        memset(dest, 'C', 100-1);
        dest[100-1] = '\0'; /* null terminate */
        destLen = strlen(dest);
        /* POTENTIAL FLAW: using length of the dest where data
         * could be smaller than dest causing buffer overread */
        for (i = 0; i < destLen; i++)
        {
            dest[i] = data[i];
        }
        dest[100-1] = '\0';
        printLine(dest);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE126_Buffer_Overread__char_alloca_loop_51b_goodG2BSink(char * data)
{
    {
        size_t i, destLen;
        char dest[100];
        memset(dest, 'C', 100-1);
        dest[100-1] = '\0'; /* null terminate */
        destLen = strlen(dest);
        /* POTENTIAL FLAW: using length of the dest where data
         * could be smaller than dest causing buffer overread */
        for (i = 0; i < destLen; i++)
        {
            dest[i] = data[i];
        }
        dest[100-1] = '\0';
        printLine(dest);
    }
}

#endif /* OMITGOOD */


text:
<?php

namespace App\Containers\AppSection\Authentication\UI\API\Tests\Functional;

use App\Containers\AppSection\Authentication\UI\API\Tests\ApiTestCase;
use Illuminate\Support\Facades\Config;

/**
 * Class ApiLoginProxyForWebClientTest
 *
 * @group authentication
 * @group api
 */
class ApiLoginProxyForWebClientTest extends ApiTestCase
{
    protected string $endpoint = 'post@v1/clients/web/login';

    public function testClientWebAdminProxyLogin(): void
    {
        $data = [
            'email' => 'testing@mail.com',
            'password' => 'testingpass',
        ];
        $this->getTestingUser($data);

        $response = $this->makeCall($data);

        $response->assertStatus(200);
        $this->assertResponseContainKeyValue([
            'token_type' => 'Bearer',
        ]);
        $this->assertResponseContainKeys(['expires_in', 'access_token']);
    }

    public function testClientWebAdminProxyLoginWithUppercaseEmail(): void
    {
        $data = [
            'email' => 'Testing@Mail.Com',
            'password' => 'testiness',
        ];
        $this->getTestingUser(['email' => 'testing@mail.com', 'password' => $data['password'],]);
        Config::set('appSection-authentication.login.case_sensitive', false);

        $response = $this->makeCall($data);

        $response->assertStatus(200);
        $this->assertResponseContainKeyValue([
            'token_type' => 'Bearer',
        ]);
        $this->assertResponseContainKeys(['expires_in', 'access_token']);
    }

    public function testLoginWithNameAttribute(): void
    {
        $data = [
            'email' => 'testing@mail.com',
            'password' => 'testingpass',
            'name' => 'username',
        ];
        $this->getTestingUser($data);
        $this->setLoginAttributes([
            'email' => [],
            'name' => [],
        ]);
        $request = [
            'password' => 'testingpass',
            'name' => 'username',
        ];

        $response = $this->makeCall($request);

        $response->assertStatus(200);
        $this->assertResponseContainKeyValue([
            'token_type' => 'Bearer',
        ]);
        $this->assertResponseContainKeys(['expires_in', 'access_token', 'refresh_token']);
    }

    private function setLoginAttributes(array $attributes): void
    {
        Config::set('appSection-authentication.login.attributes', $attributes);
    }

    public function testGivenOnlyOneLoginAttributeIsSetThenItShouldBeRequired(): void
    {
        $this->setLoginAttributes([
            'email' => [],
        ]);
        $data = [
            'password' => 'so-secret',
        ];

        $this->makeCall($data);

        $this->assertValidationErrorContain([
            'email' => 'The email field is required.',
        ]);
    }

    public function testGivenMultipleLoginAttributeIsSetThenAtLeastOneShouldBeRequired(): void
    {
        $this->setLoginAttributes([
            'email' => [],
            'name' => [],
        ]);
        $data = [
            'password' => 'so-secret',
        ];

        $this->makeCall($data);

        $this->assertValidationErrorContain([
            'email' => 'The email field is required when none of name are present.',
            'name' => 'The name field is required when none of email are present.',
        ]);
    }

    public function testGivenWrongCredential_Throw422(): void
    {
        $data = [
            'email' => 'none@existing.mail',
            'password' => 'some-unbelievable-password',
        ];

        $response = $this->makeCall($data);

        $response->assertStatus(422);
    }
}


text:
@implementation WSRadioMapper
+ (RKObjectMapping*)objectMappingForRadioData
{
    RKObjectMapping *colorMapping = [RKObjectMapping mappingForClass:[WSRColor class]];
    [colorMapping addAttributeMappingsFromDictionary:@{ @"r": @"red", @"g": @"green", @"b": @"blue", @"a" : @"alpha" }];

    RKObjectMapping *streamMapping = [RKObjectMapping mappingForClass:[WSRStream class]];
    [streamMapping addAttributeMappingsFromArray:@[ @"bitrate", @"url" ]];

    RKObjectMapping *stationMapping = [RKObjectMapping mappingForClass:[WSRStation class]];
    [stationMapping addAttributeMappingsFromArray:@[ @"name" ]];
    [stationMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"streams" toKeyPath:@"streams" withMapping:streamMapping]];
    [stationMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"color" toKeyPath:@"color" withMapping:colorMapping]];

    RKObjectMapping *radioDataMapping = [RKObjectMapping mappingForClass:[WSRadioData class]];
    [radioDataMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"radiostations" toKeyPath:@"stations" withMapping:stationMapping]];

    return radioDataMapping;
}
@end


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports["default"] = undefined;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _icon = require('../icon');

var _icon2 = _interopRequireDefault(_icon);

var _input = require('../input');

var _input2 = _interopRequireDefault(_input);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

var Search = function (_React$Component) {
    (0, _inherits3["default"])(Search, _React$Component);

    function Search() {
        (0, _classCallCheck3["default"])(this, Search);

        var _this = (0, _possibleConstructorReturn3["default"])(this, _React$Component.apply(this, arguments));

        _this.handleChange = function (e) {
            var onChange = _this.props.onChange;
            if (onChange) {
                onChange(e);
            }
        };
        _this.handleClear = function (e) {
            e.preventDefault();
            var handleClear = _this.props.handleClear;
            if (handleClear) {
                handleClear(e);
            }
        };
        return _this;
    }

    Search.prototype.render = function render() {
        var _props = this.props,
            placeholder = _props.placeholder,
            value = _props.value,
            prefixCls = _props.prefixCls;

        var icon = value && value.length > 0 ? _react2["default"].createElement(
            'a',
            { href: '#', className: prefixCls + '-action', onClick: this.handleClear },
            _react2["default"].createElement(_icon2["default"], { type: 'cross-circle' })
        ) : _react2["default"].createElement(
            'span',
            { className: prefixCls + '-action' },
            _react2["default"].createElement(_icon2["default"], { type: 'search' })
        );
        return _react2["default"].createElement(
            'div',
            null,
            _react2["default"].createElement(_input2["default"], { placeholder: placeholder, className: prefixCls, value: value, ref: 'input', onChange: this.handleChange }),
            icon
        );
    };

    return Search;
}(_react2["default"].Component);

exports["default"] = Search;

Search.defaultProps = {
    placeholder: ''
};
module.exports = exports['default'];


text:
/* We treat all letters the same in encode/decode routines so
   we need to assign some characteristics to them like signess etc.  */

#ifndef OR32_H_ISA
#define OR32_H_ISA

#define NUM_UNSIGNED (0)
#define NUM_SIGNED (1)

#define MAX_GPRS 32
#define PAGE_SIZE 4096
#undef __HALF_WORD_INSN__

#define OPERAND_DELIM (',')

#define OR32_IF_DELAY (1)
#define OR32_W_FLAG   (2)
#define OR32_R_FLAG   (4)

struct or32_letter
{
  char letter;
  int  sign;
  /* int  reloc; relocation per letter ??  */
};

/* Main instruction specification array.  */
struct or32_opcode
{
  /* Name of the instruction.  */
  char *name;

  /* A string of characters which describe the operands.
     Valid characters are:
     ,() Itself.  Characters appears in the assembly code.
     rA	 Register operand.
     rB  Register operand.
     rD  Register operand.
     I	 An immediate operand, range -32768 to 32767.
     J	 An immediate operand, range . (unused)
     K	 An immediate operand, range 0 to 65535.
     L	 An immediate operand, range 0 to 63.
     M	 An immediate operand, range . (unused)
     N	 An immediate operand, range -33554432 to 33554431.
     O	 An immediate operand, range . (unused).  */
  char *args;

  /* Opcode and operand encoding.  */
  char *encoding;
  void (*exec) (void);
  unsigned int flags;
};

#define OPTYPE_LAST (0x80000000)
#define OPTYPE_OP   (0x40000000)
#define OPTYPE_REG  (0x20000000)
#define OPTYPE_SIG  (0x10000000)
#define OPTYPE_DIS  (0x08000000)
#define OPTYPE_DST  (0x04000000)
#define OPTYPE_SBIT (0x00001F00)
#define OPTYPE_SHR  (0x0000001F)
#define OPTYPE_SBIT_SHR (8)

/* MM: Data how to decode operands.  */
extern struct insn_op_struct
{
  unsigned long type;
  unsigned long data;
} **op_start;

#ifdef HAS_EXECUTION
extern void l_invalid (void);
extern void l_sfne    (void);
extern void l_bf      (void);
extern void l_add     (void);
extern void l_sw      (void);
extern void l_sb      (void);
extern void l_sh      (void);
extern void l_lwz     (void);
extern void l_lbs     (void);
extern void l_lbz     (void);
extern void l_lhs     (void);
extern void l_lhz     (void);
extern void l_movhi   (void);
extern void l_and     (void);
extern void l_or      (void);
extern void l_xor     (void);
extern void l_sub     (void);
extern void l_mul     (void);
extern void l_div     (void);
extern void l_divu    (void);
extern void l_sll     (void);
extern void l_sra     (void);
extern void l_srl     (void);
extern void l_j       (void);
extern void l_jal     (void);
extern void l_jalr    (void);
extern void l_jr      (void);
extern void l_rfe     (void);
extern void l_nop     (void);
extern void l_bnf     (void);
extern void l_sfeq    (void);
extern void l_sfgts   (void);
extern void l_sfges   (void);
extern void l_sflts   (void);
extern void l_sfles   (void);
extern void l_sfgtu   (void);
extern void l_sfgeu   (void);
extern void l_sfltu   (void);
extern void l_sfleu   (void);
extern void l_mtspr   (void);
extern void l_mfspr   (void);
extern void l_sys     (void);
extern void l_trap    (void); /* CZ 21/06/01.  */
extern void l_macrc   (void);
extern void l_mac     (void);
extern void l_msb     (void);
extern void l_invalid (void);
extern void l_cust1   (void);
extern void l_cust2   (void);
extern void l_cust3   (void);
extern void l_cust4   (void);
#endif
extern void l_none    (void);

extern const struct or32_letter or32_letters[];

extern const struct  or32_opcode or32_opcodes[];

extern const unsigned int or32_num_opcodes;

/* Calculates instruction length in bytes.  Always 4 for OR32.  */
extern int insn_len (int);

/* Is individual insn's operand signed or unsigned?  */
extern int letter_signed (char);

/* Number of letters in the individual lettered operand.  */
extern int letter_range (char);

/* MM: Returns index of given instruction name.  */
extern int insn_index (char *);

/* MM: Returns instruction name from index.  */
extern const char *insn_name (int);

/* MM: Constructs new FSM, based on or32_opcodes.  */
extern void build_automata (void);

/* MM: Destructs FSM.  */
extern void destruct_automata (void);

/* MM: Decodes instruction using FSM.  Call build_automata first.  */
extern int insn_decode (unsigned int);

/* Disassemble one instruction from insn to disassemble.
   Return the size of the instruction.  */
int disassemble_insn (unsigned long);

#endif


text:
For the given assignment i tried to create a GUI inspired from Iron Man movie.

I read a table of elements from a .csv file which i use later to find the health status and  to increase the need
of any elements for the machine/robot to be in optimal state.

Also i included a search part where the scaners and radars are searching for any enemies.

As main documentation sources for this assignmemt i used the www.processing.org website and the notes from lectures and labs.

My git repository address is  https://github.com/jhannsg/OopAssignment1/tree/master/assignment1

The video is live at : https://youtu.be/jXlaNRuN0RY


text:
package systemd

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"

	systemd "github.com/coreos/go-systemd/dbus"
	"github.com/docker/libcontainer/cgroups"
	"github.com/docker/libcontainer/cgroups/fs"
	"github.com/docker/libcontainer/configs"
	"github.com/godbus/dbus"
)

type Manager struct {
	Cgroups *configs.Cgroup
	Paths   map[string]string
}

type subsystem interface {
	// Returns the stats, as 'stats', corresponding to the cgroup under 'path'.
	GetStats(path string, stats *cgroups.Stats) error
	// Set the cgroup represented by cgroup.
	Set(path string, cgroup *configs.Cgroup) error
}

var subsystems = map[string]subsystem{
	"devices":    &fs.DevicesGroup{},
	"memory":     &fs.MemoryGroup{},
	"cpu":        &fs.CpuGroup{},
	"cpuset":     &fs.CpusetGroup{},
	"cpuacct":    &fs.CpuacctGroup{},
	"blkio":      &fs.BlkioGroup{},
	"perf_event": &fs.PerfEventGroup{},
	"freezer":    &fs.FreezerGroup{},
}

const (
	testScopeWait = 4
)

var (
	connLock                        sync.Mutex
	theConn                         *systemd.Conn
	hasStartTransientUnit           bool
	hasTransientDefaultDependencies bool
)

func newProp(name string, units interface{}) systemd.Property {
	return systemd.Property{
		Name:  name,
		Value: dbus.MakeVariant(units),
	}
}

func UseSystemd() bool {
	s, err := os.Stat("/run/systemd/system")
	if err != nil || !s.IsDir() {
		return false
	}

	connLock.Lock()
	defer connLock.Unlock()

	if theConn == nil {
		var err error
		theConn, err = systemd.New()
		if err != nil {
			return false
		}

		// Assume we have StartTransientUnit
		hasStartTransientUnit = true

		// But if we get UnknownMethod error we don't
		if _, err := theConn.StartTransientUnit("test.scope", "invalid"); err != nil {
			if dbusError, ok := err.(dbus.Error); ok {
				if dbusError.Name == "org.freedesktop.DBus.Error.UnknownMethod" {
					hasStartTransientUnit = false
					return hasStartTransientUnit
				}
			}
		}

		// Ensure the scope name we use doesn't exist. Use the Pid to
		// avoid collisions between multiple libcontainer users on a
		// single host.
		scope := fmt.Sprintf("libcontainer-%d-systemd-test-default-dependencies.scope", os.Getpid())
		testScopeExists := true
		for i := 0; i <= testScopeWait; i++ {
			if _, err := theConn.StopUnit(scope, "replace"); err != nil {
				if dbusError, ok := err.(dbus.Error); ok {
					if strings.Contains(dbusError.Name, "org.freedesktop.systemd1.NoSuchUnit") {
						testScopeExists = false
						break
					}
				}
			}
			time.Sleep(time.Millisecond)
		}

		// Bail out if we can't kill this scope without testing for DefaultDependencies
		if testScopeExists {
			return hasStartTransientUnit
		}

		// Assume StartTransientUnit on a scope allows DefaultDependencies
		hasTransientDefaultDependencies = true
		ddf := newProp("DefaultDependencies", false)
		if _, err := theConn.StartTransientUnit(scope, "replace", ddf); err != nil {
			if dbusError, ok := err.(dbus.Error); ok {
				if strings.Contains(dbusError.Name, "org.freedesktop.DBus.Error.PropertyReadOnly") {
					hasTransientDefaultDependencies = false
				}
			}
		}

		// Not critical because of the stop unit logic above.
		theConn.StopUnit(scope, "replace")
	}
	return hasStartTransientUnit
}

func getIfaceForUnit(unitName string) string {
	if strings.HasSuffix(unitName, ".scope") {
		return "Scope"
	}
	if strings.HasSuffix(unitName, ".service") {
		return "Service"
	}
	return "Unit"
}

func (m *Manager) Apply(pid int) error {
	var (
		c          = m.Cgroups
		unitName   = getUnitName(c)
		slice      = "system.slice"
		properties []systemd.Property
	)

	if c.Slice != "" {
		slice = c.Slice
	}

	properties = append(properties,
		systemd.PropSlice(slice),
		systemd.PropDescription("docker container "+c.Name),
		newProp("PIDs", []uint32{uint32(pid)}),
	)

	// Always enable accounting, this gets us the same behaviour as the fs implementation,
	// plus the kernel has some problems with joining the memory cgroup at a later time.
	properties = append(properties,
		newProp("MemoryAccounting", true),
		newProp("CPUAccounting", true),
		newProp("BlockIOAccounting", true))

	if hasTransientDefaultDependencies {
		properties = append(properties,
			newProp("DefaultDependencies", false))
	}

	if c.Memory != 0 {
		properties = append(properties,
			newProp("MemoryLimit", uint64(c.Memory)))
	}
	// TODO: MemoryReservation and MemorySwap not available in systemd

	if c.CpuShares != 0 {
		properties = append(properties,
			newProp("CPUShares", uint64(c.CpuShares)))
	}

	if c.BlkioWeight != 0 {
		properties = append(properties,
			newProp("BlockIOWeight", uint64(c.BlkioWeight)))
	}

	if _, err := theConn.StartTransientUnit(unitName, "replace", properties...); err != nil {
		return err
	}

	if err := joinDevices(c, pid); err != nil {
		return err
	}

	// TODO: CpuQuota and CpuPeriod not available in systemd
	// we need to manually join the cpu.cfs_quota_us and cpu.cfs_period_us
	if err := joinCpu(c, pid); err != nil {
		return err
	}

	// -1 disables memorySwap
	if c.MemorySwap >= 0 && c.Memory != 0 {
		if err := joinMemory(c, pid); err != nil {
			return err
		}

	}

	// we need to manually join the freezer and cpuset cgroup in systemd
	// because it does not currently support it via the dbus api.
	if err := joinFreezer(c, pid); err != nil {
		return err
	}

	if err := joinCpuset(c, pid); err != nil {
		return err
	}

	paths := make(map[string]string)
	for _, sysname := range []string{
		"devices",
		"memory",
		"cpu",
		"cpuset",
		"cpuacct",
		"blkio",
		"perf_event",
		"freezer",
	} {
		subsystemPath, err := getSubsystemPath(m.Cgroups, sysname)
		if err != nil {
			// Don't fail if a cgroup hierarchy was not found, just skip this subsystem
			if cgroups.IsNotFound(err) {
				continue
			}
			return err
		}
		paths[sysname] = subsystemPath
	}

	m.Paths = paths

	return nil
}

func (m *Manager) Destroy() error {
	return cgroups.RemovePaths(m.Paths)
}

func (m *Manager) GetPaths() map[string]string {
	return m.Paths
}

func writeFile(dir, file, data string) error {
	return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700)
}

func joinCpu(c *configs.Cgroup, pid int) error {
	path, err := getSubsystemPath(c, "cpu")
	if err != nil {
		return err
	}
	if c.CpuQuota != 0 {
		if err = ioutil.WriteFile(filepath.Join(path, "cpu.cfs_quota_us"), []byte(strconv.FormatInt(c.CpuQuota, 10)), 0700); err != nil {
			return err
		}
	}
	if c.CpuPeriod != 0 {
		if err = ioutil.WriteFile(filepath.Join(path, "cpu.cfs_period_us"), []byte(strconv.FormatInt(c.CpuPeriod, 10)), 0700); err != nil {
			return err
		}
	}
	return nil
}

func joinFreezer(c *configs.Cgroup, pid int) error {
	path, err := getSubsystemPath(c, "freezer")
	if err != nil {
		return err
	}

	if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
		return err
	}

	return ioutil.WriteFile(filepath.Join(path, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0700)
}

func getSubsystemPath(c *configs.Cgroup, subsystem string) (string, error) {
	mountpoint, err := cgroups.FindCgroupMountpoint(subsystem)
	if err != nil {
		return "", err
	}

	initPath, err := cgroups.GetInitCgroupDir(subsystem)
	if err != nil {
		return "", err
	}

	slice := "system.slice"
	if c.Slice != "" {
		slice = c.Slice
	}

	return filepath.Join(mountpoint, initPath, slice, getUnitName(c)), nil
}

func (m *Manager) Freeze(state configs.FreezerState) error {
	path, err := getSubsystemPath(m.Cgroups, "freezer")
	if err != nil {
		return err
	}

	if err := ioutil.WriteFile(filepath.Join(path, "freezer.state"), []byte(state), 0); err != nil {
		return err
	}
	for {
		state_, err := ioutil.ReadFile(filepath.Join(path, "freezer.state"))
		if err != nil {
			return err
		}
		if string(state) == string(bytes.TrimSpace(state_)) {
			break
		}
		time.Sleep(1 * time.Millisecond)
	}

	m.Cgroups.Freezer = state

	return nil
}

func (m *Manager) GetPids() ([]int, error) {
	path, err := getSubsystemPath(m.Cgroups, "cpu")
	if err != nil {
		return nil, err
	}

	return cgroups.ReadProcsFile(path)
}

func (m *Manager) GetStats() (*cgroups.Stats, error) {
	stats := cgroups.NewStats()
	for name, path := range m.Paths {
		sys, ok := subsystems[name]
		if !ok || !cgroups.PathExists(path) {
			continue
		}
		if err := sys.GetStats(path, stats); err != nil {
			return nil, err
		}
	}

	return stats, nil
}

func (m *Manager) Set(container *configs.Config) error {
	panic("not implemented")
}

func getUnitName(c *configs.Cgroup) string {
	return fmt.Sprintf("%s-%s.scope", c.Parent, c.Name)
}

// Atm we can't use the systemd device support because of two missing things:
// * Support for wildcards to allow mknod on any device
// * Support for wildcards to allow /dev/pts support
//
// The second is available in more recent systemd as "char-pts", but not in e.g. v208 which is
// in wide use. When both these are availalable we will be able to switch, but need to keep the old
// implementation for backwards compat.
//
// Note: we can't use systemd to set up the initial limits, and then change the cgroup
// because systemd will re-write the device settings if it needs to re-apply the cgroup context.
// This happens at least for v208 when any sibling unit is started.
func joinDevices(c *configs.Cgroup, pid int) error {
	path, err := getSubsystemPath(c, "devices")
	if err != nil {
		return err
	}

	if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {
		return err
	}

	if err := ioutil.WriteFile(filepath.Join(path, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0700); err != nil {
		return err
	}

	if !c.AllowAllDevices {
		if err := writeFile(path, "devices.deny", "a"); err != nil {
			return err
		}
	}
	for _, dev := range c.AllowedDevices {
		if err := writeFile(path, "devices.allow", dev.CgroupString()); err != nil {
			return err
		}
	}
	return nil
}

// Symmetrical public function to update device based cgroups.  Also available
// in the fs implementation.
func ApplyDevices(c *configs.Cgroup, pid int) error {
	return joinDevices(c, pid)
}

func joinMemory(c *configs.Cgroup, pid int) error {
	memorySwap := c.MemorySwap

	if memorySwap == 0 {
		// By default, MemorySwap is set to twice the size of RAM.
		memorySwap = c.Memory * 2
	}

	path, err := getSubsystemPath(c, "memory")
	if err != nil {
		return err
	}

	return ioutil.WriteFile(filepath.Join(path, "memory.memsw.limit_in_bytes"), []byte(strconv.FormatInt(memorySwap, 10)), 0700)
}

// systemd does not atm set up the cpuset controller, so we must manually
// join it. Additionally that is a very finicky controller where each
// level must have a full setup as the default for a new directory is "no cpus"
func joinCpuset(c *configs.Cgroup, pid int) error {
	path, err := getSubsystemPath(c, "cpuset")
	if err != nil {
		return err
	}

	s := &fs.CpusetGroup{}

	return s.ApplyDir(path, c, pid)
}


text:
namespace ash {
namespace printing {
namespace oauth2 {

namespace {

constexpr size_t kLengthOfCodeVerifier = 64;
constexpr size_t kLengthOfState = 16;

// Returns random string in Base64 format.
// `length` must be divisible by 4.
template <size_t length>
std::string RandBase64String() {
  static_assert(length % 4 == 0);
  static_assert(length > 3);
  std::vector<uint8_t> bytes(length * 3 / 4);
  crypto::RandBytes(bytes);
  return base::Base64Encode(bytes);
}

// The code challenge created with the algorithm S256 (see RFC7636-4.2).
// RFC7636-4.1 specifies the requirements for `code_verifier`:
// "code_verifier = high-entropy cryptographic random STRING using the
// unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
// from Section 2.3 of [RFC3986], with a minimum length of 43 characters
// and a maximum length of 128 characters."
std::string CodeChallengeS256(const std::string& code_verifier) {
  DCHECK_GE(code_verifier.size(), 43);
  DCHECK_LE(code_verifier.size(), 128);
  std::string output;
  base::Base64Encode(crypto::SHA256HashString(code_verifier), &output);
  return output;
}

// Builds and returns URL for Authorization Request (see RFC6749-4.1) with
// a code challenge (see RFC7636-4).
std::string GetAuthorizationURL(const AuthorizationServerData& server_data,
                                const base::flat_set<std::string>& scope,
                                const std::string& state,
                                const std::string& code_verifier) {
  chromeos::Uri uri(server_data.AuthorizationEndpointURI().spec());
  auto query = uri.GetQuery();
  query.push_back(std::make_pair("response_type", "code"));
  query.push_back(std::make_pair("response_mode", "query"));
  query.push_back(std::make_pair("client_id", server_data.ClientId()));
  query.push_back(std::make_pair("redirect_uri", kRedirectURI));
  if (!scope.empty()) {
    std::vector<std::string> parts(scope.begin(), scope.end());
    query.push_back(std::make_pair("scope", base::JoinString(parts, " ")));
  }
  query.push_back(std::make_pair("state", state));
  query.push_back(
      std::make_pair("code_challenge", CodeChallengeS256(code_verifier)));
  query.push_back(std::make_pair("code_challenge_method", "S256"));
  uri.SetQuery(query);
  return uri.GetNormalized(false);
}

// Tries to extract the parameter `name` from `query`. Returns the value of
// extracted parameter or an error message. `query` cannot contain empty
// vectors, but the vectors may contain empty strings.
base::expected<std::string, std::string> ExtractParameter(
    const base::flat_map<std::string, std::vector<std::string>>& query,
    const std::string& name) {
  auto it = query.find(name);
  if (it == query.end()) {
    return base::unexpected(
        base::StrCat({"parameter '", name, "' is missing"}));
  }
  if (it->second.size() != 1) {
    return base::unexpected(
        base::StrCat({"parameter '", name, "' is duplicated"}));
  }
  std::string value = it->second.front();
  if (value.empty()) {
    return base::unexpected(base::StrCat({"parameter '", name, "' is empty"}));
  }
  return value;
}

// Calls `callback` with `status` and `data` as parameters. When `status` equals
// StatusCode::kOK, ignores `data` and passes an empty string instead.
void NoDataForOK(StatusCallback callback,
                 StatusCode status,
                 const std::string& data) {
  std::move(callback).Run(status, (status == StatusCode::kOK) ? "" : data);
}

}  // namespace

AuthorizationZoneImpl::WaitingAuthorization::WaitingAuthorization(
    base::flat_set<std::string>&& scopes,
    StatusCallback callback)
    : scopes(scopes), callback(std::move(callback)) {}
AuthorizationZoneImpl::WaitingAuthorization::~WaitingAuthorization() = default;

AuthorizationZoneImpl::PendingAuthorization::PendingAuthorization(
    base::flat_set<std::string>&& scopes,
    std::string&& state,
    std::string&& code_verifier)
    : scopes(scopes), state(state), code_verifier(code_verifier) {}
AuthorizationZoneImpl::PendingAuthorization::~PendingAuthorization() = default;

AuthorizationZoneImpl::AuthorizationZoneImpl(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    const GURL& authorization_server_uri,
    const std::string& client_id)
    : server_data_(url_loader_factory, authorization_server_uri, client_id),
      url_loader_factory_(url_loader_factory) {}

AuthorizationZoneImpl::~AuthorizationZoneImpl() = default;

void AuthorizationZoneImpl::InitAuthorization(const std::string& scope,
                                              StatusCallback callback) {
  DCHECK_LE(waiting_authorizations_.size(), kMaxNumberOfSessions);

  // If there are too many callbacks waiting, remove the oldest one.
  if (waiting_authorizations_.size() == kMaxNumberOfSessions) {
    std::move(waiting_authorizations_.front().callback)
        .Run(StatusCode::kTooManySessions,
             "Authorization Zone not initialized");
    waiting_authorizations_.pop_front();
  }

  // Add the callback to the waiting list.
  waiting_authorizations_.emplace_back(ParseScope(scope), std::move(callback));
  if (waiting_authorizations_.size() == 1) {
    // The list was empty and it is the first element.
    // Check if the server is ready.
    if (server_data_.IsReady()) {
      // The server is ready. Just go ahead and process the element.
      AuthorizationProcedure();
    } else {
      // The server must be initialized (it is the very first call to
      // InitAuthorization()). AuthorizationProcedure() will be called inside
      // OnInitializeCallback().
      // We can use base::Unretained() here because:
      // * AuthorizationServerData (and HttpExchange) guarantees that no calls
      //   will be returned after deletion of the object `server_data_`.
      // * `this` owns `server_data_`; it is guaranteed that deletion of
      //   `server_data_` is performed before deletion of `this`.
      server_data_.Initialize(
          base::BindOnce(&AuthorizationZoneImpl::OnInitializeCallback,
                         base::Unretained(this)));
    }
  }
}

void AuthorizationZoneImpl::FinishAuthorization(const GURL& redirect_url,
                                                StatusCallback callback) {
  // Parse the URL and retrieve the query segment.
  chromeos::Uri uri(redirect_url.spec());
  if (uri.GetLastParsingError().status !=
      chromeos::Uri::ParserStatus::kNoErrors) {
    std::move(callback).Run(StatusCode::kInvalidResponse,
                            "Authorization Request: cannot parse obtained URL");
    return;
  }
  const auto query = uri.GetQueryAsMap();

  // Extract the parameter "state".
  base::expected<std::string, std::string> val_or_err =
      ExtractParameter(query, "state");
  if (!val_or_err.has_value()) {
    std::move(callback).Run(
        StatusCode::kInvalidResponse,
        base::StrCat({"Authorization Request: ", val_or_err.error()}));
    return;
  }
  const std::string state = std::move(val_or_err.value());

  // Use `state` to match pending authorization.
  base::flat_set<std::string> scopes;
  std::string code_verifier;
  if (!FindAndRemovePendingAuthorization(state, scopes, code_verifier)) {
    std::move(callback).Run(StatusCode::kNoMatchingSession,
                            "Authorization Request");
    return;
  }

  // Check if the parameter "error" is present. If yes, try to extract the error
  // message.
  if (query.contains("error")) {
    val_or_err = ExtractParameter(query, "error");
    if (!val_or_err.has_value()) {
      std::move(callback).Run(
          StatusCode::kInvalidResponse,
          base::StrCat({"Authorization Request: ", val_or_err.error()}));
      return;
    }
    const std::string error = std::move(val_or_err.value());

    StatusCode status;
    if (error == "server_error") {
      status = StatusCode::kServerError;
    } else if (error == "temporarily_unavailable") {
      status = StatusCode::kServerTemporarilyUnavailable;
    } else {
      status = StatusCode::kAccessDenied;
    }
    std::move(callback).Run(
        status, base::StrCat({"Authorization Request: error=", error}));
    return;
  }

  // Extract the parameter "code".
  val_or_err = ExtractParameter(query, "code");
  if (!val_or_err.has_value()) {
    std::move(callback).Run(
        StatusCode::kInvalidResponse,
        base::StrCat({"Authorization Request: ", val_or_err.error()}));
    return;
  }
  const std::string code = std::move(val_or_err.value());

  // Create and add a new session.
  if (sessions_.size() == kMaxNumberOfSessions) {
    // There are too many sessions. Remove the oldest one.
    auto callbacks = sessions_.front()->TakeWaitingList();
    sessions_.pop_front();
    for (auto& callback : callbacks) {
      std::move(callback).Run(StatusCode::kTooManySessions,
                              "The oldest session was closed");
    }
    // TODO(b:228876367) - revoke the token in AuthorizationServerSession
  }
  sessions_.push_back(std::make_unique<AuthorizationServerSession>(
      url_loader_factory_, server_data_.TokenEndpointURI(), std::move(scopes)));
  AuthorizationServerSession* session = sessions_.back().get();
  session->AddToWaitingList(base::BindOnce(&NoDataForOK, std::move(callback)));
  // We can use base::Unretained() here because:
  // * AuthorizationServerSession (and HttpExchange) guarantees that no calls
  //   will be returned after deletion of the object `session`.
  // * `this` owns `session`; it is guaranteed that deletion of `session` is
  //   performed before deletion of `this`.
  session->SendFirstTokenRequest(
      server_data_.ClientId(), code, code_verifier,
      base::BindOnce(&AuthorizationZoneImpl::OnSendTokenRequestCallback,
                     base::Unretained(this), base::Unretained(session)));
}

void AuthorizationZoneImpl::GetEndpointAccessToken(
    const chromeos::Uri& ipp_endpoint,
    const std::string& scope,
    StatusCallback callback) {
  // Try to find the IPP Endpoint.
  auto it = ipp_endpoints_.find(ipp_endpoint);

  if (it == ipp_endpoints_.end()) {
    // IPP Endpoint is not known. Create a new IppEndpointFetcher.
    auto ptr = std::make_unique<IppEndpointTokenFetcher>(
        url_loader_factory_, server_data_.TokenEndpointURI(), ipp_endpoint,
        ParseScope(scope));
    IppEndpointTokenFetcher* endpoint = ptr.get();
    it = ipp_endpoints_.emplace(ipp_endpoint, std::move(ptr)).first;
    endpoint->AddToWaitingList(std::move(callback));
    AttemptTokenExchange(endpoint);
    return;
  }

  IppEndpointTokenFetcher* endpoint = it->second.get();
  if (endpoint->endpoint_access_token().empty()) {
    // Endpoint Access Token is not ready yet.
    endpoint->AddToWaitingList(std::move(callback));
    return;
  }

  std::move(callback).Run(StatusCode::kOK, endpoint->endpoint_access_token());
}

void AuthorizationZoneImpl::MarkEndpointAccessTokenAsExpired(
    const chromeos::Uri& ipp_endpoint,
    const std::string& endpoint_access_token) {
  if (endpoint_access_token.empty()) {
    return;
  }
  auto it = ipp_endpoints_.find(ipp_endpoint);
  if (it == ipp_endpoints_.end()) {
    return;
  }
  IppEndpointTokenFetcher* endpoint = it->second.get();
  if (endpoint->endpoint_access_token() == endpoint_access_token) {
    ipp_endpoints_.erase(it);
  }
}

void AuthorizationZoneImpl::AuthorizationProcedure() {
  DCHECK_LE(pending_authorizations_.size(), kMaxNumberOfSessions);

  for (auto& wa : waiting_authorizations_) {
    // Remove the oldest pending authorization if there are too many of them.
    if (pending_authorizations_.size() == kMaxNumberOfSessions) {
      pending_authorizations_.pop_front();
    }
    // Create new pending authorization and call the callback with an
    // authorization URL to open in the browser.
    PendingAuthorization& pa = pending_authorizations_.emplace_back(
        std::move(wa.scopes), RandBase64String<kLengthOfState>(),
        RandBase64String<kLengthOfCodeVerifier>());
    const std::string auth_url = GetAuthorizationURL(
        server_data_, pa.scopes, pa.state, pa.code_verifier);
    std::move(wa.callback).Run(StatusCode::kOK, auth_url);
  }
  waiting_authorizations_.clear();
}

void AuthorizationZoneImpl::MarkAuthorizationZoneAsUntrusted() {
  const std::string msg = "Authorization Server marked as untrusted";

  pending_authorizations_.clear();

  // This method will call all callbacks from `waiting_authorizations_` and
  // empty it.
  OnInitializeCallback(StatusCode::kUntrustedAuthorizationServer, msg);

  // Clear `sessions_`.
  for (std::unique_ptr<AuthorizationServerSession>& session : sessions_) {
    std::vector<StatusCallback> callbacks = session->TakeWaitingList();
    for (StatusCallback& callback : callbacks) {
      std::move(callback).Run(StatusCode::kUntrustedAuthorizationServer, msg);
    }
  }
  sessions_.clear();

  // Clear `ipp_endpoints_`.
  for (auto& [_, ipp_endpoint] : ipp_endpoints_) {
    std::vector<StatusCallback> callbacks = ipp_endpoint->TakeWaitingList();
    for (StatusCallback& callback : callbacks) {
      std::move(callback).Run(StatusCode::kUntrustedAuthorizationServer, msg);
    }
  }
  ipp_endpoints_.clear();
}

void AuthorizationZoneImpl::OnInitializeCallback(StatusCode status,
                                                 const std::string& data) {
  if (status == StatusCode::kOK) {
    AuthorizationProcedure();
    return;
  }
  // Something went wrong. Return error.
  for (auto& wa : waiting_authorizations_) {
    std::move(wa.callback).Run(status, data);
  }
  waiting_authorizations_.clear();
}

void AuthorizationZoneImpl::OnSendTokenRequestCallback(
    AuthorizationServerSession* session,
    StatusCode status,
    const std::string& data) {
  // Find the session for which the request was completed.
  auto it_session = std::find_if(
      sessions_.begin(), sessions_.end(),
      [&session](const std::unique_ptr<AuthorizationServerSession>& as) {
        return as.get() == session;
      });
  DCHECK(it_session != sessions_.end());

  // Get the list of callbacks to run and copy the data.
  std::vector<StatusCallback> callbacks = session->TakeWaitingList();
  // We have to make a copy of `data` here because it may be an error message
  // owned by the session object deleted in the next if block.
  const std::string data2 = data;
  // Erase the session if the request failed.
  if (status != StatusCode::kOK) {
    sessions_.erase(it_session);
  }
  // Run the callbacks.
  for (auto& callback : callbacks) {
    std::move(callback).Run(status, data2);
  }
}

void AuthorizationZoneImpl::OnTokenExchangeRequestCallback(
    const chromeos::Uri& ipp_endpoint,
    StatusCode status,
    const std::string& data) {
  if (status == StatusCode::kInvalidAccessToken) {
    // The access token used by IppEndpointFetcher is invalid. Find the session
    // the token came from and ask it to refresh the token.
    for (std::unique_ptr<AuthorizationServerSession>& session : sessions_) {
      if (session->access_token() == data) {  // data == invalid access token
        // We can use base::Unretained() here because:
        // * AuthorizationServerSession (and HttpExchange) guarantees that no
        //   calls will be returned after deletion of the object `session`.
        // * `this` owns `session`; it is guaranteed that deletion of `session`
        //   is performed before deletion of `this`.
        session->SendNextTokenRequest(base::BindOnce(
            &AuthorizationZoneImpl::OnSendTokenRequestCallback,
            base::Unretained(this), base::Unretained(session.get())));
      }
    }

    // Find the corresponding IppEndpointTokenFetcher object.
    auto it_endpoint = ipp_endpoints_.find(ipp_endpoint);
    DCHECK(it_endpoint != ipp_endpoints_.end());
    IppEndpointTokenFetcher* endpoint = it_endpoint->second.get();

    // Try to find a new session for IPP endpoint and perform Token Exchange
    // again.
    AttemptTokenExchange(endpoint);
    return;
  }
  // For all other statuses just send back the result.
  ResultForIppEndpoint(ipp_endpoint, status, data);
}

void AuthorizationZoneImpl::ResultForIppEndpoint(
    const chromeos::Uri& ipp_endpoint,
    StatusCode status,
    const std::string& data) {
  auto it = ipp_endpoints_.find(ipp_endpoint);
  DCHECK(it != ipp_endpoints_.end());
  // The list of callbacks to run.
  std::vector<StatusCallback> callbacks = it->second->TakeWaitingList();
  // We have to make a copy of `data` here because it may be an error message
  // owned by the ipp_endpoint object deleted in the next if block.
  const std::string data2 = data;
  // Erase the IPP Endpoint in case of an error.
  if (status != StatusCode::kOK) {
    ipp_endpoints_.erase(it);
  }
  // Run the callbacks.
  for (auto& callback : callbacks) {
    std::move(callback).Run(status, data2);
  }
}

void AuthorizationZoneImpl::OnAccessTokenForEndpointCallback(
    const chromeos::Uri& ipp_endpoint,
    StatusCode status,
    const std::string& data) {
  auto it = ipp_endpoints_.find(ipp_endpoint);
  DCHECK(it != ipp_endpoints_.end());
  IppEndpointTokenFetcher* endpoint = it->second.get();

  switch (status) {
    case StatusCode::kOK:
      // We got a new access token (in `data`). Now, we can get a new endpoint
      // access token.
      // We can use base::Unretained() here because:
      // * IppEndpointTokenFetcher (and HttpExchange) guarantees that no
      //   calls will be returned after deletion of the object `endpoint`.
      // * `this` owns `endpoint`; it is guaranteed that deletion of `endpoint`
      //   is performed before deletion of `this`.
      endpoint->SendTokenExchangeRequest(
          data,
          base::BindOnce(&AuthorizationZoneImpl::OnTokenExchangeRequestCallback,
                         base::Unretained(this), ipp_endpoint));
      break;
    case StatusCode::kInvalidAccessToken:
    case StatusCode::kTooManySessions:
      // The session timed out. Try to find other session to get an access
      // token.
      AttemptTokenExchange(endpoint);
      break;
    default:
      // For all other statuses just send back the result.
      ResultForIppEndpoint(ipp_endpoint, status, data);
      break;
  }
}

void AuthorizationZoneImpl::AttemptTokenExchange(
    IppEndpointTokenFetcher* endpoint) {
  AuthorizationServerSession* auth_session = nullptr;
  // Try to match a session starting from the newest one.
  for (auto& session : base::Reversed(sessions_)) {
    if (session->ContainsAll(endpoint->scope())) {
      auth_session = session.get();
      break;
    }
  }
  if (!auth_session) {
    // No matching sessions. Inform the callers that a new session must be
    // created.
    ResultForIppEndpoint(endpoint->ipp_endpoint_uri(),
                         StatusCode::kAuthorizationNeeded, "");
    return;
  }

  // We found a session to use. Get its access token.
  const auto access_token = auth_session->access_token();
  if (access_token.empty()) {
    // Access token not ready. Add the IPP Endpoint to the waiting list.
    // We can use base::Unretained() here because:
    // * AuthorizationServerSession (and HttpExchange) guarantees that no
    //   calls will be returned after deletion of the object `auth_session`.
    // * `this` owns `auth_session`; it is guaranteed that deletion of
    //   `auth_session` is performed before deletion of `this`.
    auth_session->AddToWaitingList(
        base::BindOnce(&AuthorizationZoneImpl::OnAccessTokenForEndpointCallback,
                       base::Unretained(this), endpoint->ipp_endpoint_uri()));
    return;
  }

  // Try to use the access token to get a new endpoint access token.
  // We can use base::Unretained() here because:
  // * IppEndpointTokenFetcher (and HttpExchange) guarantees that no
  //   calls will be returned after deletion of the object `endpoint`.
  // * `this` owns `endpoint`; it is guaranteed that deletion of `endpoint`
  //   is performed before deletion of `this`.
  endpoint->SendTokenExchangeRequest(
      access_token,
      base::BindOnce(&AuthorizationZoneImpl::OnTokenExchangeRequestCallback,
                     base::Unretained(this), endpoint->ipp_endpoint_uri()));
}

bool AuthorizationZoneImpl::FindAndRemovePendingAuthorization(
    const std::string& state,
    base::flat_set<std::string>& scopes,
    std::string& code_verifier) {
  std::list<PendingAuthorization>::iterator it = std::find_if(
      pending_authorizations_.begin(), pending_authorizations_.end(),
      [&state](const PendingAuthorization& pa) { return pa.state == state; });
  if (it == pending_authorizations_.end()) {
    return false;
  }
  scopes = std::move(it->scopes);
  code_verifier = std::move(it->code_verifier);
  pending_authorizations_.erase(it);
  return true;
}

std::unique_ptr<AuthorizationZone> AuthorizationZone::Create(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    const GURL& authorization_server_uri,
    const std::string& client_id) {
  return std::make_unique<AuthorizationZoneImpl>(
      url_loader_factory, authorization_server_uri, client_id);
}

}  // namespace oauth2
}  // namespace printing
}  // namespace ash


text:
from os import path
from setuptools import setup
from shutil import rmtree
import sys

NAME = 'python-logstash-async'
VERSION = '1.0.0'

here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst')) as f:
    LONG_DESCRIPTION = f.read().decode('utf-8')

if 'bdist_wheel' in sys.argv:
    # Remove previous build dir when creating a wheel build, since if files have been removed
    # from the project, they'll still be cached in the build dir and end up as part of the
    # build, which is really neat!
    for directory in ('build', 'dist', 'python_logstash_async.egg-info'):
        try:
            rmtree(directory)
        except:
            pass

setup(
    name=NAME,
    packages=['logstash_async'],
    version=VERSION,
    description='Asynchronous Python logging handler for Logstash.',
    long_description=LONG_DESCRIPTION,
    license='MIT',
    author='Koen Deschacht',
    author_email='koendeschacht@gmail.com',
    url='https://github.com/koendeschacht/python-logstash-async',
    keywords='logging logstash asynchronous',
    install_requires=['six'],
    setup_requires=['flake8'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: System :: Logging',
    ]
)


text:
package io.sentry;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/** No-op implementation of ISerializer */
final class NoOpSerializer implements ISerializer {

  private static final NoOpSerializer instance = new NoOpSerializer();

  public static NoOpSerializer getInstance() {
    return instance;
  }

  private NoOpSerializer() {}

  @Override
  public <T> @Nullable T deserialize(@NotNull Reader reader, @NotNull Class<T> clazz) {
    return null;
  }

  @Override
  public @Nullable SentryEnvelope deserializeEnvelope(@NotNull InputStream inputStream) {
    return null;
  }

  @Override
  public <T> void serialize(@NotNull T entity, @NotNull Writer writer) throws IOException {}

  @Override
  public void serialize(@NotNull SentryEnvelope envelope, @NotNull OutputStream outputStream)
      throws Exception {}

  @Override
  public @NotNull String serialize(@NotNull Map<String, Object> data) throws Exception {
    return "";
  }
}


text:
using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using MVVMFramework.ViewModels;
using System.ComponentModel;

namespace MVVMFramework.Droid
{
    [Activity(Label = "MVVMFramework.Droid", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        LoginViewModel viewModel;
        EditText username, password;
        TextView combo;
        ProgressBar progressBar;
        Button button;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            viewModel = new LoginViewModel();
            // Get our button from the layout resource,
            // and attach an event to it
            button = FindViewById<Button>(Resource.Id.myButton);

            username = FindViewById<EditText>(Resource.Id.username);
            password = FindViewById<EditText>(Resource.Id.password);

            combo = FindViewById<TextView>(Resource.Id.combo);

            progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar1);

            username.TextChanged += (sender, e) =>
                {
                    viewModel.Username = username.Text;
                };

            password.TextChanged += (sender, e) =>
                {
                    viewModel.Password = password.Text;
                };

            username.Text = viewModel.Username;
            password.Text = viewModel.Password;
            combo.Text = viewModel.ComboDisplay;
            progressBar.Visibility = ViewStates.Gone;

            button.Click += delegate
            {
               viewModel.GetPeopleCommand.Execute(null);
            };
        }

        protected override void OnStart()
        {
            base.OnStart();
            viewModel.PropertyChanged += ViewModel_PropertyChanged;
            viewModel.People.CollectionChanged += ViewModel_People_CollectionChanged;

        }

        protected override void OnStop()
        {
            base.OnStop();
            viewModel.PropertyChanged -= ViewModel_PropertyChanged;
            viewModel.People.CollectionChanged -= ViewModel_People_CollectionChanged;
        }

        void ViewModel_People_CollectionChanged (object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            RunOnUiThread(() =>Toast.MakeText(this, "Count: " + viewModel.People.Count, ToastLength.Short).Show());

        }

        void ViewModel_PropertyChanged (object sender, PropertyChangedEventArgs e)
        {
            RunOnUiThread(() =>
                {
                    switch(e.PropertyName)
                    {

                        case LoginViewModel.ComboDisplayPropertyName:
                            combo.Text = viewModel.ComboDisplay;
                            break;
                        case BaseViewModel.IsBusyPropertyName:

                            if(viewModel.IsBusy)
                            {
                                progressBar.Visibility = ViewStates.Visible;
                                progressBar.Indeterminate = true;
                                button.Enabled = false;

                            }
                            else
                            {
                                progressBar.Visibility = ViewStates.Gone;
                                progressBar.Indeterminate = false;
                                button.Enabled = true;
                            }

                            break;
                    }
                });
        }
    }
}


text:
using System;
using System.Linq.Expressions;

namespace Chamber.Domain.DomainModel.LinqKit
{
    /// <summary>
	/// Another good idea by Tomas Petricek.
	/// See http://tomasp.net/blog/dynamic-linq-queries.aspx for information on how it's used.
	/// </summary>
	public static class Linq
    {
        // Returns the given anonymous method as a lambda expression
        public static Expression<Func<T, TResult>> Expr<T, TResult>(Expression<Func<T, TResult>> expr)
        {
            return expr;
        }

        // Returns the given anonymous function as a Func delegate
        public static Func<T, TResult> Func<T, TResult>(Func<T, TResult> expr)
        {
            return expr;
        }
    }
}


text:
package.path = package.path..";./sys/lua/cs2dftp/?.lua"
if not jit then
	local BinaryFormat = package.cpath:match("%p[\\|/]?%p(%a+)")
	if BinaryFormat == "dll" then
		os.name = "Windows"
	elseif BinaryFormat == "so" then
		os.name = "Linux"
	elseif BinaryFormat == "dylib" then
		os.name = "MacOS"
	end

	if os.name == "Windows" then
		package.cpath = package.cpath..";./sys/lua/cs2dftp/?.dll"
	elseif os.name == "Linux" then
		package.cpath = package.cpath..";./sys/lua/cs2dftp/?.so"
	elseif os.name == "MacOS" then
		package.cpath = package.cpath..";./sys/lua/cs2dftp/?.dylib"
	end
end

local socket = require("socket")
local lfs = require("lfs")

FTP = {}
FTP.Client = {}
FTP.Queue = {}

function FTP.Login(Name, Password)
	local User = FTP.Users[Name]
	if User then
		if User[1] == Password then
			local Path = lfs.currentdir() .. User[2]
			while Path:sub(-1, -1) == "/" do
				Path = Path:sub(1, -2)
			end
			return Path
		end
	end
end

function FTP.Print(...)
	local Arguments = {}
	for _, Argument in pairs({...}) do
		table.insert(Arguments, tostring(Argument))
	end
	print("[FTP] "..table.concat(Arguments, "	"))
end

function FTP.InitServer()
	local Error
	FTP.Server, Error = socket.bind("*", FTP.Configuration.Port)

	if FTP.Server then
		FTP.Server:setoption("tcp-nodelay", true)
		FTP.Server:settimeout(0)

		local IP, Port = FTP.Server:getsockname()
		FTP.Print("Initialized FTP server  "..IP..":"..Port)
	else
		FTP.Print("Failed to start server: "..Error)
	end
end

function FTP.Start()
	if not FTP.Server then
		FTP.Client = {}
		FTP.Queue = {}
		FTP.InitServer("127.0.0.1", 21, 256)
	end
end

function FTP.Stop()
	if FTP.Server then
		for _, Client in pairs(FTP.Client) do
			Client:Close()
		end
		FTP.Server:close()
		FTP.Server = nil
		FTP.Print("Closed FTP Server")
	end
end

function FTP.RemoveQueue(id, success)
	local Queue = FTP.Queue[id]
	if Queue then
		Queue.Socket:close()
		Queue.file:close()
		Queue = nil
	end
end

local Client = {}
local ClientMetatable = {__index = Client}

function FTP.UpdateServer()
	if not FTP.Server then
		return nil
	end

	local Socket = FTP.Server:accept()
	if Socket then
		local IP, Port = Socket:getpeername()
		FTP.Print("New Client "..IP..":"..Port)

		Socket:settimeout(0)
		Socket:send("220 Hello, this is Starkkz's FTP Service\n")

		local Client = setmetatable({
			Socket = Socket,
			RenameFrom = "",
			User = "",
			Password = "",
			Dir = "",
			CONMODE = 0,
			DIP = "",
			DPORT = 0,
			CMDQUEUE = {},
			ID = #FTP.Client + 1,
		}, ClientMetatable)
		FTP.Client[Client.ID] = Client
	end
end

function FTP.UpdateClients()
	for id, Client in pairs(FTP.Client) do
		local Line, Error = Client.Socket:receive("*l")
		if Error == "closed" then
			local IP, Port = Client.Socket:getpeername()
			Client:Close()
			FTP.Client[id] = nil
			FTP.Print("Client "..IP..":"..Port.." disconnected")
		elseif Line then
			table.insert(Client.CMDQUEUE, Line)
		end

		for CMDID, CMD in pairs(Client.CMDQUEUE) do
			if Client:Parse(CMD) then
				Client.CMDQUEUE[CMDID] = nil
			end
		end
	end
end

function Client:ip()
	local ip, port = self.Socket:getsockname()
	return ip
end

function Client:port()
	local ip, port = self.Socket:getsockname()
	return port
end

function Client:DataIP()
	if self.DataSocket then
		local ip, port = self.DataSocket:getsockname()
		return ip
	end
end

function Client:DataPort()
	if self.DataSocket then
		local ip, port = self.DataSocket:getsockname()
		return port
	end
end

function Client:ConnectData()
	if self.DataSocket then
		return true
	end

	if self.CONMODE == 1 then
		if self.PasvServer then
			local Sock = self.PasvServer:accept()
			if Sock then
				Sock:settimeout(0, "b")
				Sock:settimeout(0, "t")
				self.DataSocket = Sock
				return true
			end
		end
	elseif self.CONMODE == 2 then
		if #self.DIP > 0 and self.DPORT > 0 then
			local Sock, e = socket.tcp()
			if Sock then
				Sock:settimeout(2000, "b")
				Sock:settimeout(2000, "t")

				local Success, Error = Sock:connect(self.DIP, self.DPORT)
				if Success then
					Sock:settimeout(0, "b")
					Sock:settimeout(0, "t")
					self.DataSocket = Sock
					return true
				end
				Sock:close()
			end
		end
	end
end

function Client:CloseData()
	if self.DataSocket then
		self.DataSocket:close()
		self.DataSocket = nil
	end
end

function Client:ClosePasv()
	if self.PasvServer then
		self:CloseData()
		self.PasvServer:close()
		self.PasvServer = nil
	end
end

function Client:CloseConMode()
	if Client.CONMODE == 1 then
		self:ClosePasv()
	elseif Client.CONMODE == 2 then
		self:CloseData()
	end
end

function Client:Close()
	self:CloseData()
	self:ClosePasv()
	self.Socket:close()
end

function Client:send(Datagram)
	local R, W, E = socket.select(nil, {self.Socket}, 5000)
	if not E then
		local Index, Next = next(W)
		if Next == self.Socket then
			self.Socket:send(Datagram)
		end
	else
		FTP.Print("Send error: "..E)
	end
end

function Client:Parse(Line)
	if not Line then
		return nil
	end

	if string.sub(Line, 1, 4) == "USER" then
		local UserName = string.sub(Line, 6)
		if UserName:len() > 0 then
			self.User = UserName
			self:send("331 Password required to access user account "..UserName..".\n")
		end
		return true
	elseif string.sub(Line, 1, 4) == "PASS" then
		local Password = string.sub(Line, 6)
		if Password:len() > 0 then
			local Path = FTP.Login(self.User, Password)
			if Path then
				self.Password = Password
				self.Logged = true
				self.Dir = Path
				self.DefaultDir = Path
				self:send("230 Logged in.\n")
			else
				self:send("530 Login authentication failed\n")
			end
		else
			self:send("331 Password required to access user account "..UserName..".\n")
		end
		return true
	elseif string.sub(Line, 1, 3) == "CWD" then
		if self.Logged then
			local Folder = string.sub(Line, 5)
			while string.sub(Folder, 1, 1) == "/" do
				Folder = string.sub(Folder, 2)
			end

			if Folder == ".." then
				local find
				for i = 1, #self.Dir do
					if string.sub(self.Dir, i, i) == "/" then
						find = i
					end
				end

				if find then
					self.Dir = string.sub(self.Dir, 1, find - 1) or self.DefaultDir
					self:send('250 "/'..self.Dir:sub(#self.DefaultDir + 1)..'" is new working directory\n')
				else
					self.Dir = self.DefaultDir
					self:send('250 "/'..self.Dir:sub(#self.DefaultDir + 1)..'" is new working directory\n')
				end
			elseif Folder:len() > 0 then
				if Line:sub(5, 5) == "/" then
					self.Dir = self.DefaultDir .."/".. Folder
				elseif #self.Dir <= 0 then
					self.Dir = self.DefaultDir
				else
					self.Dir = self.Dir.."/"..Folder
				end
				self:send('250 "/'..self.Dir:sub(#self.DefaultDir + 1)..'" is new working directory\n')
			else
				self.Dir = self.DefaultDir
				self:send('250 "/'..self.Dir:sub(#self.DefaultDir + 1)..'" is new working directory\n')
			end
		else
			self:send("530 You aren't logged in\n")
		end
		return true
	elseif string.sub(Line, 1, 4) == "SYST" then
		self:send("215 Lua Virtual Machine\n")
		return true
	elseif string.sub(Line, 1, 4) == "TYPE" then
		if self.Logged then
			local NewType = string.sub(Line, 6)
			if NewType == "I" then
				self:send("200 TYPE is now 8-bit binary\n")
			elseif NewType == "A" then
				self:send("200 TYPE is now ASCII\n")
			end
		else
			self:send("530 You aren't logged in\n")
		end
		return true
	elseif string.sub(Line, 1, 4) == "LIST" then
		if self.Logged then
			if not self.LSTART then
				self.LSTART = socket.gettime()
			end

			if self:ConnectData() then
				self:send("150 Opening ASCII mode data connection for file list.\n")
				local Dir
				if self.Dir:len() > 0 then
					Dir = self.Dir
				else
					Dir = self.DefaultDir
				end

				if lfs.attributes(Dir, "mode") == "directory" then
					for File in lfs.dir(Dir) do
						local Attributes = lfs.attributes(Dir.."/"..File)
						if Attributes then
							if Attributes.mode == "directory" then
								if Dir.."/"..File ~= lfs.currentdir().."/sys/lua/cs2dftp" then
									self.DataSocket:send("drwxr--r--	1	"..self.User.."	PC	"..self.ID.."	"..Attributes.size.."	"..File.."\n")
								end
							elseif Attributes.mode == "file" then
								self.DataSocket:send("-rwxr--r--	1	"..self.User.."	PC	"..self.ID.."	"..Attributes.size.."	"..File.."\n")
							end
						end
					end
				end
				self:send("226 Transfer complete.\n")
				self:CloseData()
				self.LSTART = nil
				return true
			elseif socket.gettime() - self.LSTART >= 2 then
				self:send("425 Can't open data connection\n")
				self.LSTART = nil
				return true
			end
		else
			self:send("530 You aren't logged in\n")
			return true
		end
	elseif string.sub(Line, 1, 4) == "PASV" then
		if self.Logged then
			self:ClosePasv()
			local sock, e = socket.tcp()
			if sock then
				local success, e = sock:bind("*", 0)
				if success then
					success, e = sock:listen()
					if success then
						sock:settimeout(0, "b")
						sock:settimeout(0, "t")

						local ip, port = sock:getsockname()
						local ports = {}
						ports[1] = math.floor(port/256)
						ports[2] = port - ports[1]*256

						local ips = {}
						for n in FTP.Configuration.IP:gmatch("([^%p]+)") do
							table.insert(ips, n)
						end

						self:send("227 Entering Passive Mode ("..ips[1]..","..ips[2]..","..ips[3]..","..ips[4]..","..ports[1]..","..ports[2]..")\n")
						self.PasvServer = sock
						self.CONMODE = 1
					else
						sock:close()
					end
				else
					sock:close()
				end
			else
				sock:close()
			end
		else
			self:send("530 You aren't logged in\n")
		end
		return true
	elseif string.sub(Line, 1, 4) == "PORT" then
		if self.Logged then
			self:CloseConMode()
			local adr = {string.match(Line, "PORT (%d+),(%d+),(%d+),(%d+),(%d+),(%d+)")}
			if #adr >= 6 then
				local ip = adr[1].."."..adr[2].."."..adr[3].."."..adr[4]
				local port = tonumber(adr[5])*256 + tonumber(adr[6])

				if ip == self:ip() then
					self.DataSocket = DataSocket
					self:send("200 PORT command successful\n")
					self.DIP = ip
					self.DPORT = port
					self.CONMODE = 2
				else
					self:send("500 I won't open a connection to "..ip.." (only to "..self:ip()..")\n")
				end
			else
				self:send("500 I won't open a connection\n")
			end
		else
			self:send("530 You aren't logged in\n")
		end
		return true
	elseif string.sub(Line, 1, 3) == "MKD" then
		if self.Logged then
			local Folder = string.sub(Line, 5)
			local Dir
			while string.sub(Folder, 1, 1) == "/" do
				Folder = string.sub(Folder, 2)
			end

			if Folder == "cs2dftp" then
				if self.Dir == lfs.currentdir().."/sys/lua/cs2dftp" then
					self:send("550 Can't create directory: blocked\n")
					return true
				end
			end

			if self.Dir:len() > 0 then
				Dir = self.Dir.."/"..Folder
			else
				Dir = Folder
			end

			local success, e = lfs.mkdir(Dir)
			if success then
				self:send('257 "'..Folder..'" : The directory was successfully created\n')
			else
				local e = e or "File exists"
				self:send("550 Can't create directory: "..e.."\n")
			end
		else
			self:send("530 You aren't logged in\n")
		end
		return true
	elseif string.sub(Line, 1, 3) == "RMD" then
		if self.Logged then
			local Folder = string.sub(Line, 5)
			local Dir
			while string.sub(Folder, 1, 1) == "/" do
				Folder = string.sub(Folder, 2)
			end

			if Folder == "cs2dftp" then
				if self.Dir == lfs.currentdir().."/sys/lua" then
					self:send("550 Can't remove directory: blocked\n")
					return true
				end
			end

			if self.Dir:len() > 0 then
				Dir = self.Dir.."/"..Folder
			else
				Dir = Folder
			end

			local success, e = lfs.rmdir(Dir)
			if success then
				--250 The directory was successfully removed
				self:send("250 The directory was successfully removed\n")
			else
				self:send("550 Can't remove directory: "..e.."\n")
			end
		else
			self:send("530 You aren't logged in\n")
		end
		return true
	elseif string.sub(Line, 1, 4) == "PWD" then
		if self.Logged then
			self:send('257 "/'..self.Dir:sub(#self.DefaultDir + 1)..'" is the current working directory\n')
		else
			self:send("530 You aren't logged in\n")
		end
		return true
	elseif string.sub(Line, 1, 4) == "RNFR" then
		local File = string.sub(Line, 6)
		local Dir
		if self.Dir:len() > 0 then
			Dir = self.Dir.."/"..File
		else
			Dir = File
		end

		if File:len() <= 0 then
			self:send("550 No file name\n")
		elseif File:len() > 0 then
			if lfs.attributes(Dir, "mode") == "file" then
				self:send("350 RNFR accepted - file exists, ready for destination\n")
				self.RenameFrom = File
			else
				self:send("550 Sorry, but that file doesn't exist\n")
			end
		end
		return true
	elseif string.sub(Line, 1, 4) == "RNTO" then
		if not self.RenameFrom or self.RenameFrom:len() <= 0 then
			self:send("503 Need RNFR before RNTO\n")
			return true
		end

		local File = string.sub(Line, 6)
		local RenameDir, SourceDir
		if self.Dir:len() > 0 then
			RenameDir = self.Dir.."/"..File
			SourceDir = self.Dir.."/"..self.RenameFrom
		else
			RenameDir = File
			SourceDir = self.RenameFrom
		end

		if File:len() <= 0 then
			self:send("550 No file name\n")
		elseif File:len() > 0 then
			if lfs.attributes(RenameDir, "mode") == "file" then
				self:send("550 RENAME Failed - destination file already exists\n")
			else
				self:send("250 File successfully renamed\n")
				os.rename(SourceDir, RenameDir)
			end
		end
		return true
	elseif string.sub(Line, 1, 4) == "DELE" then
		local File = string.sub(Line, 6)
		local Dir
		while string.sub(File, 1, 1) == "/" do
			File = string.sub(File, 2)
		end

		if File == "cs2dftp" then
			if self.Dir == lfs.currentdir().."/sys/lua" then
				self:send("550 Could not delete FILENAME: blocked\n")
				return true
			end
		end

		if self.Dir:len() > 0 then
			Dir = self.Dir.."/"..File
		else
			Dir = File
		end

		local success, e = os.remove(Dir)
		if success then
			self:send("250 Deleted FILENAME\n")
		else
			self:send("550 Could not delete FILENAME: "..e.."\n")
		end
		return true
	elseif string.sub(Line, 1, 4) == "STOR" then
		if self.Logged then
			local File = string.sub(Line, 6):gsub("/", "")

			if File:len() <= 0 then
				self:send("550 No file name\n")
				return true
			end

			local Dir, Path
			if self.Dir:len() > 0 then
				Dir = self.Dir.."/"..File
				Path = self.Dir
			else
				Dir = File
			end

			if lfs.attributes(Path, "mode") ~= "directory" then
				if not Path then
					self:send("500 /"..Dir..": The system cannot find the path specified.\n")
					return true
				else
					local folders = {}
					for f in Path:gmatch("([^%/]+)") do
						table.insert(folders, f)
					end

					local NewPath = ""
					for i = 1, #folders do
						NewPath = NewPath.."/"..folders[i]
						if lfs.attributes(NewPath) == nil then
							local success, e = lfs.mkdir(NewPath)
							if not success then
								self:send("500 /"..Dir..": "..e..".\n")
								return true
							end
						end
					end
				end
			end

			if not self.SSTART then
				self.SSTART = socket.gettime()
			end

			if self:ConnectData() then
				if not self.SWARN then
					self.SFILE = io.open(Dir, "w")
					self.SWARN = true
					self:send("150 Accepted data connection\n")
				end

				local data, e = self.DataSocket:receive("*a")
				if data then
					if self.SFILE then
						self.SFILE:write(data)
					end
				elseif e == "closed" then
					self.DataSocket = nil
					if self.SFILE then
						self.SFILE:close()
						self.SFILE = nil
					end
					self.SWARN = nil
					self.SSTART = nil
					self:send("226 File successfully transferred\n")
					return true
				end
			elseif socket.gettime() - self.SSTART >= 2 then
				self.SSTART = nil
				self.SWARN = nil
				self:send("425 Can't open data connection\n")
				return true
			end
		else
			self:send("530 You aren't logged in\n")
			return true
		end
	elseif string.sub(Line, 1, 4) == "RETR" then
		if self.Logged then
			local File = string.sub(Line, 6):gsub("/", "")

			if File:len() <= 0 then
				self:send("550 No file name\n")
				return true
			end

			local Dir
			if self.Dir:len() > 0 then
				Dir = self.Dir.."/"..File
			else
				Dir = File
			end

			if lfs.attributes(Dir) == nil then
				self:send("550 Can't open "..File..": No such file or directory\n")
				return true
			end

			if not self.RSTART then
				self.RSTART = socket.gettime()
			end

			if self:ConnectData() then
				if not self.RWARN then
					self.RWARN = true
					self:send("150 Accepted data connection\n")
					self.RFILE = io.open(Dir, "r")
				end

				if self.RFILE then
					local data = self.RFILE:read(FTP.Configuration.TransferSpeed)
					if data then
						self.DataSocket:send(data)
					else
						self.RFILE:close()
						self.DataSocket:close()
						self.RSTART = nil
						self.RWARN = nil
						self:send("226 File successfully transferred\n")
						return true
					end
				else
					self.RSTART = nil
					self.RWARN = nil
					self.DataSocket:close()
					self:send("226 File successfully transferred\n")
					return true
				end
			elseif socket.gettime() - self.RSTART >= 2 then
				self.RSTART = nil
				self.RWARN = nil
				self:send("425 Can't open data connection\n")
				return true
			end
		else
			self:send("530 You aren't logged in\n")
			return true
		end
	else
		self:send("502 Command not implemented.\n")
		return true
	end
end

addhook("always", "FTP.Process")
function FTP.Process()
	FTP.UpdateServer()
	FTP.UpdateClients()
end

addhook("parse", "FTP.Console")
function FTP.Console(Command)
	if Command:sub(1, 3) == "ftp" then
		Command = Command:sub(5)
		if Command:sub(1, 7) == "adduser" then
			local Username, Password = Command:match("adduser (%w+) (%w+)")
			if not Username then
				FTP.Print("User name can only contain alphanumeric characters")
				return 1
			elseif not Password then
				FTP.Print("Password can only contain alphanumeric characters")
				return 1
			end
			if FTP.User[Username] then
				FTP.User[Username][1] = Password
				FTP.Save.Users()
				FTP.Print("Changed user password from '"..Username.."' to '"..string.rep("*", #Password).."'")
			else
				FTP.User[Username] = {Password, ""}
				FTP.Save.Users()
				FTP.Print("Created user '"..Username.."' with password '"..string.rep("*", #Password).."'")
			end
			return 1
		elseif Command:sub(1, 7) == "remuser" then
			local Username = Command:match("remuser (%w+)")
			if not Username then
				FTP.Print("User name can only contain alphanumeric characters")
				return 1
			end
			if FTP.User[Username] then
				FTP.User[Username] = nil
				FTP.Save.Users()
				FTP.Print("Removed user '"..Username.."'")
			else
				FTP.Print("User '"..Username.."' does not exist")
			end
			return 1
		elseif Command:sub(1, 8) == "userpath" then
			local Username, Path = Command:match("userpath (%w+) (.+)")
			if not Username then
				FTP.Print("User name can only contain alphanumeric characters")
				return 1
			elseif not Path then
				FTP.Print("Invalid path")
				return 1
			end

			if FTP.User[Username] then
				FTP.User[Username][2] = Path
				FTP.Save.Users()
				FTP.Print("Changed user path from '"..Username.."' to '"..Path.."'")
			else
				FTP.Print("User '"..Username.."' does not exist")
			end
			return 1
		elseif Command:sub(1, 4) == "port" then
			local Port = Command:match("port (%d+)")
			if not Port then
				FTP.Print("Invalid port")
				return 1
			end

			FTP.Configuration.Port = tonumber(Port)
			if FTP.Save then
				FTP.Save.Configuration()
			end
			return 1
		elseif Command:sub(1, 7) == "localip" then
			local IP = Command:match("localip ([%w|%p]+)")
			if not IP then
				FTP.Print("Invalid local ip")
				return 1
			end

			FTP.Configuration.IP = IP
			if FTP.Save then
				FTP.Save.Configuration()
			end
			return 1
		elseif Command:sub(1, 13) == "transferspeed" then
			local TransferSpeed = Command:match("transferspeed (%d+)")
			if not TransferSpeed then
				FTP.Print("Invalid transfer speed")
				return 1
			end
			FTP.Configuration.TransferSpeed = TransferSpeed
			if FTP.Save then
				FTP.Save.Configuration()
			end
			return 1
		elseif Command:sub(1, 5) == "start" then
			FTP.Start()
			FTP.Configuration.Start = true
			if FTP.Save then
				FTP.Save.Configuration()
			end
			return 1
		elseif Command:sub(1, 4) == "stop" then
			FTP.Stop()
			FTP.Configuration.Start = nil
			if FTP.Save then
				FTP.Save.Configuration()
			end
			return 1
		end
	end
end

function FTP.Load()
	FTP.Users = {}
	FTP.Configuration = {}

	local f = io.open("sys/lua/cs2dftp/config.cfg", "r")
	if f then
		for Command in f:lines() do
			parse(Command)
		end
		f:close()
	else
		FTP.Print("Failed to load settings")
	end

	local Users = io.open("sys/lua/cs2dftp/users.cfg", "r")
	if Users then
		local LineNumber = 0
		for Line in Users:lines() do
			LineNumber = LineNumber + 1

			local Username, Password, Path = Line:match("(%w+) (%w+) (.+)")
			if not Username then
				FTP.Print("Failed to load user name at line "..LineNumber)
			elseif not Password then
				FTP.Print("Failed to load user password at line "..LineNumber)
			elseif not Path then
				FTP.Print("Failed to load user path at line "..LineNumber)
			else
				FTP.Users[Username] = {Password, Path}
			end
		end
		Users:close()
	else
		FTP.Print("Failed to load users")
	end
	FTP.Load = nil
end; FTP.Load()

FTP.Save = {}
function FTP.Save.Users()
	local f = io.open("sys/lua/cs2dftp/users.cfg", "w")
	if f then
		local List = ""
		for Username, Memory in pairs(FTP.Users) do
			List = List .. Username .." " .. Memory[1] .. " ".. Memory[2] .. "\n"
		end
		f:write(List:sub(-2))
		f:close()
		FTP.Print("Saved users successfully")
	else
		FTP.Print("Failed to save users")
	end
end

function FTP.Save.Configuration()
	local f = io.open("sys/lua/cs2dftp/config.cfg", "w")
	if f then
		f:write("ftp port "..FTP.Configuration.Port.."\n")
		f:write("ftp localip "..FTP.Configuration.IP.."\n")
		f:write("ftp transferspeed "..FTP.Configuration.TransferSpeed.."\n")
		if FTP.Configuration.Start then
			f:write("ftp start\n")
		end
		f:close()
	end
end


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SearchResultEventArgs.cs" company="Jan-Cornelius Molnar">
// The MIT License (MIT)
//
// Copyright (c) 2015 Jan-Cornelius Molnar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

namespace Jcq.IcqProtocol.Contracts
{
    public class SearchResultEventArgs : EventArgs
    {
        public SearchResultEventArgs(IEnumerable<IContact> contacts)
        {
            Contacts = new List<IContact>(contacts);
        }

        public List<IContact> Contacts { get; }
    }
}


text:
#include "py/obj.h"
#include "py/mphal.h"
#include "py/runtime.h"

#include "shared-bindings/digitalio/DigitalInOut.h"
#include "shared-bindings/neopixel_write/__init__.h"

//| :mod:`neopixel_write` --- Low-level neopixel implementation
//| ===========================================================
//|
//| .. module:: neopixel_write
//|   :synopsis: Low-level neopixel implementation
//|   :platform: SAMD21
//|
//| The `neopixel_write` module contains a helper method to write out bytes in
//| the 800khz neopixel protocol.
//|
//| For example, to turn off a single neopixel (like the status pixel on Express
//| boards.)
//|
//| .. code-block:: python
//|
//|   import board
//|   import neopixel_write
//|   import digitalio
//|
//|   pin = digitalio.DigitalInOut(board.NEOPIXEL)
//|   pin.direction = digitalio.Direction.OUTPUT
//|   pixel_off = bytearray([0, 0, 0])
//|   neopixel_write.neopixel_write(pin, pixel_off)
//|
//| .. method:: neopixel_write.neopixel_write(digitalinout, buf)
//|
//|   Write buf out on the given DigitalInOut.
//|
//|   :param ~digitalio.DigitalInOut gpio: the DigitalInOut to output with
//|   :param bytearray buf: The bytes to clock out. No assumption is made about color order
//|
STATIC mp_obj_t neopixel_write_neopixel_write_(mp_obj_t digitalinout_obj, mp_obj_t buf) {
    if (!MP_OBJ_IS_TYPE(digitalinout_obj, &digitalio_digitalinout_type)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "Expected a %q", digitalio_digitalinout_type.name));
    }
    // Convert parameters into expected types.
    const digitalio_digitalinout_obj_t *digitalinout = MP_OBJ_TO_PTR(digitalinout_obj);
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ);
    // Call platform's neopixel write function with provided buffer and options.
    common_hal_neopixel_write(digitalinout, (uint8_t*)bufinfo.buf, bufinfo.len);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(neopixel_write_neopixel_write_obj, neopixel_write_neopixel_write_);

STATIC const mp_rom_map_elem_t neopixel_write_module_globals_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_neopixel_write) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_neopixel_write), (mp_obj_t)&neopixel_write_neopixel_write_obj },
};

STATIC MP_DEFINE_CONST_DICT(neopixel_write_module_globals, neopixel_write_module_globals_table);

const mp_obj_module_t neopixel_write_module = {
    .base = { &mp_type_module },
    .globals = (mp_obj_dict_t*)&neopixel_write_module_globals,
};


text:
require 'rumale/base/base_estimator'
require 'rumale/base/cluster_analyzer'
require 'rumale/pairwise_metric'

module Rumale
  module Clustering
    # DBSCAN is a class that implements DBSCAN cluster analysis.
    #
    # @example
    #   analyzer = Rumale::Clustering::DBSCAN.new(eps: 0.5, min_samples: 5)
    #   cluster_labels = analyzer.fit_predict(samples)
    #
    # *Reference*
    # - Ester, M., Kriegel, H-P., Sander, J., and Xu, X., "A density-based algorithm for discovering clusters in large spatial databases with noise," Proc. KDD' 96, pp. 266--231, 1996.
    class DBSCAN
      include Base::BaseEstimator
      include Base::ClusterAnalyzer

      # Return the core sample indices.
      # @return [Numo::Int32] (shape: [n_core_samples])
      attr_reader :core_sample_ids

      # Return the cluster labels. The negative cluster label indicates that the point is noise.
      # @return [Numo::Int32] (shape: [n_samples])
      attr_reader :labels

      # Create a new cluster analyzer with DBSCAN method.
      #
      # @param eps [Float] The radius of neighborhood.
      # @param min_samples [Integer] The number of neighbor samples to be used for the criterion whether a point is a core point.
      # @param metric [String] The metric to calculate the distances.
      #   If metric is 'euclidean', Euclidean distance is calculated for distance between points.
      #   If metric is 'precomputed', the fit and fit_transform methods expect to be given a distance matrix.
      def initialize(eps: 0.5, min_samples: 5, metric: 'euclidean')
        check_params_numeric(eps: eps, min_samples: min_samples)
        check_params_string(metric: metric)
        @params = {}
        @params[:eps] = eps
        @params[:min_samples] = min_samples
        @params[:metric] = metric == 'precomputed' ? 'precomputed' : 'euclidean'
        @core_sample_ids = nil
        @labels = nil
      end

      # Analysis clusters with given training data.
      #
      # @overload fit(x) -> DBSCAN
      #
      # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for cluster analysis.
      #   If the metric is 'precomputed', x must be a square distance matrix (shape: [n_samples, n_samples]).
      # @return [DBSCAN] The learned cluster analyzer itself.
      def fit(x, _y = nil)
        x = check_convert_sample_array(x)
        raise ArgumentError, 'Expect the input distance matrix to be square.' if @params[:metric] == 'precomputed' && x.shape[0] != x.shape[1]

        partial_fit(x)
        self
      end

      # Analysis clusters and assign samples to clusters.
      #
      # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to be used for cluster analysis.
      #   If the metric is 'precomputed', x must be a square distance matrix (shape: [n_samples, n_samples]).
      # @return [Numo::Int32] (shape: [n_samples]) Predicted cluster label per sample.
      def fit_predict(x)
        x = check_convert_sample_array(x)
        raise ArgumentError, 'Expect the input distance matrix to be square.' if @params[:metric] == 'precomputed' && x.shape[0] != x.shape[1]

        partial_fit(x)
        labels
      end

      private

      def partial_fit(x)
        cluster_id = 0
        metric_mat = calc_pairwise_metrics(x)
        n_samples = metric_mat.shape[0]
        @core_sample_ids = []
        @labels = Numo::Int32.zeros(n_samples) - 2
        n_samples.times do |query_id|
          next if @labels[query_id] >= -1

          cluster_id += 1 if expand_cluster(metric_mat, query_id, cluster_id)
        end
        @core_sample_ids = Numo::Int32[*@core_sample_ids.flatten]
        nil
      end

      def calc_pairwise_metrics(x)
        @params[:metric] == 'precomputed' ? x : Rumale::PairwiseMetric.euclidean_distance(x)
      end

      def expand_cluster(metric_mat, query_id, cluster_id)
        target_ids = region_query(metric_mat[query_id, true])
        if target_ids.size < @params[:min_samples]
          @labels[query_id] = -1
          false
        else
          @labels[target_ids] = cluster_id
          @core_sample_ids.push(target_ids.dup)
          target_ids.delete(query_id)
          while (m = target_ids.shift)
            neighbor_ids = region_query(metric_mat[m, true])
            next if neighbor_ids.size < @params[:min_samples]

            neighbor_ids.each do |n|
              target_ids.push(n) if @labels[n] < -1
              @labels[n] = cluster_id if @labels[n] <= -1
            end
          end
          true
        end
      end

      def region_query(metric_arr)
        metric_arr.lt(@params[:eps]).where.to_a
      end
    end
  end
end


text:
$params = Parse-Args $args;

$path = Get-Attr $params "path" -failifempty $true
$state = Get-Attr $params "state" "present"
$test_path = Get-Attr $params "test_path" -failifempty $true
$extra_args = Get-Attr $params "extra_args" ""
$username = Get-Attr $params "user" -failifempty $true
$password = Get-Attr $params "pass" -failifempty $true

$result = New-Object psobject @{
    changed = $false
};

If (Test-Path $test_path)
{
    Exit-Json $result;
}

$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
 {
  Fail-Json (New-Object psobject) "This script needs to be run As Admin"
  Break
 }

# Start-Process -FilePath "$path" -ArgumentList "$extra_args" -Wait -Verb runas
$cmd = "$path $extra_args"
Invoke-Expression $cmd | Write-Verbose

Fail-Json (New-Object psobject) "$path $extra_args"

Set-Attr $result "changed" $true;
Exit-Json $result;


text:
package com.optimalCombinations.algo;

import java.util.ArrayList;

public class RoomSizeCombinations
{
	public static ArrayList<Integer> getSequence(int candidates[], int index[], int n)
	{
		ArrayList<Integer> genSeq = new ArrayList<Integer>();
		for (int i = 1; i <= n; i++)
		{
			genSeq.add(candidates[index[i]]);
		}
		return genSeq;
	}

	public static void calculate(int target, int sum, int roomSizes[], int size, int index[], int n, ArrayList<ArrayList<Integer>> sequences)
	{
		if (sum > target)
			return;
		if (sum == target)
		{
			sequences.add(getSequence(roomSizes, index, n));
		}

		for (int i = index[n]; i < size; i++)
		{
			index[n + 1] = i;
			calculate(target, sum + roomSizes[i], roomSizes, size, index, n + 1, sequences);
		}
	}

	public static ArrayList<ArrayList<Integer>> generateCombinations(int target, int roomSizes[])
	{
	  ArrayList<ArrayList<Integer>> sequence = new ArrayList<ArrayList<Integer>>();
	  int[] index = new int[10000];
	  index[0] = 0;
	  calculate(target, 0, roomSizes, roomSizes.length, index, 0, sequence);
	  System.out.println(sequence);
	  return sequence;
	}
	/*
	public static void main(String [] args)
	{
		int[] candidates = new int[]{3, 4, 5};
		generateCombinations(17, candidates);
	}*/
}