text:
// <auto-generated />
namespace BookShop.Data.Migrations
{
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Infrastructure;
    using Microsoft.EntityFrameworkCore.Metadata;
    using System;

    [DbContext(typeof(BookShopDbContext))]
    partial class BookShopDbContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "2.0.1-rtm-125")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("BookShop.Data.Models.Author", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("FirstName")
                        .IsRequired()
                        .HasMaxLength(50);

                    b.Property<string>("LastName")
                        .IsRequired()
                        .HasMaxLength(50);

                    b.HasKey("Id");

                    b.ToTable("Authors");
                });

            modelBuilder.Entity("BookShop.Data.Models.Book", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<int?>("AgeRestriction");

                    b.Property<int>("AuthorId");

                    b.Property<int>("Copies");

                    b.Property<string>("Description")
                        .IsRequired();

                    b.Property<int?>("Edition");

                    b.Property<decimal>("Price");

                    b.Property<DateTime>("ReleaseDate");

                    b.Property<string>("Title")
                        .IsRequired()
                        .HasMaxLength(100);

                    b.HasKey("Id");

                    b.HasIndex("AuthorId");

                    b.ToTable("Books");
                });

            modelBuilder.Entity("BookShop.Data.Models.Category", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd();

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasMaxLength(50);

                    b.HasKey("Id");

                    b.ToTable("Categories");
                });

            modelBuilder.Entity("BookShop.Data.Models.CategoryBook", b =>
                {
                    b.Property<int>("CategoryId");

                    b.Property<int>("BookId");

                    b.HasKey("CategoryId", "BookId");

                    b.HasIndex("BookId");

                    b.ToTable("CategoryBook");
                });

            modelBuilder.Entity("BookShop.Data.Models.Book", b =>
                {
                    b.HasOne("BookShop.Data.Models.Author", "Author")
                        .WithMany("Books")
                        .HasForeignKey("AuthorId")
                        .OnDelete(DeleteBehavior.Cascade);
                });

            modelBuilder.Entity("BookShop.Data.Models.CategoryBook", b =>
                {
                    b.HasOne("BookShop.Data.Models.Book", "Book")
                        .WithMany("Categories")
                        .HasForeignKey("BookId")
                        .OnDelete(DeleteBehavior.Cascade);

                    b.HasOne("BookShop.Data.Models.Category", "Category")
                        .WithMany("Books")
                        .HasForeignKey("CategoryId")
                        .OnDelete(DeleteBehavior.Cascade);
                });
#pragma warning restore 612, 618
        }
    }
}


text:
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.5 -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/bootstrap/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/dist/css/AdminLTE.min.css">
    <!-- AdminLTE Skins. Choose a skin from the css/skins
         folder instead of downloading all of them to reduce the load. -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/dist/css/skins/_all-skins.min.css">
    <!-- iCheck -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/plugins/iCheck/flat/blue.css">
    <!-- Morris chart -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/plugins/morris/morris.css">
    <!-- jvectormap -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/plugins/jvectormap/jquery-jvectormap-1.2.2.css">
    <!-- Date Picker -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/plugins/datepicker/datepicker3.css">
    <!-- Daterange picker -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/plugins/daterangepicker/daterangepicker-bs3.css">
    <!-- bootstrap wysihtml5 - text editor -->
    <link rel="stylesheet" href="<?php echo base_url();?>assets_admin_lte/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

redpajama_set_name: RedPajamaGithub


text:
package cherry.elemental.util;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;

import java.time.LocalDate;
import java.time.LocalDateTime;

import org.junit.Test;

public class LocalDateUtilTest {

	@Test
	public void testRangeFromLocalDate() {
		LocalDate now = LocalDate.now();
		assertThat(LocalDateUtil.rangeFrom((LocalDate) null), is(nullValue()));
		assertThat(LocalDateUtil.rangeFrom(now),
				is(LocalDate.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth())));
	}

	@Test
	public void testRangeFromLocalDateTime() {
		LocalDateTime now = LocalDateTime.now();
		assertThat(LocalDateUtil.rangeFrom((LocalDateTime) null), is(nullValue()));
		assertThat(LocalDateUtil.rangeFrom(now),
				is(LocalDate.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth())));
	}

	@Test
	public void testRangeToLocalDate() {
		LocalDate now = LocalDate.now();
		assertThat(LocalDateUtil.rangeTo((LocalDate) null), is(nullValue()));
		assertThat(LocalDateUtil.rangeTo(now), is(LocalDate.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth())
				.plusDays(1)));
	}

	@Test
	public void testRangeToLocalDateTime() {
		LocalDateTime now = LocalDateTime.now();
		assertThat(LocalDateUtil.rangeTo((LocalDateTime) null), is(nullValue()));
		assertThat(LocalDateUtil.rangeTo(now), is(LocalDate.of(now.getYear(), now.getMonthValue(), now.getDayOfMonth())
				.plusDays(1)));
	}

	@Test
	public void testNormalizeYm() {
		LocalDate now = LocalDate.now();
		assertThat(LocalDateUtil.normalizeYm(null), is(nullValue()));
		assertThat(LocalDateUtil.normalizeYm(now), is(LocalDate.of(now.getYear(), now.getMonthValue(), 1)));
	}

	@Test
	public void testYmRangeFrom() {
		LocalDate now = LocalDate.now();
		assertThat(LocalDateUtil.ymRangeFrom(null), is(nullValue()));
		assertThat(LocalDateUtil.ymRangeFrom(now), is(LocalDate.of(now.getYear(), now.getMonthValue(), 1)));
	}

	@Test
	public void testYmRangeTo() {
		LocalDate now = LocalDate.now();
		assertThat(LocalDateUtil.ymRangeTo(null), is(nullValue()));
		assertThat(LocalDateUtil.ymRangeTo(now), is(LocalDate.of(now.getYear(), now.getMonthValue(), 1).plusMonths(1)));
	}

	@Test
	public void testMisc() {
		assertThat(new LocalDateUtil(), is(notNullValue()));
	}

}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('studygroups', '0151_set_survey_sent_at'),
    ]

    operations = [
        migrations.AddField(
            model_name='application',
            name='anonymized',
            field=models.BooleanField(default=False),
        ),
    ]


text:
exports.addRoutes = function(app, config){
  //This route deals enables HTML5Mode by missing files to the index.html
  app.all('/*', function(req,res) {
    //Just send the index.html for the other files to support HTML5Mode
    res.sendfile('index.html', { root: config.server.distFolder});
  });
};


text:
package com.intellij.java.codeInsight;

import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;
import com.intellij.xml.analysis.XmlAnalysisBundle;
import org.intellij.lang.annotations.Language;
import org.intellij.lang.regexp.inspection.DuplicateCharacterInClassInspection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class IntentionPreviewTest extends LightJavaCodeInsightFixtureTestCase {
  @Override
  protected @NotNull LightProjectDescriptor getProjectDescriptor() {
    return JAVA_11_ANNOTATED;
  }

  public void testIntentionPreview() {
    myFixture.configureByText("Test.java", """
      class Test {
        public void test() {
          int <caret>variable = 2;
        }
      }""");
    IntentionAction action = myFixture.findSingleIntention("Split into declaration and assignment");
    assertPreviewText(action, """
      class Test {
        public void test() {
          int variable;
            variable = 2;
        }
      }""");
  }

  public void testIntentionPreviewAfterFileChange() {
    myFixture.configureByText("Test.java", """
      class Test {
          void f(Iterable<String> it) {
            it<caret>;
          }
        }""");
    IntentionAction action = myFixture.findSingleIntention("Iterate over Iterable<String>");
    myFixture.type("\b\b");
    PsiDocumentManager.getInstance(getProject()).commitDocument(myFixture.getFile().getViewProvider().getDocument());
    // should not be available anymore
    assertPreviewText(action, null);
  }

  public void testStaticImportsIntentionPreview() {
    myFixture.configureByText("Test.java", """
      class Computer {
          void f() {
            double pi = Ma<caret>th.PI;
          }
        }""");
    IntentionAction action = myFixture.findSingleIntention("Add on-demand static import for 'java.lang.Math'");
    assertPreviewText(action, """
      import static java.lang.Math.*;

      class Computer {
          void f() {
            double pi = PI;
          }
        }""");
  }

  public void testIntentionPreviewWithTemplate() {
    // TEMPLATE_STARTED_TOPIC event should not fire for preview editor
    getProject().getMessageBus().connect(getTestRootDisposable())
      .subscribe(TemplateManager.TEMPLATE_STARTED_TOPIC, state -> fail());
    myFixture.configureByText("Test.java", """
      class Computer {
          void f() {
            int i;
            int j = <caret>i;
          }
        }""");
    IntentionAction action = myFixture.findSingleIntention("Initialize variable 'i'");
    assertPreviewText(action, """
      class Computer {
          void f() {
            int i = 0;
            int j = i;
          }
        }""");
  }

  public void testIntentionPreviewIterate() {
    myFixture.configureByText("Test.java", """
      class Test {
          void f(Iterable<String> it) {
            <caret>it;
          }
        }""");
    IntentionAction action = myFixture.findSingleIntention("Iterate over Iterable<String>");

    assertPreviewText(action, """
      class Test {
          void f(Iterable<String> it) {
              for (String s : it) {

              }

          }
        }""");
  }

  public void testIntentionPreviewInjection() {
    myFixture.setCaresAboutInjection(false);
    myFixture.configureByText("Test.java", """
      import java.util.regex.Pattern;

      class Test {
        Pattern p = Pattern.compile("[\\"123<caret>1]");
      }""");
    myFixture.enableInspections(new DuplicateCharacterInClassInspection());
    IntentionAction action = myFixture.findSingleIntention("Remove duplicate '1' from character class");
    assertEquals("[\"123]", myFixture.getIntentionPreviewText(action));
  }

  public void testBindFieldsFromParameters() {
    myFixture.configureByText("Test.java", """
      public    class    Test {
          Test(int <caret>a, String b) {

          }
      }
      """);
    IntentionAction action = myFixture.findSingleIntention("Bind constructor parameters to fields");
    assertPreviewText(action, """
      public    class    Test {
          private final int a;
          private final String b;

          Test(int a, String b) {

              this.a = a;
              this.b = b;
          }
      }
      """);
  }

  public void testAddRemoveException() {
    myFixture.configureByText("Test.java", """
      import java.io.IOException;

      public class A {
        String test() {
          return "";
        }
      }

      class B extends A {
        String test() throws <caret>IOException {
          return "";
        }

      }""");
    IntentionAction action = myFixture.findSingleIntention("Remove 'IOException' from 'test()' throws list");
    assertPreviewText(action, """
      import java.io.IOException;

      public class A {
        String test() {
          return "";
        }
      }

      class B extends A {
        String test() {
          return "";
        }

      }""");
    action = myFixture.findSingleIntention("Add 'IOException' to 'A.test()' throws list");
    assertPreviewText(action, """
      import java.io.IOException;

      public class A {
        String test() throws IOException {
          return "";
        }
      }

      class B extends A {
        String test() throws IOException {
          return "";
        }

      }""");
  }

  public void testDefineDefaultValues() {
    myFixture.configureByText("Test.java",
                              """
                                public class Test {
                                    void test(int <caret>a,  String b) {

                                    }
                                }
                                """);
    IntentionAction action = myFixture.findSingleIntention("Generate overloaded method with default parameter values");
    assertPreviewText(action, """
      public class Test {
          void test() {
              test(0, null);
          }

          void test(int a, String b) {

          }
      }
      """);
  }

  private void assertPreviewText(@NotNull IntentionAction action, @Language("JAVA") @Nullable String expectedText) {
    assertEquals(expectedText, myFixture.getIntentionPreviewText(action));
  }

  public void testRenameFile() {
    myFixture.configureByText("Test.java", "public class <caret>Best {}");
    IntentionAction action = myFixture.findSingleIntention("Rename File");
    myFixture.checkIntentionPreviewHtml(action, "
<icon src=\"file\"/> Test.java → <icon src=\"file\"/> Best.java
");
  }

  public void testMoveMemberIntoClass() {
    myFixture.configureByText("Test.java", "public class Test {} void <caret>method() {}");
    IntentionAction action = myFixture.findSingleIntention("Move member into class");
    myFixture.checkIntentionPreviewHtml(action,
                                        "
<icon src=\"source\"/> method → <icon src=\"target\"/> Test
");
  }

  public void testNavigate() {
    myFixture.configureByText("Test.java", "public class Test {} class <caret>Test {}");
    IntentionAction action = myFixture.findSingleIntention("Navigate to duplicate class");
    myFixture.checkIntentionPreviewHtml(action, "
→ <icon src=\"icon\"/> Test.java, line #1
");
  }

  public void testPreviewInjectionCaret() {
    myFixture.setCaresAboutInjection(false);
    myFixture.configureByText("Test.java",
                              """
                                class Test {
                                  // language=HTML
                                  String s = "<caret>");
                                }""");

    IntentionAction action = myFixture.findSingleIntention(XmlAnalysisBundle.message("xml.quickfix.remove.tag.family"));
    assertEquals("", myFixture.getIntentionPreviewText(action));
  }
}


text:
package com.hazelcast.test;

import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Log4j2Factory;
import com.hazelcast.logging.LogEvent;
import com.hazelcast.logging.LoggerFactorySupport;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.spi.LoggerContext;

import java.net.URI;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

/**
 * The factory uses Log4j2 internally, but its loggers always return
 * {@code true} to guards such as {@code isFinestEnabled()} etc.
 *

 * The real filtering is happening in the log4js once again. Thus it
 * covers branches guarded by is-level-enabled checks yet the real
 * logging is configurable via {@code log4j2.xml}.
 *

 * It also supports changing logging configuration on-the-fly, see
 * {@link TestLoggerFactory#changeConfigFile}.
 */
public class TestLoggerFactory extends LoggerFactorySupport {

    /**
     * Log4j XML configuration being currently used, {@code null}
     * indicates the Log4j default behavior.
     */
    private URI configFile = null;

    /**
     * Store all the logging context being created, because we need to
     * clear them in order to change the configuration to reload it.
     */
    private final Collection<LoggerContext> loggerContexts = new ConcurrentLinkedQueue<LoggerContext>();

    /**
     * Reference to a {@link Log4j2Factory}, which is used to create
     * loggers for older Hazelcast versions.
     */
    private final AtomicReference<Log4j2Factory> legacyLog4j2Factory = new AtomicReference<Log4j2Factory>();

    /**
     * Changes the configuration to be used.
     *
     * @param configName the Log4j XML configuration to be used,
     *                   {@code null} for default behavior
     */
    public void changeConfigFile(String configName) {
        for (LoggerContext context : loggerContexts) {
            LogManager.getFactory().removeContext(context);
        }

        configFile = configName != null ? URI.create(configName) : null;
        clearLoadedLoggers();
        loggerContexts.clear();
    }

    protected ILogger createLogger(String name) {
        LoggerContext loggerContext = LogManager.getContext(null, false, configFile);
        loggerContexts.add(loggerContext);

        ILogger delegate;
        try {
            delegate = new Log4j2Factory.Log4j2Logger(loggerContext.getLogger(name));
        } catch (IllegalAccessError e) {
            // older Hazelcast versions cannot access Log4j2Logger, so we fallback to the legacy code
            delegate = getOrCreateLegacyLog4j2Factory().getLogger(name);
        }
        return new DelegatingTestLogger(delegate);
    }

    private Log4j2Factory getOrCreateLegacyLog4j2Factory() {
        Log4j2Factory factory = legacyLog4j2Factory.get();
        if (factory != null) {
            return factory;
        }
        Log4j2Factory candidate = new Log4j2Factory();
        if (legacyLog4j2Factory.compareAndSet(null, candidate)) {
            return candidate;
        }
        return legacyLog4j2Factory.get();
    }

    private static class DelegatingTestLogger implements ILogger {

        private static final long WARNING_THRESHOLD_NANOS = MILLISECONDS.toNanos(500);

        private ILogger delegate;

        private DelegatingTestLogger(ILogger delegate) {
            this.delegate = delegate;
        }

        @Override
        public void finest(String message) {
            long startTime = System.nanoTime();
            delegate.finest(message);
            logOnSlowLogging(startTime);
        }

        @Override
        public void finest(Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.finest(thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public void finest(String message, Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.finest(message, thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public boolean isFinestEnabled() {
            return true;
        }

        @Override
        public void fine(String message) {
            long startTime = System.nanoTime();
            delegate.fine(message);
            logOnSlowLogging(startTime);
        }

        @Override
        public void fine(Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.fine(thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public void fine(String message, Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.fine(message, thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public boolean isFineEnabled() {
            return true;
        }

        @Override
        public void info(String message) {
            long startTime = System.nanoTime();
            delegate.info(message);
            logOnSlowLogging(startTime);
        }

        @Override
        public void info(String message, Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.info(message, thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public void info(Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.info(thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public boolean isInfoEnabled() {
            return true;
        }

        @Override
        public void warning(String message) {
            long startTime = System.nanoTime();
            delegate.warning(message);
            logOnSlowLogging(startTime);
        }

        @Override
        public void warning(Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.warning(thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public void warning(String message, Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.warning(message, thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public boolean isWarningEnabled() {
            return true;
        }

        @Override
        public void severe(String message) {
            long startTime = System.nanoTime();
            delegate.severe(message);
            logOnSlowLogging(startTime);
        }

        @Override
        public void severe(Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.severe(thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public void severe(String message, Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.severe(message, thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public boolean isSevereEnabled() {
            return true;
        }

        @Override
        public void log(Level level, String message) {
            long startTime = System.nanoTime();
            delegate.log(level, message);
            logOnSlowLogging(startTime);
        }

        @Override
        public void log(Level level, String message, Throwable thrown) {
            long startTime = System.nanoTime();
            delegate.log(level, message, thrown);
            logOnSlowLogging(startTime);
        }

        @Override
        public void log(LogEvent logEvent) {
            long startTime = System.nanoTime();
            delegate.log(logEvent);
            logOnSlowLogging(startTime);
        }

        @Override
        public Level getLevel() {
            return Level.ALL;
        }

        @Override
        public boolean isLoggable(Level level) {
            return true;
        }

        private void logOnSlowLogging(long startTime) {
            long durationNanos = System.nanoTime() - startTime;
            if (durationNanos > WARNING_THRESHOLD_NANOS) {
                long durationMillis = NANOSECONDS.toMillis(durationNanos);
                delegate.warning("Logging took " + durationMillis + " ms.");
            }
        }
    }
}


text:
'use strict';

var assert = require('assert');

var JsigAST = require('../ast/');
var getUniqueTypes = require('./lib/get-unique-types.js');
var isSameType = require('./lib/is-same-type.js');

module.exports = TypeInference;

function TypeInference(meta) {
    this.meta = meta;
}

TypeInference.prototype.inferType = function inferType(node) {
    if (node.type === 'CallExpression') {
        return this.inferCallExpression(node);
    } else if (node.type === 'Literal') {
        return this.inferLiteral(node);
    } else if (node.type === 'ArrayExpression') {
        return this.inferArrayExpression(node);
    } else if (node.type === 'ObjectExpression') {
        return this.inferObjectExpression(node);
    } else {
        throw new Error('!! skipping inferType: ' + node.type);
    }
};

TypeInference.prototype.inferCallExpression =
function inferCallExpression(node) {
    var untypedFunc = this.meta.currentScope
        .getUntypedFunction(node.callee.name);
    if (!untypedFunc) {
        return null;
    }

    var args = node.arguments;

    var argTypes = [];
    for (var i = 0; i < args.length; i++) {
        var funcArg = this.meta.verifyNode(args[i], null);
        if (!funcArg) {
            return null;
        }

        argTypes.push(JsigAST.param(null, funcArg));
    }

    var returnType = JsigAST.literal('%Void%%UnknownReturn', true);
    if (this.meta.currentExpressionType &&
        this.meta.currentExpressionType.name !== '%Null%%Default' &&
        this.meta.currentExpressionType.name !== '%Void%%Uninitialized'
    ) {
        returnType = this.meta.currentExpressionType;
    }

    // if (this.meta.currentScope.getAssignmentType()) {
        // returnType = this.meta.currentScope.getAssignmentType();
    // } else if (this.meta.currentScope.getReturnExpressionType()) {
        // returnType = this.meta.currentScope.getReturnExpressionType();
    // }

    // TODO: infer this arg based on method calls
    var funcType = JsigAST.functionType({
        args: argTypes,
        result: returnType,
        thisArg: null
    });

    // TODO: We should see if this function actually
    // has a smaller return type. Aka given some inferred type
    // () => X, does the function actually return Y, Y <: X.
    // In which case we should mark this type as () => Y.
    if (!this.meta.tryUpdateFunction(node.callee.name, funcType)) {
        return null;
    }

    if (returnType.builtin && returnType.name === '%Void%%UnknownReturn') {
        // Grab the scope for the known function
        var funcScopes = this.meta.currentScope.getKnownFunctionScope(
            node.callee.name
        ).funcScopes;

        assert(funcScopes.length === 1,
            'cannot infer call return for overloaded function'
        );
        var funcScope = funcScopes[0];

        if (funcScope.knownReturnTypes.length > 0) {
            var uniqueKnownReturnTypes = getUniqueTypes(
                funcScope.knownReturnTypes
            );

            // TODO: grab the smallest union?
            assert(uniqueKnownReturnTypes.length === 1,
                'only support trivial single return funcs');
            funcType.result = uniqueKnownReturnTypes[0];
        }
    }

    return funcType;
};

TypeInference.prototype.inferLiteral =
function inferLiteral(node) {
    var value = node.value;

    if (typeof value === 'string') {
        return JsigAST.literal('String', true, {
            concreteValue: value
        });
    } else if (typeof value === 'number') {
        return JsigAST.literal('Number', true, {
            concreteValue: parseFloat(value, 10)
        });
    } else if (value === null) {
        return JsigAST.value('null');
    } else if (Object.prototype.toString.call(value) === '[object RegExp]') {
        return JsigAST.literal('RegExp');
    } else if (typeof value === 'boolean') {
        return JsigAST.literal('Boolean', true, {
            concreteValue: value === true ? 'true' : 'false'
        });
    } else {
        throw new Error('not recognised literal');
    }
};

function isTypeTuple(jsigType) {
    return jsigType && jsigType.type === 'tuple';
}

function isTypeArray(jsigType) {
    return jsigType && jsigType.type === 'genericLiteral' &&
        jsigType.value.type === 'typeLiteral' &&
        jsigType.value.name === 'Array' &&
        jsigType.value.builtin;
}

/*eslint complexity: [2,20] */
TypeInference.prototype.inferArrayExpression =
function inferArrayExpression(node) {
    var elems = node.elements;

    if (elems.length === 0) {
        var currExprType = this.meta.currentExpressionType;
        if (currExprType && currExprType.type === 'genericLiteral' &&
            currExprType.value.type === 'typeLiteral' &&
            currExprType.value.builtin && currExprType.value.name === 'Array'
        ) {
            return currExprType;
        }

        return JsigAST.generic(
            JsigAST.literal('Array'),
            [JsigAST.freeLiteral('T')]
        );
    }

    var currExpr = this.meta.currentExpressionType;
    if (isTypeTuple(currExpr)) {
        return this._inferTupleExpression(node);
    }

    if (isTypeArray(currExpr)) {
        return this._inferArrayExpression(node);
    }

    var i = 0;

    if (currExpr && currExpr.type === 'unionType') {
        var unions = currExpr.unions;
        for (i = 0; i < unions.length; i++) {
            var possibleType = unions[i];
            if (isTypeTuple(possibleType)) {
                return this._inferTupleExpression(node);
            }

            if (isTypeArray(possibleType)) {
                return this._inferArrayExpression(node);
            }
        }
    }

    var values = [];

    for (i = 0; i < elems.length; i++) {
        if (elems[i].type === 'Identifier') {
            this.meta.currentScope.markVarAsAlias(
                elems[i].name, null
            );
        }

        var newType = this.meta.verifyNode(elems[i], null);
        if (!newType) {
            return null;
        }

        values[i] = newType;
    }

    return JsigAST.tuple(values, null, {
        inferred: true
    });
};

TypeInference.prototype._inferArrayExpression =
function _inferArrayExpression(node) {
    var i = 0;
    var currExpr = this.meta.currentExpressionType;
    if (currExpr.type === 'unionType') {
        for (i = 0; i < currExpr.unions.length; i++) {
            var possibleType = currExpr.unions[i];
            if (isTypeArray(possibleType)) {
                currExpr = possibleType;
                break;
            }
        }
    }

    assert(isTypeArray(currExpr), 'must be an array...');

    var arrayType = currExpr.generics[0];
    var elems = node.elements;

    var type = null;
    for (i = 0; i < elems.length; i++) {
        if (elems[i].type === 'Identifier') {
            this.meta.currentScope.markVarAsAlias(
                elems[i].name, null
            );
        }

        var newType = this.meta.verifyNode(elems[i], arrayType);

        if (type && newType) {
            if (!isSameType(newType, type)) {
                assert(false, 'arrays must be homogenous');
            }
        }

        if (newType) {
            type = newType;
        }
    }

    if (!type) {
        return null;
    }

    return JsigAST.generic(JsigAST.literal('Array'), [type]);
};

TypeInference.prototype._inferTupleExpression =
function _inferTupleExpression(node) {
    var values = [];
    var i = 0;
    var currExpr = this.meta.currentExpressionType;
    if (currExpr.type === 'unionType') {
        for (i = 0; i < currExpr.unions.length; i++) {
            var possibleType = currExpr.unions[i];
            if (isTypeTuple(possibleType)) {
                currExpr = possibleType;
                break;
            }
        }
    }

    assert(isTypeTuple(currExpr), 'must be a tuple...');

    var tupleTypes = currExpr.values;
    for (i = 0; i < node.elements.length; i++) {
        var expected = tupleTypes[i] || null;

        if (node.elements[i].type === 'Identifier') {
            this.meta.currentScope.markVarAsAlias(
                node.elements[i].name, null
            );
        }

        values[i] = this.meta.verifyNode(node.elements[i], expected);
        if (!values[i]) {
            return null;
        }
    }

    return JsigAST.tuple(values);
};

TypeInference.prototype.inferObjectExpression =
function inferObjectExpression(node) {
    var properties = node.properties;

    if (properties.length === 0) {
        var openObj = JsigAST.object([]);
        openObj.open = true;
        return openObj;
    }

    var currentExpressionType = this.meta.currentExpressionType;
    if (currentExpressionType &&
        currentExpressionType.name === '%Export%%ModuleExports' &&
        this.meta.hasExportDefined()
    ) {
        currentExpressionType = this.meta.getModuleExportsType();
    }

    var index = null;
    if (currentExpressionType && currentExpressionType.type === 'object') {
        index = currentExpressionType.buildObjectIndex();
    }

    var keyValues = [];
    for (var i = 0; i < properties.length; i++) {
        var prop = properties[i];
        assert(prop.kind === 'init', 'only support init kind');

        var keyName = null;
        if (prop.key.type === 'Identifier') {
            keyName = prop.key.name;
        } else if (prop.key.type === 'Literal') {
            keyName = prop.key.value;
        }

        var expectedType = null;
        if (keyName && index && index[keyName]) {
            expectedType = index[keyName];
        }

        // If this object literal is assigned to module.exports
        // And we are in partial export mode and we do not know the
        // type of the field, then skip this field on the export
        if (this.meta.currentExpressionType &&
            this.meta.currentExpressionType.name === '%Export%%ModuleExports' &&
            this.meta.checkerRules.partialExport &&
            !expectedType
        ) {
            continue;
        }

        if (prop.value.type === 'Identifier') {
            this.meta.currentScope.markVarAsAlias(
                prop.value.name, null
            );
        }

        var value = this.meta.verifyNode(prop.value, expectedType);
        if (!value) {
            return null;
        }

        keyValues.push(JsigAST.keyValue(keyName, value));
    }

    return JsigAST.object(keyValues, null, {
        inferred: true
    });
};


text:
/**
 *  Stax based XProcScript and XProcPipelineInfo parsers
 */
package org.daisy.pipeline.script.impl.parser;


text:
/*
(Geometry: two rectangles) Write a program that prompts the user to enter the
center x-, y-coordinates, width, and height of two rectangles and determines
whether the second rectangle is inside the first or overlaps with the first, as shown
in Figure 3.9. Test your program to cover all cases.
*/
import java.util.Scanner;

public class Exercise_03_28 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);	// Create Scanner object

		// Prompt the user to enter the center x, y coorginates,
		// width, and height of two rectangles
		System.out.print("Enter r1's center x-, y-coordinates, width and height: ");
		double r1x = input.nextDouble();
		double r1y = input.nextDouble();
		double r1Width = input.nextDouble();
		double r1Height = input.nextDouble();
		System.out.print("Enter r2's center x-, y-coordinates, width and height: ");
		double r2x = input.nextDouble();
		double r2y = input.nextDouble();
		double r2Width = input.nextDouble();
		double r2Height = input.nextDouble();

		// Determine whether the second rectangle is inside the first
		if	((Math.pow(Math.pow(r2y - r1y, 2), .05) + r2Height / 2 <= r1Height / 2) &&
			(Math.pow(Math.pow(r2x - r1x, 2), .05) + r2Width / 2 <= r1Width / 2) &&
			(r1Height / 2 + r2Height / 2 <= r1Height) &&
			(r1Width / 2 + r2Width / 2 <= r1Width))
			System.out.println("r2 is inside r1");
		else if ((r1x + r1Width / 2 > r2x - r2Width) ||
					(r1y + r1Height / 2 > r2y - r2Height))
			System.out.println("r2 overlaps r1");
		else
			System.out.println("r2 does not overlap r1");
	}
}


text:
package me.mos.ti.channel;

import java.nio.channels.SocketChannel;

/**
 * 表示一个客户端连接通道.
 *
 * @author 刘飞 E-mail:liufei_it@126.com
 *
 * @version 1.0.0
 * @since 2015年6月1日 下午5:33:03
 */
public interface NioSockChannel extends Channel<SocketChannel> {
	NioSockChannel interestOps(int ops);
}


text:
#ifndef AMA_COMMON_POINTER_WRAPPER_HPP
#define AMA_COMMON_POINTER_WRAPPER_HPP 1

namespace ama
{

  /* This class store a pointer, but is not designed for memory managment purpose */
  template <typename T>
  class pointer_wrapper
  {
  public:
    typedef T element_type;

    /* costructor */
    pointer_wrapper(T * ptr = 0): m_ptr(ptr) { }

    /* copy constructor */
    pointer_wrapper(pointer_wrapper const & ptrw): m_ptr(ptrw.m_ptr) { }

    /* copy operator */
    pointer_wrapper & operator=(T * ptr)
    {
      m_ptr = ptr;
      return *this;
    }

    /* copy operator */
    pointer_wrapper & operator=(pointer_wrapper const & ptrw)
    {
      m_ptr = ptrw.m_ptr;
      return *this;
    }

    /* access operators */
    T & operator*() const { return *m_ptr; }
    T * operator->() const { return m_ptr; }

    /* check if null */
    bool null() const { return (m_ptr == 0); }

    /* get the pointer */
    T * get() const { return m_ptr; }

    /* comparison operator */
    bool operator==(T * ptr) { return m_ptr == ptr; }
    bool operator==(pointer_wrapper const & ptrw) { return m_ptr == ptrw.m_ptr; }

  protected:
    T * m_ptr;
  };

}

#endif /* AMA_COMMON_POINTER_WRAPPER_HPP */


text:
var path = require('path');
var util = require('util');
var sprintf = require('sprintf-js').sprintf;
var Constants = require(path.dirname(__filename) + '/constants');
var CodeWriter = require(path.dirname(__filename) + '/code-writer');
var ObjectWriter = require(path.dirname(__filename) + '/object-writer');
var ServiceWriter = require(path.dirname(__filename) + '/service-writer');

module.exports = ProviderWriter;

function ProviderWriter() {
    CodeWriter.call(this, beforeWrite);
    this.setName = setName;
    this.setModule = setModule;
    this.addConfig = addConfig;
    this.initialize = initialize;

    this.configFunctions = [];

    this.serviceWriter = new ServiceWriter();
    this.serviceWriter.addDependency('$http');

    this.configWriter = new ObjectWriter().setWriteVar(false).setName(Constants.PROVIDER + '.config');

    this.initialize();
}

util.inherits(ProviderWriter, CodeWriter);

function initialize() {
    this.append('var ' + Constants.PROVIDER + '=this;');
    this.append(this.configWriter);
    this.append(this.configFunctions);
}

function addConfig(key, defaultValue) {
    var str = sprintf("%s.%s=function(v){if(angular.isDefined(v)){%s.config.%s=v;}return %s.config.%s;};",
        Constants.PROVIDER, key, Constants.PROVIDER, key, Constants.PROVIDER, key);
    this.configFunctions.push(str);

    this.configWriter.addProperty(key, defaultValue);

    return this;
}

function setModule(n) {
    this.module = n;
    return this;
}

function setName(n) {
    this.name = n;
    return this;
}

function beforeWrite() {
    if (!this.name)
        throw new Error('ProviderWriter needs to have a name');

    if (!this.module)
        throw new Error('ProviderWriter needs to have a module (name)');

    var str = sprintf('angular.module(\'%s\').provider(\'%s\',%sProvider);function %sProvider(){',
        this.module, this.name, this.name, this.name);

    this.append(Constants.PROVIDER + '.$get=');
    this.append(this.serviceWriter);

    this.prepend(str).append('}');
}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Under Maintenance \ Mist — Responsive Multi-purpose HTML Template</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="keywords" content="HTML5 Template" />
        <meta name="description" content="Mist — Multi-Purpose HTML Template" />
        <meta name="author" content="zozothemes.com" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        <link rel="shortcut icon" href="img/favicon.ico" />

        <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Arimo:300,400,700,400italic,700italic' />
        <link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css' />

        <link href='css/font-awesome.min.css' rel='stylesheet' type='text/css' />

        <link href="css/bootstrap.min.css" rel="stylesheet" />

        <link href="css/icons.css" rel="stylesheet" />

        <link href="css/style.css" rel="stylesheet" />
       <link href="css/responsive.css" rel="stylesheet" />

        <link href="css/color.css" rel="stylesheet" />

This Site is Currently

Under Maintenance

We will back shortly

Why is the Site Down?

The site is under maintenance probably because we are working to improve this website drastically.

What is the Downtime?

We are usually back within 10-15 minutes but it definitely depends on the issue.

Do you need Support?

You may simply send mail at
                        support@zozothemes.com

if you need urgent support.


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Governance Center</title>

   <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
   <link href="css/custom.css" rel="stylesheet">
   <link href="css/custom-theme.css" rel="stylesheet">
   <link href="css/common.css" rel="stylesheet">

   <link rel="stylesheet" href="css/font-awesome.min.css">

   <link rel="stylesheet" href="/publisher/themes/default/css/fontwso2.css">
   <link rel="stylesheet" href="/publisher/themes/default/css/fontwso2-extend.css">

   <link href="css/select2.min.css" rel="stylesheet">
   <link href="css/sidepanel.css" rel="stylesheet">
   <link href="css/association-base.css" rel="stylesheet">

Some Presentation Subject

 10.00 AM

Some Presentation Subject

 10.00 AM

Some Presentation Subject

 10.00 AM

                        Notes

                        New

 Edit

 Delete

 Resolve Thread

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu dictum lectus, nec lacinia odio. Fusce eget malesuada lorem, vitae blandit justo. Morbi sed sapien vestibulum ipsum bibendum blandit. Integer magna dui, consequat sed velit ac, pulvinar feugiat nisi. Nulla pharetra viverra risus, quis mattis mauris elementum quis.

John Doe  11.25am | 12-April-2015

                                More ...

 Edit

 Delete

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu dictum lectus, nec lacinia odio. Fusce eget malesuada lorem, vitae blandit justo.

John Doe  11.25am | 12-April-2015

 Edit

 Delete

Added asset weather.xml

John Doe  - 11.25am | 12-April-2015

                                    <textarea placeholder="reply..."></textarea>

                                        Reply

 Edit

 Delete

 Resolve Thread

Added asset weather.xml

John Doe  11.25am | 12-April-2015

 Edit

 Delete

Added asset weather.xml

John Doe  11.25am | 12-April-2015

 Edit

 Delete

Added asset weather.xml

John Doe  11.25am | 12-April-2015

                                    <textarea placeholder="reply..."></textarea>

                                        Reply

 Edit

 Delete

 Resolve Thread

Added asset weather.xml

John Doe  11.25am | 12-April-2015

 Edit

 Delete

Added asset weather.xml

John Doe  11.25am | 12-April-2015

 Edit

 Delete

Added asset weather.xml

John Doe  11.25am | 12-April-2015

                                    <textarea placeholder="reply..."></textarea>

                                        Reply

 Re-open

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu dictum lectus, nec lacinia odio.

John Doe  11.25am | 12-April-2015

                                        Resolved

                                More ...

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu dictum lectus, nec lacinia odio. Fusce eget malesuada lorem, vitae blandit justo.

John Doe  11.25am | 12-April-2015

Added asset weather.xml

John Doe  - 11.25am | 12-April-2015

                        Tags

                    <select class="select2 select-tags" id="select-tags" multiple="multiple" data-tags="true">
                        <option id="1">Option 1</option>
                        <option id="2">Option 2</option>
                        <option id="3">Option 3</option>
                    </select>

                        Notifications Settings

                            Email
                            Email

                            Some Configuration

                                    <input type="checkbox" checked>

                                    <input type="checkbox">

                            Some Configuration

                                    <input type="checkbox">

                                    <input type="checkbox">

Governance Center

                           admin

                           Sign out

                  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                  Toggle navigation

                  </button>

API

Policy

REST Service

Schema

SOAP Service

Swagger

WADL

WADL

WSDL

                              Associations

                               Discover

                               Dependency Graph

                                35

                                Options

                  Redirecting you to the new Asset Version...

               <button class="btn btn-primary">
               Redirect now
               </button>

WeatherService

                                            1
                                         SELECT AN ASSOCIATION TYPE

Security

Security

Security

Security

Security

                                            2
                                         SELECT ASSET

                                        <select class="select2 select-resource" id="select-resource">

                                        </select>

                                             Add

Secured

WeatherReportService.xml

application/wsdl+xml

                                                 Edit

                                                 Delete

Secured

WeatherReportService.xml

application/wsdl+xml

                                                 Edit

                                                 Delete

Secured

WeatherReportService.xml

application/wsdl+xml

                                                 Edit

                                                 Delete

         Governance Center | ©   Inc. All Rights Reserved.

Sort By

    	Device Name
    	OS
    	User
    	Model


text:
require 'nrser/ext/object/as'

SPEC_FILE \
  spec_path:        __FILE__,
  module:           NRSER::Ext::Object \
do

  INSTANCE_METHOD :as_hash do
    SETUP ~%{ bind method to `receiver` } do

      subject do
        unbound_method = super()

        ->( *args, &block ) {
          unbound_method.bind( receiver ).call *args, &block
        }
      end # subject

      CASE ~%{ `receiver` is a {Hash} } do
        WHEN receiver: { a: 1 } do
          CALLED do it ~%{ returns itself } do
            is_expected.to be receiver
          end end

          CALLED_WITH :x do it ~%{ does not effect the result } do
            is_expected.to be receiver
          end end
        end#WHEN
      end#CASE

      CASE ~%{ `receiver` is `nil` }, where: { receiver: nil } do
        CALLED do it do is_expected.to eq( {} ) end end

        CALLED_WITH :x do it ~%{ does not effect the result } do
          is_expected.to eq( {} )
        end end
      end#CASE

      CASE ~%{ `receiver` responds to `#to_h` } do
        CASE ~%{ `#to_h` succeeds } do
          WHEN receiver: [ [:a, 1], [:b, 2] ] do
            CALLED do it do is_expected.to eq( a: 1, b: 2 ) end end
          end#WHEN
        end#CASE

        CASE ~%{ `#to_h` fails } do
          WHEN receiver: [ 1, 2, 3 ] do
            CALLED_WITH :a do
              it ~%{ returns a {Hash} with `receiver` keyed as `:a` } do
                is_expected.to eq a: receiver
              end
            end

            CALLED do it do
              expect { subject }.to raise_error ArgumentError
            end end
          end#WHEN
        end#CASE
      end#CASE

    end#SETUP
  end # #as_hash

  INSTANCE_METHOD :as_array do
    SETUP ~%{ bind method to `receiver` } do

      subject do
        unbound_method = super()

        ->( *args, &block ) {
          unbound_method.bind( receiver ).call *args, &block
        }
      end # subject

      CASE ~%{ `receiver` is `nil` }, where: { receiver: nil } do
        CALLED do it do is_expected.to eq [] end end
      end#CASE

    end#SETUP
  end#INSTANCE_METHOD

end # SPEC_FILE


text:
var break_and_continue = require('./break_and_continue/index.js');
exports.break_and_continue = break_and_continue;

break_and_continue.main();


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>ExponentMap: Class Members - Functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ExponentMap
    1.1.0

Generates an exponentially growing array based on provided number of steps and maximum value.

ExponentMap()
: ExponentMap< T >

operator()()
: ExponentMap< T >

operator=()
: ExponentMap< T >

printCode()
: ExponentMap< T >

printTable()
: ExponentMap< T >

stepsCount()
: ExponentMap< T >

stepsRepeat()
: ExponentMap< T >

stepToValue()
: ExponentMap< T >

valueToStep()
: ExponentMap< T >

~ExponentMap()
: ExponentMap< T >

<address class="footer">
Generated by

 1.8.12
</address>


text:
const headers = [
	{
		"key": "Access-Control-Allow-Origin",
		"value": "*"
	},
	{
		"key": "Access-Control-Allow-Headers",
		"value": "Origin, X-Requested-With, Content-Type, Accept"
	}
];

/**
 * Returns a curried function for setting request headers.
 * @memberof module:server/express-cors
 * @param {Array} headers the headers to set
 * @returns {Function} a curried function for setting request headers.
 */
const setHeaders = (headers) => (res) => headers.forEach((item) => res.header(item.key, item.value));

/**
 * The curried function for setting request headers.
 * @memberof module:server/express-cors
 * @param {Object} the request object to pass down
 * @returns {undefined} undefined
 */
const setCORSHeaders = setHeaders(headers);

/**
 * The api funtion for setting the CORS headers
 * @memberof module:server/express-cors
 * @param {Object} req the request object
 * @param {Object} res the response object
 * @param {Function} next the callback for continuing then middleware chain
 * @returns {*} undefined
 */
const api = (req, res) => {
	// set the headers on the request
	setCORSHeaders(res);
	return true;
};

module.exports = api;


text:
class ScrollViewTestLayer : public cocos2d::Layer {
    public:
        CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(ScrollViewTestLayer, create);
};

#endif


text:
package org.ihtsdo.otf.mapping.jpa.handlers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.ihtsdo.otf.mapping.helpers.MapRecordList;
import org.ihtsdo.otf.mapping.helpers.MapRecordListJpa;
import org.ihtsdo.otf.mapping.helpers.MapUserRole;
import org.ihtsdo.otf.mapping.helpers.PfsParameter;
import org.ihtsdo.otf.mapping.helpers.PfsParameterJpa;
import org.ihtsdo.otf.mapping.helpers.SearchResult;
import org.ihtsdo.otf.mapping.helpers.SearchResultJpa;
import org.ihtsdo.otf.mapping.helpers.SearchResultList;
import org.ihtsdo.otf.mapping.helpers.SearchResultListJpa;
import org.ihtsdo.otf.mapping.helpers.ValidationResult;
import org.ihtsdo.otf.mapping.helpers.WorkflowAction;
import org.ihtsdo.otf.mapping.helpers.WorkflowPath;
import org.ihtsdo.otf.mapping.helpers.WorkflowPathState;
import org.ihtsdo.otf.mapping.helpers.WorkflowStatus;
import org.ihtsdo.otf.mapping.helpers.WorkflowStatusCombination;
import org.ihtsdo.otf.mapping.jpa.MapRecordJpa;
import org.ihtsdo.otf.mapping.jpa.services.MappingServiceJpa;
import org.ihtsdo.otf.mapping.jpa.services.WorkflowServiceJpa;
import org.ihtsdo.otf.mapping.model.MapProject;
import org.ihtsdo.otf.mapping.model.MapRecord;
import org.ihtsdo.otf.mapping.model.MapUser;
import org.ihtsdo.otf.mapping.services.MappingService;
import org.ihtsdo.otf.mapping.services.WorkflowService;
import org.ihtsdo.otf.mapping.workflow.TrackingRecord;
import org.ihtsdo.otf.mapping.workflow.TrackingRecordJpa;

/**
 * Workflow path handler for "qa path".
 */
public class WorkflowQaPathHandler extends AbstractWorkflowPathHandler {

  // The workflow path states defining the QA Path Workflow
  /** The finished state. */
  private static WorkflowPathState qaNeededState;

  /** The editing state. */
  private static WorkflowPathState editingState;

  /** The finished state. */
  private static WorkflowPathState finishedState;

  /**
   * Instantiates an empty {@link WorkflowQaPathHandler}.
   */
  public WorkflowQaPathHandler() {

    setWorkflowPath(WorkflowPath.QA_PATH);

    // This really should be false, but empty workflow support not fully
    // complete
    setEmptyWorkflowAllowed(true);

    // STATE: Initial state has no tracking record
    // Only valid action is CREATE_QA_RECORD

    // workflow states representing a record marked for qa and the original
    // published record
    qaNeededState = new WorkflowPathState("QA_NEEDED");
    qaNeededState.addWorkflowCombination(new WorkflowStatusCombination(
        Arrays.asList(WorkflowStatus.REVISION, WorkflowStatus.QA_NEEDED)));
    trackingRecordStateToActionMap.put(qaNeededState, new HashSet<>(Arrays
        .asList(WorkflowAction.ASSIGN_FROM_SCRATCH, WorkflowAction.UNASSIGN)));

    // workflow states representing record marked for revision, specialist
    // work,
    // and lead QA (incomplete)
    editingState = new WorkflowPathState("QA_NEW/QA_IN_PROGRESS");
    editingState.addWorkflowCombination(
        new WorkflowStatusCombination(Arrays.asList(WorkflowStatus.REVISION,
            WorkflowStatus.QA_NEEDED, WorkflowStatus.QA_NEW)));
    editingState.addWorkflowCombination(
        new WorkflowStatusCombination(Arrays.asList(WorkflowStatus.REVISION,
            WorkflowStatus.QA_NEEDED, WorkflowStatus.QA_IN_PROGRESS)));
    trackingRecordStateToActionMap.put(editingState,
        new HashSet<>(Arrays.asList(WorkflowAction.FINISH_EDITING,
            WorkflowAction.SAVE_FOR_LATER, WorkflowAction.UNASSIGN)));

    // workflow finishedStates representing record marked for revision,
    // specialist work,
    // and lead QA (complete)
    finishedState = new WorkflowPathState("QA_RESOLVED");
    finishedState.addWorkflowCombination(
        new WorkflowStatusCombination(Arrays.asList(WorkflowStatus.REVISION,
            WorkflowStatus.QA_NEEDED, WorkflowStatus.QA_RESOLVED)));
    trackingRecordStateToActionMap.put(finishedState,
        new HashSet<>(
            Arrays.asList(WorkflowAction.FINISH_EDITING, WorkflowAction.PUBLISH,
                WorkflowAction.SAVE_FOR_LATER, WorkflowAction.UNASSIGN)));

    // final state: no tracking record, one READY_FOR_PUBLICATION record
  }

  /*
   * (non-Javadoc)
   *
   * @see org.ihtsdo.otf.mapping.jpa.handlers.AbstractWorkflowPathHandler#
   * validateTrackingRecordForActionAndUser(org.ihtsdo.otf.mapping.workflow.
   * TrackingRecord, org.ihtsdo.otf.mapping.helpers.WorkflowAction,
   * org.ihtsdo.otf.mapping.model.MapUser)
   */
  /* see superclass */
  /* see superclass */
  @Override
  public ValidationResult validateTrackingRecordForActionAndUser(
    TrackingRecord tr, WorkflowAction action, MapUser user) throws Exception {

    // first, validate the tracking record itself
    ValidationResult result = validateTrackingRecord(tr);
    if (!result.isValid()) {
      result.addError(
          "Could not validate action for user due to workflow errors.");

      return result;
    }

    // check for CANCEL action -- always valid for this path for any
    // state or user (no-op)
    if (action.equals(WorkflowAction.CANCEL)) {
      return result;
    }

    // check for CREATE_QA_RECORD action -- this is always valid, as it
    // merely
    // applies labels to concepts that are already in the workflow
    if (action.equals(WorkflowAction.CREATE_QA_RECORD)) {
      return result;
    }

    // get the user role for this map project
    MappingService mappingService = new MappingServiceJpa();
    MapUserRole userRole = mappingService
        .getMapUserRoleForMapProject(user.getUserName(), tr.getMapProjectId());
    mappingService.close();

    // get the map records and workflow path state from the tracking
    // record
    MapRecordList mapRecords = getMapRecordsForTrackingRecord(tr);
    MapRecord currentRecord = getCurrentMapRecordForUser(mapRecords, user);
    WorkflowPathState state = this.getWorkflowStateForTrackingRecord(tr);

    // /////////////////////////////////
    // Switch on workflow path state //
    // /////////////////////////////////
    if (state == null) {
      result.addError(
          "Could not determine workflow path state for tracking record");
    }

    else if (state.equals(qaNeededState)) {

      // check record -- null means none assigned
      if (currentRecord == null) {

        // check role
        if (!userRole.hasPrivilegesOf(MapUserRole.SPECIALIST)) {
          result.addError("User does not have required role");
        }

        // check action
        if (!action.equals(WorkflowAction.ASSIGN_FROM_SCRATCH)) {
          result.addError("Action is not permitted.");
        }
      } else {

        // check role
        // qa user does not have role requirements for unassign

        // check action
        if (!action.equals(WorkflowAction.UNASSIGN)) {
          result.addError("Action is not permitted.");
        }

      }

      // STATE: Specialist level work
      // Record requirement : NEW, EDITING_IN_PROGRESS
      // Permissible actions: SAVE_FOR_LATER, FINISH_EDITING, UNASSIGN
      // Minimum role : Specialist
    } else if (state.equals(editingState)) {

      // check record
      if (currentRecord == null) {
        result.addError("User must have a record");
      } else if (!currentRecord.getWorkflowStatus()
          .equals(WorkflowStatus.QA_NEW)
          && !currentRecord.getWorkflowStatus()
              .equals(WorkflowStatus.QA_IN_PROGRESS)) {
        result.addError("User's record does not meet requirements");
      }

      // check role
      if (!userRole.hasPrivilegesOf(MapUserRole.SPECIALIST)) {
        result.addError("User does not have required role");
      }

      // check action
      if (!action.equals(WorkflowAction.SAVE_FOR_LATER)
          && !action.equals(WorkflowAction.FINISH_EDITING)
          && !action.equals(WorkflowAction.UNASSIGN)) {
        result.addError("Action is not permitted.");
      }

    } else if (state.equals(finishedState)) {
      // check record
      if (currentRecord == null) {
        result.addError("User must have a record");
      } else if (!currentRecord.getWorkflowStatus()
          .equals(WorkflowStatus.QA_RESOLVED)) {
        result.addError("User's record does meet requirements");
      }

      // check role
      if (!userRole.hasPrivilegesOf(MapUserRole.SPECIALIST)) {
        result.addError("User does not have required role");
      }

      // check action
      if (!action.equals(WorkflowAction.SAVE_FOR_LATER)
          && !action.equals(WorkflowAction.FINISH_EDITING)
          && !action.equals(WorkflowAction.UNASSIGN)
          && !action.equals(WorkflowAction.PUBLISH)) {
        result.addError("Action is not permitted.");
      }
    }

    if (result.getErrors().size() != 0) {
      result.addError(
          "Error occured in workflow state " + state.getWorkflowStateName());
    }

    return result;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.ihtsdo.otf.mapping.services.helpers.WorkflowPathHandler#getName()
   */
  /* see superclass */
  @Override
  public String getName() {
    return "QA_PATH";
  }

  /* see superclass */
  @SuppressWarnings("unchecked")
  @Override
  public SearchResultList findAvailableWork(MapProject mapProject,
    MapUser mapUser, MapUserRole userRole, String query,
    PfsParameter pfsParameter, WorkflowService workflowService)
    throws Exception {
    Logger.getLogger(this.getClass())
        .debug(getName() + ": findAvailableWork for project "
            + mapProject.getName() + " and user " + mapUser.getUserName());

    SearchResultList availableWork = new SearchResultListJpa();

    final StringBuilder sb = new StringBuilder();

    // NOTE QA Path does not use normal queries, but rather filters by label
    sb.append(
        "mapProjectId:" + mapProject.getId() + " AND workflowPath:QA_PATH");

    // add the query terms specific to findAvailableReviewWork
    // - a user (any) and workflowStatus pair of QA_NEEDED_userName
    // exists
    // - the QA_NEEDED pair is not for this user (i.e. user can't review
    // their own work, UNLESS there is only one lead on the project
    // - user and workflowStatus pairs of
    // CONFLICT_NEW/CONFLICT_IN_PROGRESS_userName does not exist

    // must have a QA_NEEDED tag with any user
    sb.append(" AND userAndWorkflowStatusPairs:QA_NEEDED_*");

    // there must not be an already claimed review record
    sb.append(" AND NOT (userAndWorkflowStatusPairs:QA_NEW_*"
        + " OR userAndWorkflowStatusPairs:QA_IN_PROGRESS_*"
        + " OR userAndWorkflowStatusPairs:QA_RESOLVED_*" + ")");

    // OTHERWISE, handle case where query is set
    // QA label searching requires retrieving all results
    PfsParameter pfsLocal = new PfsParameterJpa(pfsParameter);
    if (query != null && !query.isEmpty() && !query.equals("null")) {
      pfsLocal.setMaxResults(-1);
      pfsLocal.setStartIndex(-1);
    }

    int[] totalCt = new int[1];
    final List<TrackingRecord> results =
        (List<TrackingRecord>) workflowService.getQueryResults(sb.toString(),
            TrackingRecordJpa.class, TrackingRecordJpa.class, pfsLocal,
            totalCt);
    availableWork.setTotalCount(totalCt[0]);

    for (final TrackingRecord tr : results) {

      final SearchResult result = new SearchResultJpa();
      final Set<MapRecord> mapRecords =
          workflowService.getMapRecordsForTrackingRecord(tr);

      final StringBuffer labelBuffer = new StringBuffer();
      boolean keepRecord = false;
      for (final MapRecord mr : mapRecords) {

        // extract all labels for this tracking record
        for (final String label : mr.getLabels()) {
          if (labelBuffer.indexOf(label) == -1) {
            labelBuffer.append(";").append(label);
          }
          if (label.contains(query) || query.contains(label)) {
            keepRecord = true;
          }
        }

        // Keep record if query matches the concept id or name
        if (query != null
            && (mr.getConceptId().toLowerCase().startsWith(query.toLowerCase())
                || mr.getConceptName().toLowerCase()
                    .contains(query.toLowerCase()))) {
          keepRecord = true;
        }

      }

      // if no label query supplied or this tracking record has the requested
      // label
      if (query == null || query.isEmpty() || query.equals("null")
          || keepRecord == true) {

        // construct the search result
        result.setTerminologyId(tr.getTerminologyId());
        result.setValue(tr.getDefaultPreferredName());
        result.setId(tr.getId());
        result.setValue2(labelBuffer.toString());
        availableWork.addSearchResult(result);
      }
    }

    if (query == null || query.isEmpty() || query.equals("null")) {
      return availableWork;
    }

    // otherwise construct local list for manual paging
    List<SearchResultJpa> tempResults =
        new ArrayList<>(availableWork.getCount() + 10);
    for (final SearchResult sr : availableWork.getSearchResults()) {
      tempResults.add((SearchResultJpa) sr);
    }

    // apply paging to the list
    pfsLocal = new PfsParameterJpa(pfsParameter);
    pfsLocal.setQueryRestriction("");
    pfsLocal.setSortField("");
    tempResults = workflowService.applyPfsToList(tempResults,
        SearchResultJpa.class, totalCt, pfsLocal);

    // reconstruct the assignedWork search result list
    availableWork
        .setSearchResults(new ArrayList<SearchResult>(tempResults.size() + 10));
    for (SearchResult sr : tempResults) {
      availableWork.addSearchResult(sr);
    }
    availableWork.setTotalCount(totalCt[0]);
    return availableWork;

  }

  /* see superclass */
  @SuppressWarnings({
      "unchecked", "rawtypes"
  })
  @Override
  public SearchResultList findAssignedWork(MapProject mapProject,
    MapUser mapUser, MapUserRole userRole, String query,
    PfsParameter pfsParameter, WorkflowService workflowService)
    throws Exception {

    Logger.getLogger(this.getClass())
        .debug(getName() + ": findAssignedWork for project "
            + mapProject.getName() + " and user " + mapUser.getUserName());

    SearchResultList assignedWork = new SearchResultListJpa();
    final StringBuilder sb = new StringBuilder();

    // NOTE Qa Work does not use normal queries, instead filters by label
    sb.append("mapProjectId:" + mapProject.getId() + " AND workflowPath:"
        + getName());

    final String type = pfsParameter.getQueryRestriction() != null
        ? pfsParameter.getQueryRestriction() : "";

    if (!userRole.hasPrivilegesOf(MapUserRole.SPECIALIST)) {
      throw new Exception("Specialist role or above required for QA Work");
    }

    final PfsParameter pfs = new PfsParameterJpa(pfsParameter);
    pfs.setQueryRestriction(null);

    // add terms based on query restriction
    switch (type) {
      case "QA_NEW":
        sb.append(
            " AND userAndWorkflowStatusPairs:QA_NEW_" + mapUser.getUserName());

        break;
      case "QA_IN_PROGRESS":
        sb.append(" AND userAndWorkflowStatusPairs:QA_IN_PROGRESS_"
            + mapUser.getUserName());
        break;
      case "QA_RESOLVED":
        sb.append(" AND userAndWorkflowStatusPairs:QA_RESOLVED_"
            + mapUser.getUserName());
        break;
      default:
        sb.append(
            " AND (userAndWorkflowStatusPairs:QA_NEW_" + mapUser.getUserName()
                + " OR userAndWorkflowStatusPairs:QA_IN_PROGRESS_"
                + mapUser.getUserName()
                + " OR userAndWorkflowStatusPairs:QA_RESOLVED_"
                + mapUser.getUserName() + ")");
        break;
    }

    // Read all results
    pfs.setMaxResults(-1);
    final List<TrackingRecord> results =
        (List<TrackingRecord>) workflowService.getQueryResults(sb.toString(),
            TrackingRecordJpa.class, TrackingRecordJpa.class, pfs, new int[1]);

    // Iterate through results, keep records matching label
    for (final TrackingRecord tr : results) {
      final SearchResult result = new SearchResultJpa();
      final Set<MapRecord> mapRecords =
          workflowService.getMapRecordsForTrackingRecord(tr);

      // get the map record assigned to this user -- note: can only be one
      // if QA Path properly used
      MapRecord mapRecord = null;
      final StringBuffer labelBuffer = new StringBuffer();
      boolean keepRecord = false;
      for (final MapRecord mr : mapRecords) {
        if (!mr.getOwner().equals(mapUser)) {
          continue;
        }
        // Skip map records with revision status (this is a case where the same
        // user may be owner of multiple records)
        if (mr.getWorkflowStatus() == WorkflowStatus.REVISION) {
          continue;
        }

        mapRecord = mr;

        // extract all labels for this tracking record
        for (final String label : mr.getLabels()) {
          if (labelBuffer.indexOf(label) == -1) {
            labelBuffer.append(";").append(label);
          }

          if (label.equals(query)) {
            keepRecord = true;
          }
        }

        // Keep record if query matches the concept id or name
        if (query != null
            && (mr.getConceptId().toLowerCase().startsWith(query.toLowerCase())
                || mr.getConceptName().toLowerCase()
                    .contains(query.toLowerCase()))) {
          keepRecord = true;
        }

      }

      if (mapRecord == null) {
        throw new Exception(
            "Failed to retrieve assigned work:  no map record found for user "
                + mapUser.getUserName() + " and concept "
                + tr.getTerminologyId());
      }

      // if no label query supplied or this tracking record has the requested
      // label
      if (query == null || query.isEmpty() || query.equals("null")
          || keepRecord == true) {
        result.setTerminologyId(mapRecord.getConceptId());
        result.setValue(mapRecord.getConceptName());
        result.setValue2(labelBuffer.toString());
        result.setTerminology(mapRecord.getLastModified().toString());
        result.setTerminologyVersion(mapRecord.getWorkflowStatus().toString());
        result.setId(mapRecord.getId());
        assignedWork.addSearchResult(result);
      }
    }

    // construct local list for manual paging (need Jpa objects)
    List<SearchResultJpa> tempResults =
        new ArrayList<>((List) assignedWork.getSearchResults());

    // Set the assigned count.
    assignedWork.setTotalCount(tempResults.size());

    // apply paging to the list
    final PfsParameter pfsLocal = new PfsParameterJpa(pfsParameter);
    pfsLocal.setQueryRestriction("");
    pfsLocal.setSortField("");
    tempResults = workflowService.applyPfsToList(tempResults,
        SearchResultJpa.class, new int[1], pfsLocal);

    // reconstruct the assignedWork search result list
    assignedWork.setSearchResults(new ArrayList<SearchResult>(tempResults));
    return assignedWork;
  }

  /* see superclass */
  @Override
  public Set<MapRecord> processWorkflowAction(TrackingRecord trackingRecord,
    WorkflowAction workflowAction, MapProject mapProject, MapUser mapUser,
    Set<MapRecord> mapRecords, MapRecord mapRecord) throws Exception {

    Logger.getLogger(this.getClass())
        .debug(getName() + ": Processing workflow action by "
            + mapUser.getName() + ":  " + workflowAction.toString());

    // the set of records returned after processing
    Set<MapRecord> newRecords = new HashSet<>(mapRecords);

    switch (workflowAction) {
      case CREATE_QA_RECORD:

        if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.PUBLISHED)
            || mapRecord.getWorkflowStatus()
                .equals(WorkflowStatus.READY_FOR_PUBLICATION)) {

          // deep copy the map record
          MapRecord newRecord = new MapRecordJpa(mapRecord, false);

          // set origin ids
          newRecord.addOrigin(mapRecord.getId());
          newRecord.addOrigins(mapRecord.getOriginIds());

          // set other relevant fields
          // get QA User MapUser
          newRecord.setOwner(mapUser);
          newRecord.setLastModifiedBy(mapUser);
          newRecord.setWorkflowStatus(WorkflowStatus.QA_NEEDED);

          // add the record to the list
          newRecords.add(newRecord);

          // set the workflow status of the old record to review and add
          // it to
          // new records
          mapRecord.setWorkflowStatus(WorkflowStatus.REVISION);
          newRecords.add(mapRecord);
        } else {
          throw new Exception(getName() + ", " + workflowAction
              + ": Cannot QA non-publication-ready record");
        }
        break;
      case ASSIGN_FROM_SCRATCH:

        MapRecord qaRecord =
            createMapRecordForTrackingRecordAndUser(trackingRecord, mapUser);

        // set workflow status to QA_NEW
        qaRecord.setWorkflowStatus(WorkflowStatus.QA_NEW);

        // set origin id and copy labels
        for (MapRecord record : mapRecords) {

          // copy from the QA_NEEDED record
          if (record.getWorkflowStatus().equals(WorkflowStatus.QA_NEEDED)) {
            qaRecord.setLabels(record.getLabels());
            qaRecord.addOrigin(record.getId());

            // copy flags over to newRecord so reviewer can see them
            qaRecord.setFlagForConsensusReview(record.isFlagForConsensusReview());
            qaRecord.setFlagForEditorialReview(record.isFlagForEditorialReview());
            qaRecord.setFlagForMapLeadReview(record.isFlagForMapLeadReview());
          }
        }

        // add the users QA record to the set
        newRecords.add(qaRecord);

        break;
      case CANCEL:
        newRecords.clear();
        MappingService mappingService = new MappingServiceJpa();
        for (final Long id : trackingRecord.getMapRecordIds()) {
          newRecords.add(mappingService.getMapRecord(id));
        }
        mappingService.close();
        break;

      case FINISH_EDITING:

        // a lead has finished reviewing a QA
        if (newRecords.size() == 3) {

          // assumption check: should be exactly three records
          // 1) original published record, marked REVISION
          // 2) specialist (QA) record, marked QA_NEEDED
          // 3) lead's record, marked QA_NEW or QA_IN_PROGRESS

          MapRecord originalRecord = null;
          MapRecord modifiedRecord = null;
          MapRecord leadRecord = null;

          for (MapRecord mr : newRecords) {
            if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION))
              originalRecord = mr;
            if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEEDED))
              modifiedRecord = mr;
            if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEW)
                || mr.getWorkflowStatus().equals(WorkflowStatus.QA_IN_PROGRESS)
                || mr.getWorkflowStatus().equals(WorkflowStatus.QA_RESOLVED))
              leadRecord = mr;
          }

          if (originalRecord == null)
            throw new Exception(
                "QA_PATH: User finished reviewing work, but could not find previously published record");

          if (modifiedRecord == null)
            throw new Exception(
                "QA_PATH: User finished reviewing work, but could not find the specialist's (QA) record");

          if (leadRecord == null)
            throw new Exception(
                "QA_PATH: User finished reviewing work, but could not find their record.");

          leadRecord.setWorkflowStatus(WorkflowStatus.QA_RESOLVED);

        } else {
          throw new Exception(
              "Unexpected error along QA_PATH, invalid number of records passed in");
        }
        break;
      case PUBLISH:

        // Requirements for QA_PATH publish action
        // - 1 record marked REVISION
        // - 1 record marked QA_NEEDED
        // - 1 record marked QA_RESOLVED

        // check assumption: owned record is QA_RESOLVED
        if (!mapRecord.getWorkflowStatus().equals(WorkflowStatus.QA_RESOLVED))
          throw new Exception(
              "Publish called on QA_PATH for map record not marked as QA_RESOLVED");

        mapRecord.setWorkflowStatus(WorkflowStatus.READY_FOR_PUBLICATION);

        // clear labels
        mapRecord.setLabels(new HashSet<String>());

        newRecords.clear();
        newRecords.add(mapRecord);
        break;
      case SAVE_FOR_LATER:
        if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.QA_NEW)) {
          mapRecord.setWorkflowStatus(WorkflowStatus.QA_IN_PROGRESS);
        }
        if (mapRecord.getWorkflowStatus().equals(WorkflowStatus.QA_RESOLVED)) {
          mapRecord.setWorkflowStatus(WorkflowStatus.QA_IN_PROGRESS);
        }

        break;
      case UNASSIGN:

        MapRecord revisionRecord = null;
        MapRecord qaNeededRecord = null;
        MapRecord editRecord = null;
        for (MapRecord mr : mapRecords) {
          if (mr.getWorkflowStatus().equals(WorkflowStatus.REVISION))
            revisionRecord = mr;
          else if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEEDED))
            qaNeededRecord = mr;
          else if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_IN_PROGRESS)
              || mr.getWorkflowStatus().equals(WorkflowStatus.QA_RESOLVED)
              || mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEW))
            editRecord = mr;
        }

        if (revisionRecord == null)
          throw new Exception(
              "Attempted to unassign a published revision record, but no such previously published record exists!");

        // Case 1: A lead unassigns themselves from reviewing a fixed
        // error, delete the lead's record, no other action required
        if (editRecord != null) {
          newRecords.remove(editRecord);

        }
        // Case 2: The concept is removed from QA, and unassigned from
        // the qa user
        else if (qaNeededRecord != null) {

          // clear the record set
          newRecords.clear();

          WorkflowService workflowService = new WorkflowServiceJpa();

          try {

            // get the previously published version of the revision
            // record
            revisionRecord.setWorkflowStatus(workflowService
                .getPreviouslyPublishedVersionOfMapRecord(revisionRecord)
                .getWorkflowStatus());

            // clear any labels
            revisionRecord.setLabels(new HashSet<String>());

            // remove all records and re-add the revision record
            newRecords.clear();
            newRecords.add(revisionRecord);

          } catch (Exception e) {
            throw e;
          } finally {
            workflowService.close();
          }
        } else {

          throw new Exception(
              "Unexpected error attempt to unassign a QA record.  Contact an administrator.");
        }

        break;
      default:
        throw new Exception(
            getName() + ": Unexpected workfow action " + workflowAction);
    }

    return newRecords;
  }

  @Override
  public MapRecordList getOriginMapRecordsForMapRecord(MapRecord mapRecord,
    WorkflowService workflowService) throws Exception {

    MapRecordList originRecords = new MapRecordListJpa();

    boolean qaNeededFound = true;

    for (final Long originId : mapRecord.getOriginIds()) {
      MapRecord mr = workflowService.getMapRecord(originId);
      try {

        if (mr.getWorkflowStatus().equals(WorkflowStatus.QA_NEEDED)) {
          qaNeededFound = true;
          originRecords.addMapRecord(workflowService.getMapRecord(originId));
        }
      } catch (Exception e) {
        // if not a null pointer exception due to
        // audited reference not presently in database,
        // rethrow the exception
        if (mr != null) {
          throw new Exception(e);
        }
      }
    }

    if (originRecords.getCount() == 1) {
      originRecords.setTotalCount(originRecords.getCount());
      if (qaNeededFound == false) {
        throw new Exception(
            "Could not retrieve record needing review along QA Path");
      }

      return originRecords;
    } else {
      throw new Exception(
          "Expected two origin records for review but instead found "
              + originRecords.getCount());
    }
  }

}


text:
(function (enyo, scope) {

	/**
	* Fires when a row is being initialized.
	*
	* @event onyx.FlyweightPicker#onSetupItem
	* @type {Object}
	* @property {Number} index - The row index.
	* @property {enyo.Control} flyweight - The row control, for decoration.
	* @see enyo.FlyweightRepeater.onSetupItem
	* @public
	*/

	/**
	* Fires when an item is selected.
	*
	* @event onyx.FlyweightPicker#onSelect
	* @type {Object}
	* @property {String} content - Content of the selected item.
	* @property {Number} selected - Row index of the selected item.
	* @public
	*/

	/**
	* {@link onyx.FlyweightPicker}, a subkind of {@link onyx.Picker}, is a picker
	* that employs the flyweight pattern. It is used to display a large list of
	* selectable items.	As with {@link enyo.FlyweightRepeater}, the
	* [onSetupItem]{@link onyx.FlyweightPicker#onSetupItem} event allows for
	* customization of item rendering.
	*
	* To initialize the FlyweightPicker to a particular value, call `setSelected()`
	* with the index of the item you wish to select, and call `setContent()` with
	* the item that should be shown in the activator button.
	*
	* When an item is selected, FlyweightPicker sends an
	* [onSelect]{@link onyx.FlyweightPicker#onSelect} event with the selected
	* item's information. This may be handled by a client application to determine
	* which item was selected.
	*
	* ```
	* enyo.kind({
	* 	handlers: {
	* 		onSelect: 'itemSelected'
	* 	},
	* 	components: [
	* 		{kind: 'onyx.PickerDecorator', components: [
	* 			{},
	* 			{name: 'yearPicker', kind: 'onyx.FlyweightPicker', count: 200,
	* 				onSetupItem: 'setupYear', components: [
	* 					{name: 'year'}
	* 				]
	* 			}
	* 		]}
	* 	],
	* 	create: function () {
	* 		var d = new Date();
	* 		var y = d.getYear();
	* 		this.$.yearPicker.setSelected(y);
	* 		this.$.year.setContent(1900+y);
	* 	},
	* 	setupYear: function (sender, event) {
	* 		this.$.year.setContent(1900+event.index);
	* 	},
	* 	itemSelected: function (sender, event) {
	* 		enyo.log('Picker Item Selected: ' + event.selected.content);
	* 	}
	* })
	* ```
	*
	* @class   onyx.FlyweightPicker
	* @extends onyx.Picker
	* @ui
	* @public
	*/
	enyo.kind(
		/** @lends onyx.FlyweightPicker.prototype */ {

		/**
		* @private
		*/
		name: 'onyx.FlyweightPicker',

		/**
		* @private
		*/
		kind: 'onyx.Picker',

		/**
		* @private
		*/
		classes: 'onyx-flyweight-picker',

		/**
		* @lends  onyx.FlyweightPicker.prototype
		* @private
		*/
		published: {
			/**
			* The number of rows to render.
			*
			* @type {Number}
			* @default  0
			* @public
			*/
			count: 0
		},

		/**
		* @private
		*/
		events: {
			onSetupItem: '',
			onSelect: ''
		},

		/**
		* @private
		*/
		handlers: {
			onSelect: 'itemSelect'
		},

		/**
		* @private
		*/
		components: [
			{name: 'scroller', kind: 'enyo.Scroller', strategyKind: 'TouchScrollStrategy', components: [
				{name: 'flyweight', kind: 'FlyweightRepeater', noSelect: true, ontap: 'itemTap'}
			]}
		],

		/**
		* @private
		*/
		scrollerName: 'scroller',

		/**
		* Force the flyweight's client control ([MenuItem]{@link onyx.MenuItem} by default)
		* to activate. This will result in a call to `processActivatedItem()`, which preps
		* our picker selection logic. This is a workaround for changes caused by ENYO-1609
		* which resulted in ENYO-1611.
		*
		* @private
		*/
		initComponents: function () {
			this.controlParentName = 'flyweight';
	        this.inherited(arguments);
			this.$.flyweight.$.client.children[0].setActive(true);
	    },

		/**
		* @private
		*/
		create: function () {
			this.inherited(arguments);
			this.countChanged();
		},

		/**
		* @private
		*/
		rendered: function () {
			this.inherited(arguments);
			this.selectedChanged();
		},

		/**
		* Scrolls the [selected]{@link onyx.FlyweightPicker#selected} control into view.
		*
		* @public
		*/
		scrollToSelected: function () {
			var n = this.$.flyweight.fetchRowNode(this.selected);
			this.getScroller().scrollToNode(n, !this.menuUp);
		},

		/**
		* @private
		*/
		countChanged: function () {
			this.$.flyweight.count = this.count;
		},

		/**
		* @private
		*/
		processActivatedItem: function (item) {
			this.item = item;
		},

		/**
		* @fires onyx.Picker#onChange
		* @private
		*/
		selectedChanged: function (old) {
			if (!this.item) {
				return;
			}
			if (old != null) {
				this.item.removeClass('selected');
				this.$.flyweight.renderRow(old);
			}
			var n;
			if (this.selected != null) {
				this.item.addClass('selected');
				this.$.flyweight.renderRow(this.selected);
				// need to remove the class from control to make sure it won't apply to other rows
				this.item.removeClass('selected');
				n = this.$.flyweight.fetchRowNode(this.selected);
			}
			this.doChange({selected: this.selected, content: n && n.textContent || this.item.content});
		},

		/**
		* @fires onyx.FlyweightPicker#onSelect
		* @private
		*/
		itemTap: function (sender, event) {
			this.setSelected(event.rowIndex);
			//Send the select event that we want the client to receive.
			this.doSelect({selected: this.item, content: this.item.content});
		},

		/**
		* Blocks all `select` events that aren't coming from this control. This is to
		* prevent `select` events from MenuItems since they won't have the correct value
		* in a Flyweight context.
		*
		* @private
		*/
		itemSelect: function (sender, event) {
			if (event.originator != this) {
				return true;
			}
		}
	});

})(enyo, this);


text:
using System;

using System.IO;

using System.Text.RegularExpressions;

class UseYourChainsBuddy

{

    static void Main()

    {

        // input

        Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));

        string html = Console.ReadLine();

        // regex patterns

        string pattern = @"<p>(.[^\/]+)<\/p>";

        string regex = @"[^a-z0-9]+";

        // logic - collecting the alpanumeric characters

        Regex words = new Regex(pattern);

        MatchCollection matches = words.Matches(html);

        string encrypted = "";

        for (int i = 0; i < matches.Count; i++)

        {

            string temp = matches[i].Groups[1].Value;

            encrypted += Regex.Replace(temp, regex, word => " ");

        }

        // decrypting

        string manual = "";

        for (int i = 0; i < encrypted.Length; i++)

        {

            if (encrypted[i] >= 'a' && encrypted[i] <= 'm')

            {

                manual += (char)(encrypted[i] + 13);

                //Console.WriteLine(manual);

            }

            else if (encrypted[i] >= 'n' && encrypted[i] <= 'z')

            {

                manual += (char)(encrypted[i] - 13);

            }

            else if (Char.IsDigit(encrypted[i]) || Char.IsWhiteSpace(encrypted[i]))

            {

                manual += encrypted[i];

            }

        }

        Console.WriteLine(manual);

    }

}


text:
import path from 'path';

const OPTIONS_NOT_FOUND_ERROR = 'Options are missed';
const GULP_NOT_DEFINED_ERROR = 'Gulp is missed';
const DIR_NOT_DEFINED_ERROR = 'Target directory is missed';
const INVALID_MODULE_ERROR = 'Invalid task factory module';
const INVALID_FILTER_ERROR = 'Invalid task filter';

/**
 * Validates and builds options.
 * @param params {Object} - Passed options.
 * @returns {Object} - Normalized options.
 */
export function getOptions(params) {
    if (!params) {
        throw new Error(OPTIONS_NOT_FOUND_ERROR);
    }

    if (!params.gulp) {
        throw new Error(GULP_NOT_DEFINED_ERROR);
    }

    if (!params.dir) {
        throw new Error(DIR_NOT_DEFINED_ERROR);
    }

    if (params.filter != null) {
        if (typeof params.filter !== 'string' && typeof params.filter !== 'function') {
            throw new Error(INVALID_FILTER_ERROR);
        }
    }

    return {
        gulp: params.gulp,
        dir: params.dir,
        args: params.args || [],
        panic: !!params.panic,
        group: !!params.group,
        verbose: !!params.verbose,
        filter: params.filter
    };
}

/**
 * Returns task's factory function.
 * @param module {Any} - Target module.
 * @returns {Function} - Task's factory function.
 */
export function getFactory(module) {
    if (!module) {
        throw new Error(INVALID_MODULE_ERROR);
    }

    if (typeof module === 'function') {
        return module;
    }

    if (typeof module.default === 'function') {
        return module.default;
    }

    throw new Error(INVALID_MODULE_ERROR);
}

/**
 * Creates task's path.
 * @param root {String} - Root directory.
 * @param current {String} - Current task's directory.
 * @returns {String} - Task's fpath.
 */
export function getPath(root, current) {
    const part = path.relative(root, current);

    if (part) {
        return part.split(/\/|\\/g).join(':');
    }

    return '';
}


text:
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview An interface to control the ChromeVox Panel.
 */

export class PanelInterface {
  /**
   * Close the menus and restore focus to the page. If a menu item's callback
   * was queued, execute it once focus is restored.
   */
  closeMenusAndRestoreFocus() {}

  /**
   * A callback function to be executed to perform the action from selecting
   * a menu item after the menu has been closed and focus has been restored
   * to the page or wherever it was previously.
   * @param {?Function} callback
   */
  setPendingCallback(callback) {}
}

/** @type {PanelInterface} */
PanelInterface.instance;