text:
package org.caleydo.core.view.opengl.layout2.renderer;

import gleem.linalg.Vec2f;

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

import org.caleydo.core.util.color.Color;
import org.caleydo.core.view.opengl.layout2.GLGraphics;
import org.caleydo.core.view.opengl.util.gleem.ColoredVec2f;
import org.caleydo.core.view.opengl.util.spline.TesselatedPolygons;

import com.google.common.collect.Iterators;

/**
 * @author Samuel Gratzl
 *
 */
public class PathBuilder implements Iterable<Vec2f> {
	private final List<Vec2f> l = new ArrayList<>(4);

	private PathBuilder() {

	}

	public static PathBuilder empty() {
		return new PathBuilder();
	}

	public static PathBuilder moveTo(float x, float y) {
		return empty().add(x, y);
	}

	public static PathBuilder moveTo(float x, float y, Color c) {
		return empty().add(x, y, c);
	}

	public PathBuilder lineTo(float x, float y) {
		return add(x, y);
	}

	public PathBuilder add(float x, float y) {
		return add(new Vec2f(x, y));
	}

	public PathBuilder add(Vec2f v) {
		l.add(v);
		return this;
	}

	public PathBuilder lineTo(float x, float y, Color c) {
		return add(x, y, c);
	}

	public PathBuilder add(float x, float y, Color c) {
		return add(new ColoredVec2f(x, y, c));
	}

	public PathBuilder rect(float x, float y, float w, float h) {
		return add(x, y).add(x + w, y).add(x + w, y + h).add(x, h);
	}

	public PathBuilder rect(float x, float y, float w, float h, Color topColor, Color bottomColor) {
		add(x, y, topColor).add(x + w, y, topColor);
		add(x + w, y + h, bottomColor).add(x, h, bottomColor);
		return this;
	}

	@Override
	public Iterator<Vec2f> iterator() {
		return Iterators.unmodifiableIterator(l.iterator());
	}

	public void fill(GLGraphics g) {
		g.fillPolygon(this);
	}

	public void fillTesselated(GLGraphics g) {
		g.fillPolygon(TesselatedPolygons.polygon2(l));
	}

	public void drawLoop(GLGraphics g) {
		g.drawPath(this, true);
	}

	public void drawLine(GLGraphics g) {
		g.drawPath(this, false);
	}

	public void drawPoints(GLGraphics g) {
		g.drawPoints(this);
	}
}

redpajama_set_name: RedPajamaGithub


text:
import type {ValidationOptions} from './types';

import {logValidationWarning, DEPRECATION} from './utils';

const deprecationMessage = (message: string, options: ValidationOptions) => {
  const comment = options.comment;
  const name = (options.title && options.title.deprecation) || DEPRECATION;

  logValidationWarning(name, message, comment);
};

const deprecationWarning = (
  config: Object,
  option: string,
  deprecatedOptions: Object,
  options: ValidationOptions,
): boolean => {
  if (option in deprecatedOptions) {
    deprecationMessage(deprecatedOptions[option](config), options);

    return true;
  }

  return false;
};

module.exports = {
  deprecationWarning,
};


text:
package com.intellij.openapi.vcs.actions;

import com.intellij.diff.DiffContext;
import com.intellij.diff.DiffContextEx;
import com.intellij.diff.DiffExtension;
import com.intellij.diff.FrameDiffTool.DiffViewer;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.contents.FileContent;
import com.intellij.diff.merge.TextMergeViewer;
import com.intellij.diff.requests.ContentDiffRequest;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.tools.fragmented.UnifiedDiffViewer;
import com.intellij.diff.tools.simple.SimpleThreesideDiffViewer;
import com.intellij.diff.tools.simple.ThreesideTextDiffViewerEx;
import com.intellij.diff.tools.util.DiffDataKeys;
import com.intellij.diff.tools.util.base.DiffViewerBase;
import com.intellij.diff.tools.util.base.DiffViewerListener;
import com.intellij.diff.tools.util.side.OnesideTextDiffViewer;
import com.intellij.diff.tools.util.side.TwosideTextDiffViewer;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.diff.util.Side;
import com.intellij.diff.util.ThreeSide;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.impl.NotificationsManagerImpl;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.actionSystem.ex.ActionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.localVcs.UpToDateLineNumberProvider;
import com.intellij.openapi.progress.util.BackgroundTaskUtil;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.annotate.AnnotationProvider;
import com.intellij.openapi.vcs.annotate.FileAnnotation;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.impl.BackgroundableActionLock;
import com.intellij.openapi.vcs.impl.UpToDateLineNumberProviderImpl;
import com.intellij.openapi.vcs.impl.VcsBackgroundableActions;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcs.AnnotationProviderEx;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;

public class AnnotateDiffViewerAction extends ToggleAction implements DumbAware {
  private static final Logger LOG = Logger.getInstance(AnnotateDiffViewerAction.class);

  private static final Key<AnnotationData[]> CACHE_KEY = Key.create("Diff.AnnotateAction.Cache");
  private static final Key<boolean[]> ANNOTATIONS_SHOWN_KEY = Key.create("Diff.AnnotateAction.AnnotationShown");

  private static final ViewerAnnotatorFactory[] ANNOTATORS = new ViewerAnnotatorFactory[]{
    new TwosideAnnotatorFactory(), new OnesideAnnotatorFactory(), new UnifiedAnnotatorFactory(),
    new ThreesideAnnotatorFactory(), new TextMergeAnnotatorFactory()
  };

  public AnnotateDiffViewerAction() {
    ActionUtil.copyFrom(this, "Annotate");
    setEnabledInModalContext(true);
  }

  @Override
  public void update(AnActionEvent e) {
    super.update(e);
    boolean enabled = isEnabled(e);
    e.getPresentation().setVisible(enabled);
    e.getPresentation().setEnabled(enabled && !isSuspended(e));
  }

  @Nullable
  @SuppressWarnings("unchecked")
  private static ViewerAnnotator getAnnotator(@NotNull DiffViewerBase viewer, @NotNull Editor editor) {
    for (ViewerAnnotatorFactory annotator : ANNOTATORS) {
      if (annotator.getViewerClass().isInstance(viewer)) return annotator.createAnnotator(viewer, editor);
    }
    return null;
  }

  @Nullable
  private static EventData collectEventData(AnActionEvent e) {
    DiffViewerBase viewer = getViewer(e);
    if (viewer == null) return null;
    if (viewer.getProject() == null) return null;
    if (viewer.isDisposed()) return null;

    Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (editor == null) return null;

    ViewerAnnotator annotator = getAnnotator(viewer, editor);
    if (annotator == null) return null;

    return new EventData(viewer, annotator);
  }

  @Nullable
  private static DiffViewerBase getViewer(AnActionEvent e) {
    DiffViewerBase diffViewer = ObjectUtils.tryCast(e.getData(DiffDataKeys.DIFF_VIEWER), DiffViewerBase.class);
    if (diffViewer != null) return diffViewer;

    TextMergeViewer mergeViewer = ObjectUtils.tryCast(e.getData(DiffDataKeys.MERGE_VIEWER), TextMergeViewer.class);
    if (mergeViewer != null) return mergeViewer.getViewer();

    return null;
  }

  private static boolean isEnabled(AnActionEvent e) {
    EventData data = collectEventData(e);
    if (data == null) return false;

    if (data.annotator.isAnnotationShown()) return true;
    return data.annotator.createAnnotationsLoader() != null;
  }

  private static boolean isSuspended(AnActionEvent e) {
    EventData data = collectEventData(e);
    return data != null && data.annotator.getBackgroundableLock().isLocked();
  }

  private static boolean isAnnotated(AnActionEvent e) {
    EventData data = collectEventData(e);
    assert data != null;
    return data.annotator.isAnnotationShown();
  }

  private static void perform(AnActionEvent e, boolean selected) {
    EventData data = collectEventData(e);
    assert data != null;

    boolean annotationShown = data.annotator.isAnnotationShown();
    if (annotationShown) {
      data.annotator.hideAnnotation();
    }
    else {
      doAnnotate(data.annotator);
    }
  }

  @Override
  public boolean isSelected(AnActionEvent e) {
    EventData data = collectEventData(e);
    return data != null && data.annotator.isAnnotationShown();
  }

  @Override
  public void setSelected(AnActionEvent e, boolean state) {
    perform(e, state);
  }

  private static void doAnnotate(@NotNull final ViewerAnnotator annotator) {
    final DiffViewerBase viewer = annotator.getViewer();
    final Project project = viewer.getProject();
    if (project == null) return;

    AnnotationData data = annotator.getDataFromCache();
    if (data != null) {
      annotator.showAnnotation(data);
      return;
    }

    final FileAnnotationLoader loader = annotator.createAnnotationsLoader();
    if (loader == null) return;

    final DiffContextEx diffContext = ObjectUtils.tryCast(viewer.getContext(), DiffContextEx.class);

    annotator.getBackgroundableLock().lock();
    if (diffContext != null) diffContext.showProgressBar(true);

    BackgroundTaskUtil.executeOnPooledThread(indicator -> {
      try {
        loader.run();
      }
      finally {
        ApplicationManager.getApplication().invokeLater(() -> {
          if (diffContext != null) diffContext.showProgressBar(false);
          annotator.getBackgroundableLock().unlock();

          VcsException exception = loader.getException();
          if (exception != null) {
            Notification notification = VcsNotifier.IMPORTANT_ERROR_NOTIFICATION
              .createNotification("Can't Load Annotations", exception.getMessage(), NotificationType.ERROR, null);
            showNotification(viewer, notification);
            LOG.warn(exception);
            return;
          }

          if (loader.getResult() == null) return;
          if (loader.shouldCache()) {
            // data race is possible here, but we expect AnnotationData to be immutable, so this is not an issue
            annotator.putDataToCache(loader.getResult());
          }

          if (viewer.isDisposed()) return;
          annotator.showAnnotation(loader.getResult());
        }, indicator.getModalityState());
      }
    }, viewer);
  }

  @Nullable
  private static FileAnnotationLoader createThreesideAnnotationsLoader(@NotNull Project project,
                                                                       @NotNull DiffRequest request,
                                                                       @NotNull ThreeSide side) {
    if (request instanceof ContentDiffRequest) {
      ContentDiffRequest requestEx = (ContentDiffRequest)request;
      if (requestEx.getContents().size() == 3) {
        DiffContent content = side.select(requestEx.getContents());
        FileAnnotationLoader loader = createAnnotationsLoader(project, content);
        if (loader != null) return loader;
      }
    }

    return null;
  }

  @Nullable
  private static FileAnnotationLoader createTwosideAnnotationsLoader(@NotNull Project project,
                                                                     @NotNull DiffRequest request,
                                                                     @NotNull Side side) {
    Change change = request.getUserData(ChangeDiffRequestProducer.CHANGE_KEY);
    if (change != null) {
      ContentRevision revision = side.select(change.getBeforeRevision(), change.getAfterRevision());
      if (revision != null) {
        AbstractVcs vcs = ChangesUtil.getVcsForChange(change, project);

        if (revision instanceof CurrentContentRevision) {
          VirtualFile file = ((CurrentContentRevision)revision).getVirtualFile();
          FileAnnotationLoader loader = doCreateAnnotationsLoader(project, vcs, file);
          if (loader != null) return loader;
        }
        else {
          FileAnnotationLoader loader = doCreateAnnotationsLoader(vcs, revision.getFile(), revision.getRevisionNumber());
          if (loader != null) return loader;
        }
      }
    }

    if (request instanceof ContentDiffRequest) {
      ContentDiffRequest requestEx = (ContentDiffRequest)request;
      if (requestEx.getContents().size() == 2) {
        DiffContent content = side.select(requestEx.getContents());
        return createAnnotationsLoader(project, content);
      }
    }

    return null;
  }

  @Nullable
  private static FileAnnotationLoader createAnnotationsLoader(@NotNull Project project, @NotNull DiffContent content) {
    if (content instanceof FileContent) {
      VirtualFile file = ((FileContent)content).getFile();
      AbstractVcs vcs = VcsUtil.getVcsFor(project, file);
      FileAnnotationLoader loader = doCreateAnnotationsLoader(project, vcs, file);
      if (loader != null) return loader;
    }

    Pair<FilePath, VcsRevisionNumber> info = content.getUserData(DiffUserDataKeysEx.REVISION_INFO);
    if (info != null) {
      FilePath filePath = info.first;
      AbstractVcs vcs = VcsUtil.getVcsFor(project, filePath);
      FileAnnotationLoader loader = doCreateAnnotationsLoader(vcs, filePath, info.second);
      if (loader != null) return loader;
    }
    return null;
  }

  @Nullable
  private static FileAnnotationLoader doCreateAnnotationsLoader(@NotNull Project project,
                                                                @Nullable AbstractVcs vcs,
                                                                @Nullable final VirtualFile file) {
    if (vcs == null || file == null) return null;
    final AnnotationProvider annotationProvider = vcs.getCachingAnnotationProvider();
    if (annotationProvider == null) return null;

    FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(file);
    if (fileStatus == FileStatus.UNKNOWN || fileStatus == FileStatus.ADDED || fileStatus == FileStatus.IGNORED) {
      return null;
    }

    // TODO: cache them too, listening for ProjectLevelVcsManager.getInstance(project).getAnnotationLocalChangesListener() ?
    return new FileAnnotationLoader(vcs, false) {
      @Override
      public FileAnnotation compute() throws VcsException {
        return annotationProvider.annotate(file);
      }
    };
  }

  @Nullable
  private static FileAnnotationLoader doCreateAnnotationsLoader(@Nullable AbstractVcs vcs,
                                                                @Nullable final FilePath path,
                                                                @Nullable final VcsRevisionNumber revisionNumber) {
    if (vcs == null || path == null || revisionNumber == null) return null;
    if (revisionNumber instanceof TextRevisionNumber) return null;
    final AnnotationProvider annotationProvider = vcs.getAnnotationProvider();
    if (!(annotationProvider instanceof AnnotationProviderEx)) return null;

    return new FileAnnotationLoader(vcs, true) {
      @Override
      public FileAnnotation compute() throws VcsException {
        return ((AnnotationProviderEx)annotationProvider).annotate(path, revisionNumber);
      }
    };
  }

  public static class MyDiffExtension extends DiffExtension {
    @Override
    public void onViewerCreated(@NotNull DiffViewer diffViewer, @NotNull DiffContext context, @NotNull DiffRequest request) {
      if (diffViewer instanceof DiffViewerBase) {
        DiffViewerBase viewer = (DiffViewerBase)diffViewer;
        viewer.addListener(new MyDiffViewerListener(viewer));
      }
    }
  }

  private static class MyDiffViewerListener extends DiffViewerListener {
    @NotNull private final DiffViewerBase myViewer;

    public MyDiffViewerListener(@NotNull DiffViewerBase viewer) {
      myViewer = viewer;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onInit() {
      if (myViewer.getProject() == null) return;

      for (ViewerAnnotatorFactory annotator : ANNOTATORS) {
        if (annotator.getViewerClass().isInstance(myViewer)) annotator.showRememberedAnnotations(myViewer);
      }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void onDispose() {
      if (myViewer.getProject() == null) return;

      for (ViewerAnnotatorFactory annotator : ANNOTATORS) {
        if (annotator.getViewerClass().isInstance(myViewer)) annotator.rememberShownAnnotations(myViewer);
      }
    }
  }

  private static void showNotification(@NotNull DiffViewerBase viewer, @NotNull Notification notification) {
    JComponent component = viewer.getComponent();

    Window window = UIUtil.getWindow(component);
    if (window instanceof IdeFrame && NotificationsManagerImpl.findWindowForBalloon(viewer.getProject()) == window) {
      notification.notify(viewer.getProject());
      return;
    }

    Balloon balloon = NotificationsManagerImpl.createBalloon(component, notification, false, true, null, viewer);

    Dimension componentSize = component.getSize();
    Dimension balloonSize = balloon.getPreferredSize();

    int width = Math.min(balloonSize.width, componentSize.width);
    int height = Math.min(balloonSize.height, componentSize.height);

    // top-right corner, 20px to the edges
    RelativePoint point = new RelativePoint(component, new Point(componentSize.width - 20 - width / 2, 20 + height / 2));
    balloon.show(point, Balloon.Position.above);
  }

  private static class TwosideAnnotatorFactory extends TwosideViewerAnnotatorFactory<TwosideTextDiffViewer> {
    @Override
    @NotNull
    public Class<TwosideTextDiffViewer> getViewerClass() {
      return TwosideTextDiffViewer.class;
    }

    @Override
    @Nullable
    public Side getCurrentSide(@NotNull TwosideTextDiffViewer viewer, @NotNull Editor editor) {
      Side side = null; // we can't just use getCurrentSide() here, popup can be called on unfocused editor
      if (viewer.getEditor(Side.LEFT) == editor) side = Side.LEFT;
      if (viewer.getEditor(Side.RIGHT) == editor) side = Side.RIGHT;
      return side;
    }

    @Override
    public boolean isAnnotationShown(@NotNull TwosideTextDiffViewer viewer, @NotNull Side side) {
      return viewer.getEditor(side).getGutter().isAnnotationsShown();
    }

    @Override
    public void showAnnotation(@NotNull TwosideTextDiffViewer viewer, @NotNull Side side, @NotNull AnnotationData data) {
      Project project = ObjectUtils.assertNotNull(viewer.getProject());
      AnnotateToggleAction.doAnnotate(viewer.getEditor(side), project, null, data.annotation, data.vcs);
    }

    @Override
    public void hideAnnotation(@NotNull TwosideTextDiffViewer viewer, @NotNull Side side) {
      viewer.getEditor(side).getGutter().closeAllAnnotations();
    }
  }

  private static class OnesideAnnotatorFactory extends TwosideViewerAnnotatorFactory<OnesideTextDiffViewer> {
    @Override
    @NotNull
    public Class<OnesideTextDiffViewer> getViewerClass() {
      return OnesideTextDiffViewer.class;
    }

    @Override
    @Nullable
    public Side getCurrentSide(@NotNull OnesideTextDiffViewer viewer, @NotNull Editor editor) {
      if (viewer.getEditor() != editor) return null;
      return viewer.getSide();
    }

    @Override
    public boolean isAnnotationShown(@NotNull OnesideTextDiffViewer viewer, @NotNull Side side) {
      if (side != viewer.getSide()) return false;
      return viewer.getEditor().getGutter().isAnnotationsShown();
    }

    @Override
    public void showAnnotation(@NotNull OnesideTextDiffViewer viewer, @NotNull Side side, @NotNull AnnotationData data) {
      if (side != viewer.getSide()) return;
      Project project = ObjectUtils.assertNotNull(viewer.getProject());
      AnnotateToggleAction.doAnnotate(viewer.getEditor(), project, null, data.annotation, data.vcs);
    }

    @Override
    public void hideAnnotation(@NotNull OnesideTextDiffViewer viewer, @NotNull Side side) {
      viewer.getEditor().getGutter().closeAllAnnotations();
    }
  }

  private static class UnifiedAnnotatorFactory extends TwosideViewerAnnotatorFactory<UnifiedDiffViewer> {
    @Override
    @NotNull
    public Class<UnifiedDiffViewer> getViewerClass() {
      return UnifiedDiffViewer.class;
    }

    @Override
    @Nullable
    public Side getCurrentSide(@NotNull UnifiedDiffViewer viewer, @NotNull Editor editor) {
      if (viewer.getEditor() != editor) return null;
      return viewer.getMasterSide();
    }

    @Override
    public boolean isAnnotationShown(@NotNull UnifiedDiffViewer viewer, @NotNull Side side) {
      if (side != viewer.getMasterSide()) return false;
      return viewer.getEditor().getGutter().isAnnotationsShown();
    }

    @Override
    public void showAnnotation(@NotNull UnifiedDiffViewer viewer, @NotNull Side side, @NotNull AnnotationData data) {
      if (side != viewer.getMasterSide()) return;
      Project project = ObjectUtils.assertNotNull(viewer.getProject());
      UnifiedUpToDateLineNumberProvider lineNumberProvider = new UnifiedUpToDateLineNumberProvider(viewer, side);
      AnnotateToggleAction.doAnnotate(viewer.getEditor(), project, null, data.annotation, data.vcs, lineNumberProvider);
    }

    @Override
    public void hideAnnotation(@NotNull UnifiedDiffViewer viewer, @NotNull Side side) {
      viewer.getEditor().getGutter().closeAllAnnotations();
    }
  }

  private static class UnifiedUpToDateLineNumberProvider implements UpToDateLineNumberProvider {
    @NotNull private final UnifiedDiffViewer myViewer;
    @NotNull private final Side mySide;
    @NotNull private final UpToDateLineNumberProvider myLocalChangesProvider;

    public UnifiedUpToDateLineNumberProvider(@NotNull UnifiedDiffViewer viewer, @NotNull Side side) {
      myViewer = viewer;
      mySide = side;
      myLocalChangesProvider = new UpToDateLineNumberProviderImpl(myViewer.getDocument(mySide), viewer.getProject());
    }

    @Override
    public int getLineNumber(int currentNumber) {
      int number = myViewer.transferLineFromOnesideStrict(mySide, currentNumber);
      return number != -1 ? myLocalChangesProvider.getLineNumber(number) : FAKE_LINE_NUMBER;
    }

    @Override
    public boolean isLineChanged(int currentNumber) {
      return getLineNumber(currentNumber) == ABSENT_LINE_NUMBER;
    }

    @Override
    public boolean isRangeChanged(int start, int end) {
      int line1 = myViewer.transferLineFromOnesideStrict(mySide, start);
      int line2 = myViewer.transferLineFromOnesideStrict(mySide, end);
      if (line2 - line1 != end - start) return true;

      for (int i = start; i <= end; i++) {
        if (isLineChanged(i)) return true; // TODO: a single request to LineNumberConvertor
      }
      return myLocalChangesProvider.isRangeChanged(line1, line2);
    }
  }

  private static class ThreesideAnnotatorFactory extends ThreesideViewerAnnotatorFactory<ThreesideTextDiffViewerEx> {
    @Override
    @NotNull
    public Class<? extends ThreesideTextDiffViewerEx> getViewerClass() {
      return SimpleThreesideDiffViewer.class;
    }

    @Override
    @Nullable
    public ThreeSide getCurrentSide(@NotNull ThreesideTextDiffViewerEx viewer, @NotNull Editor editor) {
      ThreeSide side = null; // we can't just use getCurrentSide() here, popup can be called on unfocused editor
      if (viewer.getEditor(ThreeSide.LEFT) == editor) side = ThreeSide.LEFT;
      if (viewer.getEditor(ThreeSide.BASE) == editor) side = ThreeSide.BASE;
      if (viewer.getEditor(ThreeSide.RIGHT) == editor) side = ThreeSide.RIGHT;
      return side;
    }

    @Override
    public boolean isAnnotationShown(@NotNull ThreesideTextDiffViewerEx viewer, @NotNull ThreeSide side) {
      return viewer.getEditor(side).getGutter().isAnnotationsShown();
    }

    @Override
    public void showAnnotation(@NotNull ThreesideTextDiffViewerEx viewer, @NotNull ThreeSide side, @NotNull AnnotationData data) {
      Project project = ObjectUtils.assertNotNull(viewer.getProject());
      AnnotateToggleAction.doAnnotate(viewer.getEditor(side), project, null, data.annotation, data.vcs);
    }

    @Override
    public void hideAnnotation(@NotNull ThreesideTextDiffViewerEx viewer, @NotNull ThreeSide side) {
      viewer.getEditor(side).getGutter().closeAllAnnotations();
    }
  }

  private static class TextMergeAnnotatorFactory extends ThreesideAnnotatorFactory {
    @Override
    @NotNull
    public Class<? extends ThreesideTextDiffViewerEx> getViewerClass() {
      return TextMergeViewer.MyThreesideViewer.class;
    }

    @Nullable
    @Override
    public ViewerAnnotator createAnnotator(@NotNull ThreesideTextDiffViewerEx viewer, @NotNull ThreeSide side) {
      if (side == ThreeSide.BASE) return null; // middle content is local Document, not the BASE one
      return super.createAnnotator(viewer, side);
    }
  }

  private static abstract class TwosideViewerAnnotatorFactory<T extends DiffViewerBase> extends ViewerAnnotatorFactory<T> {
    @Nullable
    public abstract Side getCurrentSide(@NotNull T viewer, @NotNull Editor editor);

    public abstract boolean isAnnotationShown(@NotNull T viewer, @NotNull Side side);

    public abstract void showAnnotation(@NotNull T viewer, @NotNull Side side, @NotNull AnnotationData data);

    public abstract void hideAnnotation(@NotNull T viewer, @NotNull Side side);

    @Override
    @Nullable
    public ViewerAnnotator createAnnotator(@NotNull T viewer, @NotNull Editor editor) {
      Side side = getCurrentSide(viewer, editor);
      if (side == null) return null;
      return createAnnotator(viewer, side);
    }

    @Override
    public void showRememberedAnnotations(@NotNull T viewer) {
      boolean[] annotationsShown = viewer.getRequest().getUserData(ANNOTATIONS_SHOWN_KEY);
      if (annotationsShown == null || annotationsShown.length != 2) return;
      if (annotationsShown[0]) {
        ViewerAnnotator annotator = createAnnotator(viewer, Side.LEFT);
        if (annotator != null) doAnnotate(annotator);
      }
      if (annotationsShown[1]) {
        ViewerAnnotator annotator = createAnnotator(viewer, Side.RIGHT);
        if (annotator != null) doAnnotate(annotator);
      }
    }

    @Override
    public void rememberShownAnnotations(@NotNull T viewer) {
      boolean[] annotationsShown = new boolean[2];
      annotationsShown[0] = isAnnotationShown(viewer, Side.LEFT);
      annotationsShown[1] = isAnnotationShown(viewer, Side.RIGHT);

      viewer.getRequest().putUserData(ANNOTATIONS_SHOWN_KEY, annotationsShown);
    }

    @Nullable
    public ViewerAnnotator createAnnotator(@NotNull T viewer, @NotNull Side side) {
      TwosideViewerAnnotatorFactory<T> factory = this;
      Project project = viewer.getProject();
      assert project != null;

      return new ViewerAnnotator() {
        @NotNull
        @Override
        public T getViewer() {
          return viewer;
        }

        @Override
        public boolean isAnnotationShown() {
          return factory.isAnnotationShown(viewer, side);
        }

        @Override
        public void showAnnotation(@NotNull AnnotationData data) {
          factory.showAnnotation(viewer, side, data);
        }

        @Override
        public void hideAnnotation() {
          factory.hideAnnotation(viewer, side);
        }

        @Nullable
        @Override
        public FileAnnotationLoader createAnnotationsLoader() {
          return createTwosideAnnotationsLoader(project, viewer.getRequest(), side);
        }

        @NotNull
        public BackgroundableActionLock getBackgroundableLock() {
          return BackgroundableActionLock.getLock(viewer.getProject(), VcsBackgroundableActions.ANNOTATE, viewer, side);
        }

        @Nullable
        @Override
        public AnnotationData getDataFromCache() {
          AnnotationData[] cache = viewer.getRequest().getUserData(CACHE_KEY);
          if (cache != null && cache.length == 2) {
            return side.select(cache);
          }
          return null;
        }

        @Override
        public void putDataToCache(@NotNull AnnotationData data) {
          DiffRequest request = viewer.getRequest();
          AnnotationData[] cache = request.getUserData(CACHE_KEY);
          if (cache == null || cache.length != 2) {
            cache = new AnnotationData[2];
            request.putUserData(CACHE_KEY, cache);
          }
          cache[side.getIndex()] = data;
        }
      };
    }
  }

  private static abstract class ThreesideViewerAnnotatorFactory<T extends DiffViewerBase> extends ViewerAnnotatorFactory<T> {
    @Nullable
    public abstract ThreeSide getCurrentSide(@NotNull T viewer, @NotNull Editor editor);

    public abstract boolean isAnnotationShown(@NotNull T viewer, @NotNull ThreeSide side);

    public abstract void showAnnotation(@NotNull T viewer, @NotNull ThreeSide side, @NotNull AnnotationData data);

    public abstract void hideAnnotation(@NotNull T viewer, @NotNull ThreeSide side);

    @Override
    @Nullable
    public ViewerAnnotator createAnnotator(@NotNull T viewer, @NotNull Editor editor) {
      ThreeSide side = getCurrentSide(viewer, editor);
      if (side == null) return null;
      return createAnnotator(viewer, side);
    }

    @Override
    public void showRememberedAnnotations(@NotNull T viewer) {
      boolean[] annotationsShown = viewer.getRequest().getUserData(ANNOTATIONS_SHOWN_KEY);
      if (annotationsShown == null || annotationsShown.length != 3) return;
      if (annotationsShown[0]) {
        ViewerAnnotator annotator = createAnnotator(viewer, ThreeSide.LEFT);
        if (annotator != null) doAnnotate(annotator);
      }
      if (annotationsShown[1]) {
        ViewerAnnotator annotator = createAnnotator(viewer, ThreeSide.BASE);
        if (annotator != null) doAnnotate(annotator);
      }
      if (annotationsShown[2]) {
        ViewerAnnotator annotator = createAnnotator(viewer, ThreeSide.RIGHT);
        if (annotator != null) doAnnotate(annotator);
      }
    }

    @Override
    public void rememberShownAnnotations(@NotNull T viewer) {
      boolean[] annotationsShown = new boolean[3];
      annotationsShown[0] = isAnnotationShown(viewer, ThreeSide.LEFT);
      annotationsShown[1] = isAnnotationShown(viewer, ThreeSide.BASE);
      annotationsShown[2] = isAnnotationShown(viewer, ThreeSide.RIGHT);

      viewer.getRequest().putUserData(ANNOTATIONS_SHOWN_KEY, annotationsShown);
    }

    @Nullable
    public ViewerAnnotator createAnnotator(@NotNull T viewer, @NotNull ThreeSide side) {
      ThreesideViewerAnnotatorFactory<T> factory = this;
      Project project = viewer.getProject();
      assert project != null;

      return new ViewerAnnotator() {
        @NotNull
        @Override
        public T getViewer() {
          return viewer;
        }

        @Override
        public boolean isAnnotationShown() {
          return factory.isAnnotationShown(viewer, side);
        }

        @Override
        public void showAnnotation(@NotNull AnnotationData data) {
          factory.showAnnotation(viewer, side, data);
        }

        @Override
        public void hideAnnotation() {
          factory.hideAnnotation(viewer, side);
        }

        @Nullable
        @Override
        public FileAnnotationLoader createAnnotationsLoader() {
          return createThreesideAnnotationsLoader(project, viewer.getRequest(), side);
        }

        @NotNull
        public BackgroundableActionLock getBackgroundableLock() {
          return BackgroundableActionLock.getLock(viewer.getProject(), VcsBackgroundableActions.ANNOTATE, viewer, side);
        }

        @Nullable
        @Override
        public AnnotationData getDataFromCache() {
          AnnotationData[] cache = viewer.getRequest().getUserData(CACHE_KEY);
          if (cache != null && cache.length == 3) {
            return side.select(cache);
          }
          return null;
        }

        @Override
        public void putDataToCache(@NotNull AnnotationData data) {
          DiffRequest request = viewer.getRequest();
          AnnotationData[] cache = request.getUserData(CACHE_KEY);
          if (cache == null || cache.length != 3) {
            cache = new AnnotationData[3];
            request.putUserData(CACHE_KEY, cache);
          }
          cache[side.getIndex()] = data;
        }
      };
    }
  }

  private static abstract class ViewerAnnotatorFactory<T extends DiffViewerBase> {
    @NotNull
    public abstract Class<? extends T> getViewerClass();

    @Nullable
    public abstract ViewerAnnotator createAnnotator(@NotNull T viewer, @NotNull Editor editor);

    public abstract void showRememberedAnnotations(@NotNull T viewer);

    public abstract void rememberShownAnnotations(@NotNull T viewer);
  }

  private static abstract class ViewerAnnotator {
    @NotNull
    public abstract DiffViewerBase getViewer();

    public abstract boolean isAnnotationShown();

    public abstract void showAnnotation(@NotNull AnnotationData data);

    public abstract void hideAnnotation();

    @Nullable
    public abstract FileAnnotationLoader createAnnotationsLoader();

    @NotNull
    public abstract BackgroundableActionLock getBackgroundableLock();

    @Nullable
    public abstract AnnotationData getDataFromCache();

    public abstract void putDataToCache(@NotNull AnnotationData result);
  }

  private abstract static class FileAnnotationLoader {
    @NotNull private final AbstractVcs myVcs;
    private final boolean myShouldCache;

    @Nullable private VcsException myException;
    @Nullable private FileAnnotation myResult;

    public FileAnnotationLoader(@NotNull AbstractVcs vcs, boolean cache) {
      myVcs = vcs;
      myShouldCache = cache;
    }

    @Nullable
    public VcsException getException() {
      return myException;
    }

    @Nullable
    public AnnotationData getResult() {
      return myResult != null ? new AnnotationData(myVcs, myResult) : null;
    }

    public boolean shouldCache() {
      return myShouldCache;
    }

    public void run() {
      try {
        myResult = compute();
      }
      catch (VcsException e) {
        myException = e;
      }
    }

    protected abstract FileAnnotation compute() throws VcsException;
  }

  private static class AnnotationData {
    @NotNull public final AbstractVcs vcs;
    @NotNull public final FileAnnotation annotation;

    public AnnotationData(@NotNull AbstractVcs vcs, @NotNull FileAnnotation annotation) {
      this.vcs = vcs;
      this.annotation = annotation;
    }
  }

  private static class EventData {
    @NotNull public final DiffViewerBase viewer;
    @NotNull public final ViewerAnnotator annotator;

    public EventData(@NotNull DiffViewerBase viewer, @NotNull ViewerAnnotator annotator) {
      this.viewer = viewer;
      this.annotator = annotator;
    }
  }

  public static class Provider implements AnnotateToggleAction.Provider {
    @Override
    public boolean isEnabled(AnActionEvent e) {
      return AnnotateDiffViewerAction.isEnabled(e);
    }

    @Override
    public boolean isSuspended(AnActionEvent e) {
      return AnnotateDiffViewerAction.isSuspended(e);
    }

    @Override
    public boolean isAnnotated(AnActionEvent e) {
      return AnnotateDiffViewerAction.isAnnotated(e);
    }

    @Override
    public void perform(AnActionEvent e, boolean selected) {
      AnnotateDiffViewerAction.perform(e, selected);
    }
  }
}


text:
package org.sanpra.jumble.WordSetComputers;

import org.sanpra.jumble.utils.DictionaryUtils;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Simple brute force implementation - generate all possible combinations and test for validity against dictionary
 */
public final class SimpleWordSetComputer implements WordSetComputer {

    private static final int MINIMUM_VALID_WORD_SIZE = 2;

    /**
     * Generates a set of valid words that can be formed from the characters in the input string
     * @param inputString Input string
     * @return The set of valid words
     *
     * If inputString is null or empty, returns empty set
     */
    @Override
    public Set<String> compute(String inputString) {
        if(inputString == null || inputString.isEmpty())
            return new HashSet<>();
        Set<String> wordSet = generateAllPermutations(inputString);
        removeInvalidWordsFromSet(wordSet);
        return wordSet;
    }

    /**
     * Removes all invalid words from wordSet. Word validity is based on call to DictionaryUtils.isValidWord
     * @param wordSet Set of strings. If wordSet is empty or null, returns with no changes.
     */
    private void removeInvalidWordsFromSet(Set<String> wordSet) {
        if(wordSet == null) return;
        Iterator<String> wordSetIterator = wordSet.iterator();
        while(wordSetIterator.hasNext()) {
            if(!DictionaryUtils.isValidWord(wordSetIterator.next()))
                wordSetIterator.remove();
        }
    }

    /**
     * Generate all possible permutations of characters in inputString, of length>=2
     * @param inputString String containing characters for which permutations need to be computed.
     * @return  A Set of String objects containing all possible permutations for characters in inputString
     *          If inputString is empty or null, returns empty set
     */
    private Set<String> generateAllPermutations(String inputString) {
        Set<String> permutations = new HashSet<>();
        permute("", inputString, permutations);
        return permutations;
    }

    /**
     * Generates all possible permutations(of length>=2) of characters in remaining, appends them to prefix and stores the strings in permutations
     * @param prefix Prefix string for permutation
     * @param remaining  Remaining characters for which permutations need to be generated
     * @param permutations   Set in which permutations must be stored
     */
    static void permute(String prefix, String remaining, Set<String> permutations) {
        if(permutations == null || prefix == null || remaining == null) return;
        if(remaining.isEmpty()) return;

        //generate all possible permutations for prefix as well, if it has 2 or more characters
        if(prefix.length() >= MINIMUM_VALID_WORD_SIZE)
            permute("", prefix, permutations);

        //recursion stopping condition - if remaining is single character, add to permutation set
        if(remaining.length() == 1) {
            permutations.add(prefix + remaining);
            return;
        }

        //for each character in String remaining, append to prefix and generate permutations of remaining characters
        for(int counter = 0; counter < remaining.length(); counter++) {
            String newPrefix = prefix + remaining.charAt(counter);
            String newRemaining = remaining.substring(0, counter) + remaining.substring(counter+1, remaining.length());
            permute(newPrefix, newRemaining, permutations);
        }
    }

}


text:
package flag

import (
	"reflect"
	"testing"
	"time"

	"github.com/achilleasa/usrv/config/store"
)

func TestMapFlagDynamicUpdate(t *testing.T) {
	var s store.Store

	expValue := map[string]string{
		"foo":       "bar",
		"key1":      "value1",
		"key2/key3": "value2",
	}
	s.SetKeys(1, "map-flag", map[string]string{"foo": "bar"})

	f := NewMap(&s, "map-flag")
	go func() {
		<-time.After(100 * time.Millisecond)
		s.SetKeys(1, "map-flag", expValue)
	}()
	select {
	case <-f.ChangeChan():
	case <-time.After(1000 * time.Millisecond):
		t.Fatal("timeout waiting for flag change event")
	}

	val := f.Get()
	if !reflect.DeepEqual(val, expValue) {
		t.Fatalf("expected val to be:\n%v\n\ngot:\n%v", expValue, val)
	}
}

func TestMapFlagManualSet(t *testing.T) {
	f := NewMap(nil, "")
	expValue := map[string]string{
		"key1":      "value1",
		"key2/key3": "value2",
	}
	f.Set(expValue)

	// Second attempt to set should bail out as the value has not changed
	f.Set(expValue)

	val := f.Get()
	if !reflect.DeepEqual(val, expValue) {
		t.Fatalf("expected val to be:\n%v\n\ngot:\n%v", expValue, val)
	}
}


text:
package seava.j4e.api.session;

public class Session {

	public static ThreadLocal<IUser> user = new ThreadLocal<IUser>();

}


text:
require "chef/provisioning"
require "chef/provisioning/vsphere_driver"

#
# This is the main way to connect to vSphere
#
with_vsphere_driver host: "172.16.20.2",
                    insecure: true,
                    user:     "administrator@vsphere.local",
                    password: "PASSWORD"

#
# These are the machine_options that you need to declare
#
with_machine_options bootstrap_options: {
  num_cpus: 2,
  memory_mb: 4096,
  datacenter: "Datacenter",
  resource_pool: "Cluster",
  template_folder: "Linux",
  template_name: "ubuntu16",
  ssh: {
    user: "admini",
    password: "PASSWORD",
    paranoid: false,
  },
},
                     sudo: true

#
# This is where you can declare the machine
#
machine "testing-ubuntu" do
  tag "haha"
end


text:
package org.apache.cassandra.config;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.apache.cassandra.OrderedJUnit4ClassRunner;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.gms.Gossiper;
import org.apache.cassandra.schema.KeyspaceMetadata;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.service.MigrationManager;
import org.apache.cassandra.thrift.ThriftConversion;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import static org.junit.Assert.assertTrue;

@RunWith(OrderedJUnit4ClassRunner.class)
public class DatabaseDescriptorTest
{
    @BeforeClass
    public static void setupDatabaseDescriptor()
    {
        DatabaseDescriptor.daemonInitialization();
    }

    @Test
    public void testCFMetaDataSerialization() throws ConfigurationException, InvalidRequestException
    {
        // test serialization of all defined test CFs.
        for (String keyspaceName : Schema.instance.getNonSystemKeyspaces())
        {
            for (CFMetaData cfm : Schema.instance.getTablesAndViews(keyspaceName))
            {
                CFMetaData cfmDupe = ThriftConversion.fromThrift(ThriftConversion.toThrift(cfm));
                assertNotNull(cfmDupe);
                assertEquals(cfm, cfmDupe);
            }
        }
    }

    @Test
    public void testKSMetaDataSerialization() throws ConfigurationException
    {
        for (String ks : Schema.instance.getNonSystemKeyspaces())
        {
            // Not testing round-trip on the KsDef via serDe() because maps
            KeyspaceMetadata ksm = Schema.instance.getKSMetaData(ks);
            KeyspaceMetadata ksmDupe = ThriftConversion.fromThrift(ThriftConversion.toThrift(ksm));
            assertNotNull(ksmDupe);
            assertEquals(ksm, ksmDupe);
        }
    }

    // this came as a result of CASSANDRA-995
    @Test
    public void testTransKsMigration() throws ConfigurationException, IOException
    {
        SchemaLoader.cleanupAndLeaveDirs();
        Schema.instance.loadFromDisk();
        assertEquals(0, Schema.instance.getNonSystemKeyspaces().size());

        Gossiper.instance.start((int)(System.currentTimeMillis() / 1000));
        Keyspace.setInitialized();

        try
        {
            // add a few.
            MigrationManager.announceNewKeyspace(KeyspaceMetadata.create("ks0", KeyspaceParams.simple(3)));
            MigrationManager.announceNewKeyspace(KeyspaceMetadata.create("ks1", KeyspaceParams.simple(3)));

            assertNotNull(Schema.instance.getKSMetaData("ks0"));
            assertNotNull(Schema.instance.getKSMetaData("ks1"));

            Schema.instance.clearKeyspaceMetadata(Schema.instance.getKSMetaData("ks0"));
            Schema.instance.clearKeyspaceMetadata(Schema.instance.getKSMetaData("ks1"));

            assertNull(Schema.instance.getKSMetaData("ks0"));
            assertNull(Schema.instance.getKSMetaData("ks1"));

            Schema.instance.loadFromDisk();

            assertNotNull(Schema.instance.getKSMetaData("ks0"));
            assertNotNull(Schema.instance.getKSMetaData("ks1"));
        }
        finally
        {
            Gossiper.instance.stop();
        }
    }

    @Test
    public void testConfigurationLoader() throws Exception
    {
        // By default, we should load from the yaml
        Config config = DatabaseDescriptor.loadConfig();
        assertEquals("Test Cluster", config.cluster_name);
        Keyspace.setInitialized();

        // Now try custom loader
        ConfigurationLoader testLoader = new TestLoader();
        System.setProperty("cassandra.config.loader", testLoader.getClass().getName());

        config = DatabaseDescriptor.loadConfig();
        assertEquals("ConfigurationLoader Test", config.cluster_name);
    }

    public static class TestLoader implements ConfigurationLoader
    {
        public Config loadConfig() throws ConfigurationException
        {
            Config testConfig = new Config();
            testConfig.cluster_name = "ConfigurationLoader Test";
            return testConfig;
        }
    }

    static NetworkInterface suitableInterface = null;
    static boolean hasIPv4andIPv6 = false;

    /*
     * Server only accepts interfaces by name if they have a single address
     * OS X seems to always have an ipv4 and ipv6 address on all interfaces which means some tests fail
     * if not checked for and skipped
     */
    @BeforeClass
    public static void selectSuitableInterface() throws Exception {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while(interfaces.hasMoreElements()) {
            NetworkInterface intf = interfaces.nextElement();

            System.out.println("Evaluating " + intf.getName());

            if (intf.isLoopback()) {
                suitableInterface = intf;

                boolean hasIPv4 = false;
                boolean hasIPv6 = false;
                Enumeration<InetAddress> addresses = suitableInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    if (addresses.nextElement() instanceof Inet6Address)
                        hasIPv6 = true;
                    else
                        hasIPv4 = true;
                }
                hasIPv4andIPv6 = hasIPv4 && hasIPv6;
                return;
            }
        }
    }

    @Test
    public void testRpcInterface() throws Exception
    {
        Config testConfig = DatabaseDescriptor.loadConfig();
        testConfig.rpc_interface = suitableInterface.getName();
        testConfig.rpc_address = null;
        DatabaseDescriptor.applyAddressConfig(testConfig);

        /*
         * Confirm ability to select between IPv4 and IPv6
         */
        if (hasIPv4andIPv6)
        {
            testConfig = DatabaseDescriptor.loadConfig();
            testConfig.rpc_interface = suitableInterface.getName();
            testConfig.rpc_address = null;
            testConfig.rpc_interface_prefer_ipv6 = true;
            DatabaseDescriptor.applyAddressConfig(testConfig);

            assertEquals(DatabaseDescriptor.getRpcAddress().getClass(), Inet6Address.class);

            testConfig = DatabaseDescriptor.loadConfig();
            testConfig.rpc_interface = suitableInterface.getName();
            testConfig.rpc_address = null;
            testConfig.rpc_interface_prefer_ipv6 = false;
            DatabaseDescriptor.applyAddressConfig(testConfig);

            assertEquals(DatabaseDescriptor.getRpcAddress().getClass(), Inet4Address.class);
        }
        else
        {
            /*
             * Confirm first address of interface is selected
             */
            assertEquals(DatabaseDescriptor.getRpcAddress(), suitableInterface.getInetAddresses().nextElement());
        }
    }

    @Test
    public void testListenInterface() throws Exception
    {
        Config testConfig = DatabaseDescriptor.loadConfig();
        testConfig.listen_interface = suitableInterface.getName();
        testConfig.listen_address = null;
        DatabaseDescriptor.applyAddressConfig(testConfig);

        /*
         * Confirm ability to select between IPv4 and IPv6
         */
        if (hasIPv4andIPv6)
        {
            testConfig = DatabaseDescriptor.loadConfig();
            testConfig.listen_interface = suitableInterface.getName();
            testConfig.listen_address = null;
            testConfig.listen_interface_prefer_ipv6 = true;
            DatabaseDescriptor.applyAddressConfig(testConfig);

            assertEquals(DatabaseDescriptor.getListenAddress().getClass(), Inet6Address.class);

            testConfig = DatabaseDescriptor.loadConfig();
            testConfig.listen_interface = suitableInterface.getName();
            testConfig.listen_address = null;
            testConfig.listen_interface_prefer_ipv6 = false;
            DatabaseDescriptor.applyAddressConfig(testConfig);

            assertEquals(DatabaseDescriptor.getListenAddress().getClass(), Inet4Address.class);
        }
        else
        {
            /*
             * Confirm first address of interface is selected
             */
            assertEquals(DatabaseDescriptor.getRpcAddress(), suitableInterface.getInetAddresses().nextElement());
        }
    }

    @Test
    public void testListenAddress() throws Exception
    {
        Config testConfig = DatabaseDescriptor.loadConfig();
        testConfig.listen_address = suitableInterface.getInterfaceAddresses().get(0).getAddress().getHostAddress();
        testConfig.listen_interface = null;
        DatabaseDescriptor.applyAddressConfig(testConfig);
    }

    @Test
    public void testRpcAddress() throws Exception
    {
        Config testConfig = DatabaseDescriptor.loadConfig();
        testConfig.rpc_address = suitableInterface.getInterfaceAddresses().get(0).getAddress().getHostAddress();
        testConfig.rpc_interface = null;
        DatabaseDescriptor.applyAddressConfig(testConfig);

    }

    @Test
    public void testTokensFromString()
    {
        assertTrue(DatabaseDescriptor.tokensFromString(null).isEmpty());
        Collection<String> tokens = DatabaseDescriptor.tokensFromString(" a,b ,c , d, f,g,h");
        assertEquals(7, tokens.size());
        assertTrue(tokens.containsAll(Arrays.asList(new String[]{ "a", "b", "c", "d", "f", "g", "h" })));
    }

    @Test
    public void testRepairSessionSizeToggles()
    {
        int previousDepth = DatabaseDescriptor.getRepairSessionMaxTreeDepth();
        try
        {
            Assert.assertEquals(18, DatabaseDescriptor.getRepairSessionMaxTreeDepth());
            DatabaseDescriptor.setRepairSessionMaxTreeDepth(10);
            Assert.assertEquals(10, DatabaseDescriptor.getRepairSessionMaxTreeDepth());

            try
            {
                DatabaseDescriptor.setRepairSessionMaxTreeDepth(9);
                fail("Should have received a ConfigurationException for depth of 9");
            }
            catch (ConfigurationException ignored) { }
            Assert.assertEquals(10, DatabaseDescriptor.getRepairSessionMaxTreeDepth());

            try
            {
                DatabaseDescriptor.setRepairSessionMaxTreeDepth(-20);
                fail("Should have received a ConfigurationException for depth of -20");
            }
            catch (ConfigurationException ignored) { }
            Assert.assertEquals(10, DatabaseDescriptor.getRepairSessionMaxTreeDepth());

            DatabaseDescriptor.setRepairSessionMaxTreeDepth(22);
            Assert.assertEquals(22, DatabaseDescriptor.getRepairSessionMaxTreeDepth());
        }
        finally
        {
            DatabaseDescriptor.setRepairSessionMaxTreeDepth(previousDepth);
        }
    }

    @Test
    public void testApplyTokensConfigInitialTokensSetNumTokensSetAndDoesMatch()
    {
        Config config = DatabaseDescriptor.loadConfig();
        config.initial_token = "0,256,1024";
        config.num_tokens = 3;

        try
        {
            DatabaseDescriptor.applyTokensConfig(config);
            Assert.assertEquals(Integer.valueOf(3), config.num_tokens);
            Assert.assertEquals(3, DatabaseDescriptor.tokensFromString(config.initial_token).size());
        }
        catch (ConfigurationException e)
        {
            Assert.fail("number of tokens in initial_token=0,256,1024 does not match num_tokens = 3");
        }
    }

    @Test
    public void testApplyTokensConfigInitialTokensSetNumTokensSetAndDoesntMatch()
    {
        Config config = DatabaseDescriptor.loadConfig();
        config.initial_token = "0,256,1024";
        config.num_tokens = 10;

        try
        {
            DatabaseDescriptor.applyTokensConfig(config);

            Assert.fail("initial_token = 0,256,1024 and num_tokens = 10 but applyTokensConfig() did not fail!");
        }
        catch (ConfigurationException ex)
        {
            Assert.assertEquals("The number of initial tokens (by initial_token) specified (3) is different from num_tokens value (10)",
                                ex.getMessage());
        }
    }

    @Test
    public void testApplyTokensConfigInitialTokensSetNumTokensNotSet()
    {
        Config config = DatabaseDescriptor.loadConfig();
        config.initial_token = "0,256,1024";

        try
        {
            DatabaseDescriptor.applyTokensConfig(config);
            Assert.fail("setting initial_token and not setting num_tokens is invalid");
        }
        catch (ConfigurationException ex)
        {
            Assert.assertEquals("initial_token was set but num_tokens is not!", ex.getMessage());
        }
    }

    @Test
    public void testApplyTokensConfigInitialTokensNotSetNumTokensSet()
    {
        Config config = DatabaseDescriptor.loadConfig();
        config.num_tokens = 3;

        DatabaseDescriptor.applyTokensConfig(config);

        Assert.assertEquals(Integer.valueOf(3), config.num_tokens);
        Assert.assertTrue(DatabaseDescriptor.tokensFromString(config.initial_token).isEmpty());
    }

    @Test
    public void testApplyTokensConfigInitialTokensNotSetNumTokensNotSet()
    {
        Config config = DatabaseDescriptor.loadConfig();
        DatabaseDescriptor.applyTokensConfig(config);

        Assert.assertEquals(Integer.valueOf(1), config.num_tokens);
        Assert.assertTrue(DatabaseDescriptor.tokensFromString(config.initial_token).isEmpty());
    }

    @Test
    public void testApplyTokensConfigInitialTokensOneNumTokensNotSet()
    {
        Config config = DatabaseDescriptor.loadConfig();
        config.initial_token = "123";
        config.num_tokens = null;

        DatabaseDescriptor.applyTokensConfig(config);

        Assert.assertEquals(Integer.valueOf(1), config.num_tokens);
        Assert.assertEquals(1, DatabaseDescriptor.tokensFromString(config.initial_token).size());
    }
}


text:
package nl.it.fixx.moknj.repository.custom;

/**
 *
 * @author adriaan
 */
public interface MenuRepositoryCustom {

    public boolean existsByName(String name);
}


text:
<?php
  header("Expires: Thu, 01 Dec 2003 16:00:00 GMT");
  header("Cache-Control: no-cache, must-revalidate");
  header("Pragma: no-cache");
  if ($_GET["csp"]) {
    $csp = $_GET["csp"];
    // If the magic quotes option is enabled, the CSP could be escaped and
    // the test would fail.
    if (get_magic_quotes_gpc()) {
      $csp = stripslashes($csp);
    }
    header("Content-Security-Policy: " . $csp);
  }
?>

<?php
if ($_GET["type"] == "eval") {
?>

var id = 0;
try {
  id = eval("1 + 2 + 3");
}
catch (e) {
}

postMessage(id === 0 ? "eval blocked" : "eval allowed");

<?php
} else if ($_GET["type"] == "function-function") {
?>

var fn = function() {
    postMessage('Function() function blocked');
}
try {
    fn = new Function("", "postMessage('Function() function allowed');");
}
catch(e) {
}
fn();

<?php
} else if ($_GET["type"] == "importscripts") {
?>

try {
    importScripts("http://localhost:8000/security/contentSecurityPolicy/resources/post-message.js");
    postMessage("importScripts allowed");
} catch(e) {
    postMessage("importScripts blocked: " + e);
}

<?php
} else if ($_GET["type"] == "make-xhr") {
?>

try {
    var xhr = new XMLHttpRequest;
    xhr.open("GET", "http://127.0.0.1:8000/xmlhttprequest/resources/get.txt", true);
    postMessage("xhr allowed");
} catch(e) {
    postMessage("xhr blocked");
}

<?php
} else if ($_GET["type"] == "set-timeout") {
?>

var id = 0;
try {
    id = setTimeout("postMessage('handler invoked')", 100);
} catch(e) {
}
postMessage(id === 0 ? "setTimeout blocked" : "setTimeout allowed");

<?php
} else if ($_GET["type"] == "alert-pass") {
?>

alert('PASS');

<?php
} else if ($_GET["type"] == "report-referrer") {
?>

var xhr = new XMLHttpRequest;
xhr.open("GET", "http://127.0.0.1:8000/security/resources/echo-referrer-header.php", true);
xhr.onload = function () {
    postMessage(this.responseText);
};
xhr.send();

<?php
}
?>


text:
{% extends "account/base.html" %}

{% load url from future %}
{% load i18n %}
{% load bootstrap %}

{% block head_title %}{% trans "Signup" %}{% endblock %}

{% block content %}

{% trans "Sign Up" %}

{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}

<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}" role="form">
  {% csrf_token %}
  {{ form|bootstrap }}
  {% if redirect_field_value %}

      <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />

  {% endif %}
  <button type="submit" class="btn btn-primary">{% trans "Sign Up" %} »</button>
</form>

{% endblock %}


text:
class Detection(object):

    def __init__(self, json_data, height, width, zones, active=False, side=20):
        self.left = int(json_data['left'] * height)
        self.right = int(json_data['right'] * height)
        self.top = int(json_data['top'] * width)
        self.bottom = int(json_data['bottom'] * width)
        self.name = json_data['name']
        self.active = active
        self.probility = json_data['probability']

        self.zone = zones['CENTER']

        center = [self.bottom - self.top, self.right - self.left]

        if center[0] > width / 2:
            side = width * 15 / 100
            if self.right < side:
                self.in_active_zone = zones['LEFT']
        else:
            side = width - width * 15 / 100
            if self.left > side:
                self.in_active_zone = zones['RIGHT']

    def area(self):
        return (self.bottom - self.top) * (self.right - self.left)

    def distance(self):
        if self.active:
            return None

        distance = self.area() / -1000.0 + 50
        return distance

def main():
    from camera import Camera
    from backbone import Backbone

    cam = Camera()
    bone = Backbone('data.weights', 'config.json')

    while 'pigs' != 'fly':
        frame = cam.capture()
        detections = bone.get_detections(frame)
        for detection in detections:
            print detection.name, detection.distance()

if __name__ == '__main__':
    main()


text:
/*!
 * Start Bootstrap - Full Width Pics HTML Template (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

body {
    margin-top: 50px; /* Required margin for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
    font-family: "Hiragino Kaku Gothic ProN", "ヒラギノ角ゴ ProN W3", Meiryo, "メイリオ", Osaka, "MS PGothic", "MS Pゴシック", sans-serif;
    background: url(../images/bkgd-sandpaper.png) #fafafa;
}

.navbar-inverse {
  background-color: #4f396f;
  border-bottom: #4f3950;
}

.image-bg-fluid-height {
	background: url('../images/jumbotron.jpg') no-repeat center center scroll;
  padding: 100px 0;
}
@media screen and (max-width: 568px) {
  .image-bg-fluid-height {
    background-position: 71% 50%;
    padding: 50px 0;
  }
}
/*@media screen and (max-width: 640px) {
  .image-bg-fluid-height {
    background-position: 71% 50%;
    padding: 70px 0;
  }
}*/

.image-bg-fixed-height {
	background: url('../images/jumbotron.jpg') no-repeat center center scroll;
    height: 450px;
}

.image-bg-fluid-height,
.image-bg-fixed-height {
  text-align: center;
  background-size: cover;
}

.img-center {
	margin: 0 auto;
}

section {
    padding: 25px 0;
}

section .fa {
  padding-right: 0.5rem;
}

.container.bordered {
  box-shadow: 1px 1px 4px 1px rgba(160, 160, 160, .1);
  border-radius: 5px;
  background: #fafafa;
}
@media screen and (max-width: 640px) {
  .container.bordered {
    border-radius: 0;
  }
}

.section-heading {
    margin: 30px 0;
    font-size: 4em;
}

.section-lead {
    margin: 30px 0;
    line-height: 1.9;
}

.section-paragraph {
    margin: 30px 0;
    line-height: 1.9;
}

.section-caption {
  margin: 10px 0 30px;
  line-height: 1.9;
}

.list-item {
  line-height: 1.9;
}

footer {
    margin: 50px 0;
}

@media(max-width:768px) {
    section {
        padding-top: 15px;
        padding-bottom: 15px;
    }

    .section-heading {
        font-size: 2em;
    }
}

h1 {
  /*font-weight: bold;*/
}


text:
package com.rn0_60;

import android.content.Intent;
import android.os.Bundle;

import com.facebook.react.ReactActivity;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "rn0_60";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Attempt to dismiss any system dialogs (such as "reactnative keeps stopping")
        Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        sendBroadcast(closeDialog);
    }

    @Override
    protected void onSaveInstanceState(Bundle SavedInstanceState) {
        // Do not write any state, to avoid crashes on relaunch after a crash.  If Android keeps the state Bundle from
        // before the crash, passing it back into the application it can do so with a Drawable that does not implement
        // the getConstantState method, causing another crash.
    }
}


text:
package com.dbsys.rs.client.frame;

import com.dbsys.rs.client.BarangTableFrame;
import com.dbsys.rs.client.ComponentSelectionException;
import com.dbsys.rs.client.document.DocumentException;
import com.dbsys.rs.client.document.pdf.PdfProcessor;
import com.dbsys.rs.client.document.pdf.PemakaianPdfView;
import com.dbsys.rs.client.tableModel.PemakaianTableModel;
import com.dbsys.rs.connector.ServiceException;
import com.dbsys.rs.connector.TokenHolder;
import com.dbsys.rs.connector.service.PasienService;
import com.dbsys.rs.connector.service.PemakaianService;
import com.dbsys.rs.connector.service.TokenService;
import com.dbsys.rs.client.DateUtil;
import com.dbsys.rs.client.entity.Pasien;
import com.dbsys.rs.client.entity.Pemakaian;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

/**
 *
 * @author Deddy Christoper Kakunsi
 */
public class Apotek extends javax.swing.JFrame implements BarangTableFrame {

    private final TokenService tokenService = TokenService.getInstance();
    private final PemakaianService pemakaianService = PemakaianService.getInstance();
    private final PasienService pasienService = PasienService.getInstance();

    private Pasien pasien;

    /**
     * Digunakan untuk cetak
     */
    private List<Pemakaian> listPemakaian;

    /**
     * Creates new FrameFarmasi
     */
    public Apotek() {
        initComponents();
        setSize(1280, 800);

        pnlResep.setVisible(true);

        setDetailPasien(pasien);

        lblOperator.setText(TokenHolder.getNamaOperator());
        lblUnit.setText(TokenHolder.getNamaUnit());
    }

    private void setDetailPasien(Pasien pasien) {
        if (pasien == null) {
            pasien = new Pasien();

            txtPasienKelamin.setText(null);
            txtPasienTanggalLahir.setText(null);
            txtPasienTanggungan.setText(null);
            txtPasienStatusRawat.setText(null);
            txtPasienTanggalMasuk.setText(null);
        } else {
            txtPasienKelamin.setText(pasien.getKelamin().toString());
            txtPasienTanggalLahir.setText(pasien.getTanggalLahir().toString());
            txtPasienTanggungan.setText(pasien.getPenanggung().toString());
            txtPasienStatusRawat.setText(pasien.getStatus().toString());
            txtPasienTanggalMasuk.setText(pasien.getTanggalMasuk().toString());
        }

        txtPasienNik.setText(pasien.getNik());
        txtPasienNama.setText(pasien.getNama());
        txtPasienGolonganDarah.setText(pasien.getDarah());
        txtPasienAgama.setText(pasien.getAgama());
        txtPasienTelepon.setText(pasien.getTelepon());

        this.pasien = pasien;
    }

    private List<Pemakaian> loadTableResep(Pasien pasien) {
        List<Pemakaian> list = null;
        try {
            list = pemakaianService.getByPasien(pasien);
        } catch (ServiceException ex) {
            list = new ArrayList<>();
        } finally {
            PemakaianTableModel tableModel = new PemakaianTableModel(list);
            tblResep.setModel(tableModel);
        }

        return list;
    }

    private List<Pemakaian> loadTableResep(String nomorPasien) throws ServiceException {
        List<Pemakaian> list = pemakaianService.getByNomor(nomorPasien);
        PemakaianTableModel tableModel = new PemakaianTableModel(list);

        tblResep.removeAll();
        tblResep.setModel(tableModel);

        return list;
    }

    @Override
    public void reloadTableBarang() {
        listPemakaian = loadTableResep(pasien);
    }

    private Pemakaian getPemakaian() throws ComponentSelectionException {
        int index = tblResep.getSelectedRow();

        if (index < 0)
            throw new ComponentSelectionException("Silahkan memilih data pada tabel terlebih dahulu");

        PemakaianTableModel tableModel = (PemakaianTableModel) tblResep.getModel();
        return tableModel.getPemakaian(index);
    }

    private void printPemakaian() {
        if (listPemakaian == null) {
            JOptionPane.showMessageDialog(this, "Silahakn cari pemakaian menggunakan nomor resep/kode pasien");
            return;
        }

        PdfProcessor pdfProcessor = new PdfProcessor();

        PemakaianPdfView pdfView = new PemakaianPdfView();
        Map<String, Object> model = new HashMap<>();
        model.put("list", listPemakaian);

        try {
            pdfProcessor.process(pdfView, model, String.format("pemakaian-%s.pdf", DateUtil.getTime().hashCode()));
        } catch (DocumentException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlCari = new javax.swing.JPanel();
        txtPasienKode = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        pnlPasien = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        txtPasienNik = new javax.swing.JTextField();
        txtPasienNama = new javax.swing.JTextField();
        txtPasienKelamin = new javax.swing.JTextField();
        txtPasienTanggalLahir = new javax.swing.JTextField();
        txtPasienGolonganDarah = new javax.swing.JTextField();
        txtPasienAgama = new javax.swing.JTextField();
        txtPasienTelepon = new javax.swing.JTextField();
        txtPasienTanggungan = new javax.swing.JTextField();
        txtPasienStatusRawat = new javax.swing.JTextField();
        txtPasienTanggalMasuk = new javax.swing.JTextField();
        pnlResep = new javax.swing.JPanel();
        txtResepNomor = new javax.swing.JTextField();
        btnObatTambah = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblResep = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        btnHapus = new javax.swing.JButton();
        jToolBar1 = new javax.swing.JToolBar();
        jLabel31 = new javax.swing.JLabel();
        lblOperator = new javax.swing.JLabel();
        jLabel32 = new javax.swing.JLabel();
        jLabel33 = new javax.swing.JLabel();
        lblUnit = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnLogout = new javax.swing.JButton();
        btnGudang = new javax.swing.JButton();
        btnCetakPemakaian = new javax.swing.JButton();
        background = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("RUMAH SAKIT LIUN KENDAGE TAHUNA - FARMASI");
        setBounds(new java.awt.Rectangle(0, 0, 1280, 800));
        setUndecorated(true);
        setResizable(false);
        getContentPane().setLayout(null);

        pnlCari.setBackground(Utama.colorTransparentPanel);
        pnlCari.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "PENCARIAN PASIEN", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 12))); // NOI18N
        pnlCari.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        txtPasienKode.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPasienKodeFocusLost(evt);
            }
        });
        txtPasienKode.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasienKodeKeyPressed(evt);
            }
        });
        pnlCari.add(txtPasienKode, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 20, 250, 25));

        jLabel2.setText("No. Pasien");
        pnlCari.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, 90, 25));

        getContentPane().add(pnlCari);
        pnlCari.setBounds(860, 180, 400, 60);

        pnlPasien.setBackground(Utama.colorTransparentPanel);
        pnlPasien.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "DATA PASIEN", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 12))); // NOI18N
        pnlPasien.setLayout(null);

        jLabel3.setText("No. Jaminan");
        pnlPasien.add(jLabel3);
        jLabel3.setBounds(20, 30, 90, 25);

        jLabel4.setText("Nama");
        pnlPasien.add(jLabel4);
        jLabel4.setBounds(20, 60, 90, 25);

        jLabel5.setText("Kelamin");
        pnlPasien.add(jLabel5);
        jLabel5.setBounds(20, 90, 90, 25);

        jLabel7.setText("Agama");
        pnlPasien.add(jLabel7);
        jLabel7.setBounds(20, 180, 90, 25);

        jLabel8.setText("Telepon");
        pnlPasien.add(jLabel8);
        jLabel8.setBounds(20, 210, 90, 25);

        jLabel9.setText("Gol. Darah");
        pnlPasien.add(jLabel9);
        jLabel9.setBounds(20, 150, 90, 25);

        jLabel10.setText("Tanggal Masuk");
        pnlPasien.add(jLabel10);
        jLabel10.setBounds(20, 300, 90, 25);

        jLabel11.setText("Tanggal Lahir");
        pnlPasien.add(jLabel11);
        jLabel11.setBounds(20, 120, 90, 25);

        jLabel12.setText("Tanggungan");
        pnlPasien.add(jLabel12);
        jLabel12.setBounds(20, 240, 90, 25);

        jLabel13.setText("Status Rawat");
        pnlPasien.add(jLabel13);
        jLabel13.setBounds(20, 270, 90, 25);

        txtPasienNik.setEditable(false);
        pnlPasien.add(txtPasienNik);
        txtPasienNik.setBounds(130, 30, 250, 25);

        txtPasienNama.setEditable(false);
        pnlPasien.add(txtPasienNama);
        txtPasienNama.setBounds(130, 60, 250, 25);

        txtPasienKelamin.setEditable(false);
        pnlPasien.add(txtPasienKelamin);
        txtPasienKelamin.setBounds(130, 90, 250, 25);

        txtPasienTanggalLahir.setEditable(false);
        pnlPasien.add(txtPasienTanggalLahir);
        txtPasienTanggalLahir.setBounds(130, 120, 250, 25);

        txtPasienGolonganDarah.setEditable(false);
        pnlPasien.add(txtPasienGolonganDarah);
        txtPasienGolonganDarah.setBounds(130, 150, 250, 25);

        txtPasienAgama.setEditable(false);
        pnlPasien.add(txtPasienAgama);
        txtPasienAgama.setBounds(130, 180, 250, 25);

        txtPasienTelepon.setEditable(false);
        pnlPasien.add(txtPasienTelepon);
        txtPasienTelepon.setBounds(130, 210, 250, 25);

        txtPasienTanggungan.setEditable(false);
        pnlPasien.add(txtPasienTanggungan);
        txtPasienTanggungan.setBounds(130, 240, 250, 25);

        txtPasienStatusRawat.setEditable(false);
        pnlPasien.add(txtPasienStatusRawat);
        txtPasienStatusRawat.setBounds(130, 270, 250, 25);

        txtPasienTanggalMasuk.setEditable(false);
        pnlPasien.add(txtPasienTanggalMasuk);
        txtPasienTanggalMasuk.setBounds(130, 300, 250, 25);

        getContentPane().add(pnlPasien);
        pnlPasien.setBounds(860, 250, 400, 340);

        pnlResep.setBackground(Utama.colorTransparentPanel);
        pnlResep.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "DAFTAR OBAT PASIEN", javax.swing.border.TitledBorder.RIGHT, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Times New Roman", 1, 12))); // NOI18N
        pnlResep.setLayout(null);

        txtResepNomor.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtResepNomorFocusLost(evt);
            }
        });
        txtResepNomor.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtResepNomorKeyPressed(evt);
            }
        });
        pnlResep.add(txtResepNomor);
        txtResepNomor.setBounds(160, 25, 560, 25);

        btnObatTambah.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_tambah.png"))); // NOI18N
        btnObatTambah.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnObatTambahActionPerformed(evt);
            }
        });
        pnlResep.add(btnObatTambah);
        btnObatTambah.setBounds(730, 22, 80, 30);

        tblResep.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tblResep);

        pnlResep.add(jScrollPane1);
        jScrollPane1.setBounds(20, 70, 790, 450);

        jLabel1.setText("Nomor Resep");
        pnlResep.add(jLabel1);
        jLabel1.setBounds(20, 25, 130, 25);

        btnHapus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_hapus.png"))); // NOI18N
        btnHapus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnHapusActionPerformed(evt);
            }
        });
        pnlResep.add(btnHapus);
        btnHapus.setBounds(730, 530, 80, 30);

        getContentPane().add(pnlResep);
        pnlResep.setBounds(20, 180, 830, 580);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jLabel31.setText("LOGIN SEBAGAI:");
        jToolBar1.add(jLabel31);

        lblOperator.setText("jLabel32");
        jToolBar1.add(lblOperator);

        jLabel32.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel32.setText(" - ");
        jLabel32.setMaximumSize(new java.awt.Dimension(25, 14));
        jToolBar1.add(jLabel32);

        jLabel33.setText("UNIT: ");
        jToolBar1.add(jLabel33);

        lblUnit.setText("jLabel34");
        jToolBar1.add(lblUnit);

        jSeparator1.setMaximumSize(new java.awt.Dimension(20, 32767));
        jToolBar1.add(jSeparator1);

        btnLogout.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnLogout.setText("LOGOUT");
        btnLogout.setFocusable(false);
        btnLogout.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnLogout.setMaximumSize(new java.awt.Dimension(80, 21));
        btnLogout.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnLogout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLogoutActionPerformed(evt);
            }
        });
        jToolBar1.add(btnLogout);

        btnGudang.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
        btnGudang.setText("STOK");
        btnGudang.setFocusable(false);
        btnGudang.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGudang.setMaximumSize(new java.awt.Dimension(80, 19));
        btnGudang.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGudang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGudangActionPerformed(evt);
            }
        });
        jToolBar1.add(btnGudang);

        getContentPane().add(jToolBar1);
        jToolBar1.setBounds(0, 770, 1280, 30);

        btnCetakPemakaian.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/btn_cetak.png"))); // NOI18N
        btnCetakPemakaian.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCetakPemakaianActionPerformed(evt);
            }
        });
        getContentPane().add(btnCetakPemakaian);
        btnCetakPemakaian.setBounds(1180, 600, 80, 30);

        background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/dbsys/rs/client/images/bg_apotek.png"))); // NOI18N
        getContentPane().add(background);
        background.setBounds(0, 0, 1280, 800);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtPasienKodeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPasienKodeFocusLost
        String keyword = txtPasienKode.getText();
        txtResepNomor.setText(Pemakaian.createKode());

        if (keyword.equals(""))
            return;

        try {
            pasien = pasienService.get(keyword);
            setDetailPasien(pasien);
            listPemakaian = loadTableResep(pasien);
        } catch (ServiceException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_txtPasienKodeFocusLost

    private void btnObatTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnObatTambahActionPerformed
        String nomorResep = txtResepNomor.getText();

        if (nomorResep == null || nomorResep.equals("")) {
            JOptionPane.showMessageDialog(this, "Silahkan masukan nomor resep");
            return;
        }

        new TambahTagihan(this, pasien, nomorResep).setVisible(true);
    }//GEN-LAST:event_btnObatTambahActionPerformed

    private void btnLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLogoutActionPerformed
        try {
            tokenService.lock(TokenHolder.getKode());

            new Utama().setVisible(true);
            this.dispose();
        } catch (ServiceException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnLogoutActionPerformed

    private void txtResepNomorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtResepNomorFocusLost
        String nomor = txtResepNomor.getText();
        if (nomor == null || nomor.equals(""))
            return;

        try {
            listPemakaian = loadTableResep(nomor);
        } catch (ServiceException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_txtResepNomorFocusLost

    private void btnCetakPemakaianActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCetakPemakaianActionPerformed
        if (pasien == null) {
            JOptionPane.showMessageDialog(this, "Silahkan mencari data pasien terlebih dahulu");
            return;
        }

        printPemakaian();
    }//GEN-LAST:event_btnCetakPemakaianActionPerformed

    private void btnHapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHapusActionPerformed
        try {
            Pemakaian pemakaian = getPemakaian();

            int pilihan = JOptionPane.showConfirmDialog(this, String.format("Anda yakin akan menghapus pemakaian obat/bhp '%s' ?",
                    pemakaian.getBarang().getNama()));

            if (JOptionPane.YES_OPTION == pilihan) {
                pemakaianService.hapus(pemakaian);
                loadTableResep(pasien);
            }
        } catch (ComponentSelectionException | ServiceException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnHapusActionPerformed

    private void txtPasienKodeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasienKodeKeyPressed
        if (evt.getKeyCode() == 10)
            btnCetakPemakaian.requestFocus();
    }//GEN-LAST:event_txtPasienKodeKeyPressed

    private void txtResepNomorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtResepNomorKeyPressed
        if (evt.getKeyCode() == 10)
            btnCetakPemakaian.requestFocus();
    }//GEN-LAST:event_txtResepNomorKeyPressed

    private void btnGudangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGudangActionPerformed
        new GudangFarmasi().setVisible(true);
        dispose();
    }//GEN-LAST:event_btnGudangActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel background;
    private javax.swing.JButton btnCetakPemakaian;
    private javax.swing.JButton btnGudang;
    private javax.swing.JButton btnHapus;
    private javax.swing.JButton btnLogout;
    private javax.swing.JButton btnObatTambah;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel31;
    private javax.swing.JLabel jLabel32;
    private javax.swing.JLabel jLabel33;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblOperator;
    private javax.swing.JLabel lblUnit;
    private javax.swing.JPanel pnlCari;
    private javax.swing.JPanel pnlPasien;
    private javax.swing.JPanel pnlResep;
    private javax.swing.JTable tblResep;
    private javax.swing.JTextField txtPasienAgama;
    private javax.swing.JTextField txtPasienGolonganDarah;
    private javax.swing.JTextField txtPasienKelamin;
    private javax.swing.JTextField txtPasienKode;
    private javax.swing.JTextField txtPasienNama;
    private javax.swing.JTextField txtPasienNik;
    private javax.swing.JTextField txtPasienStatusRawat;
    private javax.swing.JTextField txtPasienTanggalLahir;
    private javax.swing.JTextField txtPasienTanggalMasuk;
    private javax.swing.JTextField txtPasienTanggungan;
    private javax.swing.JTextField txtPasienTelepon;
    private javax.swing.JTextField txtResepNomor;
    // End of variables declaration//GEN-END:variables
}


text:
import * as utils from './utils.js';

export default function initializeTrack(track, players) {
	const player1 = players[0];

	const stats = $('#stats .player');
	$('img', stats)[0].src = player1.image.src;
	$('.name', stats).text(player1.name);

	var grid = $('#grid').grid(track.width, track.height, {
		'width' : track.image.width,
		'height' : track.image.height,
		'background-color-even' : 'white',
		'background-color-odd' : 'white',
		'stroke' : true,
		'stroke-color' : '#42bbed',
		'layers' : 4, // grid (obsolete?), track, targets (valid moves), player
		'created' : function(evt) {
			var ctx = evt.layers[3].getContext('2d');
			ctx.drawImage(player1.image, player1.position.x * evt.cell.width, player1.position.y * evt.cell.height);

			// show track
			//$(evt.layers[1]).css('opacity', 0.8);
			var trackCtx = evt.layers[1].getContext('2d');
			trackCtx.drawImage(track.image, 0, 0);

			// Debug checkpoint lines
			// trackCtx.save();
			// trackCtx.strokeStyle = 'blue';
			// track.checkpoints.forEach(checkpoint => {
			// 	trackCtx.beginPath();
			// 	trackCtx.moveTo(checkpoint.from.x, checkpoint.from.y);
			// 	trackCtx.lineTo(checkpoint.to.x, checkpoint.to.y);
			// 	trackCtx.stroke();
			// });
			// trackCtx.restore();

			// show initial moves
			$(evt.layers[2]).css('opacity', 0.3);
			highlightCells(evt.layers[2], player1.color, getValidMoves(player1), evt.cell.width, evt.cell.height);
		},
		'click' : function(evt) {
			console.log('grid click', evt);

			var validMoves = getValidMoves(player1);
			if (!validMoves.some(function(move) { return move.x == evt.cell.x && move.y == evt.cell.y; })) {
				return;
			}

			var canvas = evt.layers[3];

			movePlayer(player1, track, evt.cell, evt.layers);
		},
		'mouseenter' : null /*function(evt) {
			var ctx = evt.layers[3].getContext('2d');
			ctx.fillStyle = 'blue';
			ctx.fillRect(evt.cell.width * evt.cell.x, evt.cell.height * evt.cell.y, evt.cell.width, evt.cell.height);
		}*/,
		'mouseleave' : null /*function(evt) {
			var ctx = evt.layers[3].getContext('2d');
			ctx.clearRect(evt.cell.width * evt.cell.x, evt.cell.height * evt.cell.y, evt.cell.width, evt.cell.height);
		}*/,
		'mousemove' : null /*function(evt) {
			var x = evt.mouse.x;
			var y = evt.mouse.y;
			console.log(x + ',' + y + ': ' + track.data.data[(y * track.data.width + x) * 4 + 1]);
		}*/,
		'keyup' : function(evt) {
			evt.event.stopPropagation();

			const keyName = evt.event.originalEvent.code;
			if (!keyName.startsWith('Numpad')) return;

			const validMoves = getValidMoves(player1);
			const moveIndex = [7, 8, 9, 4, 5, 6, 1, 2, 3].map(n => 'Numpad' + n).indexOf(keyName);
			const cell = {...evt.cell, ...validMoves[moveIndex]};

			var canvas = evt.layers[3];

			movePlayer(player1, track, cell, evt.layers);
		}
	});
}

function getValidMoves(player) {
	return player.moves.map(function(move) {
		var targetCell = {
			x: player.position.x + player.speed.x + move.x,
			y: player.position.y + player.speed.y + move.y
		};

		return targetCell;
	});
}

function movePlayer(player, track, cell, layers) {
	const canvas = layers[3];

	player.moveCount++;

	var transform = $(canvas).data('transform');
	if (typeof transform == 'undefined' || transform === null) {
		transform = new Transform();
		$(canvas).data('transform', transform);
	}

	var ctx = canvas.getContext('2d');
	ctx.clearRect(0, 0, canvas.width, canvas.height);

	// the dx and dy in cells
	var dx = cell.x - player.position.x;
	var dy = cell.y - player.position.y;

	// the dx and dy in pixels
	var dx_px = dx * cell.width;
	var dy_px = dy * cell.height;

	transform.save();

	// Move to the center of the starting cell
	var player_x_px = player.position.x * cell.width + cell.width / 2;
	var player_y_px = player.position.y * cell.height + cell.height / 2;
	transform.translate(player_x_px, player_y_px);

	// calculate rotation
	var rotation = Math.PI - Math.atan2(dx, dy);
	transform.rotate(rotation);

	// Calculate the animation distance
	var dist = Math.sqrt(Math.pow(dx_px, 2) + Math.pow(dy_px, 2));

	// Detect collisions with track bounds
	var collision = false;
	var d = 0;
	while (d <= dist) {
		var top = utils.int(0 - d - cell.height / 2);

		var collisionPoint = transform.getTransformedPoint(0, top);
		var pixel = getPixelValue(track.data.data, track.data.width, utils.int(collisionPoint.e(1)), utils.int(collisionPoint.e(2)));

		if (pixel !== 0) {
			// Collision!
			collision = true;
			break;
		}

		d++;
	}

	// get target coordinates of the center of the player
	const playerOrigin = transform.getTransformedPoint(0, 0);
	const playerTarget = transform.getTransformedPoint(0, utils.int(0 - d));
	const playerLine = $L(playerOrigin, playerTarget.subtract(playerOrigin));
	playerLine.target = playerTarget;

	// Set the target position (cell coordinates) and speed
	player.speed = collision ? { x: 0, y: 0 } : { x: dx, y: dy };
	player.position = {
		x: utils.int(playerTarget.e(1) / cell.width),
		y: utils.int(playerTarget.e(2) / cell.height)
	}

	// Does the player cross any checkpoint lines?
	track.checkpoints.forEach((checkpoint, index) => {
		// Only check if this is the next checkpoint for the player
		if (index === (player.checkpoint + 1) % track.checkpoints.length) {
			if (!checkpoint.line) {
				checkpoint.line = $L(
					[checkpoint.from.x, checkpoint.from.y],
					[checkpoint.to.x - checkpoint.from.x, checkpoint.to.y - checkpoint.from.y]
				);
				checkpoint.line.target = $V([checkpoint.to.x, checkpoint.to.y, 0]);
			}

			// Does the playerLine intersect with the checkpoint's line?
			if (doLineSegmentsIntersect(playerLine, checkpoint.line)) {
				player.checkpoint = index;
				if (player.checkpoint === 0) {
					player.round++;
				}
			}
		}
	});

	function complete() {
		highlightCells(layers[2], player.color, getValidMoves(player), cell.width, cell.height);
	}

	// animate over distance (from 0 to dist) in 500 ms
	transform.applyToContext(ctx);
	$({ n: 0 }).animate({ n: dist }, {
		duration: 400,
		step: function(now, fx) {
			// Clear the path (whole canvas would also do the trick, but this is a little more optimized)
			var left = 0 - cell.width / 2;
			var top = 0 - now - cell.height / 2;
			ctx.clearRect(left, cell.height / 2, cell.width, top);

			// draw the player at the current position
			ctx.drawImage(player.image, left, top);

			if (collision && now >= d) {
				$(fx.elem).stop();

				transform.restore();
				transform.applyToContext(ctx);
				complete();
			}
		},
		complete: function() {
			transform.restore();
			transform.applyToContext(ctx);
			complete();
		}
	});

	// Update stats
	const stats = $('#stats .player');
	$('.stat', stats).each(function() {
		const stat = Array.from($(this)[0].classList).find(c => c !== 'stat');
		const value = player[stat];
		let stringValue = '';
		switch (stat) {
			case "speed":
				const speed = utils.int(30 * Math.sqrt(value.x ** 2 + value.y ** 2));
				stringValue = speed >= 100 ? '<strong>' + speed + ' km/h</strong>' : speed + ' km/h';
				break;
			default:
				stringValue = value > -1 ? value : '';
				break;
		}
		$(this).html(stringValue);
	});
}

function highlightCells(canvas, color, cells, cellWidth, cellHeight) {
	// clear the canvas
	var ctx = canvas.getContext('2d');
	ctx.clearRect(0, 0, canvas.width, canvas.height);

	for(var c = 0; c < cells.length; c++) {
		var cell = cells[c];

		ctx.fillStyle = color;
		ctx.fillRect(cell.x * cellWidth, cell.y * cellHeight, cellWidth, cellHeight);

		ctx.strokeStyle = 'black';
		ctx.strokeRect(cell.x * cellWidth, cell.y * cellHeight, cellWidth, cellHeight);
	}
}

function doLineSegmentsIntersect(line1, line2) {
	const intersectPoint = line1.intersectionWith(line2);

	if (intersectPoint) {
		return utils.between(intersectPoint.e(1), line1.anchor.e(1), line1.target.e(1))
			&& utils.between(intersectPoint.e(2), line1.anchor.e(2), line1.target.e(2))
			&& utils.between(intersectPoint.e(1), line2.anchor.e(1), line2.target.e(1))
			&& utils.between(intersectPoint.e(2), line1.anchor.e(2), line1.target.e(2));
	}

	return false;
}

function getPixelValue(pixels, width, x, y) {
	var offset = (y * width + x) * 4;
	return  pixels[offset]     << 24 |
			pixels[offset + 1] << 16 |
			pixels[offset + 2] <<  8 |
			pixels[offset + 3];
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>DriverCommandExecutor</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.openqa.selenium.remote.service

Class DriverCommandExecutor

java.lang.Object

org.openqa.selenium.remote.HttpCommandExecutor

org.openqa.selenium.remote.service.DriverCommandExecutor

All Implemented Interfaces:

NeedsLocalLogs, CommandExecutor

public class DriverCommandExecutor
extends HttpCommandExecutor

A specialized HttpCommandExecutor that will use a DriverService that lives
 and dies with a single WebDriver session. The service will be restarted upon each new session
 request and shutdown after each quit command.

Constructor Summary

Constructors

Constructor and Description

DriverCommandExecutor(DriverService service)

Creates a new DriverCommandExecutor which will communicate with the driver as configured
 by the given service.

Method Summary

Methods

Modifier and Type
Method and Description

Response
execute(Command command)

Sends the command to the driver server for execution.

Methods inherited from class org.openqa.selenium.remote.HttpCommandExecutor

defineCommand, getAddressOfRemoteServer, setLocalLogs

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DriverCommandExecutor

public DriverCommandExecutor(DriverService service)

Creates a new DriverCommandExecutor which will communicate with the driver as configured
 by the given service.

Parameters:

service - The DriverService to send commands to.

Method Detail

execute

public Response execute(Command command)
                 throws java.io.IOException

Sends the command to the driver server for execution. The server will be started
 if requesting a new session. Likewise, if terminating a session, the server will be shutdown
 once a response is received.

Specified by:

execute in interface CommandExecutor

Overrides:

execute in class HttpCommandExecutor

Parameters:

command - The command to execute.

Returns:

The command response.

Throws:

java.io.IOException - If an I/O error occurs while sending the command.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("ipn", "0001_initial"),
    ]

    operations = [
        migrations.AddField(
            model_name="paypalipn",
            name="mp_id",
            field=models.CharField(max_length=128, null=True, blank=True),
            preserve_default=True,
        ),
    ]


text:
package pl.touk.nussknacker.ui.security.oauth2

import io.circe.generic.JsonCodec
import pl.touk.nussknacker.ui.security.api.{AuthenticatedUser, LoggedUser, RulesSet}
import pl.touk.nussknacker.ui.security.oauth2.OAuth2Profile.getUserRoles

@JsonCodec case class GitHubProfileResponse(id: Long, email: Option[String], login: String)

object GitHubProfile extends OAuth2Profile[GitHubProfileResponse] {
  def getAuthenticatedUser(profile: GitHubProfileResponse, configuration: OAuth2Configuration): AuthenticatedUser = {
    val userRoles = getUserRoles(profile.login, configuration)
    val username = profile.login
    AuthenticatedUser(id = profile.id.toString, username = username, userRoles)
  }
}