text:
package org.spongepowered.common.service.ban;

import net.minecraft.server.management.UserListBans;
import net.minecraft.server.management.UserListEntry;
import net.minecraft.server.management.UserListIPBans;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.User;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.profile.GameProfile;
import org.spongepowered.api.service.ban.BanService;
import org.spongepowered.api.service.user.UserStorageService;
import org.spongepowered.api.util.ban.Ban;
import org.spongepowered.api.util.ban.BanTypes;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.util.UserListUtils;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

/**
 * The default implementation of {@link BanService}.
 *
 *
Many of the methods here are copied from {@link UserListBans}
 * or {@link UserListIPBans}, while the original methods have been changed
 * to delegate to the registered {@link BanService}. This allows bans to
 * function normally when the default {@link BanService} has not been replaced,
 * while allowing plugin-provided {@link BanService}s to be used for all aspects
 * of Vanilla bans.

 */
public class SpongeBanService implements BanService {

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public Collection<Ban> getBans() {
        Collection<? extends Ban> bans = this.getProfileBans();
        bans.addAll((Collection) this.getIpBans());

        return (Collection<Ban>) bans;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Collection<Ban.Profile> getProfileBans() {
        this.getUserBanList().removeExpired();
        return new ArrayList<>((Collection<Ban.Profile>) (Object) this.getUserBanList().getValues().values());
    }

    @SuppressWarnings("unchecked")
    @Override
    public Collection<Ban.Ip> getIpBans() {
        this.getIPBanList().removeExpired();
        return new ArrayList<>((Collection<Ban.Ip>) (Object) this.getIPBanList().getValues().values());
    }

    @Override
    public Optional<Ban.Profile> getBanFor(GameProfile profile) {
        UserListBans bans = this.getUserBanList();

        bans.removeExpired();
        return Optional.ofNullable((Ban.Profile) bans.getValues().get(bans.getObjectKey((com.mojang.authlib.GameProfile) profile)));
    }

    @Override
    public Optional<Ban.Ip> getBanFor(InetAddress address) {
        UserListIPBans bans = this.getIPBanList();

        bans.removeExpired();
        return Optional.ofNullable((Ban.Ip) bans.getValues().get(bans.getObjectKey(bans.addressToString(new InetSocketAddress(address, 0)))));
    }

    @Override
    public boolean isBanned(GameProfile profile) {
        UserListBans bans = this.getUserBanList();

        bans.removeExpired();
        return bans.values.containsKey(bans.getObjectKey((com.mojang.authlib.GameProfile) profile));
    }

    @Override
    public boolean isBanned(InetAddress address) {
        UserListIPBans bans = this.getIPBanList();

        bans.removeExpired();
        return bans.getValues().containsKey(bans.getObjectKey(bans.addressToString(new InetSocketAddress(address, 0))));
    }

    @Override
    public boolean pardon(GameProfile profile) {
        this.getUserBanList().removeExpired();
        boolean hadBan = this.isBanned(profile);
        UserListUtils.removeEntry(this.getUserBanList(), profile);
        return hadBan;
    }

    @Override
    public boolean pardon(InetAddress address) {
        UserListIPBans banList = this.getIPBanList();

        banList.removeExpired();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(address, 0);
        boolean hadBan = this.isBanned(address);
        UserListUtils.removeEntry(banList, banList.addressToString(inetSocketAddress));
        return hadBan;
    }

    @Override
    public boolean removeBan(Ban ban) {
        if (ban.getType().equals(BanTypes.PROFILE)) {
            return this.pardon(((Ban.Profile) ban).getProfile());
        } else if (ban.getType().equals(BanTypes.IP)) {
            return this.pardon(((Ban.Ip) ban).getAddress());
        }
        throw new IllegalArgumentException(String.format("Ban %s had unrecognized BanType %s!", ban, ban.getType()));
    }

    @Override
    public Optional<? extends Ban> addBan(Ban ban) {
        Optional<? extends Ban> prevBan;

        if (ban.getType().equals(BanTypes.PROFILE)) {
            prevBan = this.getBanFor(((Ban.Profile) ban).getProfile());

            User user = Sponge.getServiceManager().provideUnchecked(UserStorageService.class).getOrCreate(((Ban.Profile) ban).getProfile());
            Sponge.getEventManager().post(SpongeEventFactory.createBanUserEvent(Sponge.getCauseStackManager().getCurrentCause(), (Ban.Profile) ban, user));

            UserListUtils.addEntry(this.getUserBanList(), (UserListEntry<?>) ban);
        } else if (ban.getType().equals(BanTypes.IP)) {
            prevBan = this.getBanFor(((Ban.Ip) ban).getAddress());

            Sponge.getEventManager().post(SpongeEventFactory.createBanIpEvent(Sponge.getCauseStackManager().getCurrentCause(), (Ban.Ip) ban));

            UserListUtils.addEntry(this.getIPBanList(), (UserListEntry<?>) ban);
        } else {
            throw new IllegalArgumentException(String.format("Ban %s had unrecognized BanType %s!", ban, ban.getType()));
        }
        return prevBan;
    }

    @Override
    public boolean hasBan(Ban ban) {
        if (ban.getType().equals(BanTypes.PROFILE)) {
            return this.isBanned(((Ban.Profile) ban).getProfile());
        } else if (ban.getType().equals(BanTypes.IP)) {
            return this.isBanned(((Ban.Ip) ban).getAddress());
        }
        throw new IllegalArgumentException(String.format("Ban %s had unrecognized BanType %s!", ban, ban.getType()));
    }

    private UserListBans getUserBanList() {
        return SpongeImpl.getServer().getPlayerList().getBannedPlayers();
    }

    private UserListIPBans getIPBanList() {
        return SpongeImpl.getServer().getPlayerList().getBannedIPs();
    }

}


text:
from .constant_product import ConstantProduct
from msrest.serialization import Model

class Product(Model):
    """
    The product documentation.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :param display_names: Non required array of unique items from 0 to 6
     elements.
    :type display_names: list of str
    :param capacity: Non required int betwen 0 and 100 exclusive.
    :type capacity: int
    :param image: Image URL representing the product.
    :type image: str
    :param child:
    :type child: :class:`ChildProduct
     <fixtures.acceptancetestsvalidation.models.ChildProduct>`
    :ivar const_child:
    :vartype const_child: :class:`ConstantProduct
     <fixtures.acceptancetestsvalidation.models.ConstantProduct>`
    :ivar const_int: Constant int. Default value: 0 .
    :vartype const_int: int
    :ivar const_string: Constant string. Default value: "constant" .
    :vartype const_string: str
    :param const_string_as_enum: Constant string as Enum. Possible values
     include: 'constant_string_as_enum'
    :type const_string_as_enum: str or :class:`EnumConst
     <fixtures.acceptancetestsvalidation.models.EnumConst>`
    """

    _validation = {
        'display_names': {'max_items': 6, 'min_items': 0, 'unique': True},
        'capacity': {'maximum_ex': 100, 'minimum_ex': 0},
        'image': {'pattern': 'http://\w+'},
        'child': {'required': True},
        'const_child': {'required': True, 'constant': True},
        'const_int': {'required': True, 'constant': True},
        'const_string': {'required': True, 'constant': True},
    }

    _attribute_map = {
        'display_names': {'key': 'display_names', 'type': '[str]'},
        'capacity': {'key': 'capacity', 'type': 'int'},
        'image': {'key': 'image', 'type': 'str'},
        'child': {'key': 'child', 'type': 'ChildProduct'},
        'const_child': {'key': 'constChild', 'type': 'ConstantProduct'},
        'const_int': {'key': 'constInt', 'type': 'int'},
        'const_string': {'key': 'constString', 'type': 'str'},
        'const_string_as_enum': {'key': 'constStringAsEnum', 'type': 'EnumConst'},
    }

    const_child = ConstantProduct()

    const_int = 0

    const_string = "constant"

    def __init__(self, child, display_names=None, capacity=None, image=None, const_string_as_enum=None):
        self.display_names = display_names
        self.capacity = capacity
        self.image = image
        self.child = child
        self.const_string_as_enum = const_string_as_enum

redpajama_set_name: RedPajamaGithub


text:
package com.linecorp.armeria.common;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.ProgressivePromise;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.ScheduledFuture;

/**
 * A delegating {@link EventExecutor} that makes sure all submitted tasks are
 * executed within the {@link RequestContext}.
 */
final class RequestContextAwareEventLoop implements EventLoop {

    private final RequestContext context;
    private final EventLoop delegate;

    RequestContextAwareEventLoop(RequestContext context,EventLoop delegate) {
        this.context = context;
        this.delegate = delegate;
    }

    @Override
    public EventLoop next() {
        return delegate.next();
    }

    @Override
    public EventLoopGroup parent() {
        return delegate.parent();
    }

    @Override
    public boolean inEventLoop() {
        return delegate.inEventLoop();
    }

    @Override
    public boolean inEventLoop(Thread thread) {
        return delegate.inEventLoop(thread);
    }

    @Override
    public <V> Promise<V> newPromise() {
        return new RequestContextAwarePromise<>(context, delegate.newPromise());
    }

    @Override
    public <V> ProgressivePromise<V> newProgressivePromise() {
        return new RequestContextAwareProgressivePromise<>(context, delegate.newProgressivePromise());
    }

    @Override
    public <V> Future<V> newSucceededFuture(V result) {
        return new RequestContextAwareFuture<>(context, delegate.newSucceededFuture(result));
    }

    @Override
    public <V> Future<V> newFailedFuture(Throwable cause) {
        return new RequestContextAwareFuture<>(context, delegate.newFailedFuture(cause));
    }

    @Override
    public boolean isShuttingDown() {
        return delegate.isShuttingDown();
    }

    @Override
    public Future<?> shutdownGracefully() {
        return delegate.shutdownGracefully();
    }

    @Override
    public Future<?> shutdownGracefully(long quietPeriod, long timeout,
                                        TimeUnit unit) {
        return delegate.shutdownGracefully(quietPeriod, timeout, unit);
    }

    @Override
    public Future<?> terminationFuture() {
        return delegate.terminationFuture();
    }

    @Override
    public void shutdown() {
        delegate.shutdown();
    }

    @Override
    public List<Runnable> shutdownNow() {
        return delegate.shutdownNow();
    }

    @Override
    public Iterator<EventExecutor> iterator() {
        return delegate.iterator();
    }

    @Override
    public Future<?> submit(Runnable task) {
        return delegate.submit(context.makeContextAware(task));
    }

    @Override
    public <T> Future<T> submit(Runnable task, T result) {
        return delegate.submit(context.makeContextAware(task), result);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        return delegate.submit(context.makeContextAware(task));
    }

    @Override
    public ScheduledFuture<?> schedule(Runnable command, long delay,
                                       TimeUnit unit) {
        return delegate.schedule(context.makeContextAware(command), delay, unit);
    }

    @Override
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit) {
        return delegate.schedule(context.makeContextAware(callable), delay, unit);
    }

    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay,
                                                  long period,
                                                  TimeUnit unit) {
        return delegate.scheduleAtFixedRate(context.makeContextAware(command), initialDelay, period, unit);
    }

    @Override
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,
                                                     long delay,
                                                     TimeUnit unit) {
        return delegate.scheduleWithFixedDelay(context.makeContextAware(command), initialDelay, delay, unit);
    }

    @Override
    public boolean isShutdown() {
        return delegate.isShutdown();
    }

    @Override
    public boolean isTerminated() {
        return delegate.isTerminated();
    }

    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        return delegate.awaitTermination(timeout, unit);
    }

    @Override
    public <T> List<java.util.concurrent.Future<T>> invokeAll(
            Collection<? extends Callable<T>> tasks) throws InterruptedException {
        return delegate.invokeAll(makeContextAware(tasks));
    }

    @Override
    public <T> List<java.util.concurrent.Future<T>> invokeAll(
            Collection<? extends Callable<T>> tasks, long timeout,
            TimeUnit unit) throws InterruptedException {
        return delegate.invokeAll(makeContextAware(tasks), timeout, unit);
    }

    @Override
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
            throws InterruptedException, ExecutionException {
        return delegate.invokeAny(makeContextAware(tasks));
    }

    @Override
    public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout,
                           TimeUnit unit) throws InterruptedException, ExecutionException,
                                                 TimeoutException {
        return delegate.invokeAny(makeContextAware(tasks), timeout, unit);
    }

    @Override
    public void execute(Runnable command) {
        delegate.execute(context.makeContextAware(command));
    }

    private <T> Collection<? extends Callable<T>> makeContextAware(
            Collection<? extends Callable<T>> tasks) {
        return tasks.stream().map(context::makeContextAware).collect(Collectors.toList());
    }

    @Override
    public ChannelFuture register(Channel channel) {
        return delegate.register(channel);
    }

    @Override
    public ChannelFuture register(ChannelPromise channelPromise) {
        return delegate.register(channelPromise);
    }

    @Override
    public ChannelFuture register(Channel channel,
                                  ChannelPromise channelPromise) {
        return delegate.register(channel, channelPromise);
    }
}


text:
package com.jtattoo.plaf;

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;

/**
 * @author Michael Hagen
 */
public class BaseButtonUI extends BasicButtonUI {

    protected static Rectangle viewRect = new Rectangle();
    protected static Rectangle textRect = new Rectangle();
    protected static Rectangle iconRect = new Rectangle();

    public static ComponentUI createUI(JComponent c) {
        return new BaseButtonUI();
    }

    public void installDefaults(AbstractButton b) {
        super.installDefaults(b);
        b.setOpaque(false);
    }

    public void uninstallDefaults(AbstractButton b) {
        super.uninstallDefaults(b);
        b.setOpaque(true);
    }

    protected BasicButtonListener createButtonListener(AbstractButton b) {
        return new BaseButtonListener(b);
    }

    protected void paintBackground(Graphics g, AbstractButton b) {
        if (!b.isContentAreaFilled() || (b.getParent() instanceof JMenuBar)) {
            return;
        }

        int width = b.getWidth();
        int height = b.getHeight();
        Color colors[] = null;
        ButtonModel model = b.getModel();
        if (b.isEnabled()) {
            if (b.getBackground() instanceof ColorUIResource) {
                if (model.isPressed() && model.isArmed()) {
                    colors = AbstractLookAndFeel.getTheme().getPressedColors();
                } else {
                    if (model.isRollover()) {
                        colors = AbstractLookAndFeel.getTheme().getRolloverColors();
                    } else {
                        if (AbstractLookAndFeel.getTheme().doShowFocusFrame() && b.hasFocus()) {
                            colors = AbstractLookAndFeel.getTheme().getFocusColors();
                        } else {
                            colors = AbstractLookAndFeel.getTheme().getButtonColors();
                        }
                    }
                }
            } else {
                if (model.isPressed() && model.isArmed()) {
                    colors = ColorHelper.createColorArr(b.getBackground(), ColorHelper.darker(b.getBackground(), 50), 20);
                } else {
                    if (model.isRollover()) {
                        colors = ColorHelper.createColorArr(ColorHelper.brighter(b.getBackground(), 80), ColorHelper.brighter(b.getBackground(), 20), 20);
                    } else {
                        colors = ColorHelper.createColorArr(ColorHelper.brighter(b.getBackground(), 40), ColorHelper.darker(b.getBackground(), 20), 20);
                    }
                }
            }
        } else { // disabled
            colors = AbstractLookAndFeel.getTheme().getDisabledColors();
        }
        if (b.isBorderPainted() && (b.getBorder() != null)) {
            Insets insets = b.getBorder().getBorderInsets(b);
            int x = insets.left > 0 ? 1 : 0;
            int y = insets.top > 0 ? 1 : 0;
            int w = insets.right > 0 ? width - 1 : width;
            int h = insets.bottom > 0 ? height - 1 : height;
            JTattooUtilities.fillHorGradient(g, colors, x, y, w - x, h - y);
        } else {
            JTattooUtilities.fillHorGradient(g, colors, 0, 0, width, height);
        }
    }

    protected void paintText(Graphics g, AbstractButton b, Rectangle textRect) {
        ButtonModel model = b.getModel();
        FontMetrics fm = g.getFontMetrics();
        int mnemIndex = -1;
        if (JTattooUtilities.getJavaVersion() >= 1.4) {
            mnemIndex = b.getDisplayedMnemonicIndex();
        } else {
            mnemIndex = JTattooUtilities.findDisplayedMnemonicIndex(b.getText(), model.getMnemonic());
        }

        if (model.isEnabled()) {
            int offs = 0;
            if (model.isArmed() && model.isPressed()) {
                offs = 1;
            }
            g.setColor(b.getForeground());
            JTattooUtilities.drawStringUnderlineCharAt(b, g, b.getText(), mnemIndex, textRect.x + offs, textRect.y + offs + fm.getAscent());
        } else {
            g.setColor(Color.white);
            JTattooUtilities.drawStringUnderlineCharAt(b, g, b.getText(), mnemIndex, textRect.x + 1, textRect.y + 1 + fm.getAscent());
            g.setColor(AbstractLookAndFeel.getDisabledForegroundColor());
            JTattooUtilities.drawStringUnderlineCharAt(b, g, b.getText(), mnemIndex, textRect.x, textRect.y + fm.getAscent());
        }
    }

    protected void paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {
        g.setColor(AbstractLookAndFeel.getFocusColor());
        BasicGraphicsUtils.drawDashedRect(g, 4, 3, b.getWidth() - 8, b.getHeight() - 6);
    }

    public void paint(Graphics g, JComponent c) {
        Graphics2D g2D = (Graphics2D) g;

        AbstractButton b = (AbstractButton) c;
        Font f = c.getFont();
        g.setFont(f);
        FontMetrics fm = g.getFontMetrics();
        Insets insets = c.getInsets();

        viewRect.x = insets.left;
        viewRect.y = insets.top;
        viewRect.width = b.getWidth() - (insets.right + viewRect.x);
        viewRect.height = b.getHeight() - (insets.bottom + viewRect.y);

        textRect.x = textRect.y = textRect.width = textRect.height = 0;
        iconRect.x = iconRect.y = iconRect.width = iconRect.height = 0;

        int iconTextGap = defaultTextIconGap;
        if (JTattooUtilities.getJavaVersion() >= 1.4) {
            iconTextGap = b.getIconTextGap();
        }
        String text = SwingUtilities.layoutCompoundLabel(
                c, fm, b.getText(), b.getIcon(),
                b.getVerticalAlignment(), b.getHorizontalAlignment(),
                b.getVerticalTextPosition(), b.getHorizontalTextPosition(),
                viewRect, iconRect, textRect,
                b.getText() == null ? 0 : iconTextGap);

        paintBackground(g, b);

        if (b.getIcon() != null) {
            if (!b.isEnabled()) {
                Composite composite = g2D.getComposite();
                AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
                g2D.setComposite(alpha);
                paintIcon(g, c, iconRect);
                g2D.setComposite(composite);
            } else {
                if (b.getModel().isPressed() && b.getModel().isRollover()) {
                    iconRect.x++;
                    iconRect.y++;
                }
                paintIcon(g, c, iconRect);
            }
        }

        if (text != null && !text.equals("")) {
            View v = (View) c.getClientProperty(BasicHTML.propertyKey);
            if (v != null) {
                Object savedRenderingHint = null;
                if (AbstractLookAndFeel.getTheme().isTextAntiAliasingOn()) {
                    savedRenderingHint = g2D.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
                    g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                }
                v.paint(g, textRect);
                if (AbstractLookAndFeel.getTheme().isTextAntiAliasingOn()) {
                    g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, savedRenderingHint);
                }
            } else {
                paintText(g, b, textRect);
            }
        }

        if (b.isFocusPainted() && b.hasFocus()) {
            paintFocus(g, b, viewRect, textRect, iconRect);
        }
    }
}


text:
package com.netflix.spinnaker.igor.scm;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import retrofit.RetrofitError;

/** Exposes APIs to retrieve Managed Delivery declarative manifests from source control repos. */
@RestController
public class ManagedDeliveryScmController {
  private static final Logger log = LoggerFactory.getLogger(AbstractCommitController.class);

  private final ManagedDeliveryScmService mdScmService;

  public ManagedDeliveryScmController(ManagedDeliveryScmService mdScmService) {
    this.mdScmService = mdScmService;
  }

  /**
   * Given details about a supported git source control repository, and optional filters for a
   * sub-directory within the repo, the file extensions to look for, and the specific git reference
   * to use, returns a list of (potential) Managed Delivery config manifests found at that location.
   *
   *
Note that this method does not recurse the specified sub-directory when listing files.
   */
  @GetMapping("/delivery-config/manifests")
  public List<String> listDeliveryConfigManifests(
      @RequestParam final String scmType,
      @RequestParam final String project,
      @RequestParam final String repository,
      @RequestParam(required = false) final String directory,
      @RequestParam(required = false) final String extension,
      @RequestParam(required = false) final String ref) {

    return mdScmService.listDeliveryConfigManifests(
        scmType, project, repository, directory, extension, ref);
  }

  /**
   * Given details about a supported git source control repository, the filename of a Managed
   * Delivery config manifest, and optional filters for a sub-directory within the repo and the
   * specific git reference to use, returns the contents of the manifest.
   *
   *
This API supports both YAML and JSON for the format of the manifest in source control, but
   * always returns the contents as JSON.
   */
  @GetMapping(path = "/delivery-config/manifest")
  public ResponseEntity<Map<String, Object>> getDeliveryConfigManifest(
      @RequestParam String scmType,
      @RequestParam final String project,
      @RequestParam final String repository,
      @RequestParam final String manifest,
      @RequestParam(required = false) final String directory,
      @RequestParam(required = false) final String ref) {
    try {
      return new ResponseEntity<>(
          mdScmService.getDeliveryConfigManifest(
              scmType, project, repository, directory, manifest, ref),
          HttpStatus.OK);
    } catch (Exception e) {
      HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
      Object errorDetails = e.getMessage();
      if (e instanceof IllegalArgumentException) {
        status = HttpStatus.BAD_REQUEST;
      } else if (e instanceof RetrofitError) {
        RetrofitError re = (RetrofitError) e;
        if (re.getKind() == RetrofitError.Kind.HTTP) {
          status = HttpStatus.valueOf(re.getResponse().getStatus());
          errorDetails = re.getBodyAs(Map.class);
        } else {
          errorDetails = "Error calling downstream system: " + re.getMessage();
        }
      }
      return buildErrorResponse(status, errorDetails);
    }
  }

  private ResponseEntity<Map<String, Object>> buildErrorResponse(
      HttpStatus status, Object errorDetails) {
    Map<String, Object> error = Collections.singletonMap("error", errorDetails);
    return new ResponseEntity<>(error, status);
  }
}


text:
node[:deploy].each do |application, deploy|

  unless deploy.has_key(:wordpress)
    Chef::Log.debug("Skipping wordpress::configure for #{application} as it is not a WordPress app")
    next
  end

  # Create wp-config.php

  # WordPress requires authentication keys for security. They need to be the same across all our app servers.
  authentication_keys = {
    'AUTH_KEY': deploy[:wordpress][:auth_key],
    'SECURE_AUTH_KEY': deploy[:wordpress][:secure_auth_key],
    'LOGGED_IN_KEY': deploy[:wordpress][:logged_in_key],
    'NONCE_KEY': deploy[:wordpress][:nonce_key],
    'AUTH_SALT': deploy[:wordpress][:auth_key],
    'SECURE_AUTH_SALT': deploy[:wordpress][:secure_auth_key],
    'LOGGED_IN_SALT': deploy[:wordpress][:logged_in_salt],
    'NONCE_SALT': deploy[:wordpress][:nonce_salt],
  }

  template "#{deploy[:deploy_to]}/shared/wp-config.php" do
    source 'wp-config.php.erb'
    mode 0660
    group deploy[:group]

    if platform?('ubuntu')
      owner 'www-data'
    elsif platform?('amazon')
      owner 'apache'
    end

    variables {
      database_name: deploy[:database].fetch(:database),
      database_username: deploy[:database].fetch(:username),
      database_password: deploy[:database].fetch(:password),
      database_host: deploy[:database].fetch(:host),
      authentication_keys: authentication_keys
    }

    only_if do
      deploy[:database].present? && File.directory?("#{deploy[:deploy_to]}/shared/")
    end
  end

  # Create cron job to call wp-cron.php

  # TODO Need to figure out how to find the correct domain to call wget on.
  # TODO Find out how to run this on just one machine? Or should it run on all of them?
  #cron "wordpress" do
  #  hour "*"
  #  minute "*/15"
  #  weekday "*"
  #  command "wget -q -O - http://localhost/wp-cron.php?doing_wp_cron >/dev/null 2>&1"
  #end

end


text:
<?php

namespace Intervention\Gif\Encoder;

use Intervention\Gif\AbstractEntity;
use Intervention\Gif\Exception\EncoderException;
use Intervention\Gif\ImageData;

class ImageDataEncoder extends AbstractEncoder
{
    /**
     * Create new instance
     *
     * @param ImageData $source
     */
    public function __construct(ImageData $source)
    {
        $this->source = $source;
    }

    /**
     * Encode current source
     *
     * @return string
     */
    public function encode(): string
    {
        if (! $this->source->hasBlocks()) {
            throw new EncoderException("No data blocks in ImageData.");
        }

        return implode('', [
            pack('C', $this->source->getLzwMinCodeSize()),
            implode('', array_map(function ($block) {
                return $block->encode();
            }, $this->source->getBlocks())),
            AbstractEntity::TERMINATOR,
        ]);
    }
}


text:
from unittest import TestCase
import inspect
from ..sipmessaging import SIPHeaderFieldFactory
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

class AbstractSIPHeaderFieldFromFactoryTestCase(TestCase):
    @property
    def canonicalStrings(self):
        answer = []
        for field_name in self.canonicalFieldNames + self.canonicalCompactFieldNames:
            for field_value_string in self.canonicalFieldValues:
                answer.append(field_name + ": " + field_value_string)
                answer.append(field_name + ":     " + field_value_string)
                answer.append(field_name + "    : " + field_value_string)
                answer.append(field_name + "    :     " + field_value_string)
        return answer

    @property
    def canonicalFieldNames(self):
        raise NotImplementedError('call to abstract method ' + inspect.stack()[0][3])

    @property
    def canonicalCompactFieldNames(self):
        name = self.sipHeaderFieldClassUnderTest.canonical_compact_field_name
        if name:
            return [name.lower(), name.upper()]
        else:
            return []

    @property
    def canonicalFieldValues(self):
        return ["baz blarg blonk"]

    @property
    def emptyHeaderFieldBodyIsValid(self):
        return True

    @property
    def sipHeaderFieldClassUnderTest(self):
        raise NotImplementedError('call to abstract method ' + inspect.stack()[0][3])

    def basic_test_parsing(self):
        for line in self.canonicalStrings:
            header_field = SIPHeaderFieldFactory().next_for_string(line)
            # print line
            self.assertTrue(header_field.is_valid, line)
            self.assertTrue(header_field.is_known, line)
            self.assertEqual(header_field.raw_string, line, line)
            # self.assertNotEqual(header_field.value, None)
            self.assertIsInstance(header_field.parameter_names_and_value_strings, dict)
            self.assertTrue('foo' in ['foo', 'bar'])
            self.assertTrue(header_field.field_name.lower() in [name.lower() for name in self.canonicalFieldNames] + [name.lower() for name in self.canonicalCompactFieldNames])
            self.assertIsInstance(header_field.field_value_string, basestring, line)
            self.assertTrue(header_field.field_value_string in self.canonicalFieldValues)

            stringio = StringIO(line + '\r\n')
            header_field = SIPHeaderFieldFactory().all_for_stringio(stringio)[0]
            self.assertTrue(header_field.is_valid, line)
            self.assertTrue(header_field.is_known, line)
            self.assertEqual(header_field.raw_string, line, line)
            # self.assertNotEqual(header_field.value, None)
            self.assertIsInstance(header_field.parameter_names_and_value_strings, dict)
            self.assertTrue(header_field.field_name.lower() in [name.lower() for name in self.canonicalFieldNames] + [name.lower() for name in self.canonicalCompactFieldNames])
            self.assertIsInstance(header_field.field_value_string, basestring, line)
            self.assertTrue(header_field.field_value_string in self.canonicalFieldValues)
            stringio.close()

            # print self.canonicalFieldNames[0]
            header_field = SIPHeaderFieldFactory().next_for_field_name(self.canonicalFieldNames[0])
            self.assertEqual(self.emptyHeaderFieldBodyIsValid, header_field.is_valid)
            self.assertTrue(header_field.is_known)
            self.assertEqual(header_field.field_name.lower(), self.canonicalFieldNames[0].lower())
            self.assertIsInstance(header_field.field_value_string, basestring)
            # self.assertNotEqual(header_field.value, None)
            self.assertIsInstance(header_field.parameter_names_and_value_strings, dict)
            if self.canonicalCompactFieldNames:
                header_field = SIPHeaderFieldFactory().next_for_field_name(self.canonicalCompactFieldNames[0])
                self.assertEqual(self.emptyHeaderFieldBodyIsValid, header_field.is_valid)
                self.assertTrue(header_field.is_known)
                self.assertEqual(header_field.field_name.lower(), self.canonicalCompactFieldNames[0].lower())
                self.assertIsInstance(header_field.field_value_string, basestring)
                # self.assertNotEqual(header_field.value, None)
                self.assertIsInstance(header_field.parameter_names_and_value_strings, dict)

            header_field = SIPHeaderFieldFactory().next_for_field_name_and_field_value(self.canonicalFieldNames[0], self.canonicalFieldValues[0])
            self.assertEqual(header_field.field_value_string, self.canonicalFieldValues[0], line)
            self.assertTrue(header_field.is_valid, line)
            self.assertTrue(header_field.is_known, line)
            self.assertEqual(header_field.raw_string, self.canonicalStrings[0])
            self.assertEqual(header_field.field_name.lower(), self.canonicalFieldNames[0].lower())
            self.assertIsInstance(header_field.field_value_string, basestring, line)
            self.assertTrue(header_field.field_value_string in self.canonicalFieldValues)
            # self.assertNotEqual(header_field.value, None)
            self.assertIsInstance(header_field.parameter_names_and_value_strings, dict)
            if self.canonicalCompactFieldNames:
                header_field = SIPHeaderFieldFactory().next_for_field_name_and_field_value(self.canonicalCompactFieldNames[0], self.canonicalFieldValues[0])
                self.assertEqual(header_field.field_value_string, self.canonicalFieldValues[0], line)
                self.assertTrue(header_field.is_valid, line)
                self.assertTrue(header_field.is_known, line)
                self.assertTrue(header_field.raw_string in self.canonicalStrings)
                self.assertEqual(header_field.field_name.lower(), self.canonicalCompactFieldNames[0].lower())
                self.assertIsInstance(header_field.field_value_string, basestring, line)
                self.assertTrue(header_field.field_value_string in self.canonicalFieldValues)
                # self.assertNotEqual(header_field.value, None)
                self.assertIsInstance(header_field.parameter_names_and_value_strings, dict)


text:
set GO_ROOT=%~dp0\..\..\..\..\
set JRUBY_BASE=%GO_ROOT\tools\jruby-1.7.11
set SERVER_ROOT=%GO_ROOT%\server
set RAILS_ROOT=%SERVER_ROOT%\webapp\WEB-INF\rails.new
set GEM_HOME=%RAILS_ROOT%\vendor\bundle\jruby\1.9
set GEM_PATH=%JRUBY_BASE%\lib\ruby\gems\shared:%GEM_HOME%
set PATH=%JRUBY_BASE\bin:%PATH%

%JRUBY_BASE%\bin\jruby.bat %*


text:
<?php

namespace Oro\Bundle\LayoutBundle\Layout\Block\Type;

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Oro\Component\Layout\Block\Type\AbstractType;
use Oro\Component\Layout\BlockInterface;
use Oro\Component\Layout\BlockView;

class TextType extends AbstractType
{
    const NAME = 'text';

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setRequired(['text']);
    }

    /**
     * {@inheritdoc}
     */
    public function buildView(BlockView $view, BlockInterface $block, array $options)
    {
        $view->vars['text'] = $options['text'];
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return self::NAME;
    }
}


text:
namespace chromeos {

namespace {

const char kTestUser1[] = "test-user1@gmail.com";
const char kTestUser2[] = "test-user2@gmail.com";

}

class LoginUITest : public chromeos::LoginManagerTest {
 public:
  bool enable_test_screenshots_;
  LoginUITest() : LoginManagerTest(false) {
    screenshot_testing_ = new ScreenshotTestingMixin;
    AddMixin(screenshot_testing_);
  }
  virtual ~LoginUITest() {}

 protected:
  ScreenshotTestingMixin* screenshot_testing_;
};

IN_PROC_BROWSER_TEST_F(LoginUITest, PRE_LoginUIVisible) {
  RegisterUser(kTestUser1);
  RegisterUser(kTestUser2);
  StartupUtils::MarkOobeCompleted();
}

// Verifies basic login UI properties.
IN_PROC_BROWSER_TEST_F(LoginUITest, LoginUIVisible) {
  JSExpect("!!document.querySelector('#account-picker')");
  JSExpect("!!document.querySelector('#pod-row')");
  JSExpect(
      "document.querySelectorAll('.pod:not(#user-pod-template)').length == 2");

  JSExpect("document.querySelectorAll('.pod:not(#user-pod-template)')[0]"
           ".user.emailAddress == '" + std::string(kTestUser1) + "'");
  JSExpect("document.querySelectorAll('.pod:not(#user-pod-template)')[1]"
           ".user.emailAddress == '" + std::string(kTestUser2) + "'");
  screenshot_testing_->RunScreenshotTesting("LoginUITest-LoginUIVisible");
}

IN_PROC_BROWSER_TEST_F(LoginUITest, PRE_InterruptedAutoStartEnrollment) {
  StartupUtils::MarkOobeCompleted();
  PrefService* prefs = g_browser_process->local_state();
  prefs->SetBoolean(prefs::kDeviceEnrollmentAutoStart, true);
}

// Tests that the default first screen is the network screen after OOBE
// when auto enrollment is enabled and device is not yet enrolled.
IN_PROC_BROWSER_TEST_F(LoginUITest, InterruptedAutoStartEnrollment) {
  OobeScreenWaiter(OobeDisplay::SCREEN_OOBE_NETWORK).Wait();
}

}  // namespace chromeos


text:
'use strict';

var _ = require('lodash');

/**
 * Expose module.
 */

exports.create = require('./lib/middlewares/create');
exports.update = require('./lib/middlewares/update');
exports.destroy = require('./lib/middlewares/destroy');
exports.find = require('./lib/middlewares/find');
exports.findRelated = require('./lib/middlewares/find-related');
exports.findAll = require('./lib/middlewares/find-all');
exports.checkExist = _.partialRight(require('./lib/middlewares/check-exist'), true);
exports.checkNotExist = _.partialRight(require('./lib/middlewares/check-exist'), false);


text:
    <meta name="viewport" content="width=device-width initial-scale=1" charset="UTF-8">
    <title>Escape HTML String</title>


text:
package com.pfkj.oas.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor
		implements Filter {
	private FilterInvocationSecurityMetadataSource securityMetadataSource;

	@Override
	public Class<? extends Object> getSecureObjectClass() {
		// TODO Auto-generated method stub
		return FilterInvocation.class;
	}

	public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
		return securityMetadataSource;
	}

	public void setSecurityMetadataSource(
			FilterInvocationSecurityMetadataSource securityMetadataSource) {
		this.securityMetadataSource = securityMetadataSource;
	}

	@Override
	public SecurityMetadataSource obtainSecurityMetadataSource() {
		// TODO Auto-generated method stub
		return this.securityMetadataSource;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		FilterInvocation fi = new FilterInvocation(request, response, chain);
        invoke(fi);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	public void invoke(FilterInvocation fi) throws IOException,
    ServletException {

        InterceptorStatusToken token = super.beforeInvocation(fi);

        try {
             fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        } finally {
            super.afterInvocation(token, null);
        }

    }

}


text:
<?php

namespace MTD\SeleccionBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('MTDSeleccionBundle:Default:index.html.twig', array('name' => $name));
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE
{
    public class NoPiaInstantiationOfGenericClassAndStruct : CSharpTestBase
    {
        [Fact]
        public void NoPiaIllegalGenericInstantiationSymboleForClassThatInheritsGeneric()
        {
            //Test class that inherits Generic<NoPIAType>

            var localTypeSource = @"public class NoPIAGenerics
{
   Class1 field =  null;
}";

            var localConsumer1 = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType1 = localConsumer1.SourceModule.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var localField = classLocalType1.GetMembers("field").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, localField.Type.BaseType.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(localField.Type.BaseType);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymboleForGenericType()
        {
            //Test field with Generic(Of NoPIAType())

            var localTypeSource = @"public class NoPIAGenerics
{
   NestedConstructs nested = null;
}";

            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var localField = classLocalType.GetMembers("nested").OfType<FieldSymbol>().Single();
            var importedField = localField.Type.GetMembers("field2").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedField.Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedField.Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymboleForFieldWithNestedGenericType()
        {
            //Test field with Generic(Of IGeneric(Of NoPIAType))

            var localTypeSource = @"public class NoPIAGenerics
{
   NestedConstructs nested = null;
}";

            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var localField = classLocalType.GetMembers("nested").OfType<FieldSymbol>().Single();
            var importedField = localField.Type.GetMembers("field3").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedField.Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedField.Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymboleForFieldWithTwoNestedGenericType()
        {
            //Test field with IGeneric(Of IGeneric(Of Generic(Of NoPIAType)))

            var localTypeSource = @"public class NoPIAGenerics
{
   NestedConstructs nested = New NestedConstructs();
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var localField = classLocalType.GetMembers("nested").OfType<FieldSymbol>().Single();
            var importedField = localField.Type.GetMembers("field5").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.NamedType, importedField.Type.Kind);

            var outer = ((NamedTypeSymbol)importedField.Type).TypeArguments.Single();
            Assert.Equal(SymbolKind.NamedType, outer.Kind);

            var inner = ((NamedTypeSymbol)outer).TypeArguments.Single();
            Assert.Equal(SymbolKind.ErrorType, inner.Kind);
        }

        [Fact]
        public void NoPIAInterfaceInheritsGenericInterface()
        {
            //Test interface that inherits IGeneric(Of NoPIAType)

            var localTypeSource = @" public class NoPIAGenerics
{
   Interface1 i1 = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType1 = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var var1 = classLocalType1.GetMembers("i1").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.NamedType, var1.Type.Kind);
            Assert.IsAssignableFrom<PENamedTypeSymbol>(var1.Type);
        }

        [Fact]
        public void NoPIALocalClassInheritsGenericTypeWithPIATypeParameters()
        {
            //Test class that inherits Generic(Of NoPIAType) used as method return or arguments

            var localTypeSource1 = @"public class NoPIAGenerics
{
     InheritsMethods inhertsMethods = null;
}";
            var localConsumer = CreateCompilation(localTypeSource1);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var localField = classLocalType.GetMembers("inhertsMethods").OfType<FieldSymbol>().Single();

            foreach (MethodSymbol m in localField.Type.GetMembers("Method1").OfType<MethodSymbol>())
            {
                if (m.Parameters.Length > 0)
                {
                    Assert.Equal(SymbolKind.ErrorType, m.Parameters.Where(arg => arg.Name == "c1").Select(arg => arg).Single().Type.BaseType.Kind);
                    Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(m.Parameters.Where(arg => arg.Name == "c1").Select(arg => arg).Single().Type.BaseType);
                }
                if (m.ReturnType.TypeKind != TypeKind.Struct)
                {
                    Assert.Equal(SymbolKind.ErrorType, m.ReturnType.BaseType.Kind);
                    Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(m.ReturnType.BaseType);
                }
            }
        }

        [Fact]
        public void NoPIALocalStructImplementInterfaceThatInheritsGenericTypeWithPIATypeParameters()
        {
            //Test implementing an interface that inherits IGeneric(Of NoPIAType)

            var localTypeSource1 = @" public class NoPIAGenerics
{
    Interface1 i1 = new Interface1Impl();
}";
            var localConsumer = CreateCompilation(localTypeSource1);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var var1 = classLocalType.GetMembers("i1").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.NamedType, var1.Type.Kind);
            Assert.IsAssignableFrom<PENamedTypeSymbol>(var1.Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForPropertyThatTakesGenericOfPIAType()
        {
            //Test a static property that takes Generic(Of NoPIAType)

            var localTypeSource = @"public class NoPIAGenerics
{
   TypeRefs1 typeRef = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType1 = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType1.GetMembers("typeRef").OfType<FieldSymbol>().Single();
            var importedProperty = local.Type.GetMembers("Property1").OfType<PropertySymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedProperty.Parameters.Where(arg => arg.Name == "x").Single().Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedProperty.Parameters.Where(arg => arg.Name == "x").Single().Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForPropertyThatTakesGenericOfPIAType2()
        {
            //Test a static property that takes Generic(Of NoPIAType)

            var localTypeSource = @"public class NoPIAGenerics
{
   TypeRefs1 typeRef = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType1 = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType1.GetMembers("typeRef").OfType<FieldSymbol>().Single();
            var importedProperty = local.Type.GetMembers("Property2").OfType<PropertySymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedProperty.Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedProperty.Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForStaticMethodThatTakesGenericOfPiaType()
        {
            //Test a static method that takes Generic(Of NoPIAType)

            var localTypeSource = @"public class NoPIAGenerics
{
   TypeRefs1 typeRef = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType1 = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType1.GetMembers("typeRef").OfType<FieldSymbol>().Single();
            var importedMethod = local.Type.GetMembers("Method1").OfType<MethodSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedMethod.Parameters.Where(arg => arg.Name == "x").Select(arg => arg).Single().Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedMethod.Parameters.Where(arg => arg.Name == "x").Select(arg => arg).Single().Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForStaticMethodThatTakesOptionalGenericOfPiaType()
        {
            //Test a static method that takes an Optional Generic(Of NoPIAType)

            var localTypeSource = @"public class NoPIAGenerics
{
   TypeRefs1 typeRef = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType1 = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType1.GetMembers("typeRef").OfType<FieldSymbol>().Single();
            var importedMethod = local.Type.GetMembers("Method2").OfType<MethodSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedMethod.Parameters.Where(arg => arg.Name == "x").Select(arg => arg).Single().Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedMethod.Parameters.Where(arg => arg.Name == "x").Select(arg => arg).Single().Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForMethodThatTakesGenericOfEnumPiaType()
        {
            // Test an interface method that takes Generic(Of NoPIAType)

            var localTypeSource = @" public class NoPIAGenerics
{
   TypeRefs1.Interface2 i2 = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType.GetMembers("i2").OfType<FieldSymbol>().Single();
            var importedMethod = local.Type.GetMembers("Method3").OfType<MethodSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedMethod.Parameters.Where(arg => arg.Name == "x").Select(arg => arg).Single().Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedMethod.Parameters.Where(arg => arg.Name == "x").Select(arg => arg).Single().Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForStaticMethodThatTakesGenericOfInterfacePiaType()
        {
            // Test a static method that returns Generic(Of NoPIAType)

            var localTypeSource = @"public class NoPIAGenerics
{
   TypeRefs1 typeRef = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType.GetMembers("typeRef").OfType<FieldSymbol>().Single();
            var importedMethod = local.Type.GetMembers("Method4").OfType<MethodSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedMethod.ReturnType.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedMethod.ReturnType);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForConstructorThatTakesGenericOfStructPiaType()
        {
            // Test a constructor that takes Generic(Of NoPIAType)

            var localTypeSource = @" public class NoPIAGenerics
{
     TypeRefs2 tr2a = new TypeRefs2(null);
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType.GetMembers("tr2a").OfType<FieldSymbol>().Single();
            var importedMethod = local.Type.GetMembers(".ctor").OfType<MethodSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedMethod.Parameters.Where(arg => arg.Name == "x").Select(arg => arg).Single().Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedMethod.Parameters.Where(arg => arg.Name == "x").Select(arg => arg).Single().Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForOperatorThatTakesGenericOfPiaType()
        {
            // Test an operator that takes Generic(Of NoPIAType)

            var localTypeSource = @" public class NoPIAGenerics
{
     TypeRefs2 tr2a = new TypeRefs2(null);
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType.GetMembers("tr2a").OfType<FieldSymbol>().Single();
            var importedMethod = local.Type.GetMembers("op_Implicit").OfType<MethodSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedMethod.Parameters.Where(arg => arg.Name == "x").Single().Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedMethod.Parameters.Where(arg => arg.Name == "x").Single().Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForEventThatTakesGenericOfPiaType()
        {
            // Test hooking an event that takes Generic(Of NoPIAType)

            var localTypeSource = @" public class NoPIAGenerics
{
   TypeRefs2 tr2b = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var local = classLocalType.GetMembers("tr2b").OfType<FieldSymbol>().Single();
            var importedField = local.Type.GetMembers("Event1").OfType<EventSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, importedField.Type.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(importedField.Type);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationForEventWithDelegateTypeThatTakesGenericOfPiaType()
        {
            //Test declaring event with delegate type that takes generic argument

            var localTypeSource = @" public class NoPIAGenerics
{
        private event TypeRefs2.Delegate1 Event2;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var var1 = classLocalType.GetMembers("Event2").OfType<EventSymbol>().Single();

            Assert.Equal(SymbolKind.NamedType, var1.Type.Kind);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationForFieldWithDelegateTypeThatReturnGenericOfPiaType()
        {
            //Test declaring field with delegate type that takes generic argument

            var localTypeSource = @" public class NoPIAGenerics
{
        private static TypeRefs2.Delegate2 Event3;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var var1 = classLocalType.GetMembers("Event3").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.NamedType, var1.Type.Kind);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationForStaticMethodAccessedThroughImports()
        {
            //Test static method accessed through Imports

            var localTypeSource = @"
using MyClass1 = Class1;
public class NoPIAGenerics
{
    MyClass1 myclass = null;

}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var localField = classLocalType.GetMembers("myclass").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, localField.Type.BaseType.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(localField.Type.BaseType);
        }

        [Fact]
        public void NoPiaStaticMethodAccessedThroughImportsOfGenericClass()
        {
            //Test static method accessed through Imports of generic class

            var localTypeSource = @"
using MyGenericClass2 = Class2<ISubFuncProp>;

public class NoPIAGenerics
{
    MyGenericClass2 mygeneric = null;
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("NoPIAGenerics").Single();
            var localField = classLocalType.GetMembers("mygeneric").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.NamedType, localField.Type.Kind);
            Assert.IsType<ConstructedNamedTypeSymbol>(localField.Type);
        }

        [Fact]
        public void NoPIAClassThatInheritsGenericOfNoPIAType()
        {
            //Test class that inherits Generic(Of NoPIAType)

            var localTypeSource1 = @"public class BaseClass : System.Collections.Generic.List<FooStruct>
{
}

public class DrivedClass
{

    public static void Method1(BaseClass c1)
    {
    }

    public static BaseClass Method1()
    {
        return null;
    }

}";
            var localConsumer = CreateCompilation(localTypeSource1);
            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("DrivedClass").Single();

            foreach (MethodSymbol m in classLocalType.GetMembers("Method1").OfType<MethodSymbol>())
            {
                if (m.Parameters.Length > 0)
                {
                    Assert.Equal(SymbolKind.Parameter, m.Parameters.Where(arg => arg.Name == "c1").Select(arg => arg).Single().Kind);
                    Assert.True(m.Parameters.Where(arg => arg.Name == "c1").Select(arg => arg).Single().Type.IsFromCompilation(localConsumer));
                }
                if (m.ReturnType.TypeKind != TypeKind.Struct)
                {
                    Assert.Equal(SymbolKind.NamedType, m.ReturnType.Kind);
                    Assert.True(m.ReturnType.IsFromCompilation(localConsumer));
                }
            }
        }

        [Fact]
        public void NoPIATypeImplementingAnInterfaceThatInheritsIGenericOfNoPiaType()
        {
            //Test implementing an interface that inherits IGeneric(Of NoPIAType)

            var localTypeSource = @"public struct Interface1Impl2 : Interface4
{
}";
            var localConsumer = CreateCompilation(localTypeSource);

            NamedTypeSymbol classLocalType = localConsumer.GlobalNamespace.GetTypeMembers("Interface1Impl2").Single();

            Assert.Equal(SymbolKind.NamedType, classLocalType.Kind);
            Assert.True(classLocalType.IsFromCompilation(localConsumer));
            Assert.True(classLocalType.IsValueType);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolForAssemblyRefsWithClassThatInheritsGenericOfNoPiaType()
        {
            //Test class that inherits Generic(Of NoPIAType)

            var localConsumer = CreateCompilationWithMscorlib(assemblyName: "Dummy", sources: null,
                references: new[]
                {
                    TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1,
                                                               });

            var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies();

            var nestedType = localConsumerRefsAsm.Where(a => a.Name == "NoPIAGenerics1-Asm1").Single().GlobalNamespace.GetTypeMembers("NestedConstructs").Single();
            var localField = nestedType.GetMembers("field1").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.ArrayType, localField.Type.Kind);
            Assert.Equal(SymbolKind.ErrorType, ((ArrayTypeSymbol)localField.Type).ElementType.Kind);
        }

        [Fact]
        public void NoPIAGenericsAssemblyRefsWithClassThatInheritsGenericOfNoPiaType()
        {
            //Test class that inherits Generic(Of NoPIAType)

            var localConsumer = CreateCompilation(null);

            var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies();

            var nestedType = localConsumerRefsAsm[1].GlobalNamespace.GetTypeMembers("NestedConstructs").Single();
            var localField = nestedType.GetMembers("field1").OfType<FieldSymbol>().Single();

            Assert.Equal(SymbolKind.ArrayType, localField.Type.Kind);
            Assert.IsType<ArrayTypeSymbol>(localField.Type);
        }

        [Fact]
        public void NoPIAGenericsAssemblyRefs3()
        {
            //Test a static method that returns Generic(Of NoPIAType)

            var localConsumer = CreateCompilation(null);

            var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies();

            var nestedType = localConsumerRefsAsm[1].GlobalNamespace.GetTypeMembers("TypeRefs1").Single();
            var localMethod = nestedType.GetMembers("Method4").OfType<MethodSymbol>().Single();

            Assert.Equal(SymbolKind.ErrorType, localMethod.ReturnType.Kind);
            Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(localMethod.ReturnType);
        }

        [Fact]
        public void NoPiaIllegalGenericInstantiationSymbolforStaticMethodThatReturnsGenericOfNoPiaType()
        {
            //Test a static method that returns Generic(Of NoPIAType)

            var localTypeSource = @"
using System.Collections.Generic;
public class TypeRefs1
{
    public void Method1(List<FooStruct> x)
    {
    }
    public void Method2(List<ISubFuncProp> x = null)
    {
    }
    public interface Interface2
    {
        void Method3(List<FooEnum> x);
    }
    public List<ISubFuncProp> Method4()
    {
        return new List<ISubFuncProp>();
    }
    public List<FooStruct> Method4()
    {
        return null;
    }
}";

            var localType = CreateCompilationWithMscorlib(assemblyName: "Dummy", text: localTypeSource,
                references: new[] { TestReferences.SymbolsTests.NoPia.GeneralPia.WithEmbedInteropTypes(true) });

            var localConsumer = CreateCompilationWithMscorlib(assemblyName: "Dummy", sources: null,
                references: new MetadataReference[]
                {
                    TestReferences.SymbolsTests.NoPia.GeneralPiaCopy,
                    new CSharpCompilationReference(localType)
                                                        });

            var localConsumerRefsAsm = localConsumer.Assembly.GetNoPiaResolutionAssemblies();

            var nestedType = localConsumerRefsAsm.First(arg => arg.Name == "Dummy").GlobalNamespace.GetTypeMembers("TypeRefs1").Single();
            var methodSymbol = nestedType.GetMembers("Method4").OfType<MethodSymbol>();

            foreach (MethodSymbol m in methodSymbol)
            {
                Assert.Equal(SymbolKind.ErrorType, m.ReturnType.Kind);
                Assert.IsType<NoPiaIllegalGenericInstantiationSymbol>(m.ReturnType);
            }
        }

        public CSharpCompilation CreateCompilation(string source)
        {
            return CreateCompilationWithMscorlib(
                assemblyName: "Dummy",
                sources: (null == source) ? null : new string[] { source },
                references: new[]
                {
                    TestReferences.SymbolsTests.NoPia.NoPIAGenericsAsm1,
                    TestReferences.SymbolsTests.NoPia.GeneralPiaCopy
                });
        }
    }
}


text:
package com.avaje.ebean.bean;

import java.io.Serializable;
import java.util.Arrays;

/**
 * Represent the call stack (stack trace elements).
 *

 * Used with a query to identify a CallStackQuery for AutoTune automatic query
 * tuning.
 *

 *

 * This is used so that a single query called from different methods can be
 * tuned for each different call stack.
 *

 *

 * Note the call stack is trimmed to remove the common ebean internal elements.
 *

 */
public final class CallStack implements Serializable {

  private static final long serialVersionUID = -8590644046907438579L;

  private final String zeroHash;
  private final String pathHash;

  private final StackTraceElement[] callStack;

  public CallStack(StackTraceElement[] callStack, int zeroHash, int pathHash) {
    this.callStack = callStack;
    this.zeroHash = enc(zeroHash);
    this.pathHash = enc(pathHash);
  }

  public int hashCode() {
    int hc = 0;
    for (int i = 0; i < callStack.length; i++) {
      hc = 31 * hc + callStack[i].hashCode();
    }
    return hc;
  }

  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof CallStack)) {
      return false;
    }
    CallStack e = (CallStack) obj;
    return Arrays.equals(callStack, e.callStack);
  }

  /**
   * Return the first element of the call stack.
   */
  public StackTraceElement getFirstStackTraceElement() {
    return callStack[0];
  }

  /**
   * Return the call stack.
   */
  public StackTraceElement[] getCallStack() {
    return callStack;
  }

  /**
   * Return the hash for the first stack element.
   */
  public String getZeroHash() {
    return zeroHash;
  }

  /**
   * Return the hash for the stack elements (excluding first stack element).
   */
  public String getPathHash() {
    return pathHash;
  }

  public String toString() {
    return zeroHash + ":" + pathHash + ":" + callStack[0];
  }

  /**
   * Return the call stack lines appended with the given newLine string.
   */
  public String description(String newLine) {
    StringBuilder sb = new StringBuilder(400);
    for (int i = 0; i < callStack.length; i++) {
      sb.append(callStack[i].toString()).append(newLine);
    }
    return sb.toString();
  }

  public String getOriginKey(int queryHash) {
    return enc(queryHash)+ "." + zeroHash + "." + pathHash;
  }

  private static final int radix = 1 << 6;
  private static final int mask = radix - 1;

  /**
   * Convert the integer to unsigned base 64.
   */
  public static String enc(int i) {
    char[] buf = new char[32];
    int charPos = 32;
    do {
      buf[--charPos] = intToBase64[i & mask];
      i >>>= 6;
    } while (i != 0);

    return new String(buf, charPos, (32 - charPos));
  }

  private static final char intToBase64[] = {
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
      'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
      'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
  };
}


text:
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2;

/**
 * @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
 * @xmlType IndicationIndicatorType
 * @xmlName IndicationIndicator
 * @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\IndicationIndicator
 */
class IndicationIndicator extends IndicationIndicatorType
{
} // end class IndicationIndicator


text:
package io.dropwizard.testing;

import io.dropwizard.testing.app.TestApplication;
import io.dropwizard.testing.app.TestConfiguration;
import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;

import static org.assertj.core.api.Assertions.assertThatThrownBy;

class DropwizardTestSupportWithMissingConfigurationTest {
    @Test
    void configurationDoesNotExist() {
        final DropwizardTestSupport<TestConfiguration> testSupport =
                new DropwizardTestSupport<>(TestApplication.class, "not-found.yaml");

        assertThatThrownBy(testSupport::before)
                .isInstanceOf(FileNotFoundException.class)
                .hasMessage("File not-found.yaml not found");
    }
}


text:
$wmi = Get-WmiObject -Class Win32_OperatingSystem
$wmi.ConvertToDateTime($wmi.LocalDateTime) - $wmi.ConvertToDateTime($wmi.LastBootUpTime)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PKExtFramework.Visitors;
using PKExtFramework.Ext.Component;
using PKExtFramework.Ext.Component.Fields;
using PKExtFramework.Ext.Component.Panel;
using PKExtFramework.Ext.Component.Tab;
using PKExtFramework.Ext.Component.Grid;

namespace PKExtDesigner.Visitors.Code
{
    internal class PKExt3CodeGenVisitor: PKVisitor
    {
        public string Code { get; set; }

        public PKExt3CodeGenVisitor()
        {
            this.Code = string.Empty;
        }

        public override void Visit(PKControl item)
        {
            string strItems = "";
            string strItemInit = "";
            string strLayoutConfig = "";
            item.Items.ToList().ForEach(x => {
                var visitor = new PKExt3CodeGenVisitor();
                x.Accept(visitor);
                strItemInit += String.Format(@"this.{0} = {1};",
                    x.Name, visitor.Code);
                strItems += String.Format("this.{0},", x.Name);
            });

            if (strItems.Length > 0)
            {
                strItems = strItems.Remove(strItems.Length - 1, 1);
            }

            if (item.Layout.Name() == "vbox" || item.Layout.Name() == "hbox")
            {
                strLayoutConfig = "this.layoutConfig = {align: 'stretch'};";
            }

            Code = string.Format(@"{0}=Ext.extend(Ext.Container,{{
                initComponent: function(){{
                    this.layout = '{1}';
                    {2}
                    {3}
                    this.items=[{4}];
                    {0}.superclass.initComponent.apply(this, arguments);
                }}
            }});", item.Name, item.Layout.Name(), strLayoutConfig, strItemInit, strItems);
        }

        public override void Visit(PKContainer item)
        {
            string strItems = "";
            string strDimension = "";
            string strLayoutConfig = "";
            item.Items.ToList().ForEach(x =>
            {
                var visitor = new PKExt3CodeGenVisitor();
                x.Accept(visitor);
                strItems += visitor.Code + ",";
            });

            if (strItems.Length > 0)
            {
                strItems = strItems.Remove(strItems.Length - 1, 1);
            }

            if (item.Flex > 0)
            {
                strDimension = string.Format("flex: {0},", item.Flex);
            }
            else
            {
                if (item.Parent.Layout.Name() == "vbox")
                {
                    strDimension = string.Format("height: {0},", item.Height);
                }
                if (item.Parent.Layout.Name() == "hbox")
                {
                    strDimension = string.Format("width: {0},", item.Width);
                }
            }

            if(item.Layout.Name() == "vbox" || item.Layout.Name() == "hbox" )
            {
                strLayoutConfig = "layoutConfig: {align: 'stretch'},";
            }

            Code = string.Format(@"new Ext.Container({{
            xtype: 'container',
            style: 'padding: {4}px;',
            layout : '{0}',
            {1}
            {2}
            items: [{3}]
            }})", item.Layout.Name(), strLayoutConfig, strDimension, strItems, item.Padding);
        }

        public override void Visit(PKBottombar item)
        {
            item.Items.ToList().ForEach(x =>
            {
                var visitor = new PKExt3CodeGenVisitor();
                x.Accept(visitor);
                Code += visitor.Code + ",";
            });
            if (Code.Length > 0)
            {
                Code = Code.Remove(Code.Length - 1, 1);
            }
        }

        public override void Visit(PKToolbar item)
        {
            item.Items.ToList().ForEach(x =>
            {
                var visitor = new PKExt3CodeGenVisitor();
                x.Accept(visitor);
                Code += visitor.Code + ",";
            });
            if (Code.Length > 0)
            {
                Code = Code.Remove(Code.Length - 1, 1);
            }
        }

        public override void Visit(PKPanelFooter item)
        {
            item.Items.ToList().ForEach(x =>
            {
                var visitor = new PKExt3CodeGenVisitor();
                x.Accept(visitor);
                Code += visitor.Code + ",";
            });
            if (Code.Length > 0)
            {
                Code = Code.Remove(Code.Length - 1, 1);
            }
        }

        public override void Visit(PKTabPanel item)
        {
            string strDimension = "";

            var bvisitor = new PKExt3CodeGenVisitor();

            item.Body.Accept(bvisitor);

            if (item.Flex > 0)
            {
                strDimension = string.Format("flex: {0},", item.Flex);
            }
            else
            {
                if (item.Parent.Layout.Name() == "vbox")
                {
                    strDimension = string.Format("height: {0},", item.Height);
                }
                if (item.Parent.Layout.Name() == "hbox")
                {
                    strDimension = string.Format("width: {0},", item.Width);
                }
            }

            Code = string.Format(@"new Ext.TabPanel({{
                style: 'padding: {2}px;',
                {0}
                items: [{1}]
            }})",
                strDimension,
                bvisitor.Code,
                item.Padding);
        }

        public override void Visit(PKTabBar item)
        {

        }

        public string VisitPKTab(PKTab item)
        {
            string strCode = string.Empty;
            var childItem = item.Items.FirstOrDefault();

            if (childItem != null)
            {
                var visitor = new PKExt3CodeGenVisitor();
                childItem.Accept(visitor);
                strCode = visitor.Code;
            }
            return string.Format(@"new Ext.Container({{
                    title: '{0}',
                    layout: 'fit',
                    items: [{1}]
                }})", item.Text, strCode);
        }

        public override void Visit(PKTabPanelBody item)
        {
            item.Items.ToList().ForEach(x => {
                Code += VisitPKTab(x as PKTab) +",";
            });
            if (Code.Length > 0)
            {
                Code = Code.Remove(Code.Length - 1, 1);
            }
        }

        public override void Visit(PKPanel item)
        {
            string strDimension = "";

            var hvisitor = new PKExt3CodeGenVisitor();
            var tvisitor = new PKExt3CodeGenVisitor();
            var bvisitor = new PKExt3CodeGenVisitor();
            var fvisitor = new PKExt3CodeGenVisitor();
            item.Header.Accept(hvisitor);
            item.Toolbar.Accept(tvisitor);
            item.Body.Accept(bvisitor);
            item.Footer.Accept(fvisitor);

            if (item.Flex > 0)
            {
                strDimension = string.Format("flex: {0},", item.Flex);
            }
            else
            {
                if (item.Parent.Layout.Name() == "vbox")
                {
                    strDimension = string.Format("height: {0},", item.Height);
                }
                if (item.Parent.Layout.Name() == "hbox")
                {
                    strDimension = string.Format("width: {0},", item.Width);
                }
            }

            Code = string.Format(@"new Ext.Panel({{
                layout : 'fit',
                style: 'padding: {5}px;',
                {0}
                title: '{1}',
                tbar:[{2}],
                items: [{3}],
                buttons : [{4}]
            }})",
                strDimension,
                hvisitor.Code,
                tvisitor.Code,
                bvisitor.Code,
                fvisitor.Code,
                item.Padding);
        }

        public override void Visit(PKPanelHeader item)
        {
            Code = item.Value;
        }

        public override void Visit(PKField item)
        {
            var codeVisitor = new PKFieldCodeGenVisitor();
            item.ValueField.Accept(codeVisitor);
            Code = string.Format(@"new {0}({{
                width: {1},
                fieldLabel: '{2}',
                {3}
            }})", item.ValueField.ExtTypeName,
                item.ValueField.Width,
                item.LabelField.Value.Replace(":", ""),
                codeVisitor.StrCode);
        }

        public override void Visit(PKGrid item)
        {
            string strDimension = "";
            var cvisitor = new PKExt3CodeGenVisitor();
            var tvisitor = new PKExt3CodeGenVisitor();
            var bvisitor = new PKExt3CodeGenVisitor();

            item.Toolbar.Accept(tvisitor);
            item.ColumnRow.Accept(cvisitor);
            item.Bottombar.Accept(bvisitor);

            if (item.Flex > 0)
            {
                strDimension = string.Format("flex: {0},", item.Flex);
            }
            else
            {
                if (item.Parent.Layout.Name() == "vbox")
                {
                    strDimension = string.Format("height: {0},", item.Height);
                }
                if (item.Parent.Layout.Name() == "hbox")
                {
                    strDimension = string.Format("width: {0},", item.Width);
                }
            }

            Code = string.Format(@"new Ext.grid.GridPanel({{
                viewConfig: {{
                    forceFit: true,
                    sm: new Ext.grid.RowSelectionModel({{
                        singleSelect: true
                    }})
                }},
                store: new Ext.data.JsonStore({{}}),
                {0}
                title: '{1}',
                columns: [{2}],
                tbar:[{3}],
                bbar:[{4}]
            }})",
                strDimension,
                item.Header.Value,
                cvisitor.Code,
                tvisitor.Code,
                bvisitor.Code);
        }

        public override void Visit(PKGridColumnRow item)
        {
            item.Cells.ToList().ForEach(x => {
                var visitor = new PKExt3CodeGenVisitor();
                x.Accept(visitor);
                Code += visitor.Code + ",";
            });
            if (Code.Length > 0)
            {
                Code = Code.Remove(Code.Length - 1, 1);
            }
        }

        public override void Visit(PKText item)
        {
            Code = string.Format(@"{{xtype:'label', text: '{0}'}}", item.Value);
        }

        public override void Visit(PKButton item)
        {
            Code = string.Format(@"{{xtype:'button', text: '{0}'}}", item.Value);
        }

        public override void Visit(PKColumn item)
        {
            Code = string.Format(@"{{
                dataIndex: '{0}',
                header: '{1}',
                width: {2}
            }}", item.DataProperty, item.Value, item.Width);
        }

        public override void Visit(PKFieldItem item)
        {

        }
    }
}


text:
require 'rails_helper'
require 'spec_helper'

RSpec.describe SurveyAssignment, type: :model do
  before do
    @survey = create(:survey)
    @campaign = create(:campaign, title: 'Test', slug: 'test')
    @survey_assignment = create(:survey_assignment, survey_id: @survey.id, published: true)
    @survey_assignment.campaigns << @campaign
  end

  let(:course) { create(:course, start: course_start, end: course_end) }
  let(:course_start) { Time.zone.today - 1.month }
  let(:course_end) { Time.zone.today + 1.month }

  it 'has one Survey' do
    expect(@survey_assignment.survey).to be_instance_of(Survey)
  end

  it 'has one Campaign' do
    expect(@survey_assignment.campaigns.length).to eq(1)
  end

  describe '#send_at' do
    it 'returns a hash for finding courses ready for surveys' do
      @survey_assignment.update(
        send_date_days: 7,
        send_before: true,
        send_date_relative_to: 'end'
      )
      send = @survey_assignment.send_at
      expect(send[:days]).to eq(7)
      expect(send[:before]).to be(true)
      expect(send[:relative_to]).to eq('end')
    end
  end

  describe '#active?' do
    it 'returns true if there are yet-to-be-notified courses' do
      course.campaigns << @campaign
      course.save
      @survey_assignment.update(
        send_date_days: 7,
        send_before: true,
        send_date_relative_to: 'end'
      )

      expect(@survey_assignment.active?).to be(true)
    end
  end

  describe '#status' do
    let(:survey_assignment) do
      create(:survey_assignment, survey_id: survey.id, published:, courses_user_role: 1)
    end
    let(:survey) { create(:survey, closed:) }
    let(:closed) { false }
    let(:subject) { survey_assignment.status }

    context 'when it is not published' do
      let(:published) { false }

      it 'returns `Draft`' do
        expect(subject).to eq('Draft')
      end
    end

    context 'when it is published but has no applicable users' do
      let(:published) { true }

      it 'returns `Pending`' do
        expect(subject).to eq('Pending')
      end
    end

    context 'when it is published and has applicable users' do
      let(:published) { true }

      it 'returns `Active`' do
        course.campaigns << @campaign
        survey_assignment.campaigns << @campaign
        create(:user, id: 1)
        create(:courses_user, user_id: 1, course_id: course.id, role: 1)
        expect(subject).to eq('Active')
      end
    end

    context 'when it is published and has applicable users and is closed' do
      let(:published) { true }
      let(:closed) { true }

      it 'returns `Closed`' do
        course.campaigns << @campaign
        survey_assignment.campaigns << @campaign
        create(:user, id: 1)
        create(:courses_user, user_id: 1, course_id: course.id, role: 1)
        expect(subject).to eq('Closed')
      end
    end
  end

  describe '#target_user_count' do
    it 'returns the total number of users who will receive a notification' do
      course.campaigns << @campaign
      course.save

      create(:user, id: 1)
      create(:courses_user,
             user_id: 1,
             course_id: course.id,
             role: 1)

      @survey_assignment.update(
        courses_user_role: 1,
        send_date_days: 7,
        send_before: true,
        send_date_relative_to: 'end'
      )

      expect(@survey_assignment.target_user_count).to eq(1)
    end
  end

  describe '#by_courses_user_and_survey Scope' do
    it 'returns notifications that match the provided courses_user and survey ids' do
      notification = create(:survey_notification, courses_users_id: 1)
      @survey_assignment.survey_notifications << notification
      @survey_assignment.save
      expect(described_class.by_courses_user_and_survey(
        courses_users_id: 1,
        survey_id: @survey.id
      ).length).to eq(1)
    end

    it 'returns an empty array if no notifications match the courses_user and survey ids' do
      notification = create(:survey_notification, courses_users_id: 1)
      @survey_assignment.survey_notifications << notification
      @survey_assignment.save
      expect(described_class.by_courses_user_and_survey(
        courses_users_id: 99,
        survey_id: @survey.id
      ).length).to eq(0)
    end
  end

  describe '#custom_email' do
    context 'when not set' do
      it 'causes no problems' do
        expect(@survey_assignment.custom_email).to be_empty
        expect(@survey_assignment.custom_email_subject).to be_nil
      end
    end

    context 'when set with a hash' do
      it 'serializes, saves, and returns the hash' do
        @survey_assignment.custom_email = { subject: 'foo' }
        @survey_assignment.save
        expect(@survey_assignment.custom_email).to eq(subject: 'foo')
        expect(@survey_assignment.custom_email_subject).to eq('foo')
      end
    end
  end
end