text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Ansible on Sandors Systems Scribbles</title>
    <link>https://theargo.io/tags/ansible/</link>
    <description>Recent content in Ansible on Sandors Systems Scribbles</description>
    <generator>Hugo -- gohugo.io</generator>
    <copyright>&copy; 2017. All rights reserved.</copyright>
    <lastBuildDate>Wed, 08 Jul 2015 00:00:00 +0000</lastBuildDate>

	<atom:link href="https://theargo.io/tags/ansible/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Configure new servers with the basics via Ansible</title>
      <link>https://theargo.io/post/configure_new_servers_with_the_basics_via_ansible/</link>
      <pubDate>Wed, 08 Jul 2015 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/configure_new_servers_with_the_basics_via_ansible/</guid>
      <description>The Problem: You have a throw away server that you only need for the next couple of hours to try something out. You need the server configured so that you can login and get to work without messing with yum updates or adding your user and public ssh keys to access it.
The solution: This Ansible playbook that is simple and to the point. It updates yum or apt, applies a sane sshd config, adds users and groups and then gets your public ssh key onto the throwaway box so you can login without a password.</description>
    </item>

    <item>
      <title>MacBook Setup Using Ansible and Homebrew</title>
      <link>https://theargo.io/post/macbook_setup_using_ansible_and_homebrew/</link>
      <pubDate>Mon, 18 May 2015 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/macbook_setup_using_ansible_and_homebrew/</guid>
      <description>The Problem: You have a brand new fresh install of OSX on your MacBook and you need to get up and running. You want all your apps installed using Homebrew &amp; Cask and OSX setup with goodies like zsh and .dotfiles.
The solution: Use Ansible to deploy CLI apps via Homebrew and GUI Apps via Cask. Then have Ansible setup the shell with zsh and .dotfiles that are pulled from a GitHub repo.</description>
    </item>

    <item>
      <title>Ansible on HP-UX 11.31</title>
      <link>https://theargo.io/post/ansible_on_hp_ux_11_dot_31/</link>
      <pubDate>Wed, 03 Sep 2014 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/ansible_on_hp_ux_11_dot_31/</guid>
      <description> The problem Old corporations that are running ancient OS&rsquo;es desperately need configuration management and automation to keep the dinosaurs efficient.
The goal Install Python on HP-UX so Ansible can manage and automate the ancient servers.
HowTo sandor@pineapplez:$ ansible -i hosts all -m raw -a &quot;swinstall -x mount_all_filesystems=false -s depotserver:/depot/11.31/python python&quot;  </description>
    </item>

    <item>
      <title>Run Ansible through pmksh</title>
      <link>https://theargo.io/post/run_ansible_through_pmksh/</link>
      <pubDate>Wed, 03 Sep 2014 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/run_ansible_through_pmksh/</guid>
      <description>The problem Old corporations use shitty old software to do things that modern Linux is really good at doing itself. Using pmksh instead of a well laid out sudoers setup is what the problem is.
The goal Configure Ansible playbooks to execute through the pmksh shell on the targeted servers.
Shells &amp; Ansible Currently Ansible &amp; Python work together to take the output from bash and report back with formatting.</description>
    </item>

    <item>
      <title>Using Ansible to Align Passwords on Servers</title>
      <link>https://theargo.io/post/using_ansible_to_align_passwords_on_servers/</link>
      <pubDate>Thu, 17 Jul 2014 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/using_ansible_to_align_passwords_on_servers/</guid>
      <description>The Problem: A group of servers get their passwords updated every 3 months with a new shared password. The servers passwords are then inconsistently updated leaving a group of servers with one of several possible user passwords.
The Goal: Use Ansible to attempt to login to each server using each of the possible passwords to find the correct one and log it. The final step of the playbook will have Ansible logging into each server using the found to be correct password and updating each server to a new shared password.</description>
    </item>

    <item>
      <title>Installing Ansible</title>
      <link>https://theargo.io/post/installing_ansible/</link>
      <pubDate>Mon, 16 Jun 2014 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/installing_ansible/</guid>
      <description>The Problem Need to deploy an Ansible Controller to run Playbooks from that uses the latest build and is easy to upgrade/configure.
The Solution Install Ansible from the latest release on GitHub.
The Goal Create an Ansible Controller directory that will run the latest version via git clone and setup the shell with the Ansible environment scripts.
Clone the Ansible repo Go to the GitHub project page github/ansible
Choose a release version or the dev branch and clone.</description>
    </item>

    <item>
      <title>Using Ansible to deploy a PuppetMaster</title>
      <link>https://theargo.io/post/using_ansible_to_deploy_a_puppetmaster/</link>
      <pubDate>Fri, 13 Jun 2014 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/using_ansible_to_deploy_a_puppetmaster/</guid>
      <description>The Problem Need to deploy a new Puppet Enterprise cluster with a PuppetMaster, PuppetConsole and a PuppetDB while avoiding typos and misconfigurations. Also need to deploy to several environments using a consistent configuration.
The Solution Use Ansible to deploy Puppet onto freshly built servers that contain just a SysAdmins SSH public key.
The Goal A repeatable and documented way to deploy the very finicky Puppet installer in any environment needed from local vagrants to the clouds of vSphere, AWS, RackSpace or Digital Ocean.</description>
    </item>

    <item>
      <title>Using GoAccess to parse webserver logs</title>
      <link>https://theargo.io/post/using_goaccess_to_parse_webserver_logs/</link>
      <pubDate>Tue, 01 Apr 2014 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/using_goaccess_to_parse_webserver_logs/</guid>
      <description>The Problem Need the ability to track web traffic for a specific hours worth of logs.
The Solution Using GoAccess to parse Apache logs that are rotated into hour chunks.
The Goal Install GoAccess to parse webserver logs. Use Ansible Playbooks for the installation, configuration and for re-usabilty of GoAccess on other servers. Keep it simple by rotating logs on the hour.
The Links  GoAccess - real-time web log analyzer - allinurl/goaccess Ansible - Ansible Docs Apache rotatelogs - Hourly Rotated WebServer Logs Digital Ocean - My referral link, thanks!</description>
    </item>

    <item>
      <title>Ansible on RedHat 5.x</title>
      <link>https://theargo.io/post/ansible_on_redhat_5_dot_x/</link>
      <pubDate>Tue, 03 Sep 2013 00:00:00 +0000</pubDate>

      <guid>https://theargo.io/post/ansible_on_redhat_5_dot_x/</guid>
      <description> The problem Older Pythons that live on older RedHats do not have json support. Old corporations still use old OS&rsquo;es like RedHat 5.x but need to use modern configuration management tools like Ansible.
The goal Enable RedHat 5.x systems to run Ansible by installing json support on Python 2.4.
HowTo Using Ansible Raw
sandor@pineapplez:$ ansible -i hosts all -m raw -a &quot;yum -y install python-simplejson&quot;  </description>
    </item>

  </channel>
</rss>


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
		  xmlns:tools="http://schemas.android.com/tools"
		  package="uk.co.markormesher.android_utils.app">

	<application
		android:name="uk.co.markormesher.android_utils.Global"
		android:label="@string/app_name"
		android:icon="@mipmap/ic_launcher"
		android:theme="@style/global_theme"
		android:allowBackup="true"
		android:fullBackupContent="true"
		android:supportsRtl="true"
		tools:ignore="UnusedAttribute">

		<activity
			android:name=".RootActivity"
			android:label="@string/app_name"
			android:launchMode="singleInstance">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>
				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>

	</application>

</manifest>

redpajama_set_name: RedPajamaGithub


text:
"use strict";

const constructors = exports.constructors = {};
const abstractConstructors = exports.abstractConstructors = {};

class Serializable {
    constructor(config) {
        this.config = config;
    }

    getType() {
        return this.constructor.type;
    }

    getKey() {
        return this.getType();
    }

    toStoredData(/* serializer */) {
        return {
            type: this.getType(),
            config: this.config
        };
    }

    fromStoredData(/* deserializer, storedData */) {}
}
abstractConstructors.Serializable = Serializable;

class Change extends Serializable {
    getModifiedFile() {
        return this.config.modifiedFile;
    }

    getKey() {
        return `${this.getModifiedFile()}|${super.getKey()}`;
    }
}
abstractConstructors.Change = Change;

class Impact extends Serializable {
    getImpactedFile() {
        return this.config.impactedFile;
    }

    getKey() {
        return `${this.getImpactedFile()}|${super.getKey()}`;
    }

    isPropagatable() {
        return true;
    }

    addCause(cause) {
        this.getCauses().push(cause);
    }

    getCauses() {
        let res = this.causes;
        if (!res) {
            res = this.causes = [];
        }
        return res;
    }

    getRootChanges() {
        if (!this.rootChanges) {
            const rootChanges = this.rootChanges = [];
            this.computeRootChanges(new Set(), rootChanges);
        }
        return this.rootChanges;
    }

    computeRootChanges(visitedObjects, result) {
        this.getCauses().forEach(cause => {
            if (!visitedObjects.has(cause)) {
                visitedObjects.add(cause);
                if (cause instanceof Change) {
                    result.push(cause);
                } else {
                    cause.computeRootChanges(visitedObjects, result);
                }
            }
        });
    }

    toStoredData(serializer) {
        const res = super.toStoredData(serializer);
        res.causes = this.getCauses().map(cause => serializer.store(cause));
        return res;
    }

    fromStoredData(deserializer, storedData) {
        this.causes = storedData.causes.map(causeId => deserializer.restore(causeId));
    }
}
abstractConstructors.Impact = Impact;

/**
 * A `SameFlexibleHashChange` change is generated on a file when the file only contains changes which do not affect its meaning.
 * For example, reformatting the file or adding / removing comments will produce a SameFlexibleHashChange change if there is
 * no other change in the file.
 *
 * This type of change does not cause any impact. It is only generated on Javascript files and Aria Templates templates. It cannot be generated on binary files.
 * @atdiff-change
 */
class SameFlexibleHashChange extends Change {}
constructors.SameFlexibleHashChange = SameFlexibleHashChange;

/**
 * A `FileAdded` change is generated for each new file.
 *
 * This type of change does not cause any impact.
 * @atdiff-change
 */
class FileAdded extends Change {}
constructors.FileAdded = FileAdded;

/**
 * A `FileRemoved` change is generated for each deleted file.
 *
 * This change causes the `UnusableFile` impact on the deleted file and any other file which depends on it.
 * @atdiff-change
 */
class FileRemoved extends Change {}
constructors.FileRemoved = FileRemoved;

/**
 * An `UnusableFile` impact is generated for each deleted file and for each file which directly
 * or indirectly depends on the deleted files.
 *
 * @atdiff-impact
 */
class UnusableFile extends Impact {}
constructors.UnusableFile = UnusableFile;

/**
 * An `UnknownChange` change is generated for each file which changed and for which no comparator is implemented.
 * This includes all binary files, and also the Javascript files which do not contain an Aria Templates definition
 * or which contain an Aria Templates definition for which support is limited (such as `Aria.resourcesDefinition`
 * and `Aria.interfaceDefinition`).
 *
 * This change causes the `UnknownImpact` impact.
 * @atdiff-change
 */
class UnknownChange extends Change {}
constructors.UnknownChange = UnknownChange;

/**
 * A `FileChangedType` change is generated for each file whose type changed.
 *
 * Here are the different types:
 *  * `classDefinition`
 *  * `tplScriptDefinition`
 *  * `beansDefinition`
 *  * `interfaceDefinition`
 *  * `resourcesDefinition`
 *  * `js`
 *  * `template`
 *
 * For example, removing the `Aria.classDefinition` definition from a Javascript file makes
 * it pass from the `classDefinition` specific type to the `js` general type, which generates a
 * `FileChangedType` change.
 *
 * A `FileChangedType` change causes the `UnknownImpact` impact.
 * @atdiff-change
 */
class FileChangedType extends UnknownChange {}
constructors.FileChangedType = FileChangedType;

/**
 * An `UnknownImpact` impact is generated on files for which an `UnknownChange` or a `FileChangedType` change has been generated.
 * @atdiff-impact
 */
class UnknownImpact extends Impact {}
constructors.UnknownImpact = UnknownImpact;

/**
 * An `ImpactsInDependency` impact is generated on files which have a dependency which has one or more impacts
 * when the impact of those impacts on the dependent file is unknown.
 * @atdiff-impact
 */
class ImpactsInDependency extends Impact {
    isPropagatable() {
        return false;
    }

    getDependency() {
        return this.getCauses()[0].getImpactedFile();
    }

    getKey() {
        return `${super.getKey()}|${this.getDependency()}`;
    }
}
constructors.ImpactsInDependency = ImpactsInDependency;


text:
"""Test TcexJson"""
# pylint: disable=R1710
# standard library
import json
import os
import shutil
from pathlib import Path

# third-party
from deepdiff import DeepDiff

# first-party
from tcex.app_config.install_json import InstallJson
from tcex.app_config.tcex_json import TcexJson

class TestTcexJson:
    """App Config TcexJson testing."""

    # @staticmethod
    # def test_dev_testing():
    #     """."""
    #     fqfn = Path('tests/app_config/tcex_json_samples/example1-tcex.json')
    #     try:
    #         tj = TcexJson(filename=fqfn.name, path=fqfn.parent)
    #     except Exception as ex:
    #         assert False, f'Failed parsing file {fqfn.name} ({ex})'

    #     print('\nfilename', fqfn.name)
    #     print('tj.model.lib_versions', tj.model.lib_versions)
    #     print('tj.model.package', tj.model.package)
    #     print('tj.model.template', tj.model.template)

    @staticmethod
    def ij(app_name: str = 'app_1', app_type: str = 'tcpb'):
        """Return install.json instance."""
        # reset singleton
        # InstallJson._instances = {}
        tcex_test_dir = os.getenv('TCEX_TEST_DIR')

        ij_fqfn = os.path.join(
            tcex_test_dir, 'app_config', 'apps', app_type, app_name, 'install.json'
        )
        fqfn = Path(ij_fqfn)
        try:
            return InstallJson(filename=fqfn.name, path=fqfn.parent)
        except Exception as ex:
            assert False, f'Failed parsing file {fqfn.name} ({ex})'

    @staticmethod
    def tj(app_name: str = 'app_1', app_type: str = 'tcpb'):
        """Return tcex.json instance."""
        # reset singleton
        TcexJson._instances = {}
        tcex_test_dir = os.getenv('TCEX_TEST_DIR')

        tj_fqfn = os.path.join(tcex_test_dir, 'app_config', 'apps', app_type, app_name, 'tcex.json')
        fqfn = Path(tj_fqfn)
        try:
            return TcexJson(filename=fqfn.name, path=fqfn.parent)
        except Exception as ex:
            assert False, f'Failed parsing file {fqfn.name} ({ex})'

    @staticmethod
    def tj_bad(app_name: str = 'app_bad_tcex_json', app_type: str = 'tcpb'):
        """Return tcex.json instance with "bad" file."""
        # reset singleton
        TcexJson._instances = {}
        tcex_test_dir = os.getenv('TCEX_TEST_DIR')

        base_fqpn = os.path.join(tcex_test_dir, 'app_config', 'apps', app_type, app_name)
        shutil.copy2(
            f'{base_fqpn}/tcex-template.json',
            f'{base_fqpn}/tcex.json',
        )
        fqfn = Path(os.path.join(base_fqpn, 'tcex.json'))
        try:
            return TcexJson(filename=fqfn.name, path=fqfn.parent)
        except Exception as ex:
            assert False, f'Failed parsing file {fqfn.name} ({ex})'

    @staticmethod
    def model_validate(path: str):
        """Validate input model in and out."""
        tcex_test_dir = os.getenv('TCEX_TEST_DIR')
        tj_path = Path(os.path.join(tcex_test_dir, path))
        for fqfn in tj_path.glob('**/*tcex.json'):
            # reset singleton
            TcexJson._instances = {}

            fqfn = Path(fqfn)
            with fqfn.open() as fh:
                json_dict = json.load(fh)

            try:
                tj = TcexJson(filename=fqfn.name, path=fqfn.parent)
                # tj.update.multiple()
            except Exception as ex:
                assert False, f'Failed parsing file {fqfn.name} ({ex})'

            ddiff = DeepDiff(
                json_dict,
                # template requires json dump to serialize certain fields
                json.loads(tj.model.json(by_alias=True, exclude_defaults=True, exclude_none=True)),
                ignore_order=True,
            )
            assert not ddiff, f'Failed validation of file {fqfn.name}'

    def test_print_warnings(self):
        """Test method"""
        tj = self.tj_bad()
        tj.print_warnings()

        # remove temp file
        tj.fqfn.unlink()

    def test_update(self):
        """Test method"""
        tj = self.tj_bad()
        tj.ij = self.ij(app_name='app_bad_tcex_json', app_type='tcpb')

        try:
            tj.update.multiple(template='service_api')
            # print(tj.model.schema_json())
            print(
                tj.model.json(exclude_defaults=False, exclude_none=True, indent=2, sort_keys=True)
            )
            assert True
        except Exception as ex:
            assert False, f'Failed to update tcex.json file ({ex}).'
        finally:
            # cleanup temp file
            # tj.fqfn.unlink()
            pass

    def test_support(self):
        """Validate tcex.json files."""
        # self.model_validate(self.tj())
        self.model_validate('tests/app_config/apps/tcpb')


text:
package com.intellij.codeInsight.editorActions.smartEnter;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbService;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.jsp.jspJava.JspMethodCall;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.Nullable;

/**
 * Created by IntelliJ IDEA.
 * User: max
 * Date: Sep 5, 2003
 * Time: 3:35:49 PM
 * To change this template use Options | File Templates.
 */
public class MethodCallFixer implements Fixer {
  @Override
  public void apply(Editor editor, JavaSmartEnterProcessor processor, PsiElement psiElement) throws IncorrectOperationException {
    PsiExpressionList args = null;
    if (psiElement instanceof PsiMethodCallExpression && !(psiElement instanceof JspMethodCall)) {
      args = ((PsiMethodCallExpression) psiElement).getArgumentList();
    } else if (psiElement instanceof PsiNewExpression) {
      args = ((PsiNewExpression) psiElement).getArgumentList();
    }

    if (args != null && !hasRParenth(args)) {
      int caret = editor.getCaretModel().getOffset();
      PsiCallExpression innermostCall = PsiTreeUtil.findElementOfClassAtOffset(psiElement.getContainingFile(), caret - 1, PsiCallExpression.class, false);
      if (innermostCall == null) return;

      args = innermostCall.getArgumentList();
      if (args == null) return;

      int endOffset = -1;
      PsiElement child = args.getFirstChild();
      while (child != null) {
        if (child instanceof PsiErrorElement) {
          final PsiErrorElement errorElement = (PsiErrorElement)child;
          if (errorElement.getErrorDescription().contains("')'")) {
            endOffset = errorElement.getTextRange().getStartOffset();
            break;
          }
        }
        child = child.getNextSibling();
      }

      if (endOffset == -1) {
        endOffset = args.getTextRange().getEndOffset();
      }

      final PsiExpression[] params = args.getExpressions();
      if (params.length > 0 &&
          startLine(editor, args) != startLine(editor, params[0]) &&
          caret < params[0].getTextRange().getStartOffset()) {
        endOffset = args.getTextRange().getStartOffset() + 1;
      }

      if (!DumbService.isDumb(args.getProject())) {
        Integer argCount = getUnambiguousParameterCount(innermostCall);
        if (argCount != null && argCount > 0 && argCount < params.length) {
          endOffset = Math.min(endOffset, params[argCount - 1].getTextRange().getEndOffset());
        }
      }

      endOffset = CharArrayUtil.shiftBackward(editor.getDocument().getCharsSequence(), endOffset - 1, " \t\n") + 1;
      editor.getDocument().insertString(endOffset, ")");
    }
  }

  private static boolean hasRParenth(PsiExpressionList args) {
    PsiElement parenth = args.getLastChild();
    return parenth != null && ")".equals(parenth.getText());
  }

  @Nullable
  private static Integer getUnambiguousParameterCount(PsiCallExpression call) {
    int argCount = -1;
    for (CandidateInfo candidate : PsiResolveHelper.SERVICE.getInstance(call.getProject()).getReferencedMethodCandidates(call, false)) {
      PsiElement element = candidate.getElement();
      if (!(element instanceof PsiMethod)) return null;
      if (((PsiMethod)element).isVarArgs()) return null;

      int count = ((PsiMethod)element).getParameterList().getParametersCount();
      if (argCount == -1) {
        argCount = count;
      } else if (argCount != count) {
        return null;
      }
    }
    return argCount;
  }

  private static int startLine(Editor editor, PsiElement psiElement) {
    return editor.getDocument().getLineNumber(psiElement.getTextRange().getStartOffset());
  }
}


text:
<?php

namespace GrumPHP\Collection;

use Doctrine\Common\Collections\ArrayCollection;
use GrumPHP\Runner\TaskResult;
use GrumPHP\Runner\TaskResultInterface;

class TaskResultCollection extends ArrayCollection
{
    const NO_TASKS = -100;

    /**
     * @return bool
     */
    public function isPassed()
    {
        return TaskResult::PASSED == $this->getResultCode();
    }

    /**
     * @return bool
     */
    public function isFailed()
    {
        foreach ($this as $taskResult) {
            if (TaskResult::FAILED === $taskResult->getResultCode()) {
                return true;
            }
        }

        return false;
    }

    /**
     * @return int|mixed
     */
    public function getResultCode()
    {
        $resultCode = static::NO_TASKS;
        foreach ($this as $taskResult) {
            $resultCode = max($resultCode, $taskResult->getResultCode());
        }

        return $resultCode;
    }

    /**
     * @param int $resultCode
     * @return static
     */
    public function filterByResultCode($resultCode)
    {
        return $this->filter(function (TaskResultInterface $taskResult) use ($resultCode) {
            return $resultCode === $taskResult->getResultCode();
        });
    }

    /**
     * @return array
     */
    public function getAllMessages()
    {
        $messages = array();

        foreach ($this as $taskResult) {
            $messages[] = $taskResult->getMessage();
        }

        return $messages;
    }
}


text:
package org.uiautomation.ios.application;

public class NoSuchLanguageCodeException extends RuntimeException {

  public NoSuchLanguageCodeException(String languageCode) {
    super("No such language code: " + languageCode);
  }
}


text:
package com.lightbend.lagom.javadsl.testkit

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Optional
import java.util.function.{ Function => JFunction }

import akka.actor.ActorSystem
import akka.annotation.ApiMayChange
import akka.japi.function.Effect
import akka.japi.function.Procedure
import akka.stream.Materializer
import com.lightbend.lagom.devmode.ssl.LagomDevModeSSLHolder
import com.lightbend.lagom.internal.javadsl.api.broker.TopicFactory
import com.lightbend.lagom.internal.javadsl.cluster.JoinClusterModule
import com.lightbend.lagom.internal.persistence.testkit.AwaitPersistenceInit.awaitPersistenceInit
import com.lightbend.lagom.internal.persistence.testkit.PersistenceTestConfig._
import com.lightbend.lagom.internal.testkit.TestkitSslSetup.Disabled
import com.lightbend.lagom.internal.testkit._
import com.lightbend.lagom.javadsl.api.Service
import com.lightbend.lagom.javadsl.api.ServiceLocator
import com.lightbend.lagom.javadsl.persistence.PersistenceModule
import com.lightbend.lagom.javadsl.pubsub.PubSubModule
import com.lightbend.lagom.spi.persistence.InMemoryOffsetStore
import com.lightbend.lagom.spi.persistence.OffsetStore
import javax.net.ssl.SSLContext
import play.Application
import play.api.inject.ApplicationLifecycle
import play.api.inject.BindingKey
import play.api.inject.DefaultApplicationLifecycle
import play.api.inject.{ bind => sBind }
import play.api.Configuration
import play.api.Play
import play.core.server.Server
import play.core.server.ServerConfig
import play.core.server.ServerProvider
import play.inject.Injector
import play.inject.guice.GuiceApplicationBuilder

import scala.annotation.tailrec
import scala.concurrent.Promise
import scala.concurrent.duration._
import scala.util.Try
import scala.util.control.NonFatal

/**
 * Support for writing functional tests for one service. The service is running
 * in a server and in the test you can interact with it using its service client,
 * i.e. calls to the service API.
 *
 * Dependencies to other services must be replaced by stub or mock implementations by
 * overriding the bindings of the `GuiceApplicationBuilder` in the `Setup`.
 *
 * The server is ran standalone without persistence, pubsub or cluster features
 * enabled. Cassandra is also disabled by default. If your service require either of these features you
 * can enable them in the `Setup`.
 *
 * There are two different styles that can be used. It is most convenient to use [[#withServer withServer]],
 * since it automatically starts and stops the server before and after the given lambda.
 * When your test have several test methods, and especially when using persistence, it is
 * faster to only [[#startServer start]] the server once in a static method annotated with `@BeforeClass`
 * and stop it in a method annotated with `@AfterClass`.
 */
object ServiceTest {
  // These are all specified as strings so that we can say they are disabled without having a dependency on them.
  private val JdbcPersistenceModule = "com.lightbend.lagom.javadsl.persistence.jdbc.JdbcPersistenceModule"
  private val CassandraPersistenceModule =
    "com.lightbend.lagom.javadsl.persistence.cassandra.CassandraPersistenceModule"
  private val KafkaBrokerModule = "com.lightbend.lagom.internal.javadsl.broker.kafka.KafkaBrokerModule"
  private val KafkaClientModule = "com.lightbend.lagom.javadsl.broker.kafka.KafkaClientModule"

  sealed trait Setup {
    @deprecated(message = "Use withCassandra instead", since = "1.2.0")
    def withPersistence(enabled: Boolean): Setup = withCassandra(enabled)

    /**
     * Enable or disable Cassandra.
     *
     * If enabled, this will start an embedded Cassandra server before the tests start, and shut it down afterwards.
     * It will also configure Lagom to use the embedded Cassandra server. Enabling Cassandra will also enable the
     * cluster.
     *
     * @param enabled True if Cassandra should be enabled, or false if disabled.
     * @return A copy of this setup.
     */
    def withCassandra(enabled: Boolean): Setup

    /**
     * Enable Cassandra.
     *
     * If enabled, this will start an embedded Cassandra server before the tests start, and shut it down afterwards.
     * It will also configure Lagom to use the embedded Cassandra server. Enabling Cassandra will also enable the
     * cluster.
     *
     * @return A copy of this setup.
     */
    def withCassandra(): Setup = withCassandra(true)

    /**
     * Enable or disable JDBC.
     *
     * Enabling JDBC will also enable the cluster.
     *
     * @param enabled True if JDBC should be enabled, or false if disabled.
     * @return A copy of this setup.
     */
    def withJdbc(enabled: Boolean): Setup

    /**
     * Enable JDBC.
     *
     * Enabling JDBC will also enable the cluster.
     *
     * @return A copy of this setup.
     */
    def withJdbc(): Setup = withJdbc(true)

    @deprecated(message = "Use configureBuilder instead", since = "1.2.0")
    def withConfigureBuilder(configureBuilder: JFunction[GuiceApplicationBuilder, GuiceApplicationBuilder]) =
      this.configureBuilder(configureBuilder)

    /**
     * Configure the builder.
     *
     * Allows a function to be supplied to configure the Play Guice application builder. This allows components to be
     * mocked, modules to be enabled/disabled, and custom configuration to be supplied.
     *
     * @param configureBuilder The builder configuration function.
     * @return A copy of this setup.
     */
    def configureBuilder(configureBuilder: JFunction[GuiceApplicationBuilder, GuiceApplicationBuilder]): Setup

    /**
     * Enable or disable clustering.
     *
     * Disabling this will automatically disable any persistence plugins, since persistence requires clustering.
     *
     * @param enabled True if clustering should be enabled, or false if disabled.
     * @return A copy of this setup.
     */
    def withCluster(enabled: Boolean): Setup

    /**
     * Enable clustering.
     *
     * Disabling this will automatically disable any persistence plugins, since persistence requires clustering.
     *
     * @return A copy of this setup.
     */
    def withCluster(): Setup = withCluster(true)

    /**
     * Enable or disable the SSL port.
     *
     * @param enabled True if the server should bind an HTTP+TLS port, or false if only HTTP should be bound.
     * @return A copy of this setup.
     */
    @ApiMayChange
    def withSsl(enabled: Boolean): Setup

    /**
     * Enable the SSL port.
     *
     * @return A copy of this setup.
     */
    @ApiMayChange
    def withSsl(): Setup = withSsl(true)

    /**
     * Whether Cassandra is enabled.
     */
    def cassandra: Boolean

    /**
     * Whether JDBC is enabled.
     */
    def jdbc: Boolean

    /**
     * Whether clustering is enabled.
     */
    def cluster: Boolean

    /**
     * Whether HTTPS is enabled.
     */
    def ssl: Boolean

    /**
     * The builder configuration function
     */
    def configureBuilder: JFunction[GuiceApplicationBuilder, GuiceApplicationBuilder]
  }

  private case class SetupImpl(
      cassandra: Boolean,
      jdbc: Boolean,
      cluster: Boolean,
      ssl: Boolean,
      configureBuilder: JFunction[GuiceApplicationBuilder, GuiceApplicationBuilder]
  ) extends Setup {
    def this() = this(
      cassandra = false,
      jdbc = false,
      cluster = false,
      ssl = false,
      configureBuilder = new JFunction[GuiceApplicationBuilder, GuiceApplicationBuilder] {
        override def apply(b: GuiceApplicationBuilder): GuiceApplicationBuilder = b
      }
    )

    override def withCassandra(enabled: Boolean): Setup = {
      if (enabled) {
        copy(cassandra = true, cluster = true)
      } else {
        copy(cassandra = false)
      }
    }

    override def withJdbc(enabled: Boolean): Setup =
      if (enabled) {
        copy(jdbc = true, cluster = true)
      } else {
        copy(jdbc = false)
      }

    override def withCluster(enabled: Boolean): Setup = {
      if (enabled) {
        copy(cluster = true)
      } else {
        copy(cluster = false, cassandra = false)
      }
    }

    override def withSsl(enabled: Boolean): Setup = {
      copy(ssl = enabled)
    }

    override def configureBuilder(
        configureBuilder: JFunction[GuiceApplicationBuilder, GuiceApplicationBuilder]
    ): Setup = {
      copy(configureBuilder = configureBuilder)
    }
  }

  /**
   * The default `Setup` configuration, which has persistence enabled.
   */
  val defaultSetup: Setup = new SetupImpl()

  /**
   * When the server is started you can get the service client and other
   * Guice bindings here.
   */
  class TestServer(
      val port: Int,
      val app: Application,
      server: Server,
      @ApiMayChange val clientSslContext: Optional[SSLContext] = Optional.empty()
  ) {
    @ApiMayChange val portSsl: Optional[Integer] = Optional.ofNullable(server.httpsPort.map(Integer.valueOf).orNull)

    /**
     * Get the service client for a service.
     */
    def client[S <: Service](serviceClass: Class[S]): S =
      app.injector().instanceOf(serviceClass)

    /**
     * Stream materializer. Useful for Akka Streams TestKit.
     */
    def materializer: Materializer = injector.instanceOf(classOf[Materializer])

    /**
     * Current Akka `ActorSystem`. Useful for Akka Streams TestKit.
     */
    def system: ActorSystem = injector.instanceOf(classOf[ActorSystem])

    /**
     * The Guice injector that can be used for retrieving anything
     * that has been bound to Guice.
     */
    def injector: Injector = app.injector()

    /**
     * If you use `startServer` you must also stop the server with
     * this method when the test is finished. That is handled automatically
     * by `withServer`.
     */
    def stop(): Unit = {
      Try(Play.stop(app.asScala()))
      Try(server.stop())
    }
  }

  /**
   * Start the test server with the given `setup` and run the `block` (lambda). When
   * the `block` returns or throws the test server will automatically be stopped.
   *
   * This method should be used when the server can be started and stopped for each test
   * method. When your test have several test methods, and especially when using persistence, it is
   * faster to only start the server once with [[#startServer]].
   *
   * You can get the service client from the `TestServer` that is passed as parameter
   * to the `block`.
   */
  def withServer(
      setup: Setup,
      block: Procedure[TestServer]
  ): Unit = {
    // using Procedure instead of Consumer to support throwing Exception
    val testServer = startServer(setup)
    try {
      block(testServer)
    } finally {
      testServer.stop()
    }
  }

  /**
   * Start the test server with the given `setup`. You must stop the server with
   * the `stop` method of the returned `TestServer` when the test is finished.
   *
   * When your test have several test methods, and especially when using persistence, it is
   * faster to only start the server once in a static method annotated with `@BeforeClass`
   * and stop it in a method annotated with `@AfterClass`. Otherwise [[#withServer]] is
   * more convenient.
   *
   * You can get the service client from the returned `TestServer`.
   */
  def startServer(setup: Setup): TestServer = {
    val port                   = Promise[Int]()
    val testServiceLocatorPort = TestServiceLocatorPort(port.future)

    val now      = DateTimeFormatter.ofPattern("yyMMddHHmmssSSS").format(LocalDateTime.now())
    val testName = s"ServiceTest_$now"

    val lifecycle = new DefaultApplicationLifecycle

    val initialBuilder = new GuiceApplicationBuilder()
      .bindings(sBind[TestServiceLocatorPort].to(testServiceLocatorPort))
      .bindings(sBind[ServiceLocator].to(classOf[TestServiceLocator]))
      .bindings(sBind[TopicFactory].to(classOf[TestTopicFactory]))
      .overrides(sBind[ApplicationLifecycle].to(lifecycle))
      .configure("play.akka.actor-system", testName)

    val finalBuilder =
      if (setup.cassandra) {
        val cassandraPort = CassandraTestServer.run(testName, lifecycle)

        initialBuilder
          .configure(cassandraConfig(testName, cassandraPort))
          .disableModules(JdbcPersistenceModule, KafkaClientModule, KafkaBrokerModule)
      } else if (setup.jdbc) {
        initialBuilder
          .configure(JdbcConfig)
          .disableModules(CassandraPersistenceModule, KafkaClientModule, KafkaBrokerModule)
      } else if (setup.cluster) {
        initialBuilder
          .configure(ClusterConfig)
          .disable(classOf[PersistenceModule])
          .bindings(play.api.inject.bind[OffsetStore].to[InMemoryOffsetStore])
          .disableModules(CassandraPersistenceModule, JdbcPersistenceModule, KafkaClientModule, KafkaBrokerModule)
      } else {
        initialBuilder
          .configure(BasicConfig)
          .disable(classOf[PersistenceModule], classOf[PubSubModule], classOf[JoinClusterModule])
          .bindings(play.api.inject.bind[OffsetStore].to[InMemoryOffsetStore])
          .disableModules(CassandraPersistenceModule, JdbcPersistenceModule, KafkaClientModule, KafkaBrokerModule)
      }

    val application = setup.configureBuilder(finalBuilder).build()

    Play.start(application.asScala())

    val sslSetup: TestkitSslSetup.TestkitSslSetup = if (setup.ssl) {
      val sslHolder                    = new LagomDevModeSSLHolder(application.environment().asScala())
      val clientSslContext: SSLContext = sslHolder.sslContext
      // In tests we're using a self-signed certificate so we use the same keyStore for both
      // the server and the client trustStore.
      TestkitSslSetup.enabled(sslHolder.keyStoreMetadata, sslHolder.trustStoreMetadata, clientSslContext)
    } else {
      Disabled
    }

    val props = System.getProperties
    val sslConfig: Configuration =
      Configuration.load(this.getClass.getClassLoader, props, sslSetup.sslSettings, allowMissingApplicationConf = true)
    val serverConfig: ServerConfig = new ServerConfig(
      port = Some(0),
      sslPort = sslSetup.sslPort,
      mode = application.environment().mode.asScala(),
      configuration = sslConfig,
      rootDir = application.environment().rootPath,
      address = "0.0.0.0",
      properties = props
    )
    val srv          = ServerProvider.defaultServerProvider.createServer(serverConfig, application.asScala())
    val assignedPort = srv.httpPort.orElse(srv.httpsPort).get
    port.success(assignedPort)

    if (setup.cassandra || setup.jdbc) {
      val system = application.injector().instanceOf(classOf[ActorSystem])
      awaitPersistenceInit(system)
    }

    val javaSslContext = Optional.ofNullable(sslSetup.clientSslContext.orNull)
    new TestServer(assignedPort, application, srv, javaSslContext)
  }

  /**
   * Enriches [[GuiceApplicationBuilder]] with a `disableModules` method.
   */
  private implicit class GuiceBuilderOps(val builder: GuiceApplicationBuilder) extends AnyVal {
    def disableModules(classes: String*): GuiceApplicationBuilder = {
      val loadedClasses = classes.flatMap { className =>
        try {
          Seq(getClass.getClassLoader.loadClass(className))
        } catch {
          case cfne: ClassNotFoundException =>
            Seq.empty[Class[_]]
        }
      }
      if (loadedClasses.nonEmpty) {
        builder.disable(loadedClasses: _*)
      } else {
        builder
      }
    }
  }

  /**
   * Retry the give `block` (lambda) until it does not throw an exception or the timeout
   * expires, whichever comes first. If the timeout expires the last exception
   * is thrown. The `block` is retried with 100 milliseconds interval.
   */
  def eventually(max: FiniteDuration, block: Effect): Unit =
    eventually(max, 100.millis, block)

  /**
   * Retry the give `block` (lambda) until it does not throw an exception or the timeout
   * expires, whichever comes first. If the timeout expires the last exception
   * is thrown. The `block` is retried with the given `interval`.
   */
  def eventually(max: FiniteDuration, interval: FiniteDuration, block: Effect): Unit = {
    def now  = System.nanoTime.nanos
    val stop = now + max

    @tailrec
    def poll(t: Duration): Unit = {
      val failed =
        try {
          block(); false
        } catch {
          case NonFatal(e) =>
            if ((now + t) >= stop) throw e
            true
        }
      if (failed) {
        Thread.sleep(t.toMillis)
        poll((stop - now).min(interval))
      }
    }

    poll(max.min(interval))
  }

  /**
   * Create a binding that can be used with the `GuiceApplicationBuilder`
   * in the `Setup`, e.g. to override bindings to stub out dependencies to
   * other services.
   */
  def bind[T](clazz: Class[T]): BindingKey[T] =
    play.inject.Bindings.bind(clazz)
}


text:
@interface RootViewController : UIViewController

@property (nonatomic, strong) IBOutlet UIButton *helloiOSButton;

- (IBAction)helloiOSButtonTouchUpInisde:(id)sender;

@end


text:
import * as Path from 'path'
import { spawnSync, SpawnSyncOptions } from 'child_process'

import glob from 'glob'

const root = Path.dirname(__dirname)

const options: SpawnSyncOptions = {
  cwd: root,
  stdio: 'inherit',
}

function findYarnVersion(callback: (path: string) => void) {
  glob('vendor/yarn-*.js', (error, files) => {
    if (error != null) {
      throw error
    }

    // this ensures the paths returned by glob are sorted alphabetically
    files.sort()

    // use the latest version here if multiple are found
    const latestVersion = files[files.length - 1]

    callback(latestVersion)
  })
}

findYarnVersion(path => {
  let result = spawnSync(
    'node',
    [path, '--cwd', 'app', 'install', '--force'],
    options
  )

  if (result.status !== 0) {
    process.exit(result.status || 1)
  }

  result = spawnSync(
    'git',
    ['submodule', 'update', '--recursive', '--init'],
    options
  )

  if (result.status !== 0) {
    process.exit(result.status || 1)
  }

  result = spawnSync('node', [path, 'compile:script'], options)

  if (result.status !== 0) {
    process.exit(result.status || 1)
  }
})


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.filter;

import com.yahoo.jdisc.http.Cookie;

import java.util.concurrent.TimeUnit;

/**
 * Wrapper of Cookie.
 *
 * @author Tejal Knot
 *
 */
public class JDiscCookieWrapper {

    private Cookie cookie;

    protected JDiscCookieWrapper(Cookie cookie) {
        this.cookie = cookie;
    }

    public static JDiscCookieWrapper wrap(Cookie cookie) {
        return new JDiscCookieWrapper(cookie);
    }

    public String getDomain() {
        return cookie.getDomain();
    }

    public int getMaxAge() {
        return cookie.getMaxAge(TimeUnit.SECONDS);
    }

    public String getName() {
        return cookie.getName();
    }

    public String getPath() {
        return cookie.getPath();
    }

    public boolean getSecure() {
        return cookie.isSecure();
    }

    public String getValue() {
        return cookie.getValue();
    }

    public void setDomain(String pattern) {
        cookie.setDomain(pattern);
    }

    public void setMaxAge(int expiry) {
        cookie.setMaxAge(expiry, TimeUnit.SECONDS);
    }

    public void setPath(String uri) {
        cookie.setPath(uri);
    }

    public void setSecure(boolean flag) {
      cookie.setSecure(flag);
    }

    public void setValue(String newValue) {
       cookie.setValue(newValue);
    }

    /**
     * Return com.yahoo.jdisc.http.Cookie
     *
     * @return - cookie
     */
    public Cookie getCookie() {
       return cookie;
    }

}


text:
# Copyright 2018 Google LLC
#
# 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.

"""This script is used to synthesize generated parts of this library."""

import re
import textwrap

import synthtool as s
from synthtool import gcp

gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()
version = "v1"

# ----------------------------------------------------------------------------
# Generate pubsub GAPIC layer
# ----------------------------------------------------------------------------
library = gapic.py_library(
    "pubsub",
    version,
    config_path="/google/pubsub/artman_pubsub.yaml",
    include_protos=True,
)
s.move(
    library,
    excludes=[
        "docs/**/*",
        "nox.py",
        "README.rst",
        "setup.py",
        "google/cloud/pubsub_v1/__init__.py",
        "google/cloud/pubsub_v1/types.py",
    ],
)

# Adjust tests to import the clients directly.
s.replace(
    "tests/unit/gapic/v1/test_publisher_client_v1.py",
    "from google.cloud import pubsub_v1",
    "from google.cloud.pubsub_v1.gapic import publisher_client",
)

s.replace(
    "tests/unit/gapic/v1/test_publisher_client_v1.py", " pubsub_v1", " publisher_client"
)

s.replace(
    "tests/unit/gapic/v1/test_subscriber_client_v1.py",
    "from google.cloud import pubsub_v1",
    "from google.cloud.pubsub_v1.gapic import subscriber_client",
)

s.replace(
    "tests/unit/gapic/v1/test_subscriber_client_v1.py",
    " pubsub_v1",
    " subscriber_client",
)

# DEFAULT SCOPES are being used. so let's force them in.
s.replace(
    "google/cloud/pubsub_v1/gapic/*er_client.py",
    "# The name of the interface for this client. This is the key used to",
    """# The scopes needed to make gRPC calls to all of the methods defined in
    # this service
    _DEFAULT_SCOPES = (
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/pubsub', )

    \g<0>""",
)

s.replace(
    "google/cloud/pubsub_v1/gapic/publisher_client.py",
    "import google.api_core.gapic_v1.method\n",
    "\g<0>import google.api_core.path_template\n",
)

# Doc strings are formatted poorly
s.replace(
    "google/cloud/pubsub_v1/proto/pubsub_pb2.py",
    'DESCRIPTOR = _MESSAGESTORAGEPOLICY,\n\s+__module__.*\n\s+,\n\s+__doc__ = """',
    "\g<0>A message storage policy.\n\n\n    ",
)

s.replace(
    "google/cloud/pubsub_v1/gapic/subscriber_client.py",
    "subscription \(str\): The subscription whose backlog .*\n(.*\n)+?"
    "\s+Format is .*",
    """subscription (str): The subscription whose backlog the snapshot retains.
                Specifically, the created snapshot is guaranteed to retain: \\
                 (a) The existing backlog on the subscription. More precisely, this is \\
                     defined as the messages in the subscription's backlog that are \\
                     unacknowledged upon the successful completion of the \\
                     `CreateSnapshot` request; as well as: \\
                 (b) Any messages published to the subscription's topic following the \\
                     successful completion of the CreateSnapshot request. \\

                Format is ``projects/{project}/subscriptions/{sub}``.""",
)

s.replace(
    "google/cloud/pubsub_v1/gapic/publisher_client.py",
    "import functools\n",
    "import collections\n"
    "from copy import deepcopy\n\g<0>"
)

s.replace(
    "google/cloud/pubsub_v1/gapic/publisher_client.py",
    "import pkg_resources\n",
    "\g<0>import six\n"
)

s.replace(
    "google/cloud/pubsub_v1/gapic/publisher_client.py",
    "class PublisherClient",
    """# TODO: remove conditional import after Python 2 support is dropped
if six.PY3:
    from collections.abc import Mapping
else:
    from collections import Mapping

def _merge_dict(d1, d2):
    # Modifies d1 in-place to take values from d2
    # if the nested keys from d2 are present in d1.
    # https://stackoverflow.com/a/10704003/4488789
    for k, v2 in d2.items():
        v1 = d1.get(k) # returns None if v1 has no such key
        if v1 is None:
            raise Exception("{} is not recognized by client_config".format(k))
        if isinstance(v1, Mapping) and isinstance(v2, Mapping):
            _merge_dict(v1, v2)
        else:
            d1[k] = v2
    return d1
    \n\n\g<0>"""
)

s.replace(
    "google/cloud/pubsub_v1/gapic/publisher_client.py",
    "client_config \(dict\): DEPRECATED.",
    "client_config (dict):"
)

s.replace(
    "google/cloud/pubsub_v1/gapic/publisher_client.py",
    "# Raise deprecation warnings .*\n.*\n.*\n.*\n.*\n.*\n",
    """default_client_config = deepcopy(publisher_client_config.config)

        if client_config is None:
            client_config = default_client_config
        else:
            client_config = _merge_dict(default_client_config, client_config)
    """
)

s.replace(
    "google/cloud/pubsub_v1/gapic/publisher_client.py",
    "~google.api_core.page_iterator.PageIterator",
    "~google.api_core.page_iterator.GRPCIterator"
)

s.replace(
    "google/cloud/pubsub_v1/gapic/subscriber_client.py",
    "~google.api_core.page_iterator.PageIterator",
    "~google.api_core.page_iterator.GRPCIterator"
)

# Temporary fixup for 'grpc-google-iam-vi 0.12.4' (before generation).
s.replace(
    "google/cloud/pubsub_v1/gapic/transports/*_grpc_transport.py",
    "from google.iam.v1 import iam_policy_pb2",
    "from google.iam.v1 import iam_policy_pb2_grpc as iam_policy_pb2",
)

# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
templated_files = gcp.CommonTemplates().py_library(unit_cov_level=97, cov_level=100)
s.move(templated_files)

s.shell.run(["nox", "-s", "blacken"], hide_output=False)


text:
<?php
/**
 * Neo4j exception file
 *
 * @package EndyJasmi\Neo4j\Error\Neo\ClientError\Transaction
 */
namespace EndyJasmi\Neo4j\Error\Neo\ClientError\Transaction;

use EndyJasmi\Neo4j\Error\Neo\ClientError\Transaction;

/**
 * ConcurrentRequest is an exception class which represent the error status code returned by the server
 */
class ConcurrentRequest extends Transaction
{

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Dissertationes ad scientiam naturalem pertinentes 117 (1772)

#### Original name
Fungus tuberosus Scop.

### Remarks
null


text:
using ElectronicObserver.Data.Battle.Phase;
using ElectronicObserver.Resource.Record;
using ElectronicObserver.Utility.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicObserver.Data.Battle.Detail
{

	public static class BattleDetailDescriptor
	{

		public static string GetBattleDetail(BattleManager bm)
		{
			var sb = new StringBuilder();

			if (bm.IsPractice)
			{
				sb.AppendLine("演習");

			}
			else
			{
				sb.AppendFormat("{0} ({1}-{2})", bm.Compass.MapInfo.Name, bm.Compass.MapAreaID, bm.Compass.MapInfoID);
				if (bm.Compass.MapInfo.EventDifficulty > 0)
					sb.AppendFormat(" [{0}]", Constants.GetDifficulty(bm.Compass.MapInfo.EventDifficulty));
				sb.Append(" セル: ").Append(bm.Compass.Destination.ToString());
				if (bm.Compass.EventID == 5)
					sb.Append(" (ボス)");
				sb.AppendLine();

				var mapinfo = bm.Compass.MapInfo;
				if (!mapinfo.IsCleared)
				{
					if (mapinfo.RequiredDefeatedCount != -1)
					{
						sb.AppendFormat("撃破: {0} / {1} 回", mapinfo.CurrentDefeatedCount, mapinfo.RequiredDefeatedCount)
							.AppendLine();
					}
					else if (mapinfo.MapHPMax > 0)
					{
						int current = bm.Compass.MapHPCurrent > 0 ? bm.Compass.MapHPCurrent : mapinfo.MapHPCurrent;
						int max = bm.Compass.MapHPMax > 0 ? bm.Compass.MapHPMax : mapinfo.MapHPMax;
						sb.AppendFormat("{0}{1}: {2} / {3}", mapinfo.CurrentGaugeIndex > 0 ? "#" + mapinfo.CurrentGaugeIndex + " " : "", mapinfo.GaugeType == 3 ? "TP" : "HP", current, max)
							.AppendLine();
					}
				}
			}
			if (bm.Result != null)
			{
				sb.AppendLine(bm.Result.EnemyFleetName);
			}
			sb.AppendLine();

			sb.AppendFormat("◆ {0} ◆\r\n", bm.FirstBattle.BattleName).AppendLine(GetBattleDetail(bm.FirstBattle));
			if (bm.SecondBattle != null)
				sb.AppendFormat("◆ {0} ◆\r\n", bm.SecondBattle.BattleName).AppendLine(GetBattleDetail(bm.SecondBattle));

			if (bm.Result != null)
			{
				sb.AppendLine(GetBattleResult(bm));
			}

			return sb.ToString();
		}

		public static string GetBattleDetail(BattleData battle)
		{

			var sbmaster = new StringBuilder();
			bool isBaseAirRaid = battle.IsBaseAirRaid;

			foreach (var phase in battle.GetPhases())
			{

				var sb = new StringBuilder();

				switch (phase)
				{
					case PhaseBaseAirRaid p:

						sb.AppendLine("味方基地航空隊 参加中隊:");
						sb.Append(" ").AppendLine(string.Join(", ", p.Squadrons.Where(sq => sq.EquipmentInstance != null).Select(sq => sq.ToString()).DefaultIfEmpty("(なし)")));

						GetBattleDetailPhaseAirBattle(sb, p);

						break;

					case PhaseAirBattle p:

						GetBattleDetailPhaseAirBattle(sb, p);

						break;

					case PhaseBaseAirAttack p:

						foreach (var a in p.AirAttackUnits)
						{
							sb.AppendFormat("〈第{0}波〉\r\n", a.AirAttackIndex + 1);

							sb.AppendLine("味方基地航空隊 参加中隊:");
							sb.Append(" ").AppendLine(string.Join(", ", a.Squadrons.Where(sq => sq.EquipmentInstance != null).Select(sq => sq.ToString())));

							GetBattleDetailPhaseAirBattle(sb, a);
							sb.Append(a.GetBattleDetail());
						}

						break;

					case PhaseJetAirBattle p:
						GetBattleDetailPhaseAirBattle(sb, p);

						break;

					case PhaseJetBaseAirAttack p:

						foreach (var a in p.AirAttackUnits)
						{
							sb.AppendFormat("〈第{0}波〉\r\n", a.AirAttackIndex + 1);

							sb.AppendLine("味方基地航空隊 参加中隊:");
							sb.Append(" ").AppendLine(string.Join(", ", a.Squadrons.Where(sq => sq.EquipmentInstance != null).Select(sq => sq.ToString())));

							GetBattleDetailPhaseAirBattle(sb, a);
							sb.Append(a.GetBattleDetail());
						}

						break;

					case PhaseInitial p:

						if (p.FriendFleetEscort != null)
							sb.Append("〈味方主力艦隊〉");
						else
							sb.Append("〈味方艦隊〉");

						void appendFleetInfo(FleetData fleet)
						{
							sb.Append(" 制空戦力 ");
							sb.Append(GetRangeString(Calculator.GetAirSuperiority(fleet, false), Calculator.GetAirSuperiority(fleet, true)));

							double truncate2(double value) => Math.Floor(value * 100) / 100;
							sb.AppendFormat(" / 索敵能力 [1] {0}, [2] {1}, [3] {2}, [4] {3}",
								truncate2(Calculator.GetSearchingAbility_New33(fleet, 1)),
								truncate2(Calculator.GetSearchingAbility_New33(fleet, 2)),
								truncate2(Calculator.GetSearchingAbility_New33(fleet, 3)),
								truncate2(Calculator.GetSearchingAbility_New33(fleet, 4)));
						}

						if (isBaseAirRaid)
						{
							sb.AppendLine();
							OutputFriendBase(sb, p.FriendInitialHPs, p.FriendMaxHPs);
						}
						else
						{
							appendFleetInfo(p.FriendFleet);
							sb.AppendLine();
							OutputFriendData(sb, p.FriendFleet, p.FriendInitialHPs, p.FriendMaxHPs);
						}

						if (p.FriendFleetEscort != null)
						{
							sb.AppendLine();
							sb.Append("〈味方随伴艦隊〉");
							appendFleetInfo(p.FriendFleetEscort);
							sb.AppendLine();

							OutputFriendData(sb, p.FriendFleetEscort, p.FriendInitialHPsEscort, p.FriendMaxHPsEscort);
						}

						sb.AppendLine();

						void appendEnemyFleetInfo(int[] members)
						{
							int air = 0;
							int airbase = 0;
							bool indeterminate = false;
							for (int i = 0; i < members.Length; i++)
							{
								var param = RecordManager.Instance.ShipParameter[members[i]];
								if (param == null) continue;

								if (param.DefaultSlot == null || param.Aircraft == null)
								{
									indeterminate = true;
									continue;
								}

								for (int s = 0; s < Math.Min(param.DefaultSlot.Length, param.Aircraft.Length); s++)
								{
									air += Calculator.GetAirSuperiority(param.DefaultSlot[s], param.Aircraft[s]);
									if (KCDatabase.Instance.MasterEquipments[param.DefaultSlot[s]]?.IsAircraft ?? false)
										airbase += Calculator.GetAirSuperiority(param.DefaultSlot[s], param.Aircraft[s], 0, 0, 1);
								}
							}
							sb.AppendFormat(" 制空戦力 {0} (対基地 {1})", air, airbase);
							if (indeterminate)
								sb.Append(" (未確定)");
						}

						if (p.EnemyMembersEscort != null)
							sb.Append("〈敵主力艦隊〉");
						else
							sb.Append("〈敵艦隊〉");

						appendEnemyFleetInfo(p.EnemyMembers);

						if (p.IsBossDamaged)
							sb.Append(" : 装甲破壊");
						sb.AppendLine();

						OutputEnemyData(sb, p.EnemyMembersInstance, p.EnemyLevels, p.EnemyInitialHPs, p.EnemyMaxHPs, p.EnemySlotsInstance, p.EnemyParameters);

						if (p.EnemyMembersEscort != null)
						{
							sb.AppendLine();
							sb.AppendLine("〈敵随伴艦隊〉");

							appendEnemyFleetInfo(p.EnemyMembersEscort);
                            sb.AppendLine();

							OutputEnemyData(sb, p.EnemyMembersEscortInstance, p.EnemyLevelsEscort, p.EnemyInitialHPsEscort, p.EnemyMaxHPsEscort, p.EnemySlotsEscortInstance, p.EnemyParametersEscort);
						}

						sb.AppendLine();

						if (battle.GetPhases().Where(ph => ph is PhaseBaseAirAttack || ph is PhaseBaseAirRaid).Any(ph => ph != null && ph.IsAvailable))
						{
							sb.AppendLine("〈基地航空隊〉");
							GetBattleDetailBaseAirCorps(sb, KCDatabase.Instance.Battle.Compass.MapAreaID);      // :(
							sb.AppendLine();
						}

						if (p.RationIndexes.Length > 0)
						{
							sb.AppendLine("〈戦闘糧食補給〉");
							foreach (var index in p.RationIndexes)
							{
								var ship = p.GetFriendShip(index);

								if (ship != null)
								{
									sb.AppendFormat(" {0} #{1}\r\n", ship.NameWithLevel, index + 1);
								}
							}
							sb.AppendLine();
						}

						break;

					case PhaseNightInitial p:

						{
							var eq = KCDatabase.Instance.MasterEquipments[p.TouchAircraftFriend];
							if (eq != null)
							{
								sb.Append("自軍夜間触接: ").AppendLine(eq.Name);
							}
							eq = KCDatabase.Instance.MasterEquipments[p.TouchAircraftEnemy];
							if (eq != null)
							{
								sb.Append("敵軍夜間触接: ").AppendLine(eq.Name);
							}
						}

						{
							int searchlightIndex = p.SearchlightIndexFriend;
							if (searchlightIndex != -1)
							{
								sb.AppendFormat("自軍探照灯照射: {0} #{1}\r\n", p.FriendFleet.MembersInstance[searchlightIndex].Name, searchlightIndex + 1);
							}
							searchlightIndex = p.SearchlightIndexEnemy;
							if (searchlightIndex != -1)
							{
								sb.AppendFormat("敵軍探照灯照射: {0} #{1}\r\n", p.EnemyMembersInstance[searchlightIndex].NameWithClass, searchlightIndex + 1);
							}
						}

						if (p.FlareIndexFriend != -1)
						{
							sb.AppendFormat("自軍照明弾投射: {0} #{1}\r\n", p.FlareFriendInstance.NameWithLevel, p.FlareIndexFriend + 1);
						}
						if (p.FlareIndexEnemy != -1)
						{
							sb.AppendFormat("敵軍照明弾投射: {0} #{1}\r\n", p.FlareEnemyInstance.NameWithClass, p.FlareIndexEnemy + 1);
						}

						sb.AppendLine();
						break;

					case PhaseSearching p:
						sb.Append("自軍陣形: ").Append(Constants.GetFormation(p.FormationFriend));
						sb.Append(" / 敵軍陣形: ").AppendLine(Constants.GetFormation(p.FormationEnemy));
						sb.Append("交戦形態: ").AppendLine(Constants.GetEngagementForm(p.EngagementForm));
						sb.Append("自軍索敵: ").Append(Constants.GetSearchingResult(p.SearchingFriend));
						sb.Append(" / 敵軍索敵: ").AppendLine(Constants.GetSearchingResult(p.SearchingEnemy));

						sb.AppendLine();

						break;

					case PhaseSupport p:
						if (p.IsAvailable)
						{
							sb.AppendLine("〈支援艦隊〉");
							OutputSupportData(sb, p.SupportFleet);
							sb.AppendLine();
						}
						break;

					case PhaseFriendlySupportInfo p:
						if (p.IsAvailable)
						{
							OutputFriendlySupportData(sb, p);
							sb.AppendLine();
						}
						break;

					case PhaseFriendlyShelling p:
						if (p.IsAvailable)
						{
							{
								int searchlightIndex = p.SearchlightIndexFriend;
								if (searchlightIndex != -1)
								{
									sb.AppendFormat("自軍探照灯照射: {0} #{1}\r\n", p.SearchlightFriendInstance.NameWithClass, searchlightIndex + 1);
								}
								searchlightIndex = p.SearchlightIndexEnemy;
								if (searchlightIndex != -1)
								{
									sb.AppendFormat("敵軍探照灯照射: {0} #{1}\r\n", p.SearchlightEnemyInstance.NameWithClass, searchlightIndex + 1);
								}
							}

							{
								int flareIndex = p.FlareIndexFriend;
								if (flareIndex != -1)
								{
									sb.AppendFormat("自軍照明弾投射: {0} #{1}\r\n", p.FlareFriendInstance.NameWithClass, flareIndex + 1);
								}
								flareIndex = p.FlareIndexEnemy;
								if (flareIndex != -1)
								{
									sb.AppendFormat("敵軍照明弾投射: {0} #{1}\r\n", p.FlareEnemyInstance.NameWithClass, flareIndex + 1);
								}
							}

							sb.AppendLine();
						}
						break;

					case PhaseFriendlyAirBattle p:

						GetBattleDetailPhaseAirBattle(sb, p);

						break;
				}

				if (!(phase is PhaseBaseAirAttack || phase is PhaseJetBaseAirAttack))       // 通常出力と重複するため
					sb.Append(phase.GetBattleDetail());

				if (sb.Length > 0)
				{
					sbmaster.AppendFormat("《{0}》\r\n", phase.Title).Append(sb);
				}
			}

			{
				sbmaster.AppendLine("《戦闘終了》");

				var friend = battle.Initial.FriendFleet;
				var friendescort = battle.Initial.FriendFleetEscort;
				var enemy = battle.Initial.EnemyMembersInstance;
				var enemyescort = battle.Initial.EnemyMembersEscortInstance;

				if (friendescort != null)
					sbmaster.AppendLine("〈味方主力艦隊〉");
				else
					sbmaster.AppendLine("〈味方艦隊〉");

				if (isBaseAirRaid)
				{

					for (int i = 0; i < 6; i++)
					{
						if (battle.Initial.FriendMaxHPs[i] <= 0)
							continue;

						OutputResultData(sbmaster, i, string.Format("第{0}基地", i + 1),
							battle.Initial.FriendInitialHPs[i], battle.ResultHPs[i], battle.Initial.FriendMaxHPs[i]);
					}

				}
				else
				{
					for (int i = 0; i < friend.Members.Count(); i++)
					{
						var ship = friend.MembersInstance[i];
						if (ship == null)
							continue;

						OutputResultData(sbmaster, i, ship.Name,
							battle.Initial.FriendInitialHPs[i], battle.ResultHPs[i], battle.Initial.FriendMaxHPs[i]);
					}
				}

				if (friendescort != null)
				{
					sbmaster.AppendLine().AppendLine("〈味方随伴艦隊〉");

					for (int i = 0; i < friendescort.Members.Count(); i++)
					{
						var ship = friendescort.MembersInstance[i];
						if (ship == null)
							continue;

						OutputResultData(sbmaster, i + 6, ship.Name,
							battle.Initial.FriendInitialHPsEscort[i], battle.ResultHPs[i + 6], battle.Initial.FriendMaxHPsEscort[i]);
					}

				}

				sbmaster.AppendLine();
				if (enemyescort != null)
					sbmaster.AppendLine("〈敵主力艦隊〉");
				else
					sbmaster.AppendLine("〈敵艦隊〉");

				for (int i = 0; i < enemy.Length; i++)
				{
					var ship = enemy[i];
					if (ship == null)
						continue;

					OutputResultData(sbmaster, i,
						ship.NameWithClass,
						battle.Initial.EnemyInitialHPs[i], battle.ResultHPs[i + 12], battle.Initial.EnemyMaxHPs[i]);
				}

				if (enemyescort != null)
				{
					sbmaster.AppendLine().AppendLine("〈敵随伴艦隊〉");

					for (int i = 0; i < enemyescort.Length; i++)
					{
						var ship = enemyescort[i];
						if (ship == null)
							continue;

						OutputResultData(sbmaster, i + 6, ship.NameWithClass,
							battle.Initial.EnemyInitialHPsEscort[i], battle.ResultHPs[i + 18], battle.Initial.EnemyMaxHPsEscort[i]);
					}
				}

				sbmaster.AppendLine();
			}

			return sbmaster.ToString();
		}

		private static string GetRangeString(int min, int max) => min != max ? $"{min} ~ {max}" : min.ToString();

		private static void GetBattleDetailBaseAirCorps(StringBuilder sb, int mapAreaID)
		{
			foreach (var corps in KCDatabase.Instance.BaseAirCorps.Values.Where(corps => corps.MapAreaID == mapAreaID))
			{
				sb.AppendFormat("{0} [{1}] 制空戦力 {2}\r\n {3}\r\n",
					corps.Name, Constants.GetBaseAirCorpsActionKind(corps.ActionKind),
					GetRangeString(Calculator.GetAirSuperiority(corps, false), Calculator.GetAirSuperiority(corps, true)),
					string.Join(", ", corps.Squadrons.Values
						.Where(sq => sq.State == 1 && sq.EquipmentInstance != null)
						.Select(sq => sq.EquipmentInstance.NameWithLevel)));
			}
		}

		private static void GetBattleDetailPhaseAirBattle(StringBuilder sb, PhaseAirBattleBase p)
		{

			if (p.IsStage1Available)
			{
				sb.Append("Stage1: ").AppendLine(Constants.GetAirSuperiority(p.AirSuperiority));
				sb.AppendFormat(" 自軍: -{0}/{1}\r\n 敵軍: -{2}/{3}\r\n",
					p.AircraftLostStage1Friend, p.AircraftTotalStage1Friend,
					p.AircraftLostStage1Enemy, p.AircraftTotalStage1Enemy);
				if (p.TouchAircraftFriend > 0)
					sb.AppendFormat(" 自軍触接: {0}\r\n", KCDatabase.Instance.MasterEquipments[p.TouchAircraftFriend].Name);
				if (p.TouchAircraftEnemy > 0)
					sb.AppendFormat(" 敵軍触接: {0}\r\n", KCDatabase.Instance.MasterEquipments[p.TouchAircraftEnemy].Name);
			}
			if (p.IsStage2Available)
			{
				sb.Append("Stage2: ");
				if (p.IsAACutinAvailable)
				{
					sb.AppendFormat("対空カットイン( {0}, {1}({2}) )", p.AACutInShipName, Constants.GetAACutinKind(p.AACutInKind), p.AACutInKind);
				}
				sb.AppendLine();
				sb.AppendFormat(" 自軍: -{0}/{1}\r\n 敵軍: -{2}/{3}\r\n",
					p.AircraftLostStage2Friend, p.AircraftTotalStage2Friend,
					p.AircraftLostStage2Enemy, p.AircraftTotalStage2Enemy);
			}

			if (p.IsStage1Available || p.IsStage2Available)
				sb.AppendLine();
		}

		private static void OutputFriendData(StringBuilder sb, FleetData fleet, int[] initialHPs, int[] maxHPs)
		{

			for (int i = 0; i < fleet.MembersInstance.Count; i++)
			{
				var ship = fleet.MembersInstance[i];

				if (ship == null)
					continue;

				sb.AppendFormat("#{0}: {1} {2} HP: {3} / {4} - 火力{5}, 雷装{6}, 対空{7}, 装甲{8}{9}\r\n",
					i + 1,
					ship.MasterShip.ShipTypeName, ship.NameWithLevel,
					initialHPs[i], maxHPs[i],
					ship.FirepowerBase, ship.TorpedoBase, ship.AABase, ship.ArmorBase,
					fleet.EscapedShipList.Contains(ship.MasterID) ? " (退避中)" : "");

				sb.Append(" ");
				sb.AppendLine(string.Join(", ", ship.AllSlotInstance.Zip(
					ship.ExpansionSlot > 0 ? ship.Aircraft.Concat(new[] { 0 }) : ship.Aircraft,
					(eq, aircraft) => eq == null ? null : ((eq.MasterEquipment.IsAircraft ? $"[{aircraft}] " : "") + eq.NameWithLevel)
				).Where(str => str != null)));
			}
		}

		private static void OutputFriendBase(StringBuilder sb, int[] initialHPs, int[] maxHPs)
		{

			for (int i = 0; i < initialHPs.Length; i++)
			{
				if (maxHPs[i] <= 0)
					continue;

				sb.AppendFormat("#{0}: 陸上施設 第{1}基地 HP: {2} / {3}\r\n\r\n",
					i + 1,
					i + 1,
					initialHPs[i], maxHPs[i]);
			}

		}

		public static void OutputSupportData(StringBuilder sb, FleetData fleet)
		{

			for (int i = 0; i < fleet.MembersInstance.Count; i++)
			{
				var ship = fleet.MembersInstance[i];

				if (ship == null)
					continue;

				sb.AppendFormat("#{0}: {1} {2} - 火力{3}, 雷装{4}, 対空{5}, 装甲{6}\r\n",
					i + 1,
					ship.MasterShip.ShipTypeName, ship.NameWithLevel,
					ship.FirepowerBase, ship.TorpedoBase, ship.AABase, ship.ArmorBase);

				sb.Append(" ");
				sb.AppendLine(string.Join(", ", ship.AllSlotInstance.Where(eq => eq != null)));
			}

		}

		private static void OutputFriendlySupportData(StringBuilder sb, PhaseFriendlySupportInfo p)
		{

			for (int i = 0; i < p.FriendlyMembersInstance.Length; i++)
			{
				var ship = p.FriendlyMembersInstance[i];

				if (ship == null)
					continue;

				sb.AppendFormat("#{0}: {1} {2} Lv. {3} HP: {4} / {5} - 火力{6}, 雷装{7}, 対空{8}, 装甲{9}\r\n",
					i + 1,
					ship.ShipTypeName, p.FriendlyMembersInstance[i].NameWithClass, p.FriendlyLevels[i],
					p.FriendlyInitialHPs[i], p.FriendlyMaxHPs[i],
					p.FriendlyParameters[i][0], p.FriendlyParameters[i][1], p.FriendlyParameters[i][2], p.FriendlyParameters[i][3]);

				sb.Append(" ");
				sb.AppendLine(string.Join(", ", p.FriendlySlots[i]
					.Concat(new[] { p.FriendlyExpansionSlots?[i] ?? -1 })
					.Select(id => KCDatabase.Instance.MasterEquipments[id])
					.Where(eq => eq != null)
					.Select(eq => eq.Name)));
			}
		}

		private static void OutputEnemyData(StringBuilder sb, ShipDataMaster[] members, int[] levels, int[] initialHPs, int[] maxHPs, EquipmentDataMaster[][] slots, int[][] parameters)
		{

			for (int i = 0; i < members.Length; i++)
			{
				if (members[i] == null)
					continue;

				sb.AppendFormat("#{0}: ID:{1} {2} {3} Lv. {4} HP: {5} / {6}",
					i + 1,
					members[i].ShipID,
					members[i].ShipTypeName, members[i].NameWithClass,
					levels[i],
					initialHPs[i], maxHPs[i]);

				if (parameters != null)
				{
					sb.AppendFormat(" - 火力{0}, 雷装{1}, 対空{2}, 装甲{3}",
					parameters[i][0], parameters[i][1], parameters[i][2], parameters[i][3]);
				}

				sb.AppendLine().Append(" ");
				sb.AppendLine(string.Join(", ", slots[i].Where(eq => eq != null)));
			}
		}

		private static void OutputResultData(StringBuilder sb, int index, string name, int initialHP, int resultHP, int maxHP)
		{
			sb.AppendFormat("#{0}: {1} HP: ({2} → {3})/{4} ({5})\r\n",
				index + 1, name,
				Math.Max(initialHP, 0),
				Math.Max(resultHP, 0),
				Math.Max(maxHP, 0),
				resultHP - initialHP);
		}

		private static string GetBattleResult(BattleManager bm)
		{
			var result = bm.Result;

			var sb = new StringBuilder();

			sb.AppendLine("◆ 戦闘結果 ◆");
			sb.AppendFormat("ランク: {0}\r\n", result.Rank);

			if (bm.IsCombinedBattle)
			{
				sb.AppendFormat("MVP(主力艦隊): {0}\r\n",
					result.MVPIndex == -1 ? "(なし)" : bm.FirstBattle.Initial.FriendFleet.MembersInstance[result.MVPIndex - 1].NameWithLevel);
				sb.AppendFormat("MVP(随伴艦隊): {0}\r\n",
					result.MVPIndexCombined == -1 ? "(なし)" : bm.FirstBattle.Initial.FriendFleetEscort.MembersInstance[result.MVPIndexCombined - 1].NameWithLevel);

			}
			else
			{
				sb.AppendFormat("MVP: {0}\r\n",
					result.MVPIndex == -1 ? "(なし)" : bm.FirstBattle.Initial.FriendFleet.MembersInstance[result.MVPIndex - 1].NameWithLevel);
			}

			sb.AppendFormat("提督経験値: +{0}\r\n艦娘基本経験値: +{1}\r\n",
				result.AdmiralExp, result.BaseExp);

			if (!bm.IsPractice)
			{
				sb.AppendLine().AppendLine("ドロップ:");

				int length = sb.Length;

				var ship = KCDatabase.Instance.MasterShips[result.DroppedShipID];
				if (ship != null)
				{
					sb.AppendFormat(" {0} {1}\r\n", ship.ShipTypeName, ship.NameWithClass);
				}

				var eq = KCDatabase.Instance.MasterEquipments[result.DroppedEquipmentID];
				if (eq != null)
				{
					sb.AppendFormat(" {0} {1}\r\n", eq.CategoryTypeInstance.Name, eq.Name);
				}

				var item = KCDatabase.Instance.MasterUseItems[result.DroppedItemID];
				if (item != null)
				{
					sb.Append(" ").AppendLine(item.Name);
				}

				if (length == sb.Length)
				{
					sb.AppendLine(" (なし)");
				}
			}

			return sb.ToString();
		}

	}
}


text:
require 'activity_notification/optional_targets/amazon_sns'
describe ActivityNotification::OptionalTarget::AmazonSNS do
  let(:test_instance) { ActivityNotification::OptionalTarget::AmazonSNS.new(skip_initializing_target: true) }

  describe "as public instance methods" do
    describe "#to_optional_target_name" do
      it "is return demodulized symbol class name" do
        expect(test_instance.to_optional_target_name).to eq(:amazon_sns)
      end
    end

    describe "#initialize_target" do
      it "does not raise NotImplementedError" do
        begin
          test_instance.initialize_target
        rescue Aws::Errors::MissingRegionError
          # Rescue for CI without AWS client configuration
        end
      end
    end

    describe "#notify" do
      it "does not raise NotImplementedError but NoMethodError" do
        expect { test_instance.notify(create(:notification)) }
          .to raise_error(NoMethodError)
      end
    end
  end

  describe "as protected instance methods" do
    describe "#render_notification_message" do
      context "as default" do
        it "renders notification message with default template" do
          expect(test_instance.send(:render_notification_message, create(:notification))).to be_include("Move to notified")
        end
      end

      context "with unexisting template as fallback option" do
        it "raise ActionView::MissingTemplate" do
          expect { expect(test_instance.send(:render_notification_message, create(:notification), fallback: :hoge)) }
            .to raise_error(ActionView::MissingTemplate)
        end
      end
    end
  end

end


text:
package com.amazonaws.services.cognitoidp.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetUserPoolMfaConfigRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The user pool ID.
     *

     */
    private String userPoolId;
    /**
     *

     * The SMS text message MFA configuration.
     *

     */
    private SmsMfaConfigType smsMfaConfiguration;
    /**
     *

     * The software token MFA configuration.
     *

     */
    private SoftwareTokenMfaConfigType softwareTokenMfaConfiguration;
    /**
     *

     * The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA factor
     * can sign in. To learn more, see Adding Multi-Factor
     * Authentication (MFA) to a user pool. Valid values include:
     *

     *

     *

     *

     * OFF MFA won't be used for any users.
     *

     *

     *

     *

     * ON MFA is required for all users to sign in.
     *

     *

     *

     *

     * OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     *

     */
    private String mfaConfiguration;

    /**
     *

     * The user pool ID.
     *

     *
     * @param userPoolId
     *        The user pool ID.
     */

    public void setUserPoolId(String userPoolId) {
        this.userPoolId = userPoolId;
    }

    /**
     *

     * The user pool ID.
     *

     *
     * @return The user pool ID.
     */

    public String getUserPoolId() {
        return this.userPoolId;
    }

    /**
     *

     * The user pool ID.
     *

     *
     * @param userPoolId
     *        The user pool ID.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetUserPoolMfaConfigRequest withUserPoolId(String userPoolId) {
        setUserPoolId(userPoolId);
        return this;
    }

    /**
     *

     * The SMS text message MFA configuration.
     *

     *
     * @param smsMfaConfiguration
     *        The SMS text message MFA configuration.
     */

    public void setSmsMfaConfiguration(SmsMfaConfigType smsMfaConfiguration) {
        this.smsMfaConfiguration = smsMfaConfiguration;
    }

    /**
     *

     * The SMS text message MFA configuration.
     *

     *
     * @return The SMS text message MFA configuration.
     */

    public SmsMfaConfigType getSmsMfaConfiguration() {
        return this.smsMfaConfiguration;
    }

    /**
     *

     * The SMS text message MFA configuration.
     *

     *
     * @param smsMfaConfiguration
     *        The SMS text message MFA configuration.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetUserPoolMfaConfigRequest withSmsMfaConfiguration(SmsMfaConfigType smsMfaConfiguration) {
        setSmsMfaConfiguration(smsMfaConfiguration);
        return this;
    }

    /**
     *

     * The software token MFA configuration.
     *

     *
     * @param softwareTokenMfaConfiguration
     *        The software token MFA configuration.
     */

    public void setSoftwareTokenMfaConfiguration(SoftwareTokenMfaConfigType softwareTokenMfaConfiguration) {
        this.softwareTokenMfaConfiguration = softwareTokenMfaConfiguration;
    }

    /**
     *

     * The software token MFA configuration.
     *

     *
     * @return The software token MFA configuration.
     */

    public SoftwareTokenMfaConfigType getSoftwareTokenMfaConfiguration() {
        return this.softwareTokenMfaConfiguration;
    }

    /**
     *

     * The software token MFA configuration.
     *

     *
     * @param softwareTokenMfaConfiguration
     *        The software token MFA configuration.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SetUserPoolMfaConfigRequest withSoftwareTokenMfaConfiguration(SoftwareTokenMfaConfigType softwareTokenMfaConfiguration) {
        setSoftwareTokenMfaConfiguration(softwareTokenMfaConfiguration);
        return this;
    }

    /**
     *

     * The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA factor
     * can sign in. To learn more, see Adding Multi-Factor
     * Authentication (MFA) to a user pool. Valid values include:
     *

     *

     *

     *

     * OFF MFA won't be used for any users.
     *

     *

     *

     *

     * ON MFA is required for all users to sign in.
     *

     *

     *

     *

     * OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     *

     *
     * @param mfaConfiguration
     *        The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA
     *        factor can sign in. To learn more, see Adding
     *        Multi-Factor Authentication (MFA) to a user pool. Valid values include:

     *

     *

     *

     *        OFF MFA won't be used for any users.
     *

     *

     *

     *

     *        ON MFA is required for all users to sign in.
     *

     *

     *

     *

     *        OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     * @see UserPoolMfaType
     */

    public void setMfaConfiguration(String mfaConfiguration) {
        this.mfaConfiguration = mfaConfiguration;
    }

    /**
     *

     * The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA factor
     * can sign in. To learn more, see Adding Multi-Factor
     * Authentication (MFA) to a user pool. Valid values include:
     *

     *

     *

     *

     * OFF MFA won't be used for any users.
     *

     *

     *

     *

     * ON MFA is required for all users to sign in.
     *

     *

     *

     *

     * OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     *

     *
     * @return The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA
     *         factor can sign in. To learn more, see Adding
     *         Multi-Factor Authentication (MFA) to a user pool. Valid values include:

     *

     *

     *

     *         OFF MFA won't be used for any users.
     *

     *

     *

     *

     *         ON MFA is required for all users to sign in.
     *

     *

     *

     *

     *         OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     * @see UserPoolMfaType
     */

    public String getMfaConfiguration() {
        return this.mfaConfiguration;
    }

    /**
     *

     * The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA factor
     * can sign in. To learn more, see Adding Multi-Factor
     * Authentication (MFA) to a user pool. Valid values include:
     *

     *

     *

     *

     * OFF MFA won't be used for any users.
     *

     *

     *

     *

     * ON MFA is required for all users to sign in.
     *

     *

     *

     *

     * OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     *

     *
     * @param mfaConfiguration
     *        The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA
     *        factor can sign in. To learn more, see Adding
     *        Multi-Factor Authentication (MFA) to a user pool. Valid values include:

     *

     *

     *

     *        OFF MFA won't be used for any users.
     *

     *

     *

     *

     *        ON MFA is required for all users to sign in.
     *

     *

     *

     *

     *        OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see UserPoolMfaType
     */

    public SetUserPoolMfaConfigRequest withMfaConfiguration(String mfaConfiguration) {
        setMfaConfiguration(mfaConfiguration);
        return this;
    }

    /**
     *

     * The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA factor
     * can sign in. To learn more, see Adding Multi-Factor
     * Authentication (MFA) to a user pool. Valid values include:
     *

     *

     *

     *

     * OFF MFA won't be used for any users.
     *

     *

     *

     *

     * ON MFA is required for all users to sign in.
     *

     *

     *

     *

     * OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     *

     *
     * @param mfaConfiguration
     *        The MFA configuration. If you set the MfaConfiguration value to 'ON', only users who have set up an MFA
     *        factor can sign in. To learn more, see Adding
     *        Multi-Factor Authentication (MFA) to a user pool. Valid values include:

     *

     *

     *

     *        OFF MFA won't be used for any users.
     *

     *

     *

     *

     *        ON MFA is required for all users to sign in.
     *

     *

     *

     *

     *        OPTIONAL MFA will be required only for individual users who have an MFA factor activated.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     * @see UserPoolMfaType
     */

    public SetUserPoolMfaConfigRequest withMfaConfiguration(UserPoolMfaType mfaConfiguration) {
        this.mfaConfiguration = mfaConfiguration.toString();
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getUserPoolId() != null)
            sb.append("UserPoolId: ").append(getUserPoolId()).append(",");
        if (getSmsMfaConfiguration() != null)
            sb.append("SmsMfaConfiguration: ").append(getSmsMfaConfiguration()).append(",");
        if (getSoftwareTokenMfaConfiguration() != null)
            sb.append("SoftwareTokenMfaConfiguration: ").append(getSoftwareTokenMfaConfiguration()).append(",");
        if (getMfaConfiguration() != null)
            sb.append("MfaConfiguration: ").append(getMfaConfiguration());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SetUserPoolMfaConfigRequest == false)
            return false;
        SetUserPoolMfaConfigRequest other = (SetUserPoolMfaConfigRequest) obj;
        if (other.getUserPoolId() == null ^ this.getUserPoolId() == null)
            return false;
        if (other.getUserPoolId() != null && other.getUserPoolId().equals(this.getUserPoolId()) == false)
            return false;
        if (other.getSmsMfaConfiguration() == null ^ this.getSmsMfaConfiguration() == null)
            return false;
        if (other.getSmsMfaConfiguration() != null && other.getSmsMfaConfiguration().equals(this.getSmsMfaConfiguration()) == false)
            return false;
        if (other.getSoftwareTokenMfaConfiguration() == null ^ this.getSoftwareTokenMfaConfiguration() == null)
            return false;
        if (other.getSoftwareTokenMfaConfiguration() != null
                && other.getSoftwareTokenMfaConfiguration().equals(this.getSoftwareTokenMfaConfiguration()) == false)
            return false;
        if (other.getMfaConfiguration() == null ^ this.getMfaConfiguration() == null)
            return false;
        if (other.getMfaConfiguration() != null && other.getMfaConfiguration().equals(this.getMfaConfiguration()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getUserPoolId() == null) ? 0 : getUserPoolId().hashCode());
        hashCode = prime * hashCode + ((getSmsMfaConfiguration() == null) ? 0 : getSmsMfaConfiguration().hashCode());
        hashCode = prime * hashCode + ((getSoftwareTokenMfaConfiguration() == null) ? 0 : getSoftwareTokenMfaConfiguration().hashCode());
        hashCode = prime * hashCode + ((getMfaConfiguration() == null) ? 0 : getMfaConfiguration().hashCode());
        return hashCode;
    }

    @Override
    public SetUserPoolMfaConfigRequest clone() {
        return (SetUserPoolMfaConfigRequest) super.clone();
    }

}


text:
package com.example.greatbook.main.presenter.contract;

import com.example.greatbook.base.BasePresenter;
import com.example.greatbook.base.BaseView;

/**
 * Created by MDove on 2017/8/14.
 */

public interface LoginContract {
    interface View extends BaseView {
        void loginSuc(String suc);
        void loginErr(String err);
    }
    interface Presenter extends BasePresenter<LoginContract.View> {
        void login(String username,String password);
    }
}


text:
import WebSocket from 'ws';

import { Protocol, Client, ClientState, ISendOptions, getMessageBytes } from "@colyseus/core"
import { Schema } from '@colyseus/schema';

const SEND_OPTS = { binary: true };

export class WebSocketClient implements Client {
  public sessionId: string;
  public state: ClientState = ClientState.JOINING;
  public _enqueuedMessages: any[] = [];
  public _afterNextPatchQueue;

  constructor(
    public id: string,
    public ref: WebSocket,
  ) {
    this.sessionId = id;
  }

  public send(messageOrType: any, messageOrOptions?: any | ISendOptions, options?: ISendOptions) {
    this.enqueueRaw(
      (messageOrType instanceof Schema)
        ? getMessageBytes[Protocol.ROOM_DATA_SCHEMA](messageOrType)
        : getMessageBytes[Protocol.ROOM_DATA](messageOrType, messageOrOptions),
      options,
    );
  }

  public enqueueRaw(data: ArrayLike<number>, options?: ISendOptions) {
    // use room's afterNextPatch queue
    if (options?.afterNextPatch) {
      this._afterNextPatchQueue.push([this, arguments]);
      return;
    }

    if (this.state === ClientState.JOINING) {
      // sending messages during `onJoin`.
      // - the client-side cannot register "onMessage" callbacks at this point.
      // - enqueue the messages to be send after JOIN_ROOM message has been sent
      this._enqueuedMessages.push(data);
      return;
    }

    this.raw(data, options);
  }

  public raw(data: ArrayLike<number>, options?: ISendOptions, cb?: (err?: Error) => void) {
    if (this.ref.readyState !== WebSocket.OPEN) {
      console.warn('trying to send data to inactive client', this.sessionId);
      return;
    }

    this.ref.send(data, SEND_OPTS, cb);
  }

  public error(code: number, message: string = '', cb?: (err?: Error) => void) {
    this.raw(getMessageBytes[Protocol.ERROR](code, message), undefined, cb);
  }

  get readyState() {
    return this.ref.readyState;
  }

  public leave(code?: number, data?: string) {
    this.ref.close(code, data);
  }

  public close(code?: number, data?: string) {
    console.warn('DEPRECATION WARNING: use client.leave() instead of client.close()');
    try {
      throw new Error();
    } catch (e) {
      console.log(e.stack);
    }
    this.leave(code, data);
  }

  public toJSON() {
    return { sessionId: this.sessionId, readyState: this.readyState };
  }
}