text:
package com.intellij.util.ui;

import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.Gray;
import com.intellij.ui.mac.foundation.Foundation;
import com.intellij.util.ui.tree.WideSelectionTreeUI;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.awt.geom.GeneralPath;
import java.lang.reflect.Field;

public class MacUIUtil {

  public static final boolean USE_QUARTZ = "true".equals(System.getProperty("apple.awt.graphics.UseQuartz"));
  public static final String MAC_FILL_BORDER = "MAC_FILL_BORDER";
  public static final int MAC_COMBO_BORDER_V_OFFSET = SystemInfo.isMacOSLion ? 1 : 0;
  private static Cursor INVERTED_TEXT_CURSOR;

  private MacUIUtil() {}

  public static void hideCursor() {
    if (SystemInfo.isMac && Registry.is("ide.mac.hide.cursor.when.typing")) {
      Foundation.invoke("NSCursor", "setHiddenUntilMouseMoves:", true);
    }
  }

  public static void drawToolbarDecoratorBackground(Graphics g2, int width, int height) {
    final Graphics2D g = (Graphics2D)g2;
    final int h1 = height / 2;
    g.setPaint(UIUtil.getGradientPaint(0,0, Gray._247, 0, h1, Gray._240));
    g.fillRect(0, 0, width, h1);
    g.setPaint(UIUtil.getGradientPaint(0,h1, Gray._229, 0, height, Gray._234));
    g.fillRect(0, h1, width, height);
  }

  public static Color getFocusRingColor() {
    final Object o = UIManager.get("Focus.color");
    if (o instanceof Color) {
      return (Color)o;
    }

    //noinspection UseJBColor
    return new Color(64, 113, 167);
  }

  public static void paintComboboxFocusRing(@NotNull final Graphics2D g2d, @NotNull final Rectangle bounds) {
    final Color color = getFocusRingColor();
    final Color[] colors = new Color[]{
      ColorUtil.toAlpha(color, 180),
      ColorUtil.toAlpha(color, 130),
      ColorUtil.toAlpha(color, 80),
      ColorUtil.toAlpha(color, 80)
    };

    final Object oldAntialiasingValue = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Object oldStrokeControlValue = g2d.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL);

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
                         USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE);

    int _y = MAC_COMBO_BORDER_V_OFFSET;

    final GeneralPath path1 = new GeneralPath();
    path1.moveTo(2, _y + 4);
    path1.quadTo(2, +_y + 2, 4, _y + 2);
    path1.lineTo(bounds.width - 7, _y + 2);
    path1.quadTo(bounds.width - 5, _y + 3, bounds.width - 4, _y + 5);
    path1.lineTo(bounds.width - 4, bounds.height - 7 + _y);
    path1.quadTo(bounds.width - 5, bounds.height - 5 + _y, bounds.width - 7, bounds.height - 4 + _y);
    path1.lineTo(4, bounds.height - 4 + _y);
    path1.quadTo(2, bounds.height - 4 + _y, 2, bounds.height - 6 + _y);
    path1.closePath();

    g2d.setColor(colors[0]);
    g2d.draw(path1);

    final GeneralPath path2 = new GeneralPath();
    path2.moveTo(1, 5 + _y);
    path2.quadTo(1, 1 + _y, 5, 1 + _y);
    path2.lineTo(bounds.width - 8, 1 + _y);
    path2.quadTo(bounds.width - 4, 2 + _y, bounds.width - 3, 6 + _y);
    path2.lineTo(bounds.width - 3, bounds.height - 7 + _y);
    path2.quadTo(bounds.width - 4, bounds.height - 4 + _y, bounds.width - 8, bounds.height - 3 + _y);
    path2.lineTo(4, bounds.height - 3 + _y);
    path2.quadTo(1, bounds.height - 3 + _y, 1, bounds.height - 6 + _y);
    path2.closePath();

    g2d.setColor(colors[1]);
    g2d.draw(path2);

    final GeneralPath path3 = new GeneralPath();
    path3.moveTo(0, 4 + _y);
    path3.quadTo(0, _y, 7, _y);
    path3.lineTo(bounds.width - 9, _y);
    path3.quadTo(bounds.width - 2, 1 + _y, bounds.width - 2, 7 + _y);
    path3.lineTo(bounds.width - 2, bounds.height - 8 + _y);
    path3.quadTo(bounds.width - 3, bounds.height - 1 + _y, bounds.width - 12, bounds.height - 2 + _y);
    path3.lineTo(7, bounds.height - 2 + _y);
    path3.quadTo(0, bounds.height - 1 + _y, 0, bounds.height - 7 + _y);
    path3.closePath();

    g2d.setColor(colors[2]);
    g2d.draw(path3);

    // restore rendering hints
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAntialiasingValue);
    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, oldStrokeControlValue);
  }

  public static void drawComboboxFocusRing(@NotNull final JComboBox combobox, @NotNull final Graphics g) {
    if (SystemInfo.isMac && combobox.isEnabled() && combobox.isEditable() && UIUtil.isUnderAquaLookAndFeel()) {
      final Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
      if (focusOwner != null) {
        final Container ancestor = SwingUtilities.getAncestorOfClass(JComboBox.class, focusOwner);
        if (ancestor == combobox) {
          paintComboboxFocusRing((Graphics2D)g, combobox.getBounds());
        }
      }
    }
  }

  @Deprecated
  public static void doNotFillBackground(@NotNull final JTree tree, @NotNull final DefaultTreeCellRenderer renderer) {
    if (WideSelectionTreeUI.isWideSelection(tree)) {
        renderer.setOpaque(false);
        try {
          final Field fillBackground = DefaultTreeCellRenderer.class.getDeclaredField("fillBackground");
          fillBackground.setAccessible(true);
          fillBackground.set(renderer, false);
        }
        catch (Exception e) {
          // nothing
        }
    }
  }

  public static Cursor getInvertedTextCursor() {
    if (INVERTED_TEXT_CURSOR == null) {
      final Toolkit toolkit = Toolkit.getDefaultToolkit();
      Image cursorImage = toolkit.getImage(MacUIUtil.class.getClassLoader().getResource("/mac/text.png")); // will also load text@2x.png
      INVERTED_TEXT_CURSOR = toolkit.createCustomCursor(cursorImage, new Point(15, 13), "InvertedTextCursor");
    }
    return INVERTED_TEXT_CURSOR;
  }
}


text:
using System;
using System.Collections.Generic;
using OpenCvSharp.Internal;
using OpenCvSharp.Internal.Vectors;

namespace OpenCvSharp.Face;

/// <inheritdoc />
/// <summary>
///
/// </summary>
// ReSharper disable once InconsistentNaming
public sealed class FacemarkLBF : Facemark
{
    private Ptr? ptrObj;

    /// <summary>
    ///
    /// </summary>
    private FacemarkLBF()
    {
        ptrObj = null;
        ptr = IntPtr.Zero;
    }

    /// <summary>
    /// Releases managed resources
    /// </summary>
    protected override void DisposeManaged()
    {
        ptrObj?.Dispose();
        ptrObj = null;
        base.DisposeManaged();
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="parameters"></param>
    /// <returns></returns>
    public static FacemarkLBF Create(Params? parameters = null)
    {
        NativeMethods.HandleException(
            NativeMethods.face_FacemarkLBF_create(parameters?.CvPtr ?? IntPtr.Zero, out var p));
        if (p == IntPtr.Zero)
            throw new OpenCvSharpException($"Invalid cv::Ptr<{nameof(FacemarkLBF)}> pointer");
        var ptrObj = new Ptr(p);
        var detector = new FacemarkLBF
        {
            ptrObj = ptrObj,
            ptr = ptrObj.Get()
        };
        return detector;
    }

#pragma warning disable CA1034
    /// <inheritdoc />
    /// <summary>
    /// </summary>
    public sealed class Params : DisposableCvObject
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public Params()
        {
            NativeMethods.HandleException(
                NativeMethods.face_FacemarkLBF_Params_new(out ptr));
            if (ptr == IntPtr.Zero)
                throw new OpenCvSharpException($"Invalid {GetType().Name} pointer");
        }

        /// <summary>
        /// Releases managed resources
        /// </summary>
        protected override void DisposeUnmanaged()
        {
            if (ptr != IntPtr.Zero)
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_delete(ptr));
            base.DisposeUnmanaged();
        }

        /// <summary>
        /// offset for the loaded face landmark points
        /// </summary>
        public double ShapeOffset
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_shape_offset_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_shape_offset_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// filename of the face detector model
        /// </summary>
        public string CascadeFace
        {
            get
            {
                using var s = new StdString();
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_cascade_face_get(ptr, s.CvPtr));
                GC.KeepAlive(this);
                return s.ToString();
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException(nameof(value));
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_cascade_face_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// show the training print-out
        /// </summary>
        public bool Verbose
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_verbose_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret != 0;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_verbose_set(ptr, value ? 1 : 0));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// number of landmark points
        /// </summary>
        public int NLandmarks
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_n_landmarks_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_n_landmarks_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// multiplier for augment the training data
        /// </summary>
        public int InitShapeN
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_initShape_n_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_initShape_n_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// number of refinement stages
        /// </summary>
        public int StagesN
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_stages_n_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_stages_n_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// number of tree in the model for each landmark point refinement
        /// </summary>
        public int TreeN
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_tree_n_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_tree_n_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// the depth of decision tree, defines the size of feature
        /// </summary>
        public int TreeDepth
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_tree_depth_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_tree_depth_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// overlap ratio for training the LBF feature
        /// </summary>
        public double BaggingOverlap
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_bagging_overlap_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_bagging_overlap_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// filename where the trained model will be saved
        /// </summary>
        public string ModelFilename
        {
            get
            {
                using var s = new StdString();
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_model_filename_get(ptr, s.CvPtr));
                GC.KeepAlive(this);
                return s.ToString();
            }
            set
            {
                if (value == null)
                    throw new ArgumentNullException(nameof(value));
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_model_filename_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// flag to save the trained model or not
        /// </summary>
        public bool SaveModel
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_save_model_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret != 0;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_save_model_set(ptr, value ? 1 : 0));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// seed for shuffling the training data
        /// </summary>
        public uint Seed
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_seed_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_seed_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        ///
        /// </summary>
#if NET40
            public int[] FeatsM
#else
        public IReadOnlyList<int> FeatsM
#endif
        {
            get
            {
                using var vec = new VectorOfInt32();
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_feats_m_get(ptr, vec.CvPtr));
                GC.KeepAlive(this);
                return vec.ToArray();
            }
            set
            {
                using var vec = new VectorOfInt32(value);
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_feats_m_set(ptr, vec.CvPtr));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        ///
        /// </summary>
#if NET40
            public double[] RadiusM
#else
        public IReadOnlyList<double> RadiusM
#endif
        {
            get
            {
                using var vec = new VectorOfDouble();
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_radius_m_get(ptr, vec.CvPtr));
                GC.KeepAlive(this);
                return vec.ToArray();
            }
            set
            {
                using var vec = new VectorOfDouble(value);
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_radius_m_set(ptr, vec.CvPtr));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// index of facemark points on pupils of left and right eye
        /// </summary>
#if NET40
            public int[] Pupils0
#else
        public IReadOnlyList<int> Pupils0
#endif
        {
            get
            {
                using var vec = new VectorOfInt32();
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_pupils0_get(ptr, vec.CvPtr));
                GC.KeepAlive(this);
                return vec.ToArray();
            }
            set
            {
                using var vec = new VectorOfInt32(value);
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_pupils0_set(ptr, vec.CvPtr));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        /// index of facemark points on pupils of left and right eye
        /// </summary>
#if NET40
            public int[] Pupils1
#else
        public IReadOnlyList<int> Pupils1
#endif
        {
            get
            {
                using var vec = new VectorOfInt32();
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_pupils1_get(ptr, vec.CvPtr));
                GC.KeepAlive(this);
                return vec.ToArray();
            }
            set
            {
                using var vec = new VectorOfInt32(value);
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_pupils1_set(ptr, vec.CvPtr));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        ///
        /// </summary>
        // ReSharper disable once InconsistentNaming
        public Rect DetectROI
        {
            get
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_detectROI_get(ptr, out var ret));
                GC.KeepAlive(this);
                return ret;
            }
            set
            {
                NativeMethods.HandleException(
                    NativeMethods.face_FacemarkLBF_Params_detectROI_set(ptr, value));
                GC.KeepAlive(this);
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="fn"></param>
        public void Read(FileNode fn)
        {
            if (fn == null)
                throw new ArgumentNullException(nameof(fn));
            NativeMethods.HandleException(
                NativeMethods.face_FacemarkLBF_Params_write(ptr, fn.CvPtr));
            GC.KeepAlive(this);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="fs"></param>
        public void Write(FileStorage fs)
        {
            if (fs == null)
                throw new ArgumentNullException(nameof(fs));
            NativeMethods.HandleException(
                NativeMethods.face_FacemarkLBF_Params_write(ptr, fs.CvPtr));
            GC.KeepAlive(this);
        }
    }

    internal class Ptr : OpenCvSharp.Ptr
    {
        public Ptr(IntPtr ptr) : base(ptr)
        {
        }

        public override IntPtr Get()
        {
            NativeMethods.HandleException(
                NativeMethods.face_Ptr_FacemarkLBF_get(ptr, out var ret));
            GC.KeepAlive(this);
            return ret;
        }

        protected override void DisposeUnmanaged()
        {
            NativeMethods.HandleException(
                NativeMethods.face_Ptr_FacemarkLBF_delete(ptr));
            base.DisposeUnmanaged();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'test/test_helper'

class ModelSample
  extend Memorize::Keys
end

class MemorizeController < ActionController::Base

  memorize_action :index, :cache_path => lambda { |c| MockSupport.path }
  memorize_action :index2, :key_builder => ModelSample
  memorize_action :index3, :key_builder => ModelSample, :params => [:format]
  memorize_action :show, :key_builder => ModelSample, :key_param => :id, :params => [:format]

  def index
    @cache_this = MockTime.now.to_f.to_s
    render :text => @cache_this
  end

  def index2
    @cache_this = MockTime.now.to_f.to_s
    render :text => @cache_this
  end

  def index3
    @cache_this = "#{MockTime.now.to_f.to_s} format: #{params[:format]}"
    render :text => @cache_this
  end

  def show
    @cache_this = "#{MockTime.now.to_f.to_s} id: #{params[:id]} format: #{params[:format]}"
    render :text => @cache_this
  end

end

module ActionAssertions

  def test_action_with_cache_path
    Memorize.cache_store.clear
    MockSupport.path = "index"
    get :index
    assert_body_is_cached :cache_key => "index", :action_name => lambda { get :index }
  end

  def test_action_with_key_builder_only
    Memorize.cache_store.clear
    get :index2
    assert_body_is_cached :cache_key => "ModelSample/index2", :action_name => lambda { get :index2 }
  end

  def test_action_with_key_builder_and_params
    Memorize.cache_store.clear
    get :index3
    assert_body_is_cached :cache_key => "ModelSample/index3", :action_name => lambda { get :index3 }

    get :index3, :format => :rss
    assert_body_is_cached :cache_key => "ModelSample/index3/rss", :action_name => lambda { get :index3, :format => :rss }

    assert_equal ["ModelSample/index3", "ModelSample/index3/rss"], ModelSample.cache_entries(:index3)
  end

  def test_action_with_key_builder_and_key_param
    Memorize.cache_store.clear
    #simulating some previous access
    get :index
    get :index3
    get :index3, :format => :rss

    get :show, :id => 123
    assert_body_is_cached :cache_key => "ModelSample/show/123", :action_name => lambda { get :show, :id => 123 }

    get :show, :id => 123, :format => :xml
    assert_body_is_cached :cache_key => "ModelSample/show/123/xml", :action_name => lambda { get :show, :id => 123, :format => :xml }

    assert_equal ["ModelSample/show/123", "ModelSample/show/123/xml"], ModelSample.cache_entries(:show, :key => 123)
  end

  private

  def assert_body_is_cached(options)
    cache_key = options.delete(:cache_key)

    cached_time = assigns(:cache_this)
    assert_equal cached_time, @response.body
    assert Memorize.cache_store.exist?(cache_key)
    reset!

    options.delete(:action_name).call
    assert_equal cached_time, @response.body
  end

  def reset!
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    @controller = MemorizeController.new
  end

end

#test with Rails default cache store
class MemoryActionTest < ActionController::TestCase
  def setup
    Memorize.cache_store = ActiveSupport::Cache.lookup_store(:memory_store)
    reset!
  end
  include ActionAssertions
end

#test with Memcached cache store
class MemcachedActionTest < ActionController::TestCase
  def setup
    raise "Memcached should be started to test !" if `ps aux | grep memcached | grep -v grep`.empty?
    Memorize.cache_store = ActiveSupport::Cache.lookup_store(:mem_cache_store, '127.0.0.1:11211')
    reset!
  end
  include ActionAssertions
end


text:
package com.m1.mimeui.api.analyzer;

import com.m1.mimeui.api.MimeUIException;
import com.m1.mimeui.api.mimedom.AnalyzedMessage;

public interface AnalysisHandler<T>
{
    public T handle (final AnalyzedMessage analyzedMessage)
            throws MimeUIException;
}


text:
Run a test with logtostderr and mtailDebug up to 3, and parser_test_debug enabled to see any AST results.

```
go test -run TestParserRoundTrip/decrement_counter --logtostderr --mtailDebug=3 --parser_test_debug
```

`mtailDebug` at 2 dumps the parser states being traversed, and 3 includes the lexer token stream as well.

## Improving parser syntax error messages

You can use this to improve error messages in the `%error` section of [`parser.y`](../internal/vm/parser/parser.y), if you compare the "error recovery pops" messages with the state machine in the generated [`y.output`](../internal/vm/parser/y.output).

```
go generate && go test -run TestParseInvalidPrograms/statement_with_no_effect --logtostderr --mtailDebug=3  --parser_test_debug
```

error log from test:
```
...
state-14 saw LSQUARE
error recovery pops state 14
error recovery pops state 102
error recovery pops state 46
error recovery pops state 14
error recovery pops state 2
error recovery pops state 0
```

This log says the lexer sent a LSQUARE token, and the parser was in state 14 when it saw it.  The snippet below from `y.output` indicates state 14 is never expecting a LSQUARE, and the following lnies in the log above show the state stack being popped -- 0, 2, 14, 49, 102, 14.

Walking backwards from state 0 (`$start`), we can get a list of nonterminal names to put in the state machine match expression used in the `%error` directive, and fill in the gaps with our knowledge of the intermediate states in our parose tree.

`y.output`:
```
state 14
	conditional_statement:  logical_expr.compound_statement ELSE compound_statement
	conditional_statement:  logical_expr.compound_statement
	logical_expr:  logical_expr.logical_op opt_nl bitwise_expr

	AND  shift 47
	OR  shift 48
	MATCH  shift 49
	NOT_MATCH  shift 50
	LCURLY  shift 46
	.  error

	compound_statement  goto 44
	logical_op  goto 45
```

State 14 to state 46 shifts a LCURLY operator, follow state 46 and we will find ourselves in `compound_statement`.

Add to `parser.y` the names of the states that ended up at the unexpected token, followed by the error message:
```
%error stmt_list stmt conditional_statement logical_expr compound_statement conditional_statement logical_expr LSQUARE : "unexpected indexing of an expression"
```

and instead of "syntax error", the parser now emits "unexpected indexing of an expression".

## Fuzzer crashes

Build the fuzzer locally with clang and libfuzzer:

```
make vm-fuzzer fuzz CXX=clang CXXFLAGS=-fsanitize=fuzzer,address LIB_FUZZING_ENGINE=
```

Then we can run the fuzzer with our example crash; make sure it has no weird characters because the upstream fuzz executor doesn't shell-escape arguments.

```
./vm-fuzzer crash.mtail
```

If the crash is big, we can try to minimise it:

```
make fuzz-min CRASH=crash.mtail
```

Sometimes the minimiser will hit a local minima, but still look big; for example it doesn't know how to shrink variable names.

We can reformat the crash with [`cmd/mfmt`](../cmd/mfmt/main.go):

```
make mfmt
./mfmt --prog crash.mtail --write
```

so it's easier to read -- it'll be bigger cos of the whitespace and the minimiser should shrink it back to original size if everything is working well.

The formatted mtail program should help make it obvious what's happening and let you manually attempt to rename or remove parts of the program yourself -- perhaps a whole variable declaration and usage doesn't need to exist, but the minimiser will take a long time to figure that out.

Once we have the smallest program we can add it to the crash corpus in [`internal/vm/fuzz/`](../internal/vm/fuzz/) and running `make fuzz` should run and fail on it straight away.

Or, variants of the program can be added to the various `*Invalid` tests in parts of the `vm` module, e.g. [`parser_test.go`](../internal/vm/parser/parser_test.go) or [`checker_test.go`](../internal/vm/checker/checker_test.go) depending on where in the compiler the defect is occuring.

If the crash is in `vm.go` then we can dump the program to see what AST and types, and bytecode it generates.

```
make mtail
./mtail --logtostderr --dump_ast_types --dump_bytecode --mtailDebug=3 --compile_only --progs crash.mtail
```

### Fuzzer crashes, part 2

Run the fuzz-repro target with the CRASH variable set, it'll do all of the above:

```
make fuzz-repro CXX=clang CXXFLAGS=-fsanitize=fuzzer,address LIB_FUZZING_ENGINE= CRASH=bug/20720.mtail
```


text:
package gw.plugin.ij.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention( RetentionPolicy.RUNTIME )
public @interface JavaIntAnnotation {
  int value();
}


text:
function [a, sheets]=xlsfinfo('file.xls')
% function [a, sheets]=xlsfinfo('filename.xls')

for ind=1:length(sheets)
    disp('---');
    disp(sheets(ind));
    [data,header]=xlsread('file.xls',ind)
end;


text:
Celery is an asynchronous task queue based on distributed message passing. It is used to create execution units (i.e. tasks) which are then executed on one or more worker nodes, either synchronously or asynchronously.

Celery is implemented in Python.

Since Celery is based on message passing, it requires some middleware (to handle translation of the message between sender and receiver) called a _message broker_. RabbitMQ is a message broker often used in conjunction with Celery.

This example will show you how to use Kubernetes to set up a very basic distributed task queue using Celery as the task queue and RabbitMQ as the message broker. It will also show you how to set up a Flower-based front end to monitor the tasks.

## Goal

At the end of the example, we will have:

* Three pods:
    * A Celery task queue
    * A RabbitMQ message broker
    * A Flower frontend
* A service that provides access to the message broker
* A basic celery task that can be passed to the worker node

## Prerequisites

You should already have turned up a Kubernetes cluster. To get the most of this example, ensure that Kubernetes will create more than one minion (e.g. by setting your `NUM_MINIONS` environment variable to 2 or more).

## Step 1: Start the RabbitMQ service

The Celery task queue will need to communicate with the RabbitMQ broker. RabbitMQ will eventually appear on a separate pod, but since pods are ephemeral we need a service that can transparently route requests to RabbitMQ.

Use the file [`examples/celery-rabbitmq/rabbitmq-service.yaml`](rabbitmq-service.yaml):

```yaml
apiVersion: v1beta3
kind: Service
metadata:
  labels:
    name: rabbitmq
  name: rabbitmq-service
spec:
  ports:
  - port: 5672
    protocol: TCP
    targetPort: 5672
  selector:
    app: taskQueue
    component: rabbitmq
```

To start the service, run:

```shell
$ kubectl create -f examples/celery-rabbitmq/rabbitmq-service.yaml
```

**NOTE**: If you're running Kubernetes from source, you can use `cluster/kubectl.sh` instead of `kubectl`.

This service allows other pods to connect to the rabbitmq. To them, it will be seen as available on port 5672, although the service is routing the traffic to the container (also via port 5672).

## Step 2: Fire up RabbitMQ

A RabbitMQ broker can be turned up using the file [`examples/celery-rabbitmq/rabbitmq-controller.yaml`](rabbitmq-controller.yaml):

```yaml
apiVersion: v1beta3
kind: ReplicationController
metadata:
  labels:
    name: rabbitmq
  name: rabbitmq-controller
spec:
  replicas: 1
  selector:
    component: rabbitmq
  template:
    metadata:
      labels:
        app: taskQueue
        component: rabbitmq
    spec:
      containers:
      - image: rabbitmq
        name: rabbitmq
        ports:
        - containerPort: 5672
          protocol: TCP
        resources:
          limits:
            cpu: 100m
```

Running `$ kubectl create -f examples/celery-rabbitmq/rabbitmq-controller.yaml` brings up a replication controller that ensures one pod exists which is running a RabbitMQ instance.

Note that bringing up the pod includes pulling down a docker image, which may take a few moments. This applies to all other pods in this example.

## Step 3: Fire up Celery

Bringing up the celery worker is done by running `$ kubectl create -f examples/celery-rabbitmq/celery-controller.yaml`, which contains this:

```yaml
apiVersion: v1beta3
kind: ReplicationController
metadata:
  labels:
    name: celery
  name: celery-controller
spec:
  replicas: 1
  selector:
    component: celery
  template:
    metadata:
      labels:
        app: taskQueue
        component: celery
    spec:
      containers:
      - image: endocode/celery-app-add
        name: celery
        ports:
        - containerPort: 5672
          protocol: TCP
        resources:
          limits:
            cpu: 100m
```

There are several things to point out here...

Like the RabbitMQ controller, this controller ensures that there is always a pod is running a Celery worker instance. The celery-app-add Docker image is an extension of the standard Celery image. This is the Dockerfile:

```
FROM library/celery

ADD celery_conf.py /data/celery_conf.py
ADD run_tasks.py /data/run_tasks.py
ADD run.sh /usr/local/bin/run.sh

ENV C_FORCE_ROOT 1

CMD ["/bin/bash", "/usr/local/bin/run.sh"]
```

The celery\_conf.py contains the defintion of a simple Celery task that adds two numbers. This last line starts the Celery worker.

**NOTE:** `ENV C_FORCE_ROOT 1` forces Celery to be run as the root user, which is *not* recommended in production!

The celery\_conf.py file contains the following:

```python
import os

from celery import Celery

# Get Kubernetes-provided address of the broker service
broker_service_host = os.environ.get('RABBITMQ_SERVICE_SERVICE_HOST')

app = Celery('tasks', broker='amqp://guest@%s//' % broker_service_host, backend='amqp')

@app.task
def add(x, y):
    return x + y
```

Assuming you're already familiar with how Celery works, everything here should be familiar, except perhaps the part `os.environ.get('RABBITMQ_SERVICE_SERVICE_HOST')`. This environment variable contains the IP address of the RabbitMQ service we created in step 1. Kubernetes automatically provides this environment variable to all containers which have the same app label as that defined in the RabbitMQ service (in this case "taskQueue"). In the Python code above, this has the effect of automatically filling in the broker address when the pod is started.

The second python script (run\_tasks.py) periodically executes the `add()` task every 5 seconds with a couple of random numbers.

The question now is, how do you see what's going on?

## Step 4: Put a frontend in place

Flower is a web-based tool for monitoring and administrating Celery clusters. By connecting to the node that contains Celery, you can see the behaviour of all the workers and their tasks in real-time.

To bring up the frontend, run this command `$ kubectl create -f examples/celery-rabbitmq/flower-controller.yaml`. This controller is defined as so:

```yaml
apiVersion: v1beta3
kind: ReplicationController
metadata:
  labels:
    name: flower
  name: flower-controller
spec:
  replicas: 1
  selector:
    component: flower
  template:
    metadata:
      labels:
        app: taskQueue
        component: flower
    spec:
      containers:
      - image: endocode/flower
        name: flower
        ports:
        - containerPort: 5555
          hostPort: 5555
          protocol: TCP
        resources:
          limits:
            cpu: 100m
```

This will bring up a new pod with Flower installed and port 5555 (Flower's default port) exposed. This image uses the following command to start Flower:

```sh
flower --broker=amqp://guest:guest@${RABBITMQ_SERVICE_SERVICE_HOST:localhost}:5672//
```

Again, it uses the Kubernetes-provided environment variable to obtain the address of the RabbitMQ service.

Once all pods are up and running, running `kubectl get pods` will display something like this:

```
POD                         IP                  CONTAINER(S)        IMAGE(S)                           HOST                    LABELS                                                STATUS
celery-controller-h3x9k     10.246.1.11         celery              endocode/celery-app-add            10.245.1.3/10.245.1.3   app=taskQueue,name=celery                             Running
flower-controller-cegta     10.246.2.17         flower              endocode/flower                    10.245.1.4/10.245.1.4   app=taskQueue,name=flower                             Running
kube-dns-fplln              10.246.1.3          etcd                quay.io/coreos/etcd:latest         10.245.1.3/10.245.1.3   k8s-app=kube-dns,kubernetes.io/cluster-service=true   Running
                                                kube2sky            kubernetes/kube2sky:1.0
                                                skydns              kubernetes/skydns:2014-12-23-001
rabbitmq-controller-pjzb3   10.246.2.16         rabbitmq            library/rabbitmq                   10.245.1.4/10.245.1.4   app=taskQueue,name=rabbitmq                           Running

```

Now you know on which host Flower is running (in this case, 10.245.1.4), you can open your browser and enter the address (e.g. `http://10.245.1.4:5555`. If you click on the tab called "Tasks", you should see an ever-growing list of tasks called "celery_conf.add" which the run\_tasks.py script is dispatching.

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/celery-rabbitmq/README.md?pixel)]()


text:
{{foto.titulo}}

{{mensagem}}

    <form [formGroup]="meuForm" class="row" (submit)="cadastrar($event)">

                Título
                <input
                    name="titulo"
                    [(ngModel)]="foto.titulo"
                    formControlName="titulo"
                    class="form-control"
                    autocomplete="off">

                        Título obrigatório

                        O título deve ter no mínimo 4 caracteres

                URL
                <input
                    name="url"
                    [(ngModel)]="foto.url"
                    formControlName="url"
                    class="form-control"
                    autocomplete="off">

                Descrição
                <textarea
                    name="descricao"
                    [(ngModel)]="foto.descricao"
                    formControlName="descricao"
                    class="form-control"
                    autocomplete="off">
                </textarea>

            <botao
                nome="Salvar"
                tipo="submit"
                [desabilitado]="meuForm.invalid">
            </botao>

             Voltar

            <foto url="{{foto.url}}" titulo="{{foto.titulo}}"></foto>

    </form>


text:
package org.apache.flink.table.planner.runtime.batch.sql

import org.apache.flink.api.common.typeinfo.BasicTypeInfo.{INT_TYPE_INFO, LONG_TYPE_INFO, STRING_TYPE_INFO}
import org.apache.flink.api.java.typeutils.RowTypeInfo
import org.apache.flink.streaming.runtime.io.MultipleInputSelectionHandler
import org.apache.flink.table.api.config.{ExecutionConfigOptions, OptimizerConfigOptions}
import org.apache.flink.table.planner.runtime.utils.BatchTestBase
import org.apache.flink.types.Row

import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
import org.junit.{Before, Test}

import scala.collection.JavaConversions._
import scala.util.Random

/**
 * IT cases for multiple input.
 *
 * <p>This test class works by comparing the results with and without multiple input.
 * The following IT cases are picked from
 * [[org.apache.flink.table.planner.plan.batch.sql.MultipleInputCreationTest]].
 */
@RunWith(classOf[Parameterized])
class MultipleInputITCase(shuffleMode: String) extends BatchTestBase {

  @Before
  override def before(): Unit = {
    super.before()

    registerCollection(
      "x",
      MultipleInputITCase.dataX,
      MultipleInputITCase.rowType,
      "a, b, c, nx",
      MultipleInputITCase.nullables)
    registerCollection(
      "y",
      MultipleInputITCase.dataY,
      MultipleInputITCase.rowType,
      "d, e, f, ny",
      MultipleInputITCase.nullables)
    registerCollection(
      "z",
      MultipleInputITCase.dataZ,
      MultipleInputITCase.rowType,
      "g, h, i, nz",
      MultipleInputITCase.nullables)
    registerCollection(
      "t",
      MultipleInputITCase.dataT,
      MultipleInputITCase.rowType,
      "a, b, c, nt",
      MultipleInputITCase.nullables)

    tEnv.getConfig.getConfiguration.setString(
      ExecutionConfigOptions.TABLE_EXEC_SHUFFLE_MODE, shuffleMode)
  }

  @Test
  def testBasicMultipleInput(): Unit = {
    checkMultipleInputResult(
      """
        |SELECT * FROM
        |  (SELECT a FROM x INNER JOIN y ON x.a = y.d) T1
        |  INNER JOIN
        |  (SELECT d FROM y INNER JOIN t ON y.d = t.a) T2
        |  ON T1.a = T2.d
        |""".stripMargin)
  }

  @Test
  def testManyMultipleInputs(): Unit = {
    checkMultipleInputResult(
      """
        |WITH
        |  T1 AS (
        |    SELECT a, ny, nz FROM x
        |      LEFT JOIN y ON x.a = y.ny
        |      LEFT JOIN z ON x.a = z.nz),
        |  T2 AS (
        |    SELECT T1.a AS a, t.b AS b, d, T1.ny AS ny, nz FROM T1
        |      LEFT JOIN t ON T1.a = t.a
        |      INNER JOIN y ON T1.a = y.d),
        |  T3 AS (
        |    SELECT T1.a AS a, t.b AS b, d, T1.ny AS ny, nz FROM T1
        |      LEFT JOIN y ON T1.a = y.d
        |      INNER JOIN t ON T1.a = t.a),
        |  T4 AS (SELECT b, SUM(d) AS sd, SUM(ny) AS sy, SUM(nz) AS sz FROM T2 GROUP BY b),
        |  T5 AS (SELECT b, SUM(d) AS sd, SUM(ny) AS sy, SUM(nz) AS sz FROM T3 GROUP BY b)
        |SELECT * FROM
        |  (SELECT t.b, sd, sy, sz FROM T4 LEFT JOIN t ON T4.b = t.b)
        |  UNION ALL
        |  (SELECT y.e, sd, sy, sz FROM T5 LEFT JOIN y ON T5.b = y.e)
        |""".stripMargin)
  }

  @Test
  def testJoinWithAggAsProbe(): Unit = {
    checkMultipleInputResult(
      """
        |WITH T AS (SELECT a, d FROM x INNER JOIN y ON x.a = y.d)
        |SELECT * FROM
        |  (SELECT a, COUNT(*) AS cnt FROM T GROUP BY a) T1
        |  LEFT JOIN
        |  (SELECT d, SUM(a) AS sm FROM T GROUP BY d) T2
        |  ON T1.a = T2.d
        |""".stripMargin
    )
  }

  @Test
  def testNoPriorityConstraint(): Unit = {
    checkMultipleInputResult(
      """
        |SELECT * FROM x
        |  INNER JOIN y ON x.a = y.d
        |  INNER JOIN t ON x.a = t.a
        |""".stripMargin
    )
  }

  @Test
  def testRelatedInputs(): Unit = {
    checkMultipleInputResult(
      """
        |WITH
        |  T1 AS (SELECT x.a AS a, y.d AS b FROM y LEFT JOIN x ON y.d = x.a),
        |  T2 AS (
        |    SELECT a, b FROM
        |      (SELECT a, b FROM T1)
        |      UNION ALL
        |      (SELECT x.a AS a, x.b AS b FROM x))
        |SELECT * FROM T2 LEFT JOIN t ON T2.a = t.a
        |""".stripMargin
    )
  }

  @Test
  def testRelatedInputsWithAgg(): Unit = {
    checkMultipleInputResult(
      """
        |WITH
        |  T1 AS (SELECT x.a AS a, y.d AS b FROM y LEFT JOIN x ON y.d = x.a),
        |  T2 AS (
        |    SELECT a, b FROM
        |      (SELECT a, b FROM T1)
        |      UNION ALL
        |      (SELECT COUNT(x.a) AS a, x.b AS b FROM x GROUP BY x.b))
        |SELECT * FROM T2 LEFT JOIN t ON T2.a = t.a
        |""".stripMargin
    )
  }

  @Test
  def testDeadlockCausedByExchangeInAncestor(): Unit = {
    checkMultipleInputResult(
      """
        |WITH T1 AS (
        |  SELECT x1.*, x2.a AS k, (x1.b + x2.b) AS v
        |  FROM x x1 LEFT JOIN x x2 ON x1.a = x2.a WHERE x2.a > 0)
        |SELECT x.a, x.b, T1.* FROM x LEFT JOIN T1 ON x.a = T1.k WHERE x.a > 0 AND T1.v = 0
        |""".stripMargin
    )
  }

  @Test
  def testMaxSupportedInputs(): Unit = {
    val rowType = new RowTypeInfo(INT_TYPE_INFO, STRING_TYPE_INFO)
    val data = Seq(BatchTestBase.row(1, "test"))
    val nullables: Array[Boolean] = Array(true, true)
    registerCollection("left_table", data, rowType, "a, b", nullables)
    registerCollection("right_table", data, rowType, "c, d", nullables)

    val numJoins = MultipleInputSelectionHandler.MAX_SUPPORTED_INPUT_COUNT - 1

    val sql = new StringBuilder("SELECT t0.a, t0.b")
    for (i <- 1 to numJoins) {
      sql.append(s", t$i.c, t$i.d")
    }
    sql.append(" from left_table as t0")
    for (i <- 1 to numJoins) {
      sql.append(s" left join right_table as t$i on t0.a = t$i.c and t$i.c = 1")
    }
    checkMultipleInputResult(sql.toString())
  }

  def checkMultipleInputResult(sql: String): Unit = {
    tEnv.getConfig.getConfiguration.setBoolean(
      OptimizerConfigOptions.TABLE_OPTIMIZER_MULTIPLE_INPUT_ENABLED, false)
    val expected = executeQuery(sql)
    tEnv.getConfig.getConfiguration.setBoolean(
      OptimizerConfigOptions.TABLE_OPTIMIZER_MULTIPLE_INPUT_ENABLED, true)
    checkResult(sql, expected)
  }
}

object MultipleInputITCase {

  @Parameters(name = "shuffleMode: {0}")
  def parameters: Array[String] = Array("ALL_EDGES_BLOCKING", "ALL_EDGES_PIPELINED")

  def generateRandomData(): Seq[Row] = {
    val data = new java.util.ArrayList[Row]()
    val numRows = Random.nextInt(30)
    lazy val strs = Seq("multiple", "input", "itcase")
    for (_ <- 0 until numRows) {
      data.add(BatchTestBase.row(
        Random.nextInt(3),
        Random.nextInt(3).longValue(),
        strs(Random.nextInt(3)),
        Random.nextInt(3)))
    }
    data
  }

  lazy val rowType = new RowTypeInfo(INT_TYPE_INFO, LONG_TYPE_INFO, STRING_TYPE_INFO, INT_TYPE_INFO)
  lazy val nullables: Array[Boolean] = Array(true, true, true, true)

  lazy val dataX: Seq[Row] = generateRandomData()
  lazy val dataY: Seq[Row] = generateRandomData()
  lazy val dataZ: Seq[Row] = generateRandomData()
  lazy val dataT: Seq[Row] = generateRandomData()
}


text:
@class _SZUserSettingsViewController;
@protocol SocializeFullUser;

@protocol _SZUserSettingsViewControllerDelegate <SocializeBaseViewControllerDelegate>

@optional
- (void)profileEditViewController:(_SZUserSettingsViewController*)profileEditViewController didUpdateProfileWithUser:(id<SocializeFullUser>)user;

@end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace StageFSM
{
    public class ChangeSpeedLevel : StageStateMachineBehaviour
    {
        [SerializeField]
        private SpeedChange speedChange;
        [SerializeField]
        private bool changeInTransition;
        [SerializeField]
        private string microgameIndexParam = "MicrogameIndex";

        public enum SpeedChange
        {
            None,
            SpeedUp,
            ResetToRoundStart,
            ResetToStageStart,
            ResetToOne
        }

        public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
        {
            base.OnStateEnter(animator, stateInfo, layerIndex);
            if (changeInTransition)
                ChangeSpeed();
        }

        protected override void OnStateEnterOfficial()
        {
            base.OnStateEnterOfficial();
            if (!changeInTransition)
                ChangeSpeed();
        }

        void ChangeSpeed()
        {
            var speedController = toolbox.GetTool<SpeedController>();
            speedController.Speed = getChangedSpeed(speedController.Speed, speedChange);
        }

        public int getChangedSpeed(int speed, SpeedChange speedChange)
        {
            Stage stage;
            switch (speedChange)
            {
                case (SpeedChange.SpeedUp):
                    return Mathf.Clamp(speed + 1, 1, SpeedController.MaxSpeed);
                case (SpeedChange.ResetToOne):
                    return 1;
                case (SpeedChange.ResetToRoundStart):
                    stage = assetToolbox.GetStage();
                    var microgameIndex = Animator.GetInteger(microgameIndexParam);
                    var round = stage.GetRound(microgameIndex);
                    return stage.GetRoundSpeed(round);
                case (SpeedChange.ResetToStageStart):
                    stage = assetToolbox.GetStage();
                    return stage.getStartSpeed();
                default:
                    return speed;
            }
        }

    }
}


text:
#pragma once

#include "get_session_token/v0.hpp"
#include "get_session_token/v1_3.hpp"

namespace mf {
namespace api {
/** API action path "user" */
namespace user {
/** API action "user/get_session_token" */
namespace get_session_token {

// Default version
using namespace v1_3;  // NOLINT

}  // namespace get_session_token
}  // namespace user
}  // namespace api
}  // namespace mf


text:
if [[ "$1" = -* ]]
then
	echo "Usage: $0 [ path/to/hadoop/client/jars ]"
  echo "  This prepares the build environment on mstress build host"
  echo "  Default path is '/usr/lib/hadoop/client/'"
	exit
fi

JARS_SOURCE=${1:-"/usr/lib/hadoop/client/"}

DIR="$( cd "$( dirname "$0" )" && pwd )"
JARS_TARGET=${DIR}/mstress_hdfs_client_jars

if [ ! -d "$JARS_SOURCE" ] || [ -z "$(ls -A "$JARS_SOURCE"/*.jar)" ]; then
  echo ""$JARS_SOURCE" is not a directory or does not have the jars."
  exit 1
fi

if [ -d "$JARS_TARGET" ]; then
  if [ "$(ls -A "$JARS_TARGET"/*.jar 2> /dev/null)" ]; then
    echo ""$JARS_TARGET" already has the jars. Nothing to do."
    exit 0
  fi
fi

mkdir -p "$JARS_TARGET"
cp $JARS_SOURCE/*.jar "$JARS_TARGET"

if [ $? -ne 0 ]
then
  echo "Failed to copy jars."
  exit 1
fi

echo "Hadoop client jars from $JARS_SOURCE copied to $JARS_TARGET."

exit 0


text:
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using SDKTemplate;
using System;
using Windows.Security.ExchangeActiveSyncProvisioning;

namespace EAS
{
    public sealed partial class Scenario3_ApplyEASPolicy : Page
    {
        MainPage rootPage = MainPage.Current;

        public Scenario3_ApplyEASPolicy()
        {
            this.InitializeComponent();
        }
        private async void Launch_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                EasClientSecurityPolicy RequestedPolicy = new EasClientSecurityPolicy();

                if (RequireEncryptionValue == null)
                {
                    RequestedPolicy.RequireEncryption = false;
                }
                else
                {
                    if (RequireEncryptionValue.SelectedIndex == 1)
                    {
                        RequestedPolicy.RequireEncryption = true;
                    }
                    else
                    {
                        RequestedPolicy.RequireEncryption = false;
                    }
                }

                if (MinPasswordLengthValue == null || MinPasswordLengthValue.Text.Length == 0)
                {
                    RequestedPolicy.MinPasswordLength = 0;
                }
                else
                {
                    RequestedPolicy.MinPasswordLength = Convert.ToByte(MinPasswordLengthValue.Text);
                }

                if (DisallowConvenienceLogonValue == null)
                {
                    RequestedPolicy.DisallowConvenienceLogon = false;
                }
                else
                {
                    if (DisallowConvenienceLogonValue.SelectedIndex == 1)
                        RequestedPolicy.DisallowConvenienceLogon = true;
                    else
                        RequestedPolicy.DisallowConvenienceLogon = false;
                }

                if (MinPasswordComplexCharactersValue == null || MinPasswordComplexCharactersValue.Text.Length == 0)
                {
                    RequestedPolicy.MinPasswordComplexCharacters = 0;
                }
                else
                {
                    RequestedPolicy.MinPasswordComplexCharacters = Convert.ToByte(MinPasswordComplexCharactersValue.Text);
                }

                if (PasswordExpirationValue == null || PasswordExpirationValue.Text.Length == 0)
                {
                    RequestedPolicy.PasswordExpiration = TimeSpan.Parse("0");
                }
                else
                {
                    RequestedPolicy.PasswordExpiration = TimeSpan.FromDays(Convert.ToDouble(PasswordExpirationValue.Text));
                }

                if (PasswordHistoryValue == null || PasswordHistoryValue.Text.Length == 0)
                {
                    RequestedPolicy.PasswordHistory = 0;
                }
                else
                {
                    RequestedPolicy.PasswordHistory = Convert.ToByte(PasswordHistoryValue.Text);
                }

                if (MaxPasswordFailedAttemptsValue == null || MaxPasswordFailedAttemptsValue.Text.Length == 0)
                {
                    RequestedPolicy.MaxPasswordFailedAttempts = 0;
                }
                else
                {
                    RequestedPolicy.MaxPasswordFailedAttempts = Convert.ToByte(MaxPasswordFailedAttemptsValue.Text);
                }

                if (MaxInactivityTimeLockValue == null || MaxInactivityTimeLockValue.Text.Length == 0)
                {
                    RequestedPolicy.MaxInactivityTimeLock = TimeSpan.Parse("0");
                }
                else
                {
                    RequestedPolicy.MaxInactivityTimeLock = TimeSpan.FromSeconds(Convert.ToDouble(MaxInactivityTimeLockValue.Text));
                }

                EasComplianceResults ApplyResult = await RequestedPolicy.ApplyAsync();

                RequireEncryptionResult.Text = ApplyResult.RequireEncryptionResult.ToString();
                MinPasswordLengthResult.Text = ApplyResult.MinPasswordLengthResult.ToString();
                DisallowConvenienceLogonResult.Text = ApplyResult.DisallowConvenienceLogonResult.ToString();
                MinPasswordComplexCharactersResult.Text = ApplyResult.MinPasswordComplexCharactersResult.ToString();
                PasswordExpirationResult.Text = ApplyResult.PasswordExpirationResult.ToString();
                PasswordHistoryResult.Text = ApplyResult.PasswordHistoryResult.ToString();
                MaxPasswordFailedAttemptsResult.Text = ApplyResult.MaxPasswordFailedAttemptsResult.ToString();
                MaxInactivityTimeLockResult.Text = ApplyResult.MaxInactivityTimeLockResult.ToString();
            }
            catch (Exception Error)
            {
                rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage);
            }
        }

        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            RequireEncryptionValue.SelectedIndex = 0;
            MinPasswordLengthValue.Text = "";
            DisallowConvenienceLogonValue.SelectedIndex = 0;
            MinPasswordComplexCharactersValue.Text = "";
            PasswordExpirationValue.Text = "";
            PasswordHistoryValue.Text = "";
            MaxPasswordFailedAttemptsValue.Text = "";
            MaxInactivityTimeLockValue.Text = "";
            RequireEncryptionResult.Text = "";
            MinPasswordLengthResult.Text = "";
            DisallowConvenienceLogonResult.Text = "";
            MinPasswordComplexCharactersResult.Text = "";
            PasswordExpirationResult.Text = "";
            PasswordHistoryResult.Text = "";
            MaxPasswordFailedAttemptsResult.Text = "";
            MaxInactivityTimeLockResult.Text = "";
        }
    }
}


text:
var _ = require('lodash');
var helpers = require('../helpers');

function TableBuilder(client, method, tableName, fn) {
  this.client      = client
  this._fn         = fn;
  this._method     = method;
  this._schemaName = undefined;
  this._tableName  = tableName;
  this._statements = [];
  this._single     = {};
}

TableBuilder.prototype.setSchema = function(schemaName) {
  this._schemaName = schemaName;
};

// Convert the current tableBuilder object "toSQL"
// giving us additional methods if we're altering
// rather than creating the table.
TableBuilder.prototype.toSQL = function() {
  if (this._method === 'alter') {
    _.extend(this, AlterMethods);
  }
  this._fn.call(this, this);
  return this.client.tableCompiler(this).toSQL();
};

_.each([

  // Each of the index methods can be called individually, with the
  // column name to be used, e.g. table.unique('column').
  'index', 'primary', 'unique',

  // Key specific
  'dropPrimary', 'dropUnique', 'dropIndex', 'dropForeign'

], function(method) {
  TableBuilder.prototype[method] = function() {
    this._statements.push({
      grouping: 'alterTable',
      method: method,
      args: _.toArray(arguments)
    });
    return this;
  };
});

// Warn if we're not in MySQL, since that's the only time these
// three are supported.
var specialMethods = ['engine', 'charset', 'collate'];
_.each(specialMethods, function(method) {
  TableBuilder.prototype[method] = function(value) {
    if (false) {
      helpers.warn('Knex only supports ' + method + ' statement with mysql.');
    } if (this._method === 'alter') {
      helpers.warn('Knex does not support altering the ' + method + ' outside of the create table, please use knex.raw statement.');
    }
    this._single[method] = value;
  };
});

// Each of the column types that we can add, we create a new ColumnBuilder
// instance and push it onto the statements array.
var columnTypes = [

  // Numeric
  'tinyint',
  'smallint',
  'mediumint',
  'int',
  'bigint',
  'decimal',
  'float',
  'double',
  'real',
  'bit',
  'boolean',
  'serial',

  // Date / Time
  'date',
  'datetime',
  'timestamp',
  'time',
  'year',

  // String
  'char',
  'varchar',
  'tinytext',
  'tinyText',
  'text',
  'mediumtext',
  'mediumText',
  'longtext',
  'longText',
  'binary',
  'varbinary',
  'tinyblob',
  'tinyBlob',
  'mediumblob',
  'mediumBlob',
  'blob',
  'longblob',
  'longBlob',
  'enum',
  'set',

  // Increments, Aliases, and Additional
  'bool',
  'dateTime',
  'increments',
  'bigincrements',
  'bigIncrements',
  'integer',
  'biginteger',
  'bigInteger',
  'string',
  'timestamps',
  'json',
  'uuid',
  'enu',
  'specificType'
];

// For each of the column methods, create a new "ColumnBuilder" interface,
// push it onto the "allStatements" stack, and then return the interface,
// with which we can add indexes, etc.
_.each(columnTypes, function(type) {
  TableBuilder.prototype[type] = function() {
    var args = _.toArray(arguments);

    // The "timestamps" call is really a compound call to set the
    // `created_at` and `updated_at` columns.
    if (type === 'timestamps') {
      if (args[0] === true) {
        this.timestamp('created_at');
        this.timestamp('updated_at');
      } else {
        this.datetime('created_at');
        this.datetime('updated_at');
      }
      return;
    }
    var builder       = this.client.columnBuilder(this, type, args);

    this._statements.push({
      grouping: 'columns',
      builder: builder
    });
    return builder;
  };

});

// Set the comment value for a table, they're only allowed to be called
// once per table.
TableBuilder.prototype.comment = function(value) {
  this._single.comment = value;
};

// Set a foreign key on the table, calling
// `table.foreign('column_name').references('column').on('table').onDelete()...
// Also called from the ColumnBuilder context when chaining.
TableBuilder.prototype.foreign = function(column) {
  var foreignData = {column: column};
  this._statements.push({
    grouping: 'alterTable',
    method: 'foreign',
    args: [foreignData]
  });
  var returnObj = {
    references: function(tableColumn) {
      var pieces;
      if (_.isString(tableColumn)) {
        pieces = tableColumn.split('.');
      }
      if (!pieces || pieces.length === 1) {
        foreignData.references = pieces ? pieces[0] : tableColumn;
        return {
          on: function(tableName) {
            foreignData.inTable = tableName;
            return returnObj;
          },
          inTable: function() {
            return this.on.apply(this, arguments);
          }
        };
      }
      foreignData.inTable = pieces[0];
      foreignData.references = pieces[1];
      return returnObj;
    },
    onUpdate: function(statement) {
      foreignData.onUpdate = statement;
      return returnObj;
    },
    onDelete: function(statement) {
      foreignData.onDelete = statement;
      return returnObj;
    },
    _columnBuilder: function(builder) {
      _.extend(builder, returnObj);
      returnObj = builder;
      return builder;
    }
  };
  return returnObj;
}

var AlterMethods = {

  // Renames the current column `from` the current
  // TODO: this.column(from).rename(to)
  renameColumn: function(from, to) {
    this._statements.push({
      grouping: 'alterTable',
      method: 'renameColumn',
      args: [from, to]
    });
    return this;
  },

  dropTimestamps: function() {
    return this.dropColumns(['created_at', 'updated_at']);
  }

  // TODO: changeType
};

// Drop a column from the current table.
// TODO: Enable this.column(columnName).drop();
AlterMethods.dropColumn =
AlterMethods.dropColumns = function() {
  this._statements.push({
    grouping: 'alterTable',
    method: 'dropColumn',
    args: _.toArray(arguments)
  });
  return this;
};

module.exports = TableBuilder;


text:
load('test/mjsunit/wasm/wasm-module-builder.js');

// Generate a re-exported function that wraps a JavaScript callable, but with a
// function signature that is incompatible (i.e. i64 return type) with JS.
var fun1 = (function GenerateFun1() {
  let builder = new WasmModuleBuilder();
  function fun() { return 0 }
  let fun_index = builder.addImport("m", "fun", kSig_l_v)
  builder.addExport("fun", fun_index);
  let instance = builder.instantiate({ m: { fun: fun }});
  return instance.exports.fun;
})();

// Generate an exported function that calls the above re-export from another
// module, still with a function signature that is incompatible with JS.
var fun2 = (function GenerateFun2() {
  let builder = new WasmModuleBuilder();
  let fun_index = builder.addImport("m", "fun", kSig_l_v)
  builder.addFunction('main', kSig_v_v)
      .addBody([
        kExprCallFunction, fun_index,
        kExprDrop
      ])
      .exportFunc();
  let instance = builder.instantiate({ m: { fun: fun1 }});
  return instance.exports.main;
})();

// Both exported functions should throw, no matter how often they get wrapped.
assertThrows(fun1, TypeError, /wasm function signature contains illegal type/);
assertThrows(fun2, TypeError, /wasm function signature contains illegal type/);


text:
"""Organization related views module"""
import json

from flask import (
    Blueprint,
    abort,
    current_app,
    jsonify,
    render_template,
    request,
)
from flask_user import roles_required
from sqlalchemy import and_, exc

from ..audit import auditable_event
from ..cache import FIVE_MINS, cache, request_args_in_key
from ..database import db
from ..extensions import oauth
from ..models.coding import Coding
from ..models.identifier import Identifier
from ..models.organization import Organization, OrganizationIdentifier, OrgTree
from ..models.reference import MissingReference, Reference
from ..models.role import ROLE
from ..models.user import current_user, get_user
from ..system_uri import IETF_LANGUAGE_TAG, PRACTICE_REGION
from .crossdomain import crossdomain

org_api = Blueprint('org_api', __name__, url_prefix='/api')

@org_api.route('/organization')
@crossdomain()
@oauth.require_oauth()
@cache.cached(timeout=FIVE_MINS, key_prefix=request_args_in_key)
def organization_search():
    """Obtain a bundle (list) of all matching organizations

    Takes key=value pairs to look up.

    Example search:
        /api/organization?state=NJ

    Or to lookup by identifier, include system and value:
        /api/organization?system=http%3A%2F%2Fpcctc.org%2F&value=146-31

    Returns a JSON FHIR bundle of organizations as per given search terms.
    Without any search terms, returns all organizations known to the system.
    If search terms are provided but no matching organizations are found,
    a 404 is returned.

    ---
    operationId: organization_search
    tags:
      - Organization
    parameters:
      - name: search_parameters
        in: query
        description:
            Search parameters, such as `state`, which should be the two
            letter state code.
        required: false
        type: string
      - name: filter
        in: query
        description:
            Filter to apply to search, such as `leaves` to restrict results
            to just the leaf nodes of the organization tree.
        required: false
        type: string
      - name: tree_view
        in: query
        description:
            If given a `True` value, alters the return type to HTML and
            generates a `tree` view of the organization hierarchy for easier
            human comprehension of the structure.  Can NOT be combined with
            other filters or search parameters.
        required: false
        type: string
    produces:
      - application/json
    responses:
      200:
        description:
          Returns a FHIR bundle of [organization
          resources](http://www.hl7.org/fhir/patient.html) in JSON.
      401:
        description:
          if missing valid OAuth token or logged-in user lacks permission
          to view requested patient
    security:
      - ServiceToken: []

    """
    filter = None
    found_ids = []
    system, value, tree_view = None, None, None
    for k, v in request.args.items():
        if k == 'state':
            if not v or len(v) != 2:
                abort(400, "state search requires two letter state code")
            region = 'state:{}'.format(v.upper())

            query = OrganizationIdentifier.query.join(
                Identifier).filter(and_(
                    OrganizationIdentifier.identifier_id == Identifier.id,
                    Identifier.system == PRACTICE_REGION,
                    Identifier._value == region))
            found_ids = [oi.organization_id for oi in query]
            if not found_ids:
                abort(404, "no organzations found for state {}".format(v))
        elif k == 'filter':
            filter = v
            if not filter == 'leaves':
                abort(
                    400, "unknown filter request '{}' - expecting "
                         "'leaves'".format(filter))
        elif k == 'system':
            system = v
        elif k == 'value':
            value = v
        elif k == 'tree_view':
            tree_view = v and v.lower() == 'true'
        else:
            abort(
                400, "only search on `state`, `filter` or `system` AND `value`"
                     " are available at this time")

    if system and value:
        query = OrganizationIdentifier.query.join(
            Identifier).filter(and_(
                OrganizationIdentifier.identifier_id == Identifier.id,
                Identifier.system == system,
                Identifier._value == value))
        found_ids = [oi.organization_id for oi in query]
        if not found_ids:
            abort(
                404, "no organzations found for system, value {}, {}".format(
                    system, value))

    # Apply search on org fields like inheritence - include any children
    # of the matching nodes.  If filter is set, apply to results.
    ot = OrgTree()
    matching_orgs = set()

    # Lookout for filter w/o a search term, use top level ids in this case
    if filter and not found_ids:
        found_ids = ot.all_top_level_ids()

    for org in found_ids:
        if filter == 'leaves':
            matching_orgs |= set(ot.all_leaves_below_id(org))
        else:
            matching_orgs |= set(ot.here_and_below_id(org))

    bundle = Organization.generate_bundle(matching_orgs, include_empties=False)
    if tree_view:
        if matching_orgs:
            abort(400, "Can't combine search filters with `tree_view`")
        return render_template('org_tree.html', bundle=bundle)
    return jsonify(bundle)

@org_api.route('/organization/<string:id_or_code>')
@crossdomain()
@oauth.require_oauth()
def organization_get(id_or_code):
    """Access to the requested organization as a FHIR resource

    If 'system' param is provided, looks up the organization by identifier,
    using the `id_or_code` string as the identifier value; otherwise,
    treats `id_or_code` as the organization.id

    ---
    operationId: organization_get
    tags:
      - Organization
    produces:
      - application/json
    parameters:
      - name: id_or_code
        in: path
        description: TrueNTH organization ID OR Identifier value code
        required: true
        type: string
      - name: system
        in: query
        description: Identifier system
        required: false
        type: string
      - name: include_inherited_attributes
        in: query
        description: include attributes defined at a parent or higher level
        required: false
        type: string
    responses:
      200:
        description:
          Returns the requested organization as a FHIR [organization
          resource](https://www.hl7.org/fhir/DSTU2/organization.html) in JSON.
      401:
        description:
          if missing valid OAuth token or logged-in user lacks permission
          to view requested patient
    security:
      - ServiceToken: []
      - OAuth2AuthzFlow: []

    """
    system = request.args.get('system')
    if system:
        query = Organization.query.join(
            OrganizationIdentifier).join(
            Identifier).filter(and_(
                Organization.id == OrganizationIdentifier.organization_id,
                OrganizationIdentifier.identifier_id == Identifier.id,
                Identifier.system == system,
                Identifier._value == id_or_code))
        if query.count() == 1:
            org = query.first()
        else:
            abort(
                404, 'no organization found with identifier: '
                     'system `{}`, value `{}`'.format(system, id_or_code))
    else:
        try:
            organization_id = int(id_or_code)
            org = Organization.query.get_or_404(organization_id)
        except ValueError:
            abort(
                400, "invalid input '{}' - expected integer without system "
                     "parameter".format(id_or_code))

    include_inherited = request.args.get(
        'included_inherited_attributes', 'false').lower() != 'false'
    return jsonify(org.as_fhir(
        include_empties=False, include_inherited=include_inherited))

@org_api.route('/organization/<int:organization_id>', methods=('DELETE',))
@crossdomain()
@roles_required(ROLE.ADMIN.value)
@oauth.require_oauth()
def organization_delete(organization_id):
    """Delete the requested organization

    NB - only organizations without any relationships to entities such
    as patients and other organizations may be deleted.
    ---
    tags:
      - Organization
    operationId: organization_delete
    produces:
      - application/json
    parameters:
      - name: organization_id
        in: path
        description: TrueNTH organization ID
        required: true
        type: integer
        format: int64
    responses:
      200:
        description: message reporting successful deletion
      400:
        description: Cannot delete organization with related entities
      401:
        description:
          if missing valid OAuth token or if the authorized user lacks
          permission to view requested user_id
    security:
      - ServiceToken: []
      - OAuth2AuthzFlow: []

    """
    org = Organization.query.get_or_404(organization_id)
    try:
        db.session.delete(org)
        db.session.commit()
    except exc.IntegrityError as e:
        message = "Cannot delete organization with related entities"
        current_app.logger.warn(message + str(e), exc_info=True)
        abort(message, 400)
    auditable_event(
        "deleted {}".format(org), user_id=current_user().id,
        subject_id=current_user().id, context='organization')
    OrgTree.invalidate_cache()
    return jsonify(message='deleted organization {}'.format(org))

@org_api.route('/organization', methods=('POST',))
@crossdomain()
@oauth.require_oauth()  # for service token access, oauth must come first
@roles_required([ROLE.ADMIN.value, ROLE.SERVICE.value])
def organization_post():
    """Add a new organization.  Updates should use PUT

    Returns the JSON FHIR organization as known to the system after adding.

    Submit JSON format [Organization
    Resource](https://www.hl7.org/fhir/organization.html) to add an
    organization.

    Include an **identifier** with system of
    http://us.truenth.org/identity-codes/shortcut-alias to name a shortcut
    alias for the organization, useful at `/go/<alias>`.

    A resource mentioned as partOf the given organization must exist as a
    prerequisit or a 400 will result.

    ---
    operationId: organization_post
    tags:
      - Organization
    produces:
      - application/json
    parameters:
      - name: organization_id
        in: path
        description: TrueNTH organization ID
        required: true
        type: integer
        format: int64
      - in: body
        name: body
        schema:
          id: FHIROrganization
          required:
            - resourceType
          properties:
            resourceType:
              type: string
              description: defines FHIR resource type, must be Organization
    responses:
      200:
        description:
          Returns updated [FHIR organization
          resource](http://www.hl7.org/fhir/patient.html) in JSON.
      400:
        description:
          if partOf resource does not exist
      401:
        description:
          if missing valid OAuth token or logged-in user lacks permission
          to view requested patient
    security:
      - ServiceToken: []
      - OAuth2AuthzFlow: []

    """
    if (not request.json or 'resourceType' not in request.json or
            request.json['resourceType'] != 'Organization'):
        abort(400, "Requires FHIR resourceType of 'Organization'")
    try:
        org = Organization.from_fhir(request.json)
    except MissingReference as e:
        abort(400, str(e))
    db.session.add(org)
    db.session.commit()
    auditable_event("added new organization {}".format(org),
                    user_id=current_user().id, subject_id=current_user().id,
                    context='organization')
    OrgTree.invalidate_cache()
    return jsonify(org.as_fhir(include_empties=False))

@org_api.route('/organization/<int:organization_id>', methods=('PUT',))
@crossdomain()
@oauth.require_oauth()  # for service token access, oauth must come first
@roles_required([ROLE.ADMIN.value, ROLE.SERVICE.value])
def organization_put(organization_id):
    """Update organization via FHIR Resource Organization. New should POST

    Submit JSON format [Organization
    Resource](https://www.hl7.org/fhir/organization.html) to update an
    existing organization.

    Include an **identifier** with system of
    http://us.truenth.org/identity-codes/shortcut-alias to name a shortcut
    alias for the organization, useful at `/go/<alias>`.  NB, including a
    partial list of identifiers will result in the non mentioned identifiers
    being deleted.  Consider calling GET first.

    A resource mentioned as partOf the given organization must exist as a
    prerequisit or a 400 will result.

    ---
    operationId: organization_put
    tags:
      - Organization
    produces:
      - application/json
    parameters:
      - name: organization_id
        in: path
        description: TrueNTH organization ID
        required: true
        type: integer
        format: int64
      - in: body
        name: body
        schema:
          id: FHIROrganization
          required:
            - resourceType
          properties:
            resourceType:
              type: string
              description: defines FHIR resource type, must be Organization
    responses:
      200:
        description:
          Returns updated [FHIR organization
          resource](http://www.hl7.org/fhir/patient.html) in JSON.
      400:
        description:
          if partOf resource does not exist
      401:
        description:
          if missing valid OAuth token or logged-in user lacks permission
          to view requested patient
    security:
      - ServiceToken: []
      - OAuth2AuthzFlow: []

    """
    if (not request.json or 'resourceType' not in request.json or
            request.json['resourceType'] != 'Organization'):
        abort(400, "Requires FHIR resourceType of 'Organization'")
    org = Organization.query.get_or_404(organization_id)
    try:
        # As we allow partial updates, first obtain a full representation
        # of this org, and update with any provided elements
        complete = org.as_fhir(include_empties=True)
        complete.update(request.json)
        org.update_from_fhir(complete)
    except MissingReference as e:
        abort(400, str(e))
    db.session.commit()
    auditable_event("updated organization from input {}".format(
        json.dumps(request.json)), user_id=current_user().id,
        subject_id=current_user().id, context='organization')
    OrgTree.invalidate_cache()
    return jsonify(org.as_fhir(include_empties=False))

@org_api.route('/user/<int:user_id>/organization')
@crossdomain()
@oauth.require_oauth()
def user_organizations(user_id):
    """Obtain list of organization references currently associated with user

    ---
    tags:
      - User
      - Organization
    operationId: user_organizations
    produces:
      - application/json
    parameters:
      - name: user_id
        in: path
        description: TrueNTH user ID
        required: true
        type: integer
        format: int64
    responses:
      200:
        description: return list of user's organizations by reference
        schema:
          id: organization_references
          properties:
            organizations:
              type: array
              items:
                type: object
                required:
                  - reference
                properties:
                  reference:
                    type: string
                    description: FHIR compliant reference to an organization
      401:
        description:
          if missing valid OAuth token or if the authorized user lacks
          permission to edit requested user_id
      404:
        description: if user_id doesn't exist
    security:
      - ServiceToken: []

    """
    # Return user's current organizations
    user = get_user(
        user_id, 'view', allow_on_url_authenticated_encounters=True)
    return jsonify(organizations=[
        Reference.organization(org.id).as_fhir()
        for org in user.organizations])

@org_api.route('/user/<int:user_id>/organization', methods=('POST',))
@crossdomain()
@oauth.require_oauth()
def add_user_organizations(user_id):
    """Associate organization with user via reference

    POST a list of references to each existing organization to associate with
    given user.  These will be added to the user's current organizations.

    Both organization reference formats are supported, i.e.:

        {'organizations': [
            {'reference': 'api/organization/1001'},
            {'reference': 'api/organization/123-45?system=http://pcctc.org/'}
        ]}

    Additional attributes may be applied to the user, from the named
    organization's matching defaults.  For example, both the default
    timezone and the language may be assigned using the respective values:

        {'organizations': [
            {'reference': 'api/organizations/1001',
             'language': 'apply_to_user',
             'timezone': 'apply_to_user'}
        ]}

    If user is already associated with one or more of the posted organizations,
    a 409 will be raised.

    ---
    tags:
      - User
      - Organization
    operationId: add_user_organizations
    produces:
      - application/json
    parameters:
      - name: user_id
        in: path
        description: TrueNTH user ID
        required: true
        type: integer
        format: int64
      - in: body
        name: body
        schema:
          $ref: "#/definitions/organization_references"
    responses:
      200:
        description:
          return list of user's organizations by reference after change
        schema:
          $ref: "#/definitions/organization_references"
      401:
        description:
          if missing valid OAuth token or if the authorized user lacks
          permission to edit requested user_id
      404:
        description: if user_id doesn't exist
      409:
        description: if any of the given identifiers are already assigned to the user
    security:
      - ServiceToken: []
      - OAuth2AuthzFlow: []

    """
    user = get_user(user_id, 'edit')
    if not request.json or 'organizations' not in request.json:
        abort(400, "Requires `organizations` list")

    # validate input - don't allow multiple orgs with `apply_to_user`
    # attributes for any given field
    applied_fields = []

    def apply_defaults(item, org, applied):
        for field in 'timezone', 'language':
            if field in item:
                if item[field] != 'apply_to_user':
                    abort(400, "expected 'apply_to_user' on {}".format(field))
                if field in applied:
                    abort(400, "can't apply defaults from more than one org")
                if field == 'language':
                    # Org's default_locale respects the org tree inheritance,
                    # but only returns the 'code' - need full Coding to set
                    if not org.default_locale:
                        abort(
                            400, "can't apply language from org w/o a value")
                    locale_code = Coding.query.filter(
                        Coding.system == IETF_LANGUAGE_TAG).filter(
                        Coding.code == org.default_locale).one()
                    user.locale = (locale_code.code, locale_code.display)
                else:
                    setattr(user, field, getattr(org, field))
                applied.append(field)

    for item in request.json.get('organizations'):
        try:
            org = Reference.parse(item)
        except MissingReference as e:
            abort(400, "Organization {}".format(e))
        apply_defaults(item, org, applied_fields)
        if not isinstance(org, Organization):
            abort(400, "Expecting only `Organization` references")
        if org in user.organizations:
            abort(
                409,
                "POST restricted to organizations not already assigned to "
                "user")
        user.organizations.append(org)
        auditable_event(
            message='Added {}'.format(org), user_id=current_user().id,
            subject_id=user.id, context='organization')
    db.session.commit()

    # Return current organizations

    return jsonify(organizations=[
        Reference.organization(org.id).as_fhir()
        for org in user.organizations])


text:
<bill session="115" type="s" number="1161" updated="2017-08-19T04:31:58Z">
  <state datetime="2017-05-17">REFERRED</state>
  <status>
    <introduced datetime="2017-05-17"/>
  </status>
  <introduced datetime="2017-05-17"/>
  <titles>
    <title type="short" as="introduced">Veterans Preventive Health Coverage Fairness Act</title>
    <title type="short" as="introduced">Veterans Preventive Health Coverage Fairness Act</title>
    <title type="official" as="introduced">A bill to amend title 38, United States Code, to eliminate copayments by the Department of Veterans Affairs for medicines relating to preventative health services, and for other purposes.</title>
    <title type="display">Veterans Preventive Health Coverage Fairness Act</title>
  </titles>
  <sponsor bioguide_id="D000622"/>
  <cosponsors>
    <cosponsor bioguide_id="B001277" joined="2017-05-17"/>
    <cosponsor bioguide_id="C001035" joined="2017-05-17"/>
  </cosponsors>
  <actions>
    <action datetime="2017-05-17">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-05-17" state="REFERRED">
      <text>Read twice and referred to the Committee on Veterans' Affairs.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="SSVA" name="Senate Veterans' Affairs" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="h" session="115" relation="unknown" number="1100"/>
  </relatedbills>
  <subjects>
    <term name="Armed forces and national security"/>
  </subjects>
  <amendments/>
  <summary date="2017-05-17T04:00:00Z" status="Introduced in Senate">Veterans Preventive Health Coverage Fairness Act

This bill exempts veterans from Department of Veteran Affairs medical copayments for medication or hospital care and medical services related to preventive health services.

 The bill includes in the definition of "preventive health services": (1) evidence-based items or services that have an A or B rating in the recommendations of the United States Preventive Services Task Force; (2) immunizations that have a recommendation from the Advisory Committee on Immunization Practices of the Centers for Disease Control and Prevention with respect to the individual involved; and (3) with respect to women, the preventive care and screenings provided for in the Health Resources and Services Administration Preventive Services Guidelines in effect as of January 1, 2017.</summary>
  <committee-reports/>
</bill>


text:
namespace DNNConnect.CKEditorProvider.Objects
{
    using System;

    /// <summary>
    /// Toolbar Class
    /// </summary>
    [Obsolete("This class is phasing out please use ToolbarSet Class instead")]
    public class Toolbar
    {
        /// <summary>
        /// Gets or sets The Name of the Toolbar Set
        /// </summary>
        public string sToolbarName { get; set; }

        /// <summary>
        /// Gets or sets The Hole Toolbar Set
        /// </summary>
        public string sToolbarSet { get; set; }

        /// <summary>
        /// Gets or sets Toolbar Prioritity from 1-20
        /// </summary>
        public int iPriority { get; set; }
    }
}


text:
<?php

namespace PHPWarrior\Abilities;

class Pivot extends Base
{
    public static $ROTATION_DIRECTIONS = ['forward', 'right', 'backward', 'left'];

    public function description()
    {
        return __("Rotate left, right or backward (default)");
    }

    public function perform($direction = 'backward')
    {
        $direction = \PHPWarrior\Position::normalize_direction($direction);
        $this->verify_direction($direction);
        $this->unit->position->rotate(
            array_search($direction, self::$ROTATION_DIRECTIONS)
        );
        $this->unit->say(sprintf(
            __("pivots %s"),
            __($direction)
        ));
    }
}


text:
namespace sh
{

class TOutputGLSL : public TOutputGLSLBase
{
  public:
    TOutputGLSL(TInfoSinkBase &objSink,
                ShArrayIndexClampingStrategy clampingStrategy,
                ShHashFunction64 hashFunction,
                NameMap &nameMap,
                TSymbolTable *symbolTable,
                sh::GLenum shaderType,
                int shaderVersion,
                ShShaderOutput output,
                ShCompileOptions compileOptions);

  protected:
    bool writeVariablePrecision(TPrecision) override;
    void visitSymbol(TIntermSymbol *node) override;
    TString translateTextureFunction(const TString &name) override;
};

}  // namespace sh

#endif  // COMPILER_TRANSLATOR_OUTPUTGLSL_H_


text:
class FileEventHandler():
	def __init__(self):
		pass

	def on_init(self, item):
		# procedure when there are initial items
		print "initial item; %s was detected." %(item.filename)

	def on_add(self, item):
		#  procedure when an item is added
		print "%s was added." %(item.filename)

	def on_modify(self, item):
		# procedure when an item is modified
		print "%s was modified." %(item.filename)

	def on_move(self, item):
		# procedure when an item is moved
		print "An item was moved to %s" %(item.filename)

	def on_delete(self, item):
		# procedure when an item is deleted
		print "%s was deleted." %(item.filename)


text:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Warcraft.Buildings.Orcs;
using Warcraft.Managers;
using Warcraft.Units.Neutral;
using Warcraft.Util;

namespace Warcraft.Units.Humans
{
	class Battleship : Unit
	{
        public static bool move = false;

        public Battleship(int tileX, int tileY, int lastX, ManagerMouse managerMouse, ManagerMap managerMap, ManagerUnits managerUnits, ManagerBuildings managerBuildings, ManagerEnemies managerEnemies)
            : base(tileX, tileY, 96, 96, 1, managerMouse, managerMap, managerUnits)
        {
			Dictionary<AnimationType, List<Sprite>> sprites = new Dictionary<AnimationType, List<Sprite>>();
			List<Sprite> spriteWalking = new List<Sprite>();
			spriteWalking.Add(new Sprite(19, 6, 52, 81));
			spriteWalking.Add(new Sprite(18, 93, 52, 88));
			spriteWalking.Add(new Sprite(186, 7, 84, 67));
            spriteWalking.Add(new Sprite(102, 4, 67, 83));
			spriteWalking.Add(new Sprite(281, 0, 80, 88));
			sprites.Add(AnimationType.WALKING, spriteWalking);

			Dictionary<string, Frame> animations = new Dictionary<string, Frame>();
			animations.Add("up", new Frame(0, 1));
			animations.Add("down", new Frame(1, 1));
			animations.Add("right", new Frame(2, 1));
			animations.Add("left", new Frame(2, 1, true));
			animations.Add("upRight", new Frame(3, 1));
			animations.Add("downRight", new Frame(4, 1));
			animations.Add("upLeft", new Frame(3, 1, true));
			animations.Add("downLeft", new Frame(4, 5, true));

			this.animations = new Animation(sprites, animations, "down", width, height);

			textureName.Add(AnimationType.WALKING, "Battleship");

            information = new InformationUnit("Battleship", Race.HUMAN, Faction.ALLIANCE, 9999, 0, 0, 10, 0, 0, Util.Buildings.NONE, 0, 0, 0, Util.Units.BATTLESHIP, 0);
			Information = information;

            managerMouse.MouseEventHandler += (sender, e) => {
                if (e.SelectRectangle.Intersects(rectangle) && !move)
                {
                    int total = 0, dead = 0;
                    managerEnemies.managerUnits.units.ForEach(unit => {
                        if (!(unit is Skeleton))
                        {
                            total++;
                            if (unit.information.HitPoints <= 0)
                                dead++;
                        }
                    });

                    if (total == dead && managerEnemies.managerBuildings.buildings.Count < 2)
                    {
                        if (managerEnemies.managerBuildings.buildings.Count == 0 || (managerEnemies.managerBuildings.buildings.Count == 1 && managerEnemies.managerBuildings.buildings[0] is DarkPortal))
                        {
                            goal = new Vector2(lastX * Warcraft.TILE_SIZE, position.Y + 5 * Warcraft.TILE_SIZE);
                            transition = true;
                            move = true;

                            Warcraft.ISLAND++;

                            if (Warcraft.ISLAND > 2)
                            {
                                Warcraft.ISLAND = 0;
                            }
                        }
					}
                }
            };
		}

        public override void Update()
        {
            base.Update();

            animations.currentAnimation = AnimationType.WALKING;
            selected = false;
            target = null;
            targetBuilding = null;

            if (move)
            {
                Warcraft.camera.center = position - new Vector2(Warcraft.WINDOWS_WIDTH / 2, Warcraft.WINDOWS_HEIGHT / 2);
            }
        }
	}
}


text:
#ifndef EL_IO_WIN32_RES_FILE_SYSTEM_WIN_H_
#define EL_IO_WIN32_RES_FILE_SYSTEM_WIN_H_

#include <memory>
#include <string>

#include "el/io/file_system.h"

namespace el {
namespace io {

class Win32ResFileSystem : public FileSystem {
 public:
  explicit Win32ResFileSystem(std::string prefix);

  std::unique_ptr<File> OpenRead(std::string filename) override;

 private:
  std::string prefix_;
};

}  // namespace io
}  // namespace el

#endif  // EL_IO_WIN32_RES_FILE_SYSTEM_WIN_H_


text:
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances,
  UndecidableInstances, FlexibleContexts, EmptyDataDecls, ScopedTypeVariables,
  TypeOperators, TypeSynonymInstances, TypeFamilies #-}

module Methods where

  import Records
  import References

  {-
  un metodo prende un a e ritorna una reference di b
  -}
  type Method s a b = (a -> Reference s b)

  {-
  un record dotato di metodi va definito come ricorsivo
  affinché non risulti in un tipo infinito; infatti un
  record rischierebbe di aver tipo:
  type MyObject = ... .* Method MyObject a b .* ...
  che non é accettabile; per questo definiamo:
  type MyObject k = ... .* Method k a b .* ...
  dove k verrá istanziato ad un opportuno contenitore:
  data RecMyObject = RecMyObject (MyObject RecMyObject)
  -}
  class Recursive s where
    type Rec s :: *
    cons :: s -> Rec s
    elim :: Rec s -> s

  {-
  in virtú del fatto che i metodi ritornano il contenitore
  ricorsivo del record, e non il record stesso, definiamo
  una funzione che prende il metodo definito in modo
  naturale (ossia in termini del record vero e proprio)
  e lo converte alla forma che ci serve
  -}
  mk_method :: forall a b s . (Recursive s) => Method s a b -> Method (Rec s) a b
  mk_method m =
        \(x :: a) ->
            let (Reference getter setter) = m x
            in
                (Reference (\(rs :: Rec s) ->
                               let rs' = elim rs :: s
                                   (v,rs'') = getter rs' :: (b,s)
                               in (v,cons rs'') :: (b,Rec s))
                            (\(rs :: Rec s) -> \(x :: b) ->
                               let rs' = elim rs :: s
                                   (v,rs'') = getter rs' :: (b,s)
                                   ((),rs''') = setter rs'' x :: ((),s)
                               in ((),cons rs''')))

  {-
  diamo un operatore di selezione per i metodi
  -}
  (<<-) :: forall a s b c n . (CNum n, Recursive a, HasField n (Method (Rec a) b c) a) => (Reference s a) -> n -> (b -> Reference s c)
  (<<-) (Reference get set) n =
    \(x :: b) ->
        from_constant( Constant(\(s :: s)->
                          let (v,s') = get s :: (a,s)
                              m = v .! n
                              ry = m x :: Reference (Rec a) c
                              (y,v') = getter ry (cons v) :: (c,Rec a)
                              v'' = elim v'
                              ((),s'') = set s' v''
                              in (y,s'')))