text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.map;

import com.gdx.bomberman.Constants;

/**
 *
 * @author qubasa
 */
public class MapCellCoordinates {

    private int x;
    private int y;

    public MapCellCoordinates(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public MapCellCoordinates(float x, float y)
    {
        this.x = (int) (x / Constants.MAPTEXTUREWIDTH);
        this.y = (int) (y / Constants.MAPTEXTUREHEIGHT);
    }

    public MapCellCoordinates(ThinGridCoordinates a)
    {
        this.x = (int) (a.getX() / Constants.MAPTEXTUREWIDTH);
        this.y = (int) (a.getY() / Constants.MAPTEXTUREHEIGHT);
    }

    public boolean equalCoordinates(MapCellCoordinates e)
    {
        return e.getX() == x && e.getY() == y;
    }

    /**
     * @return the x
     */
    public int getX() {
        return x;
    }

    /**
     * @param x the x to set
     */
    public void setX(int x) {
        this.x = x;
    }

        /**
     * @param x the x to set
     */
    public void setX(float x) {
        this.x = (int) (x / Constants.MAPTEXTUREWIDTH);
    }

    /**
     * @return the y
     */
    public int getY() {
        return y;
    }

    /**
     * @param y the y to set
     */
    public void setY(int y) {
        this.y = y;
    }

        /**
     * @param y the y to set
     */
    public void setY(float y) {
        this.y = (int) (y / Constants.MAPTEXTUREHEIGHT);
    }

}


text:
local mal = require "libmal"
local malzmq = require "malzmq"
local argparse = require "3rdparty.argparse"

local parser = argparse("acqd", "A telemetry acquisition daemon in lua")
parser:argument("inputfile")
parser:option("-p --port", "Control port number", "6666")
parser:flag("-v --verbose")

local args = parser:parse()

local Context = mal.Context
local binding = malzmq('localhost', args.port)
local malctx = Context:new(binding)

malctx:add_actor('acq', '@acqactor.lua', args)
malctx:start()

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.card.MaterialCardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="16dp"
        android:clickable="true"
        android:padding="16dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayout"
                style="@style/TabLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary" />

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </LinearLayout>

    </com.google.android.material.card.MaterialCardView>

</FrameLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 678 (1887)

#### Original name
Agaricus eugraptus Berk. & Broome

### Remarks
null


text:
package org.hisp.dhis.db.migration.v31;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;

/**
 * @author David Katuscak (katuscak.d@gmail.com)
 */
public class V2_31_4__Add_defaults_for_validationstrategy extends BaseJavaMigration
{
    @Override
    public void migrate( Context context )
        throws Exception
    {

        List<Integer> programStageIds = new ArrayList<>();

        String sql = "SELECT programstageid FROM programstage ps JOIN program p ON p.programid = ps.programid " +
            "WHERE p.type = 'WITHOUT_REGISTRATION'";
        try ( Statement stmt = context.getConnection().createStatement();
            ResultSet rs = stmt.executeQuery( sql ); )
        {
            while ( rs.next() )
            {
                programStageIds.add( rs.getInt( "programstageid" ) );
            }
        }

        if ( programStageIds.size() > 0 )
        {
            String inStatement = StringUtils.join( programStageIds, "," );
            sql = "UPDATE programstage SET validationstrategy = 'ON_UPDATE_AND_INSERT' " +
                "WHERE programstageid IN (" + inStatement + ")";

            try ( Statement stmt = context.getConnection().createStatement() )
            {
                stmt.executeUpdate( sql );
            }
        }
    }
}


text:
/* -*- Mode: C++; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 noexpandtab: */

/*******************************************************************************
 * FShell 2
 * Copyright 2009 Michael Tautschnig, tautschnig@forsyte.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/

/*! \file fshell2/command/command_processing.cpp
 * \brief TODO
 *
 * $Id$
 * \author Michael Tautschnig <tautschnig@forsyte.de>
 * \date   Thu Apr  2 17:29:47 CEST 2009
*/

#include <fshell2/command/command_processing.hpp>
#include <fshell2/config/annotations.hpp>
#include <fshell2/exception/command_processing_error.hpp>

#if FSHELL2_DEBUG__LEVEL__ > -1
#  include <diagnostics/basic_exceptions/violated_invariance.hpp>
#  include <diagnostics/basic_exceptions/invalid_argument.hpp>
#endif

#include <util/config.h>
#include <util/arith_tools.h>
#include <util/std_expr.h>
#include <util/std_code.h>
#include <util/replace_symbol.h>
#include <ansi-c/c_types.h>
#include <ansi-c/ansi_c_typecheck.h>
#include <langapi/language_ui.h>
#include <goto-programs/goto_convert_functions.h>
#include <pointer-analysis/add_failed_symbols.h>
#include <goto-programs/remove_function_pointers.h>
#include <goto-programs/goto_inline.h>
#include <goto-programs/loop_ids.h>
#include <analyses/goto_check.h>
#include <ansi-c/ansi_c_entry_point.h>

#include <cerrno>
#include <fstream>
#include <sys/stat.h>
#include <cstdlib>

/* parser */
#define yyFlexLexer CMDFlexLexer
#include <FlexLexer.h>

extern int CMDparse(CMDFlexLexer *,
		::fshell2::command::Command_Processing::parsed_command_t &, char **,
		int *, ::std::list< ::std::pair< char*, char* > > &);
// extern int yydebug;
/* end parser */

#include <fshell2/command/grammar.hpp>

FSHELL2_NAMESPACE_BEGIN;
FSHELL2_COMMAND_NAMESPACE_BEGIN;

::std::ostream & operator<<(::std::ostream & os, Command_Processing::status_t const& s) {
	switch (s) {
		case Command_Processing::NO_CONTROL_COMMAND:
			os << "NO_CONTROL_COMMAND";
			break;
		case Command_Processing::HELP:
			os << "HELP";
			break;
		case Command_Processing::QUIT:
			os << "QUIT";
			break;
		case Command_Processing::DONE:
			os << "DONE";
			break;
	}

	return os;
}

// cleanup char* stuff
class Cleanup {
	public:
		Cleanup(char ** a, ::std::list< ::std::pair< char*, char* > > & l);
		~Cleanup();
	private:
		char ** m_a;
		::std::list< ::std::pair< char*, char* > > & m_l;
};

Cleanup::Cleanup(char ** a, ::std::list< ::std::pair< char*, char* > > & l) :
	m_a(a), m_l(l) {
}

Cleanup::~Cleanup() {
	free(*m_a);

	while (!m_l.empty()) {
		free(m_l.front().first);
		m_l.front().first = 0;
		free(m_l.front().second);
		m_l.front().second = 0;
		m_l.erase(m_l.begin());
	}
}

Command_Processing::Command_Processing(::optionst & opts, ::goto_functionst & gf) :
	m_opts(opts), m_gf(gf),
	m_finalized(::config.main.empty() &&
				m_opts.get_unsigned_int_option("max-argc") == 0),
	m_remove_zero_init(false) {
	if (::config.main.empty()) ::config.main = id2string(ID_main);
	m_opts.set_option(F2_O_LIMIT, 0);
	m_opts.set_option(F2_O_MULTIPLE_COVERAGE, 1);
}

::std::ostream & Command_Processing::help(::std::ostream & os) {
	os << "Control commands:" << ::std::endl << COMMAND_HELP
		<< "Comments start with `//' and end at the end of the line" << ::std::endl;
	return os;
}

::std::ostream & Command_Processing::print_file_contents(::std::ostream & os, char const * name) const {
	FSHELL2_AUDIT_ASSERT(::diagnostics::Invalid_Argument, name != 0);
	// file might not correspond to what has been parsed, check file date
	::std::map< ::std::string, time_t >::const_iterator entry(m_parse_time.find(name));
	if (m_parse_time.end() == entry) {
		os << "WARNING: parse time of " << name
			<< " unknown, internal data may be inconsistent with file on disk!" << ::std::endl;
	} else {
		// try to obtain the file modification date
		struct stat info;
		FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error, 0 == ::stat(name, &info),
				::std::string("Failed to stat() file ") + name);
		FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error, info.st_mtime <= entry->second,
				::std::string("File ") + name + " changed on disk");
	}
	// read the file using an ifstream
	::std::ifstream fs(name);
	// make sure the file could be opened
	FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error, fs.is_open(),
			::std::string("Failed to open file ") + name);
	int lc(0);
	::std::string line;
	while(!::std::getline(fs, line).eof())
	{
		os << ++lc << "\t " << line << ::std::endl;
	}
	return os;
}

void Command_Processing::add_sourcecode(::language_uit & manager, char const * file,
		::std::list< ::std::pair< char*, char* > > const& defines) {
	// defines -- keep a marker of global defines
	::std::list< ::std::string >::iterator last_global(::config.ansi_c.defines.end());
	if (!::config.ansi_c.defines.empty()) --last_global;
	// add the specific defines given with the ADD_SOURCE command
	if (!defines.empty())
		for (::std::list< ::std::pair<char*,char*> >::const_iterator iter(defines.begin());
				iter != defines.end(); ++iter)
			// CBMC internally does -D' and the closing ', thus we
			// generate define_ident=definition
			config.ansi_c.defines.push_back(
					::std::string(iter->first) + "=" + iter->second);
	// keep a private copy of previously loaded files
	::language_filest::filemapt prev_files;
	prev_files.swap(manager.language_files.filemap);
	// store the parse time to warn the user in case a modified file
	// is to be printed
	m_parse_time[file] = ::std::time(0);
	// attempt to parse the file
	// we don't even try to catch any exception thrown by CBMC here,
	// these would be fatal anyway
	bool err(manager.parse(file));
	// reset defines
	if (::config.ansi_c.defines.end() != last_global) {
		++last_global;
		::config.ansi_c.defines.erase(last_global, ::config.ansi_c.defines.end());
	}
	if (err) {
		manager.language_files.filemap.swap(prev_files);
		FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error, false,
				::std::string("Failed to parse ") + file);
	}
	if (manager.typecheck()) {
		manager.language_files.filemap.swap(prev_files);
		FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error, false,
				::std::string("Failed to typecheck ") + file);
	}
	// build the full list of loaded files
	manager.language_files.filemap.insert(prev_files.begin(), prev_files.end());
	// reset entry routine
	m_finalized = false;
}

Command_Processing::status_t Command_Processing::process(::language_uit & manager,
		::std::ostream & os, char const * cmd) {
	while (0 != *cmd && ::std::isspace(*cmd)) ++cmd;
	if (0 == *cmd || ('/' == *cmd && '/' == *(cmd + 1))) return DONE;

	// new lexer
	CMDFlexLexer lexer;
	// put the input into a stream
	::std::istringstream is(cmd);
	// set the stream as the input to the parser
	lexer.switch_streams(&is, &os);
	// reset errno, readline for some reason sets this to EINVAL
	errno = 0;
	// information returned by parser
	parsed_command_t parsed_cmd(FAIL);
	char * arg(0);
	int numeric_arg(-1);
	::std::list< ::std::pair< char*, char* > > defines;
	Cleanup cleanup(&arg, defines);
	// yyparse returns 0 iff there was no error
	if (0 != CMDparse(&lexer, parsed_cmd, &arg, &numeric_arg, defines)) return NO_CONTROL_COMMAND;

	// parsing succeeded, what has to be done?
	switch (parsed_cmd) {
		case FAIL:
			FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, false);
			return NO_CONTROL_COMMAND;
		case CMD_HELP:
			return HELP;
		case CMD_QUIT:
			return QUIT;
		case CMD_ADD_SOURCECODE:
			FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, arg != 0);
			add_sourcecode(manager, arg, defines);
			return DONE;
		case CMD_SHOW_FILENAMES:
			for(::language_filest::filemapt::const_iterator iter(manager.language_files.filemap.begin());
					iter != manager.language_files.filemap.end(); ++iter)
				os << iter->first << ::std::endl;
			return DONE;
		case CMD_SHOW_SOURCECODE:
			FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, arg != 0);
			print_file_contents(os, arg);
			return DONE;
		case CMD_SHOW_SOURCECODE_ALL:
			for(::language_filest::filemapt::const_iterator iter(manager.language_files.filemap.begin());
					iter != manager.language_files.filemap.end(); ++iter)
				print_file_contents(os, iter->first.c_str());
			return DONE;
		case CMD_SET_ENTRY:
			FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, arg != 0);
			{
				::config.main = arg;
				m_finalized = false;
			}
			return DONE;
		case CMD_SET_LIMIT_COUNT:
			FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, numeric_arg >= 0);
			FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error, numeric_arg > 0,
					"Limit must be greater than 0");
			m_opts.set_option(F2_O_LIMIT, numeric_arg);
			return DONE;
		case CMD_SET_NO_ZERO_INIT:
			m_remove_zero_init = true;
			m_finalized = false;
			return DONE;
		case CMD_SET_ABSTRACT:
			FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, arg != 0);
			{
				::symbol_tablet::symbolst::iterator sym_entry(
						manager.symbol_table.symbols.find(arg));
				FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error,
						sym_entry != manager.symbol_table.symbols.end(),
						::std::string("Function ") + arg + " not found");
				sym_entry->second.value.make_nil();
				m_finalized = false;
			}
			return DONE;
		case CMD_SET_MULTIPLE_COVERAGE:
			FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, numeric_arg >= 0);
			FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error, numeric_arg > 1,
					"Multiplicity must be greater than 1");
			m_opts.set_option(F2_O_MULTIPLE_COVERAGE, numeric_arg);
			return DONE;
	}

	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, false);
	return NO_CONTROL_COMMAND;
}

void Command_Processing::remove_zero_init(::language_uit & manager) const {
	::symbol_tablet::symbolst::iterator init_iter(
	  manager.symbol_table.symbols.find("__CPROVER_initialize"));
	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance,
						 init_iter != manager.symbol_table.symbols.end());

	// check all operands
	for (::exprt::operandst::iterator iter(init_iter->second.value.operands().begin());
		 iter != init_iter->second.value.operands().end();)
	{
		if (iter->get(ID_statement) == ID_assign &&
			iter->source_location().get_file() != "<built-in>") {
			FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, 2 == iter->operands().size());
			if (iter->op1().get_bool(ID_C_zero_initializer)) {
				iter = init_iter->second.value.operands().erase(iter);
			} else {
				++iter;
			}
		} else {
			++iter;
		}
	}
}

void Command_Processing::model_argv(::language_uit & manager) const {
	::symbol_tablet &symbol_table=manager.symbol_table;
	::namespacet const ns(symbol_table);

	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, symbol_table.has_symbol(ID_main));
	source_locationt const& main_loc=symbol_table.symbols.find(ID_main)->second.location;
	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, main_loc.is_not_nil());

	/*
	unsigned next=0;
	unsigned i=0;
   	__CPROVER_assume(argc'<=max_argc);
   	while(i<argc' && i<max_argc)
   	{
    	unsigned len;
     	__CPROVER_assume(len<4096);
     	__CPROVER_assume(next+len<4096);
     	argv'[i]=argv''+next;
     	argv''[next+len]=0;
     	next=next+len+1;
		i=i+1;
   	}
	*/
	int max_argc=m_opts.get_unsigned_int_option("max-argc");
	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, max_argc > 0);

	::symbol_tablet::symbolst::iterator main_iter(
	  symbol_table.symbols.find(ID_main));
	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance,
						 main_iter != symbol_table.symbols.end());

	// turn argv' into a bounded array
	{
		FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, symbol_table.has_symbol("argv'"));
		symbol_table.symbols.find("argv'")->second.type.set(ID_size, from_integer(max_argc+1, index_type()));

		replace_symbolt replace_argvp;

		::symbolt const& argvp_symbol(ns.lookup("argv'"));
		symbol_exprt argvp(argvp_symbol.name, argvp_symbol.type);
		replace_argvp.insert(argvp_symbol.name, argvp);

		bool replaced=replace_argvp.replace(main_iter->second.value);
		assert(!replaced);
	}

	// add argv'' to the symbol table
	if(!symbol_table.has_symbol("main::1::argv''"))
	{
		// POSIX guarantees that at least 4096 characters can be passed as
		// arguments
		::array_typet argv_type(char_type(), from_integer(4096, index_type()));

		::symbolt argv_symbol;
		argv_symbol.pretty_name="argv''";
		argv_symbol.base_name="main::1::argv''";
		argv_symbol.name="main::1::argv''";
		argv_symbol.type=argv_type;
		argv_symbol.is_file_local=true;
		argv_symbol.is_type=false;
		argv_symbol.is_thread_local=false;
		argv_symbol.is_static_lifetime=false;
		argv_symbol.value.make_nil();
		argv_symbol.location=main_loc;

		symbol_table.add(argv_symbol);
	}

	// add counters/size
	::irep_idt locals[] = { "next", "i", "len'" };
	for(size_t i=0; i<sizeof(locals)/sizeof(::irep_idt); ++i)
	{
		::irep_idt name="main::1::"+id2string(locals[i]);
		if(symbol_table.has_symbol(name))
			continue;

		symbolt next_symbol;
		next_symbol.pretty_name=id2string(locals[i]);
		next_symbol.base_name="main::1::"+id2string(locals[i]);
		next_symbol.name=name;
		next_symbol.type=unsigned_short_int_type();
		next_symbol.is_file_local=true;
		next_symbol.is_type=false;
		next_symbol.is_thread_local=false;
		next_symbol.is_static_lifetime=false;
		next_symbol.is_lvalue=true;
		next_symbol.value.make_nil();
		next_symbol.location=main_loc;

		symbol_table.add(next_symbol);
	}

	/*
	char argv''[4096];
	*/
	::symbolt const& argvpp_symbol(ns.lookup("main::1::argv''"));
	symbol_exprt argvpp(argvpp_symbol.base_name, argvpp_symbol.type);
	code_declt argvpp_decl(argvpp);
	argvpp_decl.add_source_location()=main_loc;

	code_blockt code;

	/*
	unsigned next=0;
	unsigned i=0;
	*/
	for(int i=0; i<2; ++i)
	{
		::symbolt const& symbol(ns.lookup("main::1::"+id2string(locals[i])));
		::symbol_exprt symbol_expr(symbol.base_name, symbol.type);

		code_declt decl(symbol_expr);
		decl.add_source_location()=main_loc;
		code.move_to_operands(decl);

		code_assignt assign(symbol_expr, from_integer(0, unsigned_short_int_type()));
		assign.add_source_location()=main_loc;
		code.move_to_operands(assign);
	}

	/*
   	__CPROVER_assume(argc'<=max_argc);
	*/
	::symbolt const& argcp_symbol(ns.lookup("argc'"));
	symbol_exprt argcp("argc'", argcp_symbol.type); /* for some reason the base_name of argc' was set to argc */
	{
		binary_relation_exprt le(
		  argcp,
		  ID_le,
		  from_integer(max_argc, argcp_symbol.type));
		code_assumet assume(le);
		assume.add_source_location()=main_loc;
		code.move_to_operands(assume);
	}

	/*
   	while(i<argc' && i<max_argc)
   	{
    	unsigned len;
     	__CPROVER_assume(len<4096);
     	__CPROVER_assume(next+len<4096);
     	argv'[i]=argv''+next;
     	argv''[next+len]=0;
     	next=next+len+1;
		i=i+1;
   	}
	*/
	{
		::symbolt const& next_symbol(ns.lookup("main::1::next"));
		::symbol_exprt next(next_symbol.base_name, next_symbol.type);
		::symbolt const& len_symbol(ns.lookup("main::1::len'"));
		::symbol_exprt len(len_symbol.base_name, len_symbol.type);
		::symbolt const& i_symbol(ns.lookup("main::1::i"));
		symbol_exprt i(i_symbol.base_name, i_symbol.type);

		::symbolt const& argvp_symbol(ns.lookup("argv'"));
		symbol_exprt argvp(argvp_symbol.base_name, argvp_symbol.type);

		code_whilet while_loop;
		while_loop.add_source_location()=main_loc;

		while_loop.cond()=and_exprt(
		  binary_relation_exprt(i, ID_lt, argcp),
		  binary_relation_exprt(i, ID_lt, from_integer(max_argc, i_symbol.type)));

		while_loop.body()=code_blockt();

		code_declt decl(len);
		decl.add_source_location()=main_loc;
		while_loop.body().move_to_operands(decl);

		exprt e4096=from_integer(4096, len_symbol.type);
		binary_relation_exprt lt1(len, ID_lt, e4096);
		code_assumet assume1(lt1);
		assume1.add_source_location()=main_loc;
		while_loop.body().move_to_operands(assume1);
		binary_relation_exprt lt2(plus_exprt(next, len), ID_lt, e4096);
		code_assumet assume2(lt2);
		assume2.add_source_location()=main_loc;
		while_loop.body().move_to_operands(assume2);

		code_assignt assign1(
		  index_exprt(argvp, i),
		  plus_exprt(argvpp, next));
		assign1.add_source_location()=main_loc;
		while_loop.body().move_to_operands(assign1);

		code_assignt assign2(
		  index_exprt(argvpp, plus_exprt(next, len)),
		  from_integer(0, char_type()));
		assign2.add_source_location()=main_loc;
		while_loop.body().move_to_operands(assign2);

		code_assignt assign3(next, plus_exprt(plus_exprt(next, len), from_integer(1, unsigned_short_int_type())));
		assign3.add_source_location()=main_loc;
		while_loop.body().move_to_operands(assign3);

		code_assignt assign4(i, plus_exprt(i, from_integer(1, unsigned_short_int_type())));
		assign4.add_source_location()=main_loc;
		while_loop.body().move_to_operands(assign4);

		code.move_to_operands(while_loop);
	}

	ansi_c_parse_treet ansi_c_parse_tree;
	ansi_c_typecheckt ansi_c_typecheck(
	  ansi_c_parse_tree, symbol_table, "", manager.get_message_handler());
	try
	{
		side_effect_exprt expr(ID_statement_expression, empty_typet());
		expr.move_to_operands(code);

		ansi_c_typecheck.typecheck_expr(expr);
		code.swap(expr.op0());

		code_blockt dummyb;
		dummyb.move_to_operands(argvpp_decl);
		expr.op0()=dummyb;
		ansi_c_typecheck.typecheck_expr(expr);
		argvpp_decl.swap(to_code_block(to_code(expr.op0())).operands().front());
	}

	catch(int)
	{
		ansi_c_typecheck.error();
	}

	catch(const char *e)
	{
		ansi_c_typecheck.error() << e << messaget::eom;
	}

	catch(const std::string &e)
	{
		ansi_c_typecheck.error() << e << messaget::eom;
	}
	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance,
						 !ansi_c_typecheck.get_error_found());

	// find main() call and insert code before
	for (::exprt::operandst::iterator iter(main_iter->second.value.operands().begin());
		 iter != main_iter->second.value.operands().end();
		 ++iter)
	{
		if (iter->get(ID_statement) == ID_function_call &&
			to_symbol_expr(to_code_function_call(to_code(*iter)).function()).get_identifier() == ID_main)
		{
			::exprt::operandst items;

			items.push_back(argvpp_decl);
			items.push_back(code);

			main_iter->second.value.operands().insert(iter, items.begin(), items.end());

			code.make_nil();
			break;
		}
	}
	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, code.is_nil());
}

bool Command_Processing::finalize(::language_uit & manager) {
	FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error,
			!manager.symbol_table.symbols.empty(),
			"No source files loaded!");

	FSHELL2_PROD_CHECK1(::fshell2::Command_Processing_Error,
			manager.symbol_table.has_symbol(::config.main),
			::std::string("Could not find entry function " + ::config.main));

	if (m_finalized) return false;

	manager.symbol_table.remove(ID__start);

	m_finalized = ! ::ansi_c_entry_point(manager.symbol_table,
								  id2string(ID_main),
								  manager.ui_message_handler);
	// this must never fail, given all the previous sanity checks
	FSHELL2_AUDIT_ASSERT(::diagnostics::Violated_Invariance, m_finalized);

	// remove 0-initialization of global variables, if requested by user
	if (m_remove_zero_init) remove_zero_init(manager);

	// create init code for argv, if max-argc was set
	if (m_opts.get_unsigned_int_option("max-argc") > 0 &&
		config.main==id2string(ID_main) &&
		manager.symbol_table.has_symbol("argc'"))
		model_argv(manager);

	// convert all symbols; iterators are unstable, copy symbol names first
	::std::vector< ::irep_idt > symbols;
	for(::symbol_tablet::symbolst::iterator iter(manager.symbol_table.symbols.begin());
			iter != manager.symbol_table.symbols.end(); ++iter)
		if(iter->second.type.id() == ID_code)
			symbols.push_back(iter->first);

	::goto_convert_functionst converter(manager.symbol_table, m_gf,
			manager.ui_message_handler);
	for(::std::vector< ::irep_idt >::const_iterator iter(symbols.begin());
			iter != symbols.end(); ++iter) {
		::goto_functionst::function_mapt::iterator fct(m_gf.function_map.find(*iter));
		if (m_gf.function_map.end() != fct)
		{
			if(*iter!=ID__start && // main was possibly modified
			   fct->second.body_available() && // ADD SOURCECODE may have added sth
			   manager.symbol_table.symbols.find(*iter)->second.value.is_not_nil()) //not ABSTRACT
				continue;
			m_gf.function_map.erase(fct);
		}
		converter.convert_function(*iter);
	}

	finalize_goto_program(manager);

	return true;
}

void Command_Processing::finalize_goto_program(::language_uit & manager) {

	manager.status() << "Function Pointer Removal" << messaget::eom;
	::remove_function_pointers(manager.symbol_table, m_gf, false);

	manager.status() << "Partial Inlining" << messaget::eom;
	// do partial inlining
	::namespacet ns(manager.symbol_table);
	::goto_partial_inline(m_gf, ns, manager.ui_message_handler);

	// add generic checks
	manager.status() << "Generic Property Instrumentation" << messaget::eom;
	::goto_check(ns, m_opts, m_gf);

	// add failed symbols
	::add_failed_symbols(manager.symbol_table);

	// recalculate numbers, etc.
	m_gf.update();

	// add loop ids
	m_gf.compute_loop_numbers();

	// show loops, if requested
	if (m_opts.get_bool_option("show-loops"))
		::show_loop_ids(manager.get_ui(), m_gf);
}

FSHELL2_COMMAND_NAMESPACE_END;
FSHELL2_NAMESPACE_END;


text:
describe ActionSubscriber::Middleware::Router do
  include_context 'action subscriber middleware env'

  subject { described_class.new(app) }

  it "routes the event to the proper action" do
    allow_any_instance_of(env.subscriber).to receive(env.action)
    subject.call(env)
  end
end


text:
<android.support.v4.widget.SlidingPaneLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/panes"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<fragment
		android:id="@+id/sensors"
		android:name="com.commonsware.android.signature.dump.PackagesFragment"
		android:layout_width="300sp"
		android:layout_height="match_parent"/>

	<fragment
		android:id="@+id/log"
		android:name="com.commonsware.android.signature.dump.SignatureFragment"
		android:layout_width="400dp"
		android:layout_height="match_parent"
		android:layout_weight="1"/>

</android.support.v4.widget.SlidingPaneLayout>


text:
#ifndef GOLDFISH_DEVICE_H
#define GOLDFISH_DEVICE_H

struct goldfish_device {
    struct goldfish_device *next;
    struct goldfish_device *prev;
    uint32_t reported_state;
    void *cookie;
    const char *name;
    uint32_t id;
    uint32_t base; // filled in by goldfish_device_add if 0
    uint32_t size;
    uint32_t irq; // filled in by goldfish_device_add if 0
    uint32_t irq_count;
};

void goldfish_device_set_irq(struct goldfish_device *dev, int irq, int level);
int goldfish_device_add(struct goldfish_device *dev,
                       CPUReadMemoryFunc **mem_read,
                       CPUWriteMemoryFunc **mem_write,
                       void *opaque);

int goldfish_add_device_no_io(struct goldfish_device *dev);

void goldfish_device_init(qemu_irq *pic, uint32_t base, uint32_t size, uint32_t irq, uint32_t irq_count);
int goldfish_device_bus_init(uint32_t base, uint32_t irq);

// device init functions:
qemu_irq *goldfish_interrupt_init(uint32_t base, qemu_irq parent_irq, qemu_irq parent_fiq);
void goldfish_timer_and_rtc_init(uint32_t timerbase, int timerirq);
int goldfish_tty_add(CharDriverState *cs, int id, uint32_t base, int irq);
void goldfish_fb_init(int id);
void goldfish_audio_init(uint32_t base, int id, const char* input_source);
void goldfish_battery_init();
void goldfish_battery_set_prop(int ac, int property, int value);
void goldfish_battery_display(void (* callback)(void *data, const char* string), void *data);
void goldfish_mmc_init(uint32_t base, int id, BlockDriverState* bs);
void *goldfish_switch_add(char *name, uint32_t (*writefn)(void *opaque, uint32_t state), void *writeopaque, int id);
void goldfish_switch_set_state(void *opaque, uint32_t state);

// these do not add a device
void trace_dev_init();
void events_dev_init(uint32_t base, qemu_irq irq);
void nand_dev_init(uint32_t base);

#ifdef TARGET_I386
/* Maximum IRQ number available for a device on x86. */
#define GFD_MAX_IRQ      16
/* IRQ reserved for keyboard. */
#define GFD_KBD_IRQ      1
/* IRQ reserved for mouse. */
#define GFD_MOUSE_IRQ    12
/* IRQ reserved for error (raising an exception in TB code). */
#define GFD_ERR_IRQ      13
#else
/* Maximum IRQ number available for a device on ARM. */
#define GFD_MAX_IRQ     32
#endif

#endif  /* GOLDFISH_DEVICE_H */


text:
FROM ruby:2.2.0

RUN mkdir /app
COPY . /app
WORKDIR /app
RUN bundle install --without development --system

CMD ["bundle", "exec", "bin/memot", "-i", "15"]


text:
package softlayer_monitoring_agent_configuration_value

// DO NOT EDIT. THIS FILE WAS AUTOMATICALLY GENERATED

import (
	slapi "github.com/sudorandom/softlayer-go/slapi"
)

// GetObject - no documentation
func GetObject(ID interface{}) slapi.Request {
	return slapi.Request{
		Service: "SoftLayer_Monitoring_Agent_Configuration_Value",
		Method:  "getObject",
		ID:      ID,
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Skermstafir.Models
{
    public class SubtitleModel
    {
        public Subtitle subtitle { get; set; }
		// 8 is count of genres.
		public bool[] genreValue = new bool[8];

		public SubtitleModel()
		{
			subtitle = new Subtitle();
		}
	}
}


text:
package org.apache.cassandra.stress.generatedata;

import org.apache.commons.math3.distribution.AbstractRealDistribution;

public class DistributionOffsetApache extends Distribution
{

    final AbstractRealDistribution delegate;
    final long min, delta;

    public DistributionOffsetApache(AbstractRealDistribution delegate, long min, long max)
    {
        this.delegate = delegate;
        this.min = min;
        this.delta = max - min;
    }

    @Override
    public long next()
    {
        return offset(min, delta, delegate.sample());
    }

    @Override
    public long inverseCumProb(double cumProb)
    {
        return offset(min, delta, delegate.inverseCumulativeProbability(cumProb));
    }

    private long offset(long min, long delta, double val)
    {
        long r = (long) val;
        if (r < 0)
            r = 0;
        if (r > delta)
            r = delta;
        return min + r;
    }

}


text:
<VerticalLayout margin="true" width="100%" spacing="true">
  <ValidationSettings withApply="true" withAttach="true" withPrint="false" />
  <VerticalLayout captionMargin="0" margin="true" spacing="true" style="container">
    <HorizontalLayout captionMargin="0" margin="true" spacing="true">
      <GuiField name="NAME" caption="Name" width="180px" />
      <GuiField name="DESCRIP" caption="Description" width="180px" />
    </HorizontalLayout>
    <HorizontalLayout captionMargin="0" margin="true" spacing="true">
      <GuiField name="IS_APPROVAL" caption="Approves Document" captionPos="left" captionWidth="-1px" />
      <GuiField name="IS_CLOSE" caption="Closes Document" captionPos="left" captionWidth="-1px" />
    </HorizontalLayout>
  </VerticalLayout>
</VerticalLayout>


text:
package serviceComponents;

import db.DBConnector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import serviceRepresentations.LoginDataSocial;
import serviceResources.LoginDataSocialDAO;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/v1/social")
public class LoginDataSocialController {

    // TODO: add implementation
    @Autowired
    DBConnector dbConnector;
    LoginDataSocialDAO loginDataSocialDAO;

    /**
     * Rest endpoint for getting the auth hash of an user.
     * @param userId The id of the targeted user.
     * @return
     */
    @RequestMapping(
            value = "/{userId}",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
    )
    public ResponseEntity<String> getEntry(@PathVariable Long userId) {

        loginDataSocialDAO = new LoginDataSocialDAO(dbConnector);

        List<LoginDataSocial> entries = loginDataSocialDAO.getAllEntries(userId);

        if (entries.size() == 0) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<>(entries.get(0).getAuthHash(), HttpStatus.OK);
    }

    /**
     * Rest endpoint for adding a new entry, for social login/register.
     * @param params The id of the user and the hash.
     * @return
     */
    @RequestMapping(
            value = "",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public ResponseEntity<Void> createEntry(
            @RequestBody Map<String, String> params) {

        loginDataSocialDAO = new LoginDataSocialDAO(dbConnector);
        LoginDataSocial loginDataSocial = new LoginDataSocial();
        loginDataSocial.setUserId(Long.parseLong(params.get("userId")));
        loginDataSocial.setAuthHash(params.get("authHash"));

        Long id = loginDataSocialDAO.createEntry(loginDataSocial);

        if (id == 0) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * Endpoint for updating the hash key for a user.
     * @param params the user_id and the authhash
     * @return
     */
    @RequestMapping(
            value = "/",
            method = RequestMethod.PUT,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public ResponseEntity<Void> updateEntry(
            @RequestBody Map<String, String> params) {

        loginDataSocialDAO = new LoginDataSocialDAO(dbConnector);
        LoginDataSocial loginDataSocial = new LoginDataSocial();
        loginDataSocial.setAuthHash(params.get("authHash"));
        loginDataSocial.setUserId(Long.parseLong(params.get("userId")));

        Boolean status = loginDataSocialDAO.updateEntry(loginDataSocial);

        if (status == Boolean.FALSE) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * Endpoint for deleting a social login credentials for a user.
     * @param userId
     * @return
     */
    @RequestMapping(
            value = "/{userId}",
            method = RequestMethod.DELETE,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public ResponseEntity<Void> deleteEntry(
            @PathVariable Long userId) {

        loginDataSocialDAO = new LoginDataSocialDAO(dbConnector);
        // TODO: Check possible empty returned lists
        List<LoginDataSocial> logins =
                loginDataSocialDAO.getAllEntries(userId);
        if(logins.size() == 0)
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);

        Boolean status = loginDataSocialDAO.removeEntry(logins.get(0).getId());

        if (status == Boolean.FALSE) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<>(HttpStatus.OK);
    }
}


text:
/**
**  @file tcFormationObject.cpp
*/
/*
**  Copyright (c) 2014, GCBLUE PROJECT
**  All rights reserved.
**
**  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
**
**  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
**
**  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
**     documentation and/or other materials provided with the distribution.
**
**  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
**     this software without specific prior written permission.
**
**  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
**  NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
**  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
**  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
**  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
**  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "stdwx.h" // precompiled header file

#include "tcFormationObject.h"
#include "tcSimState.h"
#include "tcGameObject.h"
#include "tcPlatformObject.h"
#include "common/tcStream.h"
#include "tc3DWindow2.h"
#include "tcMapView.h"
#include "tcGeometry.h"
#include "tcTexture2D.h"
#include "tcUnits.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

boost::shared_ptr<tcGeometry> tcFormationObject::cornerMarkerOn;
boost::shared_ptr<tcGeometry> tcFormationObject::cornerMarkerOff;
boost::shared_ptr<tcGeometry> tcFormationObject::cornerMarkerOff2;

void tcFormationObject::LoadCornerMarker(const std::string& filename_on, const std::string& filename_off, const std::string& filename_off2)
{
    float w = 8.0f;

    cornerMarkerOn = boost::shared_ptr<tcGeometry>(new tcGeometry);
    tcTexture2D* texOn = new tcTexture2D(filename_on);
    cornerMarkerOn->MakeTexturedSymbol(boost::shared_ptr<tcTexture2D>(texOn), w);

    cornerMarkerOff = boost::shared_ptr<tcGeometry>(new tcGeometry);
    tcTexture2D* texOff = new tcTexture2D(filename_off);
    cornerMarkerOff->MakeTexturedSymbol(boost::shared_ptr<tcTexture2D>(texOff), w);

    cornerMarkerOff2 = boost::shared_ptr<tcGeometry>(new tcGeometry);
    tcTexture2D* texOff2 = new tcTexture2D(filename_off2);
    cornerMarkerOff->MakeTexturedSymbol(boost::shared_ptr<tcTexture2D>(texOff2), w);
}

/**
* Loads state from stream
*/
tcStream& tcFormationObject::operator<<(tcStream& stream)
{
    return tcMapObject::operator<<(stream);
}

/**
* Saves state to stream
*/
tcStream& tcFormationObject::operator>>(tcStream& stream)
{
    return tcMapObject::operator>>(stream);
}

/**
* @param mousePoint screen coords of mouse click point
*/
int tcFormationObject::CalculateDragMode(const tcPoint& pos)
{
    float diagonalDistance = sectorBL.DistanceTo(sectorTR);
    if (diagonalDistance < 32.0)
    {
        return 0;
    }

    const float dragDist = 8.0f;

    float distBL = pos.DistanceTo(sectorBL);
    float distBR = pos.DistanceTo(sectorBR);
    float distTL = pos.DistanceTo(sectorTL);
    float distTR = pos.DistanceTo(sectorTR);

    if (distBL < dragDist) return DRAG_BL;
    else if (distBR < dragDist) return DRAG_BR;
    else if (distTL < dragDist) return DRAG_TL;
    else if (distTR < dragDist) return DRAG_TR;
    else return DRAG_ALL;

}

void tcFormationObject::Draw(tc3DWindow2* host)
{
    if (!IsDragActive() && markFormationWhenDragDone)
    {
        MarkFormationUpdated();
        markFormationWhenDragDone = false;
    }

    if (!isActive) return;

    if (CloseRequested())
    {
        FlagForDelete();
        return;
    }

    bool valid = UpdateDrawData();
    if (!valid)
    {
        FlagForDelete();
        return;
    }

    if (isLeader)
    {
        DrawLeader(host);
        return;
    }

    bool showSecondaryColor = (formationMode == tcFormation::SPRINTDRIFT) && (!isLeader);

    Vec4 color;
    if (IsDragActive())
    {
        if (showSecondaryColor)
        {
            color.set(1.0f, 1.0f, 0.6f, 0.8f);
        }
        else
        {
            color.set(0.4f, 1, 0.5f, 0.7f);
        }
    }
    else
    {
        if (showSecondaryColor)
        {
            color.set(1.0f, 1.0f, 0.5f, 0.5f);
        }
        else
        {
            color.set(0, 1, 0.1f, 0.3f);
        }
    }

    //host->DrawLineR(leaderPoint.x, leaderPoint.y, ownPoint.x, ownPoint.y, color);

    host->DrawLineR(leaderPoint.x, leaderPoint.y, sectorCenter.x, sectorCenter.y, color);

    // if sector is big enough on screen, then draw it, otherwise just draw line
    float diagonalDistance = sectorBL.DistanceTo(sectorTR);
    if (diagonalDistance > 8.0)
    {

        host->DrawPieSection(leaderPoint.x, leaderPoint.y, rx1, -ry1, rx2, -ry2,
            start_angle_rad, stop_angle_rad, color, tc3DWindow2::FILL_OFF);

        if (IsDragActive() && (dragMode != DRAG_ALL))
        {
            host->DrawGeometryR(cornerMarkerOn.get(), sectorBL.x, sectorBL.y);
            host->DrawGeometryR(cornerMarkerOn.get(), sectorBR.x, sectorBR.y);
            host->DrawGeometryR(cornerMarkerOn.get(), sectorTL.x, sectorTL.y);
            host->DrawGeometryR(cornerMarkerOn.get(), sectorTR.x, sectorTR.y);
        }
        else if (showSecondaryColor)
        {
            host->DrawGeometryR(cornerMarkerOff.get(), sectorBL.x, sectorBL.y);
            host->DrawGeometryR(cornerMarkerOff.get(), sectorBR.x, sectorBR.y);
            host->DrawGeometryR(cornerMarkerOff.get(), sectorTL.x, sectorTL.y);
            host->DrawGeometryR(cornerMarkerOff.get(), sectorTR.x, sectorTR.y);
        }
        else
        {
            host->DrawGeometryR(cornerMarkerOff2.get(), sectorBL.x, sectorBL.y);
            host->DrawGeometryR(cornerMarkerOff2.get(), sectorBR.x, sectorBR.y);
            host->DrawGeometryR(cornerMarkerOff2.get(), sectorTL.x, sectorTL.y);
            host->DrawGeometryR(cornerMarkerOff2.get(), sectorTR.x, sectorTR.y);
        }
    }

    // drag range, bearing to sector center if drag is active
    if (IsDragActive())
    {
        tcUnits* units = tcUnits::Get();
        wxString s;
        s.Printf("%s, %03.0f deg", units->GetUserDistanceString(1000.0f*range_km),
            C_RADTODEG*bearing_center_rad);

        float x = 0.5f*(leaderPoint.x + sectorCenter.x);
        float y = 0.5f*(leaderPoint.y + sectorCenter.y);

        host->DrawTextR(s.c_str(), x, y, host->GetDefaultFont(),
            Vec4(1, 1, 1, 1), 10.0f, tc3DWindow2::LEFT_CENTER);
    }

    host->DrawRectangleR(bearingModeSelect, color, tc3DWindow2::FILL_ON);
    if (useNorthBearing)
    {
        host->DrawTextInRectR("N", bearingModeSelect, host->GetDefaultFont(), Vec4(1, 1, 1, 1),
            10.0f, tc3DWindow2::CENTER_CENTER);
    }
    else
    {
        host->DrawTextInRectR("R", bearingModeSelect, host->GetDefaultFont(), Vec4(1, 1, 1, 1),
            10.0f, tc3DWindow2::CENTER_CENTER);
    }

}

/**
* Version for leader object
*/
void tcFormationObject::DrawLeader(tc3DWindow2* host)
{
    tcSimState* simState = tcSimState::Get();
    tcPlatformObject* leader = dynamic_cast<tcPlatformObject*>(simState->GetObject(platformId));
    if (leader == 0)
    {
        wxASSERT(false);
        return;
    }

    Vec4 color(0, 1, 0.1f, 0.3f);

    // draw line from leader to each of followers
    for (size_t k=0; k<leader->formation.followers.size(); k++)
    {
        long followerId = leader->formation.followers[k];
        tcGameObject* follower = simState->GetObject(followerId);
        if (follower != 0)
        {
            tcPoint p = mapView->GeoToScreen(follower->mcKin.mfLon_rad, follower->mcKin.mfLat_rad);
            host->DrawLineR(ownPoint.x, ownPoint.y, p.x, p.y, color);
        }
        else
        {
            wxASSERT(false);
        }
    }
}

void tcFormationObject::MarkFormationUpdated()
{
    tcSimState* simState = tcSimState::Get();

    tcPlatformObject* platform =
        dynamic_cast<tcPlatformObject*>(simState->GetObject(platformId));

    if (platform == 0) return;

    platform->MarkFormationUpdated();
}

void tcFormationObject::MoveToScreenPoint(const wxPoint& pos)
{
    if (!IsDragActive()) return;
    tcSimState* simState = tcSimState::Get();

    tcPlatformObject* platform =
        dynamic_cast<tcPlatformObject*>(simState->GetObject(platformId));

    if (platform == 0) return;

    tcFormation& formation = platform->formation;
    if (!formation.isActive) return;

    tcPlatformObject* leader = dynamic_cast<tcPlatformObject*>(simState->GetObject(formation.leaderId));

    tcPoint geo = mapView->ScreenToGeo(pos);

    // calculate bearing and range
    float bearing_rad = leader->mcKin.HeadingToGeoRad(geo.x, geo.y);
    float range_km = leader->mcKin.RangeToKm(geo.x, geo.y);

    if (dragMode == DRAG_ALL)
    {
        bearing_rad -= deltaBearing_rad;
        range_km -= deltaRange_km;
    }

    float range_error_km = range_km - formation.range_center_km;

    // bearing of sector center wrt North
    float effectiveBearing = formation.useNorthBearing ?
        formation.bearing_center_rad : formation.bearing_center_rad + leader->mcKin.mfHeading_rad;
    if (effectiveBearing < -C_PI) effectiveBearing += C_TWOPI;
    else if (effectiveBearing >= C_PI) effectiveBearing -= C_TWOPI;

    float bearing_error_rad = bearing_rad - effectiveBearing;

    if (bearing_error_rad < -C_PI) bearing_error_rad += C_TWOPI;
    else if (bearing_error_rad >= C_PI) bearing_error_rad -= C_TWOPI;

    switch (dragMode)
    {
    case DRAG_ALL:
        // move formation sector
        if (formation.useNorthBearing)
        {
            formation.bearing_center_rad = bearing_rad;
        }
        else
        {
            formation.bearing_center_rad = bearing_rad - leader->mcKin.mfHeading_rad;
            if (formation.bearing_center_rad < -C_PI) formation.bearing_center_rad += C_TWOPI;
        }
        formation.range_center_km = range_km;
        break;
    default:
        formation.bearing_span_rad = 2.05f * fabsf(bearing_error_rad);
        formation.range_span_km = 2.05f * fabsf(range_error_km);
        if (formation.bearing_span_rad > C_TWOPI) formation.bearing_span_rad = C_TWOPI;

        break;
    }
}

bool tcFormationObject::ProcessLButtonDown(const wxPoint& pos)
{
    tcSimState* simState = tcSimState::Get();

    tcPlatformObject* platform =
        dynamic_cast<tcPlatformObject*>(simState->GetObject(platformId));

    if (platform == 0) return false;

    tcFormation& formation = platform->formation;

    if (formation.IsLeader()) return false; // no interaction with leader graphics
    if (!formation.isActive) return false;

    tcPlatformObject* leader = dynamic_cast<tcPlatformObject*>(simState->GetObject(formation.leaderId));

    tcPoint geo = mapView->ScreenToGeo(pos);

    // calculate bearing and range
    float bearing_rad = leader->mcKin.HeadingToGeoRad(geo.x, geo.y);
    float range_km = leader->mcKin.RangeToKm(geo.x, geo.y);

    bool pointWithinSector = formation.IsInPositionLoose2(platform, bearing_rad, range_km, deltaBearing_rad, deltaRange_km);

    if (pointWithinSector)
    {
        dragMode = CalculateDragMode(tcPoint(pos.x, pos.y));
        SetDragActive(true);
        markFormationWhenDragDone = true;
        return true;
    }
    else if (bearingModeSelect.ContainsPoint(pos.x, pos.y))
    {
        ToggleBearingMode();
        return true;
    }
    else
    {
        return false;
    }
}

void tcFormationObject::ToggleBearingMode()
{
    tcSimState* simState = tcSimState::Get();

    tcPlatformObject* platform =
        dynamic_cast<tcPlatformObject*>(simState->GetObject(platformId));

    if (platform == 0) return;

    tcFormation& formation = platform->formation;
    if (!formation.isActive) return;

    tcPlatformObject* leader = dynamic_cast<tcPlatformObject*>(simState->GetObject(formation.leaderId));
    if (leader == 0) return;

    if (formation.useNorthBearing)
    {
        formation.useNorthBearing = false; // switch to relative bearing
        formation.bearing_center_rad -= leader->mcKin.mfHeading_rad;
        if (formation.bearing_center_rad < -C_PI) formation.bearing_center_rad += C_TWOPI;
    }
    else
    {
        formation.useNorthBearing = true; // switch to north bearing
        formation.bearing_center_rad += leader->mcKin.mfHeading_rad;
        if (formation.bearing_center_rad >= C_PI) formation.bearing_center_rad -= C_TWOPI;
    }

    platform->MarkFormationUpdated();
}

/**
* @return true if formation is valid, false if invalid (should delete if invalid)
*/
bool tcFormationObject::UpdateDrawData()
{
    tcSimState* simState = tcSimState::Get();

    tcPlatformObject* platform =
        dynamic_cast<tcPlatformObject*>(simState->GetObject(platformId));

    if ((platform == 0) || (!platform->IsOwnAlliance())) return false; // delete if not player alliance for cases where we toggle alliance in game

    tcFormation& formation = platform->formation;
    if (!formation.isActive) return false;

    isLeader = formation.IsLeader();
    if (isLeader)
    {
        ownPoint = mapView->GeoToScreen(platform->mcKin.mfLon_rad, platform->mcKin.mfLat_rad);
        return true;
    }

    tcPlatformObject* leader = dynamic_cast<tcPlatformObject*>(simState->GetObject(formation.leaderId));
    if (leader == 0) return false;

    formationMode = (int)formation.formationMode;
    range_km = formation.range_center_km;
    min_range_km = formation.range_center_km - 0.5f*formation.range_span_km;
    max_range_km = formation.range_center_km + 0.5f*formation.range_span_km;

    float min_lat = leader->mcKin.mfLat_rad + C_KMTORAD*min_range_km;
    float max_lat = leader->mcKin.mfLat_rad + C_KMTORAD*max_range_km;

    ownPoint = mapView->GeoToScreen(platform->mcKin.mfLon_rad, platform->mcKin.mfLat_rad);
    leaderPoint = mapView->GeoToScreen(leader->mcKin.mfLon_rad, leader->mcKin.mfLat_rad);

    tcPoint minNorthPoint = mapView->GeoToScreen((float)leader->mcKin.mfLon_rad, min_lat);
    tcPoint maxNorthPoint = mapView->GeoToScreen((float)leader->mcKin.mfLon_rad, max_lat);

    ry1 = leaderPoint.y - minNorthPoint.y;
    ry2 = leaderPoint.y - maxNorthPoint.y;

    float lon_scale = mapView->LonToLatScale() / cosf(leader->mcKin.mfLat_rad);
    rx1 = lon_scale * ry1;
    rx2 = lon_scale * ry2;

    float effectiveBearing_rad =
        formation.useNorthBearing ? formation.bearing_center_rad : formation.bearing_center_rad + leader->mcKin.mfHeading_rad;
    if (effectiveBearing_rad < -C_PI) effectiveBearing_rad += C_TWOPI;
    else if (effectiveBearing_rad >= C_PI) effectiveBearing_rad -= C_TWOPI;

    angle_rad = effectiveBearing_rad;
    start_angle_rad = effectiveBearing_rad - 0.5f*formation.bearing_span_rad;
    stop_angle_rad = effectiveBearing_rad + 0.5f*formation.bearing_span_rad;
    bearing_center_rad = formation.bearing_center_rad;

    tcTrack formCenter;
    formCenter.mfLat_rad = leader->mcKin.mfLat_rad;
    formCenter.mfLon_rad = leader->mcKin.mfLon_rad;
    formCenter.Offset(formation.range_center_km, effectiveBearing_rad);
    sectorCenter = mapView->GeoToScreen(formCenter.mfLon_rad, formCenter.mfLat_rad);

    tcTrack formBL;
    formBL.mfLat_rad = leader->mcKin.mfLat_rad;
    formBL.mfLon_rad = leader->mcKin.mfLon_rad;
    formBL.Offset(min_range_km, start_angle_rad);
    sectorBL = mapView->GeoToScreen(formBL.mfLon_rad, formBL.mfLat_rad);

    tcTrack formBR;
    formBR.mfLat_rad = leader->mcKin.mfLat_rad;
    formBR.mfLon_rad = leader->mcKin.mfLon_rad;
    formBR.Offset(min_range_km, stop_angle_rad);
    sectorBR = mapView->GeoToScreen(formBR.mfLon_rad, formBR.mfLat_rad);

    tcTrack formTL;
    formTL.mfLat_rad = leader->mcKin.mfLat_rad;
    formTL.mfLon_rad = leader->mcKin.mfLon_rad;
    formTL.Offset(max_range_km, start_angle_rad);
    sectorTL = mapView->GeoToScreen(formTL.mfLon_rad, formTL.mfLat_rad);

    tcTrack formTR;
    formTR.mfLat_rad = leader->mcKin.mfLat_rad;
    formTR.mfLon_rad = leader->mcKin.mfLon_rad;
    formTR.Offset(max_range_km, stop_angle_rad);
    sectorTR = mapView->GeoToScreen(formTR.mfLon_rad, formTR.mfLat_rad);

    tcTrack bearingSelect;
    bearingSelect.mfLat_rad = leader->mcKin.mfLat_rad;
    bearingSelect.mfLon_rad = leader->mcKin.mfLon_rad;
    bearingSelect.Offset(max_range_km, angle_rad);
    tcPoint pb = mapView->GeoToScreen(bearingSelect.mfLon_rad, bearingSelect.mfLat_rad);
    pb.y = -pb.y;
    pb.Offset(15.0f, angle_rad);
    pb.y = -pb.y;
    bearingModeSelect.Set(pb.x, pb.x, pb.y, pb.y);
    bearingModeSelect.Expand(8.0f, 8.0f);

    useNorthBearing = formation.useNorthBearing;

    return true;
}

tcFormationObject::tcFormationObject(long id)
: platformId(id),
  dragMode(DRAG_ALL),
  markFormationWhenDragDone(false),
  formationMode(0)
{
    SetComplexInteractive(true);

    if (cornerMarkerOn.get() == 0)
    {
        LoadCornerMarker("images\\white_marker.png", "images\\green_marker.png", "images\\yellow_marker.png");
    }
}

tcFormationObject::~tcFormationObject()
{
    if (markFormationWhenDragDone)
    {
        MarkFormationUpdated();
    }
}


text: Course project


text:
namespace IdokladSdk.ApiFilters
{
    /// <summary>
    /// Custom filter for bank
    /// </summary>
    public class BankFilter : FilterableObjectBase
    {
        public FilterItem CountryId { get; set; } = new FilterItem("CountryId");
        public CompareFilterItem DateLastChange { get; set; } = new CompareFilterItem("DateLastChange");
        public FilterItem IsOutOfDate { get; set; } = new FilterItem("IsOutOfDate");
    }
}


text:
// -*- C++ -*-

#ifndef _RWSTD_CMATH_H_INCLUDED
#define _RWSTD_CMATH_H_INCLUDED

#include <rw/_defs.h>

_RWSTD_NAMESPACE (std) {

#ifndef HUGE_VAL
#  define HUGE_VAL _RWSTD_DBL_MAX
#endif   // HUGE_VAL

extern "C" {

double acos (double);
double asin (double);
double atan (double);
double atan2(double, double);
double cos (double);
double sin (double);
double tan (double);
double cosh (double);
double sinh (double);
double tanh (double);
double exp (double);
double frexp (double, int *);
double ldexp (double, int);
double log (double);
double log10 (double);
double modf (double, double*);
double pow (double, double);
double sqrt (double);
double ceil (double);
double fabs (double);
double floor (double);
double fmod (double, double);

}

}   // namespace std

#endif   // _RWSTD_CMATH_H_INCLUDED


text:
#ifndef ThreadableLoaderClientWrapper_h
#define ThreadableLoaderClientWrapper_h

#include "core/loader/ThreadableLoaderClient.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassRefPtr.h"
#include "wtf/ThreadSafeRefCounted.h"
#include "wtf/Threading.h"

namespace blink {

class ThreadableLoaderClientWrapper : public ThreadSafeRefCounted<ThreadableLoaderClientWrapper> {
public:
    class ResourceTimingClient {
    public:
        virtual void didReceiveResourceTiming(const ResourceTimingInfo&) = 0;
    };

    static PassRefPtr<ThreadableLoaderClientWrapper> create(ThreadableLoaderClient* client)
    {
        return adoptRef(new ThreadableLoaderClientWrapper(client));
    }

    void clearClient()
    {
        m_done = true;
        m_client = 0;
        clearResourceTimingClient();
    }

    bool done() const
    {
        return m_done;
    }

    void setResourceTimingClient(ResourceTimingClient* client)
    {
        m_resourceTimingClient = client;
    }

    void clearResourceTimingClient()
    {
        m_resourceTimingClient = nullptr;
    }

    void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
    {
        if (m_client)
            m_client->didSendData(bytesSent, totalBytesToBeSent);
    }

    void didReceiveResponse(unsigned long identifier, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
    {
        if (m_client)
            m_client->didReceiveResponse(identifier, response, handle);
    }

    void didReceiveData(const char* data, unsigned dataLength)
    {
        if (m_client)
            m_client->didReceiveData(data, dataLength);
    }

    void didReceiveCachedMetadata(const char* data, int dataLength)
    {
        if (m_client)
            m_client->didReceiveCachedMetadata(data, dataLength);
    }

    void didFinishLoading(unsigned long identifier, double finishTime)
    {
        m_done = true;
        if (m_client)
            m_client->didFinishLoading(identifier, finishTime);
    }

    void didFail(const ResourceError& error)
    {
        m_done = true;
        if (m_client)
            m_client->didFail(error);
    }

    void didFailAccessControlCheck(const ResourceError& error)
    {
        // Let the client first handle the failure by possibly issuing
        // a didFail() with a cancellation error before marking this
        // wrapper as 'done'.
        if (m_client)
            m_client->didFailAccessControlCheck(error);
        m_done = true;
    }

    void didFailRedirectCheck()
    {
        if (m_client)
            m_client->didFailRedirectCheck();
        m_done = true;
    }

    void didReceiveAuthenticationCancellation(unsigned long identifier, const ResourceResponse& response)
    {
        if (m_client)
            m_client->didReceiveResponse(identifier, response, nullptr);
    }

    void didDownloadData(int dataLength)
    {
        if (m_client)
            m_client->didDownloadData(dataLength);
    }

    void didReceiveResourceTiming(const ResourceTimingInfo& info)
    {
        if (m_resourceTimingClient)
            m_resourceTimingClient->didReceiveResourceTiming(info);
    }

protected:
    explicit ThreadableLoaderClientWrapper(ThreadableLoaderClient* client)
        : m_client(client)
        , m_resourceTimingClient(nullptr)
        , m_done(false)
    {
    }

    ThreadableLoaderClient* m_client;
    ResourceTimingClient* m_resourceTimingClient;
    bool m_done;
};

} // namespace blink

#endif // ThreadableLoaderClientWrapper_h


text:
- Azure Resource Manager Billing client library for Java. This package contains Microsoft Azure SDK for Billing Management SDK. Billing client provides access to billing resources for Azure subscriptions. Package tag package-2020-05. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt).

### Breaking Changes

#### `models.Instruction` was modified

* `java.lang.Float amount()` -> `float amount()`

### Features Added

#### `models.ProductsListResult` was modified

* `totalCount()` was added

#### `models.TransactionListResult` was modified

* `totalCount()` was added

#### `models.BillingSubscription` was modified

* `suspensionReasons()` was added

#### `BillingManager$Configurable` was modified

* `withScope(java.lang.String)` was added

#### `models.InvoiceSection` was modified

* `tags()` was added

## 1.0.0-beta.1 (2021-04-13)

- Azure Resource Manager Billing client library for Java. This package contains Microsoft Azure SDK for Billing Management SDK. Billing client provides access to billing resources for Azure subscriptions. Package tag package-2020-05. For documentation on how to use this package, please see [Azure Management Libraries for Java](https://aka.ms/azsdk/java/mgmt).


text:
<?php

namespace Twilio\Options;

use Zend\Stdlib\AbstractOptions;

/**
 * Class ModuleOptions
 *
 * @package Twilio\Options
 */
class ModuleOptions extends AbstractOptions
{
    /**
     * @var string
     */
    protected $sid = '';

    /**
     * @var string
     */
    protected $token = '';

    /**
     * @return string
     */
    public function getSid()
    {
        return $this->sid;
    }

    /**
     * @param string $sid
     */
    public function setSid($sid = '')
    {
        $this->sid = $sid;
    }

    /**
     * @return string
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * @param string $token
     */
    public function setToken($token = '')
    {
        $this->token = $token;
    }

}


text:
class AddImgUrlToCharacter < ActiveRecord::Migration[5.1]
  def change
    add_column :characters, :img_src, :string
  end
end


text:
package org.jclouds.ec2.compute;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;
import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;
import static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTagsFromValuesOfEmptyString;
import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsValuesOfEmptyString;
import static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_GENERATE_INSTANCE_NAMES;
import static org.jclouds.ec2.util.Tags.resourceToTagsAsMap;
import static org.jclouds.util.Predicates2.retry;

import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableMultimap.Builder;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.inject.Inject;
import org.jclouds.Constants;
import org.jclouds.aws.util.AWSUtils;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.callables.RunScriptOnNode;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.extensions.SecurityGroupExtension;
import org.jclouds.compute.functions.GroupNamingConvention;
import org.jclouds.compute.functions.GroupNamingConvention.Factory;
import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.compute.internal.PersistNodeCredentials;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetImageStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import org.jclouds.ec2.EC2Api;
import org.jclouds.ec2.compute.domain.RegionAndName;
import org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;
import org.jclouds.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.ec2.domain.InstanceState;
import org.jclouds.ec2.domain.KeyPair;
import org.jclouds.ec2.domain.RunningInstance;
import org.jclouds.ec2.domain.Tag;
import org.jclouds.ec2.util.TagFilterBuilder;
import org.jclouds.scriptbuilder.functions.InitAdminAccess;
import org.jclouds.util.Strings2;

@Singleton
public class EC2ComputeService extends BaseComputeService {
   private final EC2Api client;
   private final ConcurrentMap<RegionAndName, KeyPair> credentialsMap;
   private final LoadingCache<RegionAndName, String> securityGroupMap;
   private final Factory namingConvention;
   private final boolean generateInstanceNames;
   private final Timeouts timeouts;

   @Inject
   protected EC2ComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,
            @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,
            @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
            GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,
            CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,
            DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy startNodeStrategy,
            SuspendNodeStrategy stopNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,
            @Named("DEFAULT") Provider<TemplateOptions> templateOptionsProvider,
            @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,
            @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,
            @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,
            InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory,
            RunScriptOnNode.Factory runScriptOnNodeFactory, InitAdminAccess initAdminAccess,
            PersistNodeCredentials persistNodeCredentials, Timeouts timeouts,
            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, EC2Api client,
            ConcurrentMap<RegionAndName, KeyPair> credentialsMap,
            @Named("SECURITY") LoadingCache<RegionAndName, String> securityGroupMap,
            Optional<ImageExtension> imageExtension, GroupNamingConvention.Factory namingConvention,
            @Named(PROPERTY_EC2_GENERATE_INSTANCE_NAMES) boolean generateInstanceNames,
            Optional<SecurityGroupExtension> securityGroupExtension) {
      super(context, credentialStore, images, sizes, locations, listNodesStrategy, getImageStrategy,
               getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,
               startNodeStrategy, stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,
               nodeTerminated, nodeSuspended, initScriptRunnerFactory, initAdminAccess, runScriptOnNodeFactory,
               persistNodeCredentials, timeouts, userExecutor, imageExtension, securityGroupExtension);
      this.client = client;
      this.credentialsMap = credentialsMap;
      this.securityGroupMap = securityGroupMap;
      this.namingConvention = namingConvention;
      this.generateInstanceNames = generateInstanceNames;
      this.timeouts = timeouts;
   }

   @Override
   public Set<? extends NodeMetadata> createNodesInGroup(String group, int count, final Template template)
            throws RunNodesException {
      Set<? extends NodeMetadata> nodes = super.createNodesInGroup(group, count, template);
      String region = AWSUtils.getRegionFromLocationOrNull(template.getLocation());

      if (client.getTagApiForRegion(region).isPresent()) {
         Map<String, String> common = metadataAndTagsAsValuesOfEmptyString(template.getOptions());
         if (generateInstanceNames || !common.isEmpty() || !template.getOptions().getNodeNames().isEmpty()) {
            return addTagsAndNamesToInstancesInRegion(common, template.getOptions().getNodeNames(),
                    nodes, region, group);
         }
      }
      return nodes;
   }

   private static final Function<NodeMetadata, String> instanceId = new Function<NodeMetadata, String>() {
      @Override
      public String apply(NodeMetadata in) {
         return in.getProviderId();
      }
   };

   private Set<NodeMetadata> addTagsAndNamesToInstancesInRegion(Map<String, String> common, Set<String> nodeNames,
                                                                Set<? extends NodeMetadata> input, String region,
                                                                String group) {
      Map<String, ? extends NodeMetadata> instancesById = Maps.uniqueIndex(input, instanceId);
      ImmutableSet.Builder<NodeMetadata> builder = ImmutableSet.<NodeMetadata> builder();

      List<String> namesToUse = newArrayList(nodeNames);
      if (generateInstanceNames && !common.containsKey("Name")) {
         for (Map.Entry<String, ? extends NodeMetadata> entry : instancesById.entrySet()) {
            String id = entry.getKey();
            String name;
            if (!namesToUse.isEmpty()) {
               name = namesToUse.remove(0);
            } else {
               name = id.replaceAll(".*-", group + "-");
            }
            Map<String, String> tags = ImmutableMap.<String, String> builder().putAll(common)
                  .put("Name", name).build();
            logger.debug(">> applying tags %s to instance %s in region %s", tags, id, region);
            client.getTagApiForRegion(region).get().applyToResources(tags, ImmutableSet.of(id));
            builder.add(addTagsForInstance(tags, instancesById.get(id)));
         }
      } else {
         Iterable<String> ids = instancesById.keySet();
         logger.debug(">> applying tags %s to instances %s in region %s", common, ids, region);
         client.getTagApiForRegion(region).get().applyToResources(common, ids);
         for (NodeMetadata in : input)
            builder.add(addTagsForInstance(common, in));
      }
      if (logger.isDebugEnabled()) {
         Multimap<String, String> filter = new TagFilterBuilder().resourceIds(instancesById.keySet()).build();
         FluentIterable<Tag> tags = client.getTagApiForRegion(region).get().filter(filter);
         logger.debug("<< applied tags in region %s: %s", region, resourceToTagsAsMap(tags));
      }
      return builder.build();
   }

   private static NodeMetadata addTagsForInstance(Map<String, String> tags, NodeMetadata input) {
      NodeMetadataBuilder builder = NodeMetadataBuilder.fromNodeMetadata(input).name(tags.get("Name"));
      return addMetadataAndParseTagsFromValuesOfEmptyString(builder, tags).build();
   }

   @Inject(optional = true)
   @Named(RESOURCENAME_DELIMITER)
   char delimiter = '#';

   /**
    * @throws IllegalStateException If the security group was in use
    */
   @VisibleForTesting
   void deleteSecurityGroup(String region, String group) {
      checkNotNull(emptyToNull(region), "region must be defined");
      checkNotNull(emptyToNull(group), "group must be defined");
      String groupName = namingConvention.create().sharedNameForGroup(group);

      if (!client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupName).isEmpty()) {
         logger.debug(">> deleting securityGroup(%s)", groupName);
         client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(region, groupName);
         // TODO: test this clear happens
         securityGroupMap.invalidate(new RegionNameAndIngressRules(region, groupName, null, false));
         logger.debug("<< deleted securityGroup(%s)", groupName);
      }
   }

   @VisibleForTesting
   void deleteKeyPair(String region, String group) {
      for (KeyPair keyPair : client.getKeyPairApi().get().describeKeyPairsInRegionWithFilter(region,
              ImmutableMultimap.<String, String>builder()
                      .put("key-name", Strings2.urlEncode(
                              String.format("jclouds#%s#*", group).replace('#', delimiter)))
                      .build())) {
         String keyName = keyPair.getKeyName();
         Predicate<String> keyNameMatcher = namingConvention.create().containsGroup(group);
         String oldKeyNameRegex = String.format("jclouds#%s#%s#%s", group, region, "[0-9a-f]+").replace('#', delimiter);
         // old keypair pattern too verbose as it has an unnecessary region qualifier

         if (keyNameMatcher.apply(keyName) || keyName.matches(oldKeyNameRegex)) {
            Set<String> instancesUsingKeyPair = extractIdsFromInstances(concat(client.getInstanceApi().get()
                  .describeInstancesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder()
                          .put("instance-state-name", InstanceState.TERMINATED.toString())
                          .put("instance-state-name", InstanceState.SHUTTING_DOWN.toString())
                          .put("key-name", keyPair.getKeyName()).build())));

            if (!instancesUsingKeyPair.isEmpty()) {
               logger.debug("<< inUse keyPair(%s), by (%s)", keyPair.getKeyName(), instancesUsingKeyPair);
            } else {
               logger.debug(">> deleting keyPair(%s)", keyPair.getKeyName());
               client.getKeyPairApi().get().deleteKeyPairInRegion(region, keyPair.getKeyName());
               // TODO: test this clear happens
               credentialsMap.remove(new RegionAndName(region, keyPair.getKeyName()));
               credentialsMap.remove(new RegionAndName(region, group));
               logger.debug("<< deleted keyPair(%s)", keyPair.getKeyName());
            }
         }
      }
   }

   protected ImmutableSet<String> extractIdsFromInstances(Iterable<? extends RunningInstance> deadOnes) {
      return ImmutableSet.copyOf(transform(deadOnes, new Function<RunningInstance, String>() {

         @Override
         public String apply(RunningInstance input) {
            return input.getId();
         }

      }));
   }

   /**
    * Cleans implicit keypairs and security groups.
    */
   @Override
   protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {
      Builder<String, String> regionGroups = ImmutableMultimap.builder();
      for (NodeMetadata nodeMetadata : deadNodes) {
         if (nodeMetadata.getGroup() != null)
            regionGroups.put(AWSUtils.parseHandle(nodeMetadata.getId())[0], nodeMetadata.getGroup());
         }
      for (Entry<String, String> regionGroup : regionGroups.build().entries()) {
         cleanUpIncidentalResources(regionGroup.getKey(), regionGroup.getValue());
      }
   }

   protected void cleanUpIncidentalResources(final String region, final String group) {
      // For issue #445, tries to delete security groups first: ec2 throws exception if in use, but
      // deleting a key pair does not.
      // This is "belt-and-braces" because deleteKeyPair also does extractIdsFromInstances & usingKeyPairAndNotDead
      // for us to check if any instances are using the key-pair before we delete it.
      // There is (probably?) still a race if someone is creating instances at the same time as deleting them:
      // we may delete the key-pair just when the node-being-created was about to rely on the incidental
      // resources existing.

      // Also in #445, in aws-ec2 the deleteSecurityGroup sometimes fails after terminating the final VM using a
      // given security group, if called very soon after the VM's state reports terminated. Empirically, it seems that
      // waiting a small time (e.g. enabling logging or debugging!) then the tests pass. We therefore retry.
      // TODO: this could be moved to a config module, also the narrative above made more concise
      long timeout = timeouts.cleanupIncidentalResources;
      retry(new Predicate<RegionAndName>() {
         public boolean apply(RegionAndName input) {
            try {
               logger.debug(">> deleting incidentalResources(%s)", input);
               deleteSecurityGroup(input.getRegion(), input.getName());
               deleteKeyPair(input.getRegion(), input.getName()); // not executed if securityGroup was in use
               logger.debug("<< deleted incidentalResources(%s)", input);
               return true;
            } catch (IllegalStateException e) {
               logger.debug("<< inUse incidentalResources(%s)", input);
               return false;
            }
         }
      }, timeout, 50, 1000, MILLISECONDS).apply(new RegionAndName(region, group));
   }

   /**
    * returns template options, except of type {@link EC2TemplateOptions}.
    */
   @Override
   public EC2TemplateOptions templateOptions() {
      return EC2TemplateOptions.class.cast(super.templateOptions());
   }

}


text:
require 'spec_helper'

describe Marli::ApplicationDetails do
  include Marli::ApplicationDetails

  let(:purpose) { 'my_purpose' }
  before { create(:application_detail, purpose: purpose)}

  describe '#detail_by_purpose' do
    subject { detail_by_purpose(purpose) }
    it { is_expected.to be_a ApplicationDetail }
  end

  describe '#get_sanitized_detail' do
    subject { get_sanitized_detail(purpose) }
    it { is_expected.to eql "You have already submitted your information" }
  end

  describe '#text_exists?' do
    subject { text_exists?(purpose) }
    it { is_expected.to be true }
  end

end


text:
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "opentelemetry/common/macros.h"
#include "opentelemetry/sdk/common/atomic_shared_ptr.h"
#include "opentelemetry/sdk/instrumentationscope/instrumentation_scope.h"
#include "opentelemetry/sdk/resource/resource.h"
#include "opentelemetry/sdk/trace/processor.h"
#include "opentelemetry/sdk/trace/samplers/always_on.h"
#include "opentelemetry/sdk/trace/tracer_context.h"
#include "opentelemetry/trace/noop.h"
#include "opentelemetry/trace/tracer.h"
#include "opentelemetry/version.h"

#include <memory>

OPENTELEMETRY_BEGIN_NAMESPACE
namespace sdk
{
namespace trace
{

using namespace opentelemetry::sdk::instrumentationscope;

class Tracer final : public trace_api::Tracer, public std::enable_shared_from_this<Tracer>
{
public:
  /** Construct a new Tracer with the given context pipeline. */
  explicit Tracer(std::shared_ptr<sdk::trace::TracerContext> context,
                  std::unique_ptr<InstrumentationScope> instrumentation_scope =
                      InstrumentationScope::Create("")) noexcept;

  nostd::shared_ptr<trace_api::Span> StartSpan(
      nostd::string_view name,
      const opentelemetry::common::KeyValueIterable &attributes,
      const trace_api::SpanContextKeyValueIterable &links,
      const trace_api::StartSpanOptions &options = {}) noexcept override;

  void ForceFlushWithMicroseconds(uint64_t timeout) noexcept override;

  void CloseWithMicroseconds(uint64_t timeout) noexcept override;

  /** Returns the configured span processor. */
  SpanProcessor &GetProcessor() noexcept { return context_->GetProcessor(); }

  /** Returns the configured Id generator */
  IdGenerator &GetIdGenerator() const noexcept { return context_->GetIdGenerator(); }

  /** Returns the associated instrumentation scope */
  const InstrumentationScope &GetInstrumentationScope() const noexcept
  {
    return *instrumentation_scope_;
  }

  OPENTELEMETRY_DEPRECATED_MESSAGE("Please use GetInstrumentationScope instead")
  const InstrumentationScope &GetInstrumentationLibrary() const noexcept
  {
    return GetInstrumentationScope();
  }

  /** Returns the currently configured resource **/
  const opentelemetry::sdk::resource::Resource &GetResource() { return context_->GetResource(); }

  // Note: Test only
  Sampler &GetSampler() { return context_->GetSampler(); }

private:
  // order of declaration is important here - instrumentation scope should destroy after
  // tracer-context.
  std::shared_ptr<InstrumentationScope> instrumentation_scope_;
  std::shared_ptr<sdk::trace::TracerContext> context_;
};
}  // namespace trace
}  // namespace sdk
OPENTELEMETRY_END_NAMESPACE


text:
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gx.Rs.Api.Util;
using Gx.Links;

namespace Gx.Rs.Api
{
    /// <summary>
    /// The AncestryResultsState exposes management functions for ancestry results.
    /// </summary>
    public class AncestryResultsState : GedcomxApplicationState<Gedcomx>
    {
        internal AncestryResultsState(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, StateFactory stateFactory)
            : base(request, response, client, accessToken, stateFactory)
        {
        }

        /// <summary>
        /// Clones the current state instance.
        /// </summary>
        /// <param name="request">The REST API request used to create this state instance.</param>
        /// <param name="response">The REST API response used to create this state instance.</param>
        /// <param name="client">The REST API client used to create this state instance.</param>
        /// <returns>A cloned instance of the current state instance.</returns>
        protected override GedcomxApplicationState Clone(IRestRequest request, IRestResponse response, IFilterableRestClient client)
        {
            return new AncestryResultsState(request, response, client, this.CurrentAccessToken, this.stateFactory);
        }

        /// <summary>
        /// Gets the rel name for the current state instance. This is expected to be overridden.
        /// </summary>
        /// <value>
        /// The rel name for the current state instance
        /// </value>
        public override String SelfRel
        {
            get
            {
                return Rel.ANCESTRY;
            }
        }

        /// <summary>
        /// Gets the tree represented by the REST API response.
        /// </summary>
        /// <value>
        /// The tree represented by the REST API response.
        /// </value>
        public AncestryTree Tree
        {
            get
            {
                return Entity != null ? new AncestryTree(Entity) : null;
            }
        }

        /// <summary>
        /// Reads the person at the specified one-based index number.
        /// </summary>
        /// <param name="ancestorNumber">The ancestor number of the person to read.</param>
        /// <param name="options">The options to apply before executing the REST API call.</param>
        /// <returns>
        /// A <see cref="PersonState"/> instance containing the REST API response.
        /// </returns>
        public PersonState ReadPerson(int ancestorNumber, params IStateTransitionOption[] options)
        {
            AncestryTree.AncestryNode ancestor = Tree.GetAncestor(ancestorNumber);
            if (ancestor == null)
            {
                return null;
            }

            Link selfLink = ancestor.Person.GetLink(Rel.PERSON);
            if (selfLink == null || selfLink.Href == null)
            {
                selfLink = ancestor.Person.GetLink(Rel.SELF);
            }

            String personUri = selfLink == null || selfLink.Href == null ? null : selfLink.Href;
            if (personUri == null)
            {
                return null;
            }

            IRestRequest request = CreateAuthenticatedGedcomxRequest().Build(personUri, Method.GET);
            return this.stateFactory.NewPersonState(request, Invoke(request, options), this.Client, this.CurrentAccessToken);
        }
    }
}


text:
package com.ponkotuy.run

import java.io.{BufferedReader, InputStreamReader}

import pl.project13.scala.rainbow._
import skinny.http.HTTP

import scala.util.{Failure, Success, Try}

/**
 *
 * @author ponkotuy
 * Date: 15/03/03.
 */
object Tester extends App {
  val Host = args.headOption.getOrElse("http://localhost:9000")
  val urlFile = getClass.getResource("/urls")
  val br = new BufferedReader(new InputStreamReader(urlFile.openStream()))
  Iterator.continually(br.readLine()).takeWhile(_ != null).foreach { line =>
    val url = Host + line
    Try {
      HTTP.get(url).status
    } match {
      case Success(200) => println(s"Success: $url".green)
      case Success(status) if 300 <= status && status < 400 => println(s"Redirect ${status}: $url".green)
      case Success(status) => println(s"Bad status $status: $url".red)
      case Failure(e) => println(s"Error ${e.getMessage}: $url".red)
    }
  }
}


text:
set(_ANDROID_ABI_CLANG_TARGET "aarch64-none-linux-android")

# Suppress -Wl,-z,nocopyreloc flag on arm64-v8a
set(_ANDROID_ABI_INIT_EXE_LDFLAGS_NO_nocopyreloc 1)

include(Platform/Android/abi-common-Clang)


text:
# Enforce spacing around the * in generator functions (generator-star-spacing)

Generators are a new type of function in ECMAScript 6 that can return multiple values over time.
These special functions are indicated by placing an `*` after the `function` keyword.

Here is an example of a generator function:

```js
/*eslint-env es6*/

function* generator() {
    yield "44";
    yield "55";
}
```

This is also valid:

```js
/*eslint-env es6*/

function *generator() {
    yield "44";
    yield "55";
}
```

This is valid as well:

```js
/*eslint-env es6*/

function * generator() {
    yield "44";
    yield "55";
}
```

To keep a sense of consistency when using generators this rule enforces a single position for the `*`.

**Fixable:** This rule is automatically fixable using the `--fix` flag on the command line.

## Rule Details

This rule aims to enforce spacing around the `*` of generator functions.

The rule takes one option, an object, which has two keys `before` and `after` having boolean values `true` or `false`.

* `before` enforces spacing between the `*` and the `function` keyword.
  If it is `true`, a space is required, otherwise spaces are disallowed.

  In object literal shorthand methods, spacing before the `*` is not checked, as they lack a `function` keyword.

* `after` enforces spacing between the `*` and the function name.
  If it is `true`, a space is required, otherwise spaces are disallowed.

  In anonymous function expressions, spacing between the `*` and the opening parenthesis is not checked. This is checked by the [space-before-function-paren](space-before-function-paren.md) rule.

The default is `{"before": true, "after": false}`.

```json
"generator-star-spacing": [2, {"before": false, "after": true}]
```

And the option has shorthand as a string keyword:

* `{"before": true, "after": false}` → `"before"`
* `{"before": false, "after": true}` → `"after"`
* `{"before": true, "after": true}` → `"both"`
* `{"before": false, "after": false}` → `"neither"`

```json
"generator-star-spacing": [2, "after"]
```

When using `{"before": true, "after": false}` this placement will be enforced:

```js
/*eslint generator-star-spacing: [2, {"before": true, "after": false}]*/
/*eslint-env es6*/

function *generator() {}

var anonymous = function *() {};

var shorthand = { *generator() {} };
```

When using `{"before": false, "after": true}` this placement will be enforced:

```js
/*eslint generator-star-spacing: [2, {"before": false, "after": true}]*/
/*eslint-env es6*/

function* generator() {}

var anonymous = function*() {};

var shorthand = { * generator() {} };
```

When using `{"before": true, "after": true}` this placement will be enforced:

```js
/*eslint generator-star-spacing: [2, {"before": true, "after": true}]*/
/*eslint-env es6*/

function * generator() {}

var anonymous = function *() {};

var shorthand = { * generator() {} };
```

When using `{"before": false, "after": false}` this placement will be enforced:

```js
/*eslint generator-star-spacing: [2, {"before": false, "after": false}]*/
/*eslint-env es6*/

function*generator() {}

var anonymous = function*() {};

var shorthand = { *generator() {} };
```

To use this rule you must set the `generators` flag to `true` in the `ecmaFeatures` configuration object.

## When Not To Use It

If your project will not be using generators or you are not concerned with spacing consistency, you do not need this rule.

## Further Reading

* [Understanding ES6: Generators](https://leanpub.com/understandinges6/read/#leanpub-auto-generators)


text:
<?php

namespace Dudulina\Aggregate;

class AggregateDescriptor
{

    private $aggregateId;
    /**
     * @var string
     */
    private $aggregateClass;

    public function __construct(
        $aggregateId,
        string $aggregateClass
    )
    {
        $this->aggregateId = $aggregateId;
        $this->aggregateClass = $aggregateClass;
    }

    public function getAggregateId()
    {
        return $this->aggregateId;
    }

    public function getAggregateClass(): string
    {
        return $this->aggregateClass;
    }
}


text:
void gamepadtest()
{
}


text:
using System;
using FluentMethods;

public static partial class Extensions
{
    /// <summary>
    /// Returns an specified array which represents a subset of the elements in the source array.
    /// </summary>
    /// <typeparam name="T">The array element type.</typeparam>
    /// <param name="sourceArray">The source array to be sliced.</param>
    /// <param name="startIndex">A 32-bit integer that represents the index in the <paramref name="sourceArray"/> at which slicing begins.</param>
    /// <param name="length">A 32-bit integer that represents the number of elements to slice.</param>
    /// <returns>An specified array which represents a subset of the elements in the source array.</returns>
    /// <exception cref="ArgumentNullException">The <paramref name="sourceArray"/> is <see langword="null"/></exception>
    /// <exception cref="ArgumentOutOfRangeException">
    ///     <paramref name="startIndex"/> is less than the lower bound of the first dimension of sourceArray.
    /// </exception>
    /// <exception cref="ArgumentOutOfRangeException">
    ///     <paramref name="length"/> is less than zero.
    /// </exception>
    /// <exception cref="ArgumentException">
    ///     <paramref name="startIndex"/> and <paramref name="length"/> do not denote a valid range of elements in the <paramref name="sourceArray"/>.
    /// </exception>
    public static T[] Slice<T>(this T[] sourceArray, int startIndex, int length)
    {
        if (sourceArray == null)
        {
            throw new ArgumentNullException(nameof(sourceArray));
        }
        if (startIndex < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(startIndex));
        }
        if (length < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(length));
        }
        if (startIndex + length > sourceArray.Length)
        {
            throw new ArgumentException(Strings.ArgumentOutOfRange_ArraySlice);
        }
        var copyArray = new T[length];
        Array.Copy(sourceArray, startIndex, copyArray, 0, length);
        return copyArray;
    }
}


text:
import { Connectable, Statable } from '../interfaces';

export type OscillatorCustomType = {
  real: Float32Array,
  imag: Float32Array
};

export type OscillatorParams = {
  state?: boolean,
  type?: OscillatorType | OscillatorCustomType,
  octave?: number,
  fine?: number,
  volume?: number
};

/**
 * This private class is entity for oscillator.
 * @constructor
 * @implements {Connectable}
 * @implements {Statable}
 */
export class Oscillator implements Connectable, Statable {
  // 1 Octave = 1200 cent
  public static readonly OCTAVE = 1200 as const;

  private context: AudioContext;
  private source: OscillatorNode;
  private volume: GainNode;

  private octave = 0;
  private fine = 0;
  private custom: OscillatorCustomType = {
    real: new Float32Array([0, 1]),
    imag: new Float32Array([0, 1])
  };

  private isActive: boolean;

  // in order to not call in duplicate `start` or `stop`  method in instance of `OscillatorNode`
  private paused = true;

  /**
   * @param {AudioContext} context This argument is in order to use Web Audio API.
   * @param {boolean} state This argument is initial state.
   */
  constructor(context: AudioContext, state: boolean) {
    this.context = context;
    this.source  = context.createOscillator();
    this.volume  = context.createGain();

    this.isActive = state;
  }

  /**
   * This method connects `AudioNode`s.
   * @param {AudioNode} output This argument is instance of `AudioNode` as output.
   */
  public ready(output: AudioNode): void {
    if (!this.isActive) {
      return;
    }

    // Store parameters
    const type      = this.source.type;
    const frequency = this.source.frequency.value;
    const detune    = this.source.detune.value;

    if (!this.paused) {
      this.source.stop(this.context.currentTime);
      this.source.disconnect(0);
    }

    this.source = this.context.createOscillator();

    if (type === 'custom') {
      // Custom wave
      const reals        = this.custom.real;
      const imags        = this.custom.imag;
      const periodicWave = this.context.createPeriodicWave(reals, imags);

      this.source.setPeriodicWave(periodicWave);
    } else {
      this.source.type = type;
    }

    this.source.frequency.value = frequency;
    this.source.detune.value    = detune;

    this.volume.connect(output);
  }

  /**
   * This method starts sound.
   * @param {number} startTime This argument is start time.
   */
  public start(startTime?: number): void {
    if (this.isActive) {
      this.source.start(startTime ?? this.context.currentTime);
      this.paused = false;
    } else {
      if (!this.paused) {
        this.source.stop(this.context.currentTime);
        this.paused = true;
      }

      this.source.disconnect(0);
    }
  }

  /**
   * This method stops sound.
   * @param {number} stopTime This argument is stop time.
   */
  public stop(stopTime?: number): void {
    if (this.paused) {
      return;
    }

    this.source.stop(stopTime ?? this.context.currentTime);
    this.source.disconnect(0);

    this.paused = true;
  }

  /**
   * This method gets or sets parameters for oscillator.
   * @param {keyof OscillatorParams|OscillatorParams} params This argument is string if getter. Otherwise, setter.
   * @return {OscillatorParams[keyof OscillatorParams]} Return value is parameter for oscillator if getter.
   *     Otherwise, return value is for method chain.
   */
  public param(params: 'state'): boolean;
  public param(params: 'type'): OscillatorType | OscillatorCustomType;
  public param(params: 'octave'): number;
  public param(params: 'fine'): number;
  public param(params: 'volume'): number;
  public param(params: OscillatorParams): Oscillator;
  public param(params: keyof OscillatorParams | OscillatorParams): OscillatorParams[keyof OscillatorParams] | Oscillator {
    if (typeof params === 'string') {
      switch (params) {
        case 'state':
          return this.isActive;
        case 'type':
          return this.source.type;
        case 'octave':
          return this.octave;
        case 'fine':
          return this.fine;
        case 'volume':
          return this.volume.gain.value;
        default:
          return this;
      }
    }

    for (const [key, value] of Object.entries(params)) {
      switch (key) {
        case 'state':
          if (typeof value === 'boolean') {
            this.isActive = value;
          }

          break;
        case 'type':
          if (typeof value === 'string') {
            this.source.type = value;
          } else if (typeof value === 'object') {
            let { real, imag } = value;

            const MAX_SIZE = 4096;  // This size is defined by specification

            if (real.length > MAX_SIZE) { real = real.subarray(0, MAX_SIZE); }
            if (imag.length > MAX_SIZE) { imag = imag.subarray(0, MAX_SIZE); }

            // The 1st value is fixed by 0 (This is is defined by specification)
            if (real[0] !== 0) { real[0] = 0; }
            if (imag[0] !== 0) { imag[0] = 0; }

            const periodicWave = this.context.createPeriodicWave(real, imag);

            this.source.setPeriodicWave(periodicWave);

            this.custom.real = real;
            this.custom.imag = imag;
          }

          break;
        case 'octave':
          if (typeof value === 'number') {
            this.octave = value;
            this.source.detune.value = this.fine + (value * Oscillator.OCTAVE);
          }

          break;
        case 'fine':
          if (typeof value === 'number') {
            this.fine = value;
            this.source.detune.value = value + (this.octave * Oscillator.OCTAVE);
          }

          break;
        case 'volume':
          if (typeof value === 'number') {
            this.volume.gain.value = value;
          }

          break;
        default:
          break;
      }
    }

    return this;
  }

  /**
   * This method gets instance of `OscillatorNode`.
   * @return {OscillatorNode}
   */
  public get(): OscillatorNode {
    return this.source;
  }

  /** @override */
  public state(): boolean {
    return this.isActive;
  }

  /** @override */
  public activate(): Oscillator {
    this.isActive = true;
    return this;
  }

  /** @override */
  public deactivate(): Oscillator {
    this.isActive = false;
    return this;
  }

  /**
   * This method gets oscillator parameters as associative array.
   * @return {OscillatorParams}
   */
  public params(): Required<OscillatorParams> {
    return {
      state : this.isActive,
      type  : this.source.type,
      octave: this.octave,
      fine  : this.fine,
      volume: this.volume.gain.value
    };
  }

  /** @override */
  public get INPUT(): OscillatorNode {
    return this.source;
  }

  /** @override */
  public get OUTPUT(): GainNode {
    return this.volume;
  }
}