text:
// MIT License
// Copyright (c) 2011-2016 Elisée Maurer, Sparklin Labs, Creative Patterns
// Copyright (c) 2016 Thomas Morgner, Rabbit-StewDio Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using Steropes.UI.Components;
using Steropes.UI.Platform;
using Steropes.UI.Styles.Watcher;
using Steropes.UI.Widgets.Container;

namespace Steropes.UI.Styles
{
  public interface IStyleResolver
  {
    ObservableCollection<IStyleRule> StyleRules { get; }

    void AddRoot(IWidget root);

    IResolvedStyle CreateStyleFor(IWidget widget);

    // ReSharper disable once UnusedMember.Global
    void RemoveRoot(IWidget root);

    bool Revalidate();

    bool IsRegistered(IWidget widget);
  }

  /// <summary>
  ///   Resolves styles for the current UI. The style resolver monitors the composition of the UI tree and
  ///   re-resolves rules as the tree changes. For rules that have additional conditions (match by style-class,
  ///   pseudo-class or attribute contents), the system also monitors property-change events.
  /// </summary>
  public class StyleResolver : IStyleResolver
  {
    readonly HashSet<IWatchRule> affectedNodesSet;

    readonly EventHandler<ContainerEventArgs> onChildrenChangedHandler;

    readonly Dictionary<IWidget, WidgetChangeTracker> registeredWidgets;

    readonly WidgetWatchRuleFactory ruleFactory;

    readonly List<IStyleRule> styleRules;

    readonly Comparison<IStyleRule> styleRuleSortOrder = StyleRule.StyleRuleSortOrder;

    readonly IStyleSystem styleSystem;
    readonly TraceSource tracer = TracingUtil.StyleTracing;

    public StyleResolver(IStyleSystem styleSystem)
    {
      this.styleSystem = styleSystem;
      ruleFactory = new WidgetWatchRuleFactory();
      registeredWidgets = new Dictionary<IWidget, WidgetChangeTracker>();
      StyleRules = new ObservableCollection<IStyleRule>();
      StyleRules.CollectionChanged += OnRuleCompositionChanged;
      onChildrenChangedHandler = OnChildrenChanged;
      affectedNodesSet = new HashSet<IWatchRule>();
      styleRules = new List<IStyleRule>();
    }

    public bool Dirty { get; private set; }

    public ObservableCollection<IStyleRule> StyleRules { get; }

    public void AddRoot(IWidget root)
    {
      Install(root);
    }

    public IResolvedStyle CreateStyleFor(IWidget widget)
    {
      return new ResolvedStyle(styleSystem, widget);
    }

    public void RemoveRoot(IWidget root)
    {
      Uninstall(root);
    }

    public bool Revalidate()
    {
      if (Dirty)
      {
        var sw = Stopwatch.StartNew();
        var widgetCount = 0;
        foreach (var pair in registeredWidgets)
        {
          var widget = pair.Key;
          var value = pair.Value;
          if (ResolveAsRegisteredWidget(widget, value))
          {
            widgetCount += 1;
          }
        }

        Dirty = false;
        sw.Stop();

        tracer.TraceEvent(TraceEventType.Verbose, 0,
                          "Finished revalidate of {0} widgets in {1} seconds.", widgetCount,
                          sw.Elapsed.TotalSeconds);
        return true;
      }
      return false;
    }

    public bool IsRegistered(IWidget widget)
    {
      return registeredWidgets.ContainsKey(widget);
    }

    public void MarkDirty(IWidget w)
    {
      WidgetChangeTracker tracker;
      if (registeredWidgets.TryGetValue(w, out tracker))
      {
        // is a registered widget?
        tracker.Dirty = WidgetState.Dirty;
        Dirty = true;
      }
    }

    public void ResolveStyle(IWidget widget)
    {
      WidgetChangeTracker t;
      if (registeredWidgets.TryGetValue(widget, out t))
      {
        ResolveAsRegisteredWidget(widget, t);
        return;
      }

      ////Debug.WriteLine("Resolving unregistered element: " + widget);
      styleRules.Clear();
      for (var index = 0; index < StyleRules.Count; index++)
      {
        var rule = StyleRules[index];

        // we collect style information regardless on whether conditions match.
        // conditions may change often over the lifetime of this object, so we want
        // to keep an eye on every potential rule that  may apply.
        if (rule.Selector.Matches(widget))
        {
          styleRules.Add(rule);
        }
      }

      // apply resolved styles
      styleRules.Sort(styleRuleSortOrder);
      for (var index = 0; index < styleRules.Count; index++)
      {
        var rule = styleRules[index];
        rule.Style.CopyInto(widget.ResolvedStyle);
      }
      widget.ResolvedStyle.InvalidateCaches("After resolve.");
    }

    void Install(IWidget widget)
    {
      if (registeredWidgets.ContainsKey(widget))
      {
        return;
      }

      registeredWidgets.Add(widget, new WidgetChangeTracker(this, widget));
      Dirty = true;
      widget.ChildrenChanged += onChildrenChangedHandler;
      widget.VisitStructuralChildren(Install);
    }

    void OnChildrenChanged(object sender, ContainerEventArgs e)
    {
      var w = sender as IWidget;
      if (w == null)
      {
        return;
      }

      if (registeredWidgets.ContainsKey(w))
      {
        Dirty = true;
        if (e.RemovedChild != null)
        {
          Uninstall(e.RemovedChild);
        }
        if (e.AddedChild != null)
        {
          Install(e.AddedChild);
        }
      }
    }

    void OnRuleCompositionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
      Dirty = true;
      foreach (var pair in registeredWidgets)
      {
        var widgetChangeTracker = registeredWidgets[pair.Key];
        widgetChangeTracker.Dirty = WidgetState.Invalidated;
      }
    }

    bool ResolveAsRegisteredWidget(IWidget widget, WidgetChangeTracker value)
    {
      if (value.Dirty != WidgetState.Clean)
      {
        ////Debug.WriteLine($"Resolving registered element: {widget}");
        // rebind style rules
        affectedNodesSet.Clear();
        styleRules.Clear();
        for (var index = 0; index < StyleRules.Count; index++)
        {
          var rule = StyleRules[index];

          // we collect style information regardless on whether conditions match.
          // conditions may change often over the lifetime of this object, so we want
          // to keep an eye on every potential rule that  may apply.
          rule.Selector.CollectConditionTargets(widget, ruleFactory, affectedNodesSet);
          if (rule.Selector.Matches(widget))
          {
            styleRules.Add(rule);
          }
        }

        value.ClearMonitors();
        foreach (var match in affectedNodesSet)
        {
          value.RegisterMonitor(match);
        }

        widget.ResolvedStyle.StartResolve();

        // apply resolved styles
        styleRules.Sort(styleRuleSortOrder);
        for (var index = 0; index < styleRules.Count; index++)
        {
          var rule = styleRules[index];
          rule.Style.CopyInto(widget.ResolvedStyle);
        }

        widget.ResolvedStyle.EndResolve();
        value.Dirty = WidgetState.Clean;
        return true;
      }
      return false;
    }

    void Uninstall(IWidget widget)
    {
      WidgetChangeTracker tracker;
      if (registeredWidgets.TryGetValue(widget, out tracker))
      {
        registeredWidgets.Remove(widget);
        tracker.ClearMonitors();
        widget.ChildrenChanged -= onChildrenChangedHandler;
        widget.VisitStructuralChildren(Uninstall);
      }
    }

    enum WidgetState
    {
      Clean,

      /// <summary>
      ///   Something in the widget or the widget-composition changed.
      /// </summary>
      Dirty,

      /// <summary>
      ///   The style rules have changed and we have to invalidate all caches.
      /// </summary>
      Invalidated
    }

    class WidgetChangeTracker
    {
      readonly EventHandler<EventArgs> onStateChangedHandler;

      readonly StyleResolver resolver;

      readonly IWidget widget;

      public WidgetChangeTracker(StyleResolver resolver, IWidget widget)
      {
        this.resolver = resolver;
        this.widget = widget;
        onStateChangedHandler = OnWidgetStateChanged;
        DependentWidgets = new HashSet<IWatchRule>();
        Dirty = WidgetState.Dirty;
      }

      HashSet<IWatchRule> DependentWidgets { get; }

      public WidgetState Dirty { get; set; }

      public void ClearMonitors()
      {
        foreach (var rule in DependentWidgets)
        {
          rule.Remove();
          rule.StateChanged -= onStateChangedHandler;
        }
        DependentWidgets.Clear();
      }

      public void RegisterMonitor(IWatchRule match)
      {
        DependentWidgets.Add(match);
        match.StateChanged += onStateChangedHandler;
      }

      void OnWidgetStateChanged(object sender, EventArgs e)
      {
        resolver.MarkDirty(widget);
        widget.ResolvedStyle.InvalidateCaches("Widget State change");
      }
    }

    class WidgetWatchRuleFactory : IWatchRuleFactory
    {
      public IWatchRule CreatePropertyWatcher(IStyledObject styledObject, string property, object value)
      {
        var widget = styledObject as IWidget;
        if (widget == null)
        {
          throw new ArgumentException();
        }
        return new PropertyWatchRule(widget, property, value);
      }

      public IWatchRule CreatePseudoClassWatcher(IStyledObject styledObject, string styleClass)
      {
        var widget = styledObject as IWidget;
        if (widget == null)
        {
          throw new ArgumentException();
        }
        return new PseudoClassWatchRule(widget, styleClass);
      }

      public IWatchRule CreateStyleClassWatcher(IStyledObject styledObject, string styleClass)
      {
        var widget = styledObject as IWidget;
        if (widget == null)
        {
          throw new ArgumentException();
        }

        return new StyleClassWatchRule(widget, styleClass);
      }
    }
  }
}


text:
#pragma once

#include "Transition.h"
#include "CharItem.h"
#include "Context.h"
#include "PtrPool.h"
#include <map>

namespace Hpipe {
class InstructionMark;
class CppEmitter;

/**
*/
class Instruction {
public:
    Instruction( Context cx );
    virtual ~Instruction();

    virtual void          write_to_stream       ( std::ostream &os ) const;
    virtual void          write_dot             ( std::ostream &os, std::vector<std::string> *edge_labels = 0 ) const = 0;
    virtual void          write_dot_add         ( std::ostream &os, bool disp_inst_pred, bool disp_trans_freq, bool disp_rc_item ) const;
    void                  write_dot_rec         ( std::ostream &os, bool disp_inst_pred, bool disp_trans_freq, bool disp_rc_item, bool rec = true ) const;
    virtual Instruction  *clone                 ( PtrPool<Instruction> &inst_pool, const Context &ncx, const Vec<unsigned> &keep_ind ) = 0;
    unsigned              get_display_id        () const;
    void                  apply                 ( std::function<void(Instruction *)> f, bool subgraphs = false );
    void                  apply_rw              ( std::function<void(Instruction *)> f, bool subgraphs = false );
    virtual void          apply_rec             ( std::function<void(Instruction *)> f, bool subgraphs = false );
    virtual void          apply_rw_rec          ( std::function<void(Instruction *)> f, bool subgraphs = false );
    virtual void          get_unused_rec        ( Vec<Instruction *> &to_remove, Instruction *&init );
    bool                  find_rec              ( std::function<bool(Instruction *)> f );
    virtual void          apply_rec_rewind_l    ( std::function<void(Instruction *, unsigned)> f, unsigned rewind_level = 0 );
    virtual Transition   *train                 ( std::string::size_type &s, std::string::size_type &m, const std::string &inp, double freq, bool use_contiguous );
    void                  train_rec             ( std::string::size_type &s, std::string::size_type &m, const std::string &inp, double freq, bool use_contiguous );
    virtual bool          can_be_deleted        () const;
    virtual int           save_in_loc_reg       () const;
    void                  remove                ( bool update_rcitem = true ); ///< remove from graph
    void                  insert_before_this    ( Instruction *inst, Instruction *&init ); ///< inst -> this
    void                  insert_after_this     ( Instruction *inst ); ///< this -> inst -> next
    void                  repl_in_preds         ( Instruction *inst ); ///< replace in graph
    virtual void          write_cpp             ( StreamSepMaker &ss, StreamSepMaker &es, CppEmitter *cpp_emitter );
    int                   get_id_gen            ( CppEmitter *cpp_emitter );
    void                  write_trans           ( StreamSepMaker &ss, CppEmitter *cpp_emitter, unsigned num = 0 );
    virtual void          optimize_conditions   ( PtrPool<Instruction> &inst_pool );
    virtual void          find_cond_leaves      ( std::map<Instruction *, Cond> &leaves, const Cond &in, Instruction *orig );
    virtual bool          with_code             () const;
    virtual bool          data_code             () const;
    virtual bool          has_ret_cont          () const;
    virtual bool          always_need_id_gen    ( CppEmitter *cpp_emitter ) const;
    void                  update_in_a_branch    ();
    void                  update_in_a_cycle     ();
    // void               get_boyer_moore_seq   ( Vec<std::pair<Vec<Cond>, Instruction *> > &front );
    virtual void          write_cpp_code_seq    ( StreamSepMaker &ss, StreamSepMaker &es, CppEmitter *cpp_emitter, std::string repl_data = "data", std::string repl_buf = "buf" );
    virtual bool          merge_predecessors    ( Instruction **init = 0 );
    virtual std::string   code_repr             ();
    virtual void          get_code_repr         ( std::ostream &os ) = 0;
    virtual void          boyer_moore_opt       ( PtrPool<Instruction> &inst_pool, Instruction **init = 0 );
    virtual void          merge_eq_next         ( PtrPool<Instruction> &inst_pool );
    unsigned              need_buf_next         () const;
    Vec<std::string>      strs_not_in           ( const Context &cx ) const;
    unsigned              nb_next_rw            () const;

    Context               cx;
    Vec<double>           freq;          ///< freq by char
    double                cum_freq;      ///< tot freq
    Vec<Transition>       next;          ///< transitions to other states
    Vec<Transition>       prev;          ///< transitions to other states

    // helpers for mark/rewind
    int                   num_in_dfs_stack;
    bool                  in_a_branch;
    bool                  in_a_cycle;
    Instruction          *orig;          ///< if is a clone (for a rewind)
    Vec<unsigned>         orig_keed_ind; ///<
    Vec<Vec<Transition>>  next_rw;       ///< transitions to other states (with potential undecidability)

    InstructionMark      *mark;          ///<
    std::set<std::string> running_strs;  ///<

    // for code generation
    int                   num_ordering;
    unsigned              id_gen;

    // display and graph stuff
    std::string           _cache_code_repr;
    mutable unsigned      display_id;
    mutable unsigned      op_id;
    mutable unsigned      op_mp;
    static unsigned       cur_op_id;
};

} // namespace Hpipe

redpajama_set_name: RedPajamaGithub


text:
package org.xito.dazzle.animation.timing.triggers;

/**
 * Superclass for all TriggerEvents used in the Trigger classes.  The methods
 * here are mostly protected; it is expected that callers will not use this
 * class directly, but will instead use subclasses with pre-defined event
 * types. The purpose of this superclass is to provide the ability for
 * {@link Trigger} to treat event types generically, rather than to have
 * all even logic in the subclasses of Trigger.
 *
 * @author Chet
 */
public class TriggerEvent {

    /**
     * The ID of events are simple strings.  It is expected that subclasses
     * will define static objects that callers will use instead of users
     * having to manually create TriggerEvent objects from strings directly
     */
    private String name;

    /**
     * Protected constructor; this helps ensure type-safe use of
     * pre-define TriggerEvent objects.
     */
    protected TriggerEvent(String name) {
        this.name = name;
    }

    /**
     * This method returns the 'opposite' event from itself. This is used by
     * {@link Trigger} in running an auto-reversing animation, to determine
     * whether an opposite event has occurred (and whether to stop/reverse
     * the animation).  Note that some events may have no opposite.
     * Default behavior returns same event; subclasses with multiple/opposite
     * events must override to do the right thing here.
     */
    public TriggerEvent getOppositeEvent() {
        return this;
    }
}


text:
package org.eclipse.rdf4j.query.algebra.evaluation.iterator;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;

import org.eclipse.rdf4j.common.iteration.CloseableIteration;
import org.eclipse.rdf4j.common.iteration.EmptyIteration;
import org.eclipse.rdf4j.common.iteration.Iteration;
import org.eclipse.rdf4j.common.iteration.LookAheadIteration;
import org.eclipse.rdf4j.model.BNode;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.QueryEvaluationException;
import org.eclipse.rdf4j.query.algebra.StatementPattern;
import org.eclipse.rdf4j.query.algebra.Var;
import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy;

/**
 * Iteration that implements a simplified version of Symmetric Concise Bounded Description (omitting reified
 * statements).
 *
 * @author Jeen Broekstra
 * @see Concise Bounded Description - alternatives
 */
@Deprecated(since = "4.1.0")
public class DescribeIteration extends LookAheadIteration<BindingSet, QueryEvaluationException> {

	protected final static String VARNAME_SUBJECT = "subject";

	protected final static String VARNAME_PREDICATE = "predicate";

	protected final static String VARNAME_OBJECT = "object";

	private final List<String> describeExprNames;

	private final EvaluationStrategy strategy;

	private Value startValue;

	private final Queue<BNode> nodeQueue = new ArrayDeque<>();

	private final Set<BNode> processedNodes = new HashSet<>();

	private CloseableIteration<BindingSet, QueryEvaluationException> currentDescribeExprIter;

	private enum Mode {
		OUTGOING_LINKS,
		INCOMING_LINKS
	}

	private Mode currentMode = Mode.OUTGOING_LINKS;

	private final Iteration<BindingSet, QueryEvaluationException> sourceIter;

	public DescribeIteration(Iteration<BindingSet, QueryEvaluationException> sourceIter, EvaluationStrategy strategy,
			Set<String> describeExprNames, BindingSet parentBindings) {
		this.strategy = strategy;
		this.sourceIter = sourceIter;
		this.describeExprNames = new ArrayList<>(describeExprNames);
		this.parentBindings = parentBindings;
	}

	private BindingSet currentBindings;

	private int describeExprsIndex;

	protected BindingSet parentBindings;

	private void resetCurrentDescribeExprIter() throws QueryEvaluationException {
		while (currentDescribeExprIter == null) {
			if (currentBindings == null && startValue == null) {
				if (sourceIter.hasNext()) {
					currentBindings = sourceIter.next();
				} else {
					// no more bindings, therefore no more results to return.
					return;
				}
			}

			if (startValue == null) {
				String nextValueExpr = describeExprNames.get(describeExprsIndex++);
				if (nextValueExpr != null) {
					startValue = currentBindings.getValue(nextValueExpr);
					if (describeExprsIndex == describeExprNames.size()) {
						// reached the end of the list of valueExprs, reset to
						// read next value from source iterator if any.
						currentBindings = null;
						describeExprsIndex = 0;
					}
					currentMode = Mode.OUTGOING_LINKS;
				}
			}

			switch (currentMode) {
			case OUTGOING_LINKS:
				currentDescribeExprIter = createNextIteration(startValue, null);
				if (!currentDescribeExprIter.hasNext()) {
					// start value has no outgoing links.
					currentDescribeExprIter.close();
					currentDescribeExprIter = null;
					currentMode = Mode.INCOMING_LINKS;
				}
				break;
			case INCOMING_LINKS:
				currentDescribeExprIter = createNextIteration(null, startValue);
				if (!currentDescribeExprIter.hasNext()) {
					// no incoming links for this start value.
					currentDescribeExprIter.close();
					currentDescribeExprIter = null;
					startValue = null;
					currentMode = Mode.OUTGOING_LINKS;
				}
				break;
			}
		} // end while
	}

	@Override
	protected BindingSet getNextElement() throws QueryEvaluationException {
		resetCurrentDescribeExprIter();
		if (currentDescribeExprIter == null) {
			return null;
		}

		while (!currentDescribeExprIter.hasNext() && !nodeQueue.isEmpty()) {
			// process next node in queue
			BNode nextNode = nodeQueue.poll();
			currentDescribeExprIter.close();
			switch (currentMode) {
			case OUTGOING_LINKS:
				currentDescribeExprIter = createNextIteration(nextNode, null);
				break;
			case INCOMING_LINKS:
				currentDescribeExprIter = createNextIteration(null, nextNode);
				break;

			}
			processedNodes.add(nextNode);

			if (nodeQueue.isEmpty() && !currentDescribeExprIter.hasNext()) {
				// we have hit a blank node that has no further expansion. reset to
				// initialize next in value expression queue.
				currentDescribeExprIter.close();
				currentDescribeExprIter = null;

				if (currentMode == Mode.OUTGOING_LINKS) {
					currentMode = Mode.INCOMING_LINKS;
				} else {
					// done with this valueExpr, reset to initialize next in value
					// expression queue.
					currentMode = Mode.OUTGOING_LINKS;
					startValue = null;
				}

				resetCurrentDescribeExprIter();
				if (currentDescribeExprIter == null) {
					return null;
				}
			}

		}

		if (currentDescribeExprIter.hasNext()) {
			BindingSet bs = currentDescribeExprIter.next();

			String varname = currentMode == Mode.OUTGOING_LINKS ? VARNAME_OBJECT : VARNAME_SUBJECT;

			Value v = bs.getValue(varname);
			if (v instanceof BNode) {
				if (!processedNodes.contains(v)) { // duplicate/cycle detection
					nodeQueue.add((BNode) v);
				}
			}

			if (!currentDescribeExprIter.hasNext() && nodeQueue.isEmpty()) {
				currentDescribeExprIter.close();
				currentDescribeExprIter = null;

				if (currentMode == Mode.OUTGOING_LINKS) {
					currentMode = Mode.INCOMING_LINKS;
				} else {
					// done with this valueExpr, reset to initialize next in value
					// expression queue.
					currentMode = Mode.OUTGOING_LINKS;
					startValue = null;
				}
			}

			return bs;
		}

		return null;
	}

	protected CloseableIteration<BindingSet, QueryEvaluationException> createNextIteration(Value subject, Value object)
			throws QueryEvaluationException {
		if (subject == null && object == null) {
			return new EmptyIteration<>();
		}

		Var subjVar = new Var(VARNAME_SUBJECT, subject);
		Var predVar = new Var(VARNAME_PREDICATE);
		Var objVar = new Var(VARNAME_OBJECT, object);

		StatementPattern pattern = new StatementPattern(subjVar, predVar, objVar);
		return strategy.evaluate(pattern, parentBindings);
	}

}


text:
using System;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.Popups;
using Windows.UI.Xaml;

namespace Podcasts
{
    public static class Messenger
    {
        public static async Task<bool> QuestionAsync(string message, string okLabel = null, string cancelLabel = null)
        {
            try
            {
                MessageDialog md = new MessageDialog(message, StringsHelper.Confirmation);

                if (okLabel == null)
                {
                    okLabel = StringsHelper.OK;
                }

                if (cancelLabel == null)
                {
                    cancelLabel = StringsHelper.Cancel;
                }

                bool? result = null;
                md.Commands.Add(new UICommand(okLabel, cmd => result = true));
                md.Commands.Add(new UICommand(cancelLabel, cmd => result = false));

                await md.ShowAsync();
                return result == true;
            }
            catch
            {
                return false;
            }
        }

        public static void Notify(string title, string message, string arguments, string image)
        {
            try
            {
                ToastTemplateType toastTemplate = ToastTemplateType.ToastImageAndText03;
                XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);

                XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
                toastTextElements[0].AppendChild(toastXml.CreateTextNode(title));
                toastTextElements[1].AppendChild(toastXml.CreateTextNode(message));

                XmlNodeList toastImageAttributes = toastXml.GetElementsByTagName("image");
                ((XmlElement)toastImageAttributes[0]).SetAttribute("src", image ?? "ms-appx:///Assets/icon.png");

                ((XmlElement)toastXml.SelectSingleNode("/toast")).SetAttribute("launch", arguments);

                ToastNotification toast = new ToastNotification(toastXml);

                ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
            catch
            {
                // Ignore error
            }
        }

        public static void Notify(string message, string arguments)
        {
            try
            {
                ToastTemplateType toastTemplate = ToastTemplateType.ToastImageAndText01;
                XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);

                XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
                toastTextElements[0].AppendChild(toastXml.CreateTextNode(message));

                XmlNodeList toastImageAttributes = toastXml.GetElementsByTagName("image");
                ((XmlElement)toastImageAttributes[0]).SetAttribute("src", "ms-appx:///Assets/icon.png");

                ((XmlElement)toastXml.SelectSingleNode("/toast")).SetAttribute("launch", arguments);

                ToastNotification toast = new ToastNotification(toastXml);

                ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
            catch
            {
                // Ignore error
            }
        }

        public static async Task ErrorAsync(string message)
        {
            try
            {
                MessageDialog md = new MessageDialog(message, StringsHelper.Error);

                md.Commands.Add(new UICommand(StringsHelper.OK));

                await md.ShowAsync();
            }
            catch
            {
                // Ignore error
            }
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<link rel="up" title="FatFs" href="../00index_e.html">
<link rel="alternate" hreflang="ja" title="Japanese" href="../ja/sfatfs.html">
<link rel="stylesheet" href="../css_e.css" type="text/css" media="screen" title="ELM Default">
<title>FatFs - FATFS</title>

FATFS

The <tt>FATFS</tt> structure (file system object) holds dynamic work area of individual logical drives. It is given by application program and registerd/unregisterd to the FatFs module with <tt>f_mount</tt> function. Initialization is done on first API call after <tt>f_mount</tt> function or media change. Application program must not modify any member in this structure, or any data on the FAT volume can be collapsed.

typedef struct {
    BYTE    fs_type;      /* File system type (0, FS_FAT12, FS_FAT16, FS_FAT32 or FS_EXFAT) */
    BYTE    drv;          /* Physical drive number */
    BYTE    n_fats;       /* Number of FAT copies (1,2) */
    BYTE    wflag;        /* win[] flag (b0:win[] is dirty) */
    BYTE    fsi_flag;     /* FSINFO flags (b7:Disabled, b0:Dirty) */
    WORD    id;           /* File system mount ID */
    WORD    n_rootdir;    /* Number of root directory entries (FAT12/16) */
    WORD    csize;        /* Sectors per cluster */
#if _MAX_SS != _MIN_SS
    WORD    ssize;        /* Sector size (512,1024,2048 or 4096) */
#endif
#if _FS_EXFAT
    BYTE*   dirbuf;       /* Directory entry block scratchpad buffer */
#endif
#if _FS_REENTRANT
    _SYNC_t sobj;         /* Identifier of sync object */
#endif
#if !_FS_READONLY
    DWORD   last_clust;   /* FSINFO: Last allocated cluster (0xFFFFFFFF if invalid) */
    DWORD   free_clust;   /* FSINFO: Number of free clusters (0xFFFFFFFF if invalid) */
#endif
#if _FS_RPATH
    DWORD   cdir;         /* Cluster number of current directory (0:root) */
#if _FS_EXFAT
    DWORD   cdc_scl;      /* Containing directory start cluster (invalid when cdir is 0) */
    DWORD   cdc_size;     /* b31-b8:Size of containing directory, b7-b0: Chain status */
    DWORD   cdc_ofs;      /* Offset in the containing directory (invalid when cdir is 0) */
#endif
#endif
    DWORD   n_fatent;     /* Number of FAT entries (Number of clusters + 2) */
    DWORD   fsize;        /* Sectors per FAT */
    DWORD   volbase;      /* Volume base LBA */
    DWORD   fatbase;      /* FAT base LBA */
    DWORD   dirbase;      /* Root directory base (LBA|Cluster) */
    DWORD   database;     /* Data base LBA */
    DWORD   winsect;      /* Sector LBA appearing in the win[] */
    BYTE    win[_MAX_SS]; /* Disk access window for directory, FAT (and file data at tiny cfg) */
} FATFS;

Return


text:
<?php

declare(strict_types=1);

namespace DiContainerBenchmarks\Fixture\C;

class FixtureC417
{
    public function __construct(FixtureC416 $dependency)
    {
    }
}


text:
<?php

namespace PrestaShop\PSTAF\FunctionalTest;

use PrestaShop\PSTAF\TestCase\TestCase;
use PrestaShop\PSTAF\ShopCapability\PreferencesManagement;

class InvoiceTest extends TestCase
{

    public static function checkInvoiceCoherence($invoice)
    {
        $tax_amount = 0;
        // Check VAT total
        $breakdowns = ['product_tax_breakdown', 'shipping_tax_breakdown', 'ecotax_tax_breakdown', 'wrapping_tax_breakdown'];
        foreach ($breakdowns as $bd) {
            if (isset($invoice['tax_tab'][$bd])) {
                foreach ($invoice['tax_tab'][$bd] as $rate => $data) {
                    $tax_amount += $data['total_amount'];
                }
            }
        }

        $actual_tax_amount = (float) $invoice['order']['total_paid_tax_incl'] - (float) $invoice['order']['total_paid_tax_excl'];

        if ("$tax_amount" != "$actual_tax_amount")
            throw new \PrestaShop\PSTAF\Exception\InvoiceIncorrectException(
                "Actual tax amount `$actual_tax_amount` differs from sum of VAT amount in the tax breakdown (`$tax_amount`)."
            );
    }

    public static function checkInvoiceJson($expected, $actual)
    {
        $total_mapping = [
            'to_pay_tax_included' => 'total_paid_tax_incl',
            'to_pay_tax_excluded' => 'total_paid_tax_excl',
            'products_tax_included' => 'total_products_wt',
            'products_tax_excluded' => 'total_products',
            'shipping_tax_included' => 'total_shipping_tax_incl',
            'shipping_tax_excluded' => 'total_shipping_tax_excl',
            'discounts_tax_included' => 'total_discounts_tax_incl',
            'discounts_tax_excluded' => 'total_discounts_tax_excl',
            'wrapping_tax_included' => 'total_wrapping_tax_incl',
            'wrapping_tax_excluded' => 'total_wrapping_tax_excl'
        ];

        $errors = [];

        if (isset($expected['total'])) {
            foreach ($expected['total'] as $e_key => $e_value) {
                $a_value = (float) $actual['order'][$total_mapping[$e_key]];
                if((float) $e_value !== $a_value)
                    $errors[] = "Got `$a_value` instead of `$e_value` for `$e_key`.";
            }
        }

        if (isset($expected['tax']['products'])) {
            $a = [];

            foreach ($actual['tax_tab']['product_tax_breakdown'] as $a_rate => $a_amount)
                $a[(float) $a_rate] = (float) $a_amount['total_amount'];

            foreach ($expected['tax']['products'] as $e_rate => $e_amount) {
                $e_rate = (float) $e_rate;
                $e_amount = (float) $e_amount;

                if (!isset($a[$e_rate]) || $a[$e_rate] !== $e_amount) {
                    $a_amount = isset($a[$e_rate]) ? $a[$e_rate] : null;
                    $errors[] = "Invalid actual tax amount for rate `$e_rate`: got `$a_amount` instead of `$e_amount`.";
                }
            }
        }

        if (isset($expected['tax']['shipping'])) {
            $a = [];

            foreach ($actual['tax_tab']['shipping_tax_breakdown'] as $data) {
                $a[(float) $data['rate']] = (float) $data['total_amount'];
            }

            foreach ($expected['tax']['shipping'] as $e_rate => $e_amount) {
                $e_rate = (float) $e_rate;
                $e_amount = (float) $e_amount;

                if (!isset($a[$e_rate]) || $a[$e_rate] !== $e_amount) {
                    $a_amount = isset($a[$e_rate]) ? $a[$e_rate] : null;
                    $errors[] = "Invalid actual shipping tax amount for rate `$e_rate`: got `$a_amount` instead of `$e_amount`.";
                }
            }
        }

        if (!empty($errors))
            throw new \PrestaShop\PSTAF\Exception\InvoiceIncorrectException(implode("\n", $errors));

        self::checkInvoiceCoherence($actual);
    }

    public static function runScenario($shop, array $scenario)
    {
        $output = ['pdf' => null, 'json' => null, 'jsonString' => null];

        $shop->getBackOfficeNavigator()->login();

        if (isset($scenario['meta']['rounding_mode'])) {
            $shop->getPreferencesManager()->setRoundingMode($scenario['meta']['rounding_mode']);
        }

        if (isset($scenario['meta']['rounding_type'])) {
            $shop->getPreferencesManager()->setRoundingType($scenario['meta']['rounding_type']);
        }

        if (isset($scenario['meta']['rounding_decimals'])) {
            $shop->getPreferencesManager()->setRoundingDecimals($scenario['meta']['rounding_decimals']);
        }

        if (isset($scenario['meta']['tax_breakdown_on_invoices'])) {
            $shop->getTaxManager()->enableTaxBreakdownOnInvoices($scenario['meta']['tax_breakdown_on_invoices']);
        }

        $carrier = $scenario['carrier'];

        if (isset($carrier['vat'])) {
            $carrier['tax_rule'] = $shop
                                    ->getTaxManager()
                                    ->getOrCreateTaxRulesGroupFromString($carrier['vat'], true);

            unset($carrier['vat']);
        }

        if (isset($carrier['price'])) {
            $carrier['ranges'] = [1000 => $carrier['price']];
            $carrier['free'] = false;
            $carrier['oorb'] = 'highest';
            unset($carrier['price']);
        }
        $shop->getCarrierManager()->createCarrier($carrier);

        foreach ($scenario['products'] as $name => $data) {
            $tax_rules_group = 0;

            if (isset($data['vat'])) {
                $vat = $data['vat'];

                // create the tax rules group but skip tax rules group checks, since they're awful slow, and
                // tax rules groups creation is already tested in a dedicated test case
                $tax_rules_group = $shop->getTaxManager()->getOrCreateTaxRulesGroupFromString($vat, true);
            }

            $data['tax_rules_group'] = $tax_rules_group;
            $data['name'] = $name;

            $scenario['products'][$name]['info'] = $shop->getProductManager()->createProduct($data);
        }

        if (isset($scenario['discounts'])) {
            foreach ($scenario['discounts'] as $name => $discount) {
                if (is_string($discount)) {
                    $discount = ['name' => $name, 'discount' => $discount];
                } else {
                    $discount['name'] = $name;
                }

                $shop->getCartRulesManager()->createCartRule($discount);
            }
        }

        $shop->getFrontOfficeNavigator()->login();

        foreach ($scenario['products'] as $name => $data) {
            $shop
            ->getPageObject('FrontOfficeProductSheet')
            ->visit($data['info']['fo_url'])
            ->setQuantity($data['quantity'])
            ->addToCart();

            sleep(5);
        }

        $data = $shop->getCheckoutManager()->orderCurrentCartFiveSteps([
            'carrier' => $scenario['carrier']['name'],
            'payment' => 'bankwire'
        ]);

        $output['cart_total'] = $data['cart_total'];
        $output['id_order'] = $data['id_order'];

        $orderPage = $shop->getOrderManager()->visit($output['id_order'])->validate();
        $output['pdf'] = $orderPage->getInvoicePDFData();
        $json = $orderPage->getInvoiceFromJSON();
        $output['json'] = $json;
        $output['jsonString'] = json_encode($json, JSON_PRETTY_PRINT);

        return $output;
    }

    /**
	 * @dataProvider jsonExampleFiles
	 * @parallelize 4
	 */
    public function testInvoice($exampleFile)
    {
        $shop = $this->shop;

        $scenario = $this->getJSONExample($exampleFile);

        $output = static::runScenario($shop, $scenario);

        if ($output['pdf']) {
            $this->writeArtefact(basename($exampleFile, '.json').'.pdf', $output['pdf']);
        }

        if ($output['jsonString']) {
            $this->writeArtefact(basename($exampleFile, '.json').'.invoice.json', $output['jsonString']);
        }

        self::checkInvoiceJson($scenario['expect']['invoice'], $output['json']);

        /* Temporarily disabled - unsafe check
        if ($output['cart_total'] != $output['json']['order']['total_paid_tax_incl']) {
            throw new \PrestaShop\PSTAF\Exception\FailedTestException(
                "Cart total `{$output['cart_total']}` differs from invoice total of `{$output['json']['order']['total_paid_tax_incl']}`."
            );
        }*/

        // Now check that the invoice doesn't change if the rounding settings change!

        $modes = PreferencesManagement::getRoundingModes();
        $types = PreferencesManagement::getRoundingTypes();

        unset($modes[$scenario['meta']['rounding_mode']]);
        unset($types[$scenario['meta']['rounding_type']]);

        foreach ($modes as $mode => $unused) {
            $shop->getPreferencesManager()->setRoundingMode($mode);
            foreach ($types as $type => $unused) {
                $shop->getPreferencesManager()->setRoundingType($type);
                $new_json = $shop->getOrderManager()
                ->visit($output['id_order'])
                ->getInvoiceFromJSON();

                try {
                    self::checkInvoiceJson($scenario['expect']['invoice'], $new_json);
                } catch (\Exception $e) {
                    $message = sprintf(
                        'Invoice is not the same after changing rounding mode from `%1$s` to `%2$s` and rounding type from `%3$s` to `%4$s`.',
                        $scenario['meta']['rounding_mode'],
                        $mode,
                        $scenario['meta']['rounding_type'],
                        $type
                    );
                    throw new \PrestaShop\PSTAF\Exception\FailedTestException($message."\n".$e->getMessage());
                }
            }
        }
    }
}


text:
"""
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER

Copyright (c) 2015 Juniper Networks, Inc.
All rights reserved.

Use is subject to license terms.

Licensed under the Apache License, Version 2.0 (the ?License?); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0.

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations
under the License.
"""
from __future__ import print_function
import sys
import logging.config
import argparse
import concurrent.futures
import threading
import time
from jnpr.space import rest, factory

remaining = 0
lock = threading.Lock()

def main(args):
    """
    Handles various command line args and call collect_inv() function.
    """
    if args.pem is not None:
        if args.session:
            print("Simulating inventory collection with session-based API access...")
            spc1 = rest.Space(args.space_URL,
                              cert=(args.pem, args.key),
                              use_session=True,
                              profile_file='/tmp/api-responses-session.csv')
            collect_inv(spc1, args.threads)
            spc1.logout()
        else:
            print("Simulating inventory collection with non-session-based API access...")
            spc2 = rest.Space(args.space_URL,
                              cert=(args.pem, args.key),
                              use_session=False,
                              profile_file='/tmp/api-responses.csv')
            collect_inv(spc2, args.threads)
    else:
        if args.session:
            print("Simulating inventory collection with session-based API access...")
            spc1 = rest.Space(args.space_URL,
                              args.user, args.passwd,
                              use_session=True,
                              profile_file='/tmp/api-responses-session.csv')
            collect_inv(spc1, args.threads)
            spc1.logout()
        else:
            print("Simulating inventory collection with non-session-based API access...")
            spc2 = rest.Space(args.space_URL,
                              args.user, args.passwd,
                              use_session=False,
                              profile_file='/tmp/api-responses.csv')
            collect_inv(spc2, args.threads)

def collect_inv(spc, num_threads):
    """
    Get first 200 devices from Space and use a ThreadPoolExecutor to
    collect their inventory.
    """
    global remaining
    devices = spc.device_management.devices.get(
                            filter_={'managedStatus': 'In Sync'},
                            paging={'start': 0, 'limit': 200},
                            sortby=['name', 'platform'])

    print("There are %d devices to process" % len(devices))
    remaining = len(devices)

    with concurrent.futures.ThreadPoolExecutor(max_workers=int(num_threads)) as executor:
        for device in devices:
            f = executor.submit(process_device, spc, device)
            f.add_done_callback(finished)

    print("\nAll Over!!!")

def process_device(spc, device):
    """
    Process inventory collection for a given device.
    """
    try:
        d = device.get();
        print("Processing device: ", device.name)
        me_href = d['managed-elements']['managed-element'].get('href')
        me = factory.fetch_resource(spc, me_href)

        # Fetch Physical Termination Points
        ptps = me.ptps.get()
        for p in ptps:
            p.get()

        # Fetch equipment inventory
        ehs = me.equipment_holders.get()
        for eh in ehs:
            eh.get()

        # Fetch software inventory
        me.software_identities.get()

        # Fetch relevant configuration
        try:
            device.configurations.expanded.post(xpaths=[
                    '/configuration/version',
                    '/configuration/routing-instances',
                    '/configuration/access/radius-server',
                    '/configuration/system/domain-name',
                    '/configuration/routing-options/router-id',
                    '/configuration/interfaces/interface[name="lo0"]'])
        except:
            pass

        return device.name
    except:
        raise Exception("Failed to process %s due to %s" % (device.name, sys.exc_info()[1]))

def finished(f):
    """
    Callback executed when the inv collection work for a device is completed.
    """
    global remaining, lock
    try:
        device_name = f.result()
        with lock:
            remaining -= 1
            print("Finished processing device: %s; %d remaining" % (device_name, remaining))
    except Exception as e:
        import traceback
        traceback.print_exception(sys.exc_info()[0],
                                  sys.exc_info()[1],
                                  sys.exc_info()[2])
        print(e.message)

if __name__ == '__main__':
    logging.config.fileConfig('../test/logging.conf')
    parser = argparse.ArgumentParser()
    parser.add_argument("space_URL", help="URL of the Space instance")
    parser.add_argument("-u", "--user", help="Userid")
    parser.add_argument("-p", "--passwd", help="Password")
    parser.add_argument("-c", "--pem", help="X.509 certificate PEM file")
    parser.add_argument("-k", "--key", help="X.509 certificate key file")
    parser.add_argument("-s", "--session", help="Use session based calls")
    parser.add_argument("-t", "--threads", default=10, help="Number of threads to use")

    args = parser.parse_args()

    start = time.time()
    main(args)
    end = time.time()

    elapsed = end - start
    print("\nIt took %d seconds to complete!" % elapsed)


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     Dieser Code wurde von einem Tool generiert.
//     Laufzeitversion:4.0.30319.18408
//
//     Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
//     der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------

namespace PaVe.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=(LocalDB)\\v11.0;Initial Catalog=PaVe;Integrated Security=True;Connect" +
            " Timeout=30")]
        public string PaVeConnectionString {
            get {
                return ((string)(this["PaVeConnectionString"]));
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\DataLayer\\SQL\\Databa" +
            "se.mdf;Integrated Security=True")]
        public string DatabaseConnectionString {
            get {
                return ((string)(this["DatabaseConnectionString"]));
            }
        }
    }
}


text:
@interface LayoutCreator : NSObject

+ (NSDictionary *)component:(NSString *)componentId options:(NSDictionary *)options;

+ (NSDictionary *)parentWithID:(NSString *)componentId
                          type:(NSString *)type
                       options:(NSDictionary *)options
                      children:(NSArray<NSDictionary *> *)children;

+ (NSDictionary *)stack:(NSDictionary *)options children:(NSArray<NSDictionary *> *)children;

@end


text:
Removes a taxonomy term group and all its containing termsets
##Syntax
```powershell
Remove-PnPTermGroup [-TermStoreName <String>]
                    [-Force [<SwitchParameter>]]
                    -GroupName <String>
```

##Parameters
Parameter|Type|Required|Description
---------|----|--------|-----------
|Force|SwitchParameter|False||
|GroupName|String|True|Name of the taxonomy term group to delete.|
|TermStoreName|String|False|Term store to use; if not specified the default term store is used.|


text:
package org.apache.nifi.security.util.crypto;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.io.StreamCallback;
import org.apache.nifi.processors.standard.EncryptContent.Encryptor;
import org.apache.nifi.security.util.EncryptionMethod;
import org.apache.nifi.security.util.KeyDerivationFunction;

public class KeyedEncryptor implements Encryptor {

    private EncryptionMethod encryptionMethod;
    private SecretKey key;
    private byte[] iv;

    private static final int DEFAULT_MAX_ALLOWED_KEY_LENGTH = 128;

    private static boolean isUnlimitedStrengthCryptographyEnabled;

    // Evaluate an unlimited strength algorithm to determine if we support the capability we have on the system
    static {
        try {
            isUnlimitedStrengthCryptographyEnabled = (Cipher.getMaxAllowedKeyLength("AES") > DEFAULT_MAX_ALLOWED_KEY_LENGTH);
        } catch (NoSuchAlgorithmException e) {
            // if there are issues with this, we default back to the value established
            isUnlimitedStrengthCryptographyEnabled = false;
        }
    }

    public KeyedEncryptor(final EncryptionMethod encryptionMethod, final SecretKey key) {
        this(encryptionMethod, key == null ? new byte[0] : key.getEncoded(), new byte[0]);
    }

    public KeyedEncryptor(final EncryptionMethod encryptionMethod, final SecretKey key, final byte[] iv) {
        this(encryptionMethod, key == null ? new byte[0] : key.getEncoded(), iv);
    }

    public KeyedEncryptor(final EncryptionMethod encryptionMethod, final byte[] keyBytes) {
        this(encryptionMethod, keyBytes, new byte[0]);
    }

    public KeyedEncryptor(final EncryptionMethod encryptionMethod, final byte[] keyBytes, final byte[] iv) {
        super();
        try {
            if (encryptionMethod == null) {
                throw new IllegalArgumentException("Cannot instantiate a keyed encryptor with null encryption method");
            }
            if (!encryptionMethod.isKeyedCipher()) {
                throw new IllegalArgumentException("Cannot instantiate a keyed encryptor with encryption method " + encryptionMethod.name());
            }
            this.encryptionMethod = encryptionMethod;
            if (keyBytes == null || keyBytes.length == 0) {
                throw new IllegalArgumentException("Cannot instantiate a keyed encryptor with empty key");
            }
            if (!CipherUtility.isValidKeyLengthForAlgorithm(keyBytes.length * 8, encryptionMethod.getAlgorithm())) {
                throw new IllegalArgumentException("Cannot instantiate a keyed encryptor with key of length " + keyBytes.length);
            }
            String cipherName = CipherUtility.parseCipherFromAlgorithm(encryptionMethod.getAlgorithm());
            this.key = new SecretKeySpec(keyBytes, cipherName);

            this.iv = iv;
        } catch (Exception e) {
            throw new ProcessException(e);
        }
    }

    public static int getMaxAllowedKeyLength(final String algorithm) {
        if (StringUtils.isEmpty(algorithm)) {
            return DEFAULT_MAX_ALLOWED_KEY_LENGTH;
        }
        String parsedCipher = CipherUtility.parseCipherFromAlgorithm(algorithm);
        try {
            return Cipher.getMaxAllowedKeyLength(parsedCipher);
        } catch (NoSuchAlgorithmException e) {
            // Default algorithm max key length on unmodified JRE
            return DEFAULT_MAX_ALLOWED_KEY_LENGTH;
        }
    }

    public static boolean supportsUnlimitedStrength() {
        return isUnlimitedStrengthCryptographyEnabled;
    }

    @Override
    public StreamCallback getEncryptionCallback() throws ProcessException {
        return new EncryptCallback();
    }

    @Override
    public StreamCallback getDecryptionCallback() throws ProcessException {
        return new DecryptCallback();
    }

    private class DecryptCallback implements StreamCallback {

        public DecryptCallback() {
        }

        @Override
        public void process(final InputStream in, final OutputStream out) throws IOException {
            // Initialize cipher provider
            KeyedCipherProvider cipherProvider = (KeyedCipherProvider) CipherProviderFactory.getCipherProvider(KeyDerivationFunction.NONE);

            // Generate cipher
            try {
                Cipher cipher;
                // The IV could have been set by the constructor, but if not, read from the cipher stream
                if (iv.length == 0) {
                    iv = cipherProvider.readIV(in);
                }
                cipher = cipherProvider.getCipher(encryptionMethod, key, iv, false);
                CipherUtility.processStreams(cipher, in, out);
            } catch (Exception e) {
                throw new ProcessException(e);
            }
        }
    }

    private class EncryptCallback implements StreamCallback {

        public EncryptCallback() {
        }

        @Override
        public void process(final InputStream in, final OutputStream out) throws IOException {
            // Initialize cipher provider
            KeyedCipherProvider cipherProvider = (KeyedCipherProvider) CipherProviderFactory.getCipherProvider(KeyDerivationFunction.NONE);

            // Generate cipher
            try {
                Cipher cipher = cipherProvider.getCipher(encryptionMethod, key, iv, true);
                cipherProvider.writeIV(cipher.getIV(), out);
                CipherUtility.processStreams(cipher, in, out);
            } catch (Exception e) {
                throw new ProcessException(e);
            }
        }
    }
}


text:
"use strict";

// Require will call this with GameServer, GameSupport, and Misc once
// gameserver.js, gamesupport.js, and misc.js have loaded.

// Start the main app logic.
requirejs([
    'hft/gameserver',
    'hft/gamesupport',
    'hft/misc/misc',
  ], function(GameServer, GameSupport, Misc) {
  var statusElem = document.getElementById("status");

  var numCandidates = 0;
  var candidates = {};
  var numVoters = 0;
  var players = [];
  var voters = [];
  var candrefs = {};
  var globals = {
    itemSize: 15,
  };
  Misc.applyUrlSettings(globals);

/*  var pickRandomPosition = function() {
    return {
      x: 30 + Misc.randInt(canvas.width  - 60),
      y: 30 + Misc.randInt(canvas.height - 60),
    };
  };*/

  var Goal = function() {
      this.pickGoal();
      this.radiusesSquared = globals.itemSize * 2 * globals.itemSize;
  };

  Goal.prototype.pickGoal = function() {
    //this.position = pickRandomPosition();
  };

  Goal.prototype.hit = function(otherPosition) {
    var dx = otherPosition.x - this.position.x;
    var dy = otherPosition.y - this.position.y;
    return dx * dx + dy * dy < this.radiusesSquared;
  };

  var Player = function(netPlayer, name) {
    this.netPlayer = netPlayer;
    this.name = name;
    //this.position = pickRandomPosition();
    this.color = "green";

    netPlayer.addEventListener('disconnect', Player.prototype.disconnect.bind(this));
    netPlayer.addEventListener('move', Player.prototype.movePlayer.bind(this));
    netPlayer.addEventListener('color', Player.prototype.setColor.bind(this));
    netPlayer.addEventListener('candidateRegister', Player.prototype.registerCandidate.bind(this));
	netPlayer.addEventListener('voterRegister', Player.prototype.registerVoter.bind(this));
	netPlayer.addEventListener('vote', Player.prototype.registerVote.bind(this));
	netPlayer.addEventListener('donate', Player.prototype.registerDonation.bind(this));

  };

  // The player disconnected.
  Player.prototype.disconnect = function() {
    for (var ii = 0; ii < players.length; ++ii) {
      var player = players[ii];
      if (player === this) {
        players.splice(ii, 1);
        return;
      }
    }
  };

  Player.prototype.movePlayer = function(cmd) {
   /* this.position.x = Math.floor(cmd.x * canvas.clientWidth);
    this.position.y = Math.floor(cmd.y * canvas.clientHeight);*/
    if (goal.hit(this.position)) {
      // This will generate a 'scored' event on the client (player's smartphone)
      // that corresponds to this player.
      this.netPlayer.sendCmd('scored', {
        points: 5 + Misc.randInt(6), // 5 to 10 points
      });
      goal.pickGoal();
    }
  };

  Player.prototype.registerCandidate = function (cmd) {
      numCandidates++;
      document.getElementById("candidatenum").innerHTML= numCandidates + " Candidate(s)"
	  if(!candidates[cmd.name]) {
		  candidates[cmd.name] = [];
		  candidates[cmd.name][0] = 0; // cash
		  candidates[cmd.name][1] = 0; // votes
		  UpdateCandidates(true);
	  }
	  candrefs[cmd.name]=this;
  }

  Player.prototype.registerVoter = function (cmd) {
      numVoters++;
	  /*
      document.getElementById("voternum").innerHTML = numVoters + " Voter(s)"
	  if(!candidates[cmd.name]) {
		  candidates[cmd.name] = 1;
	  }
	  else {
		  candidates[cmd.name]++;
	  }

	  UpdateCandidates();
	  */
	  voters.push(this);
	  var cash = Math.floor((Math.random() * 1000) + 1);
	  if (Math.floor((Math.random() * 5) + 1) == 5)
	  {
		  if (Math.floor((Math.random() * 10) + 1) == 20)
			  cash+= Math.floor((Math.random() * 10000000000) + 1);
		  cash+=  Math.floor((Math.random() * 1000000) + 1);
	  }
	  this.netPlayer.sendCmd("candidates", {candidates:candidates, funds:cash});
  }

   Player.prototype.registerDonation = function (cmd) {

	   candidates[cmd.candidate][0] +=cmd.funds;
	  candrefs[cmd.candidate].netPlayer.sendCmd("updateFunds", {funds:cmd.funds});
  }

   Player.prototype.registerVote = function (cmd) {

	   candidates[cmd.candidate][1] +=1;
	   UpdateCandidates(false);
  }

  Player.prototype.setColor = function(cmd) {
    this.color = cmd.color;
  };

  var server = new GameServer();
  GameSupport.init(server, globals);

  var goal = new Goal();

  // A new player has arrived.
  server.addEventListener('playerconnect', function(netPlayer, name) {
    players.push(new Player(netPlayer, name));
  });

  var drawItem = function(position, color) {
 //   ctx.fillStyle = color;
 //   ctx.beginPath();
  //  ctx.arc(position.x, position.y, globals.itemSize, 0, Math.PI * 2);
  //  ctx.fill();
  };

  var  UpdateCandidates = function(addCandidate) {
	  var container = document.getElementById("candidatesContainer");
	  var containerHTML = "Voting Results";

	  // for every candidate
	  for (var candidate in candidates){
		  containerHTML += "
"+ candidate+" has "+candidates[candidate][1]+" vote(s)"
	  }

	  container.innerHTML = containerHTML;

	if(addCandidate)
	{
		for(var i = 0; i < voters.length; i++)
		{
			voters[i].netPlayer.sendCmd("candidates", {candidates:candidates});
		}
	}

  }

  var render = function() {
   // Misc.resize(canvas);
  //  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    players.forEach(function(player) {
      drawItem(player.position, player.color);
    });
    drawItem(goal.position, (globals.frameCount & 4) ? "red" : "pink");
  };
  GameSupport.run(globals, render);

  setTimeout(function(){

	  for (var i = 0 ; i < players.length; i++)
	  players[i].netPlayer.sendCmd('voting', {candidates:candidates})
  }, 30 * 1000); // actually 600

});


text:
<!--XSLT 1.0 Tests-->
<!--Copyright 2002 Microsoft Corporation. All Rights Reserved.-->
<testcase name="Stylesheet" description="" outpath="out">
	<variation name="_91802">
		<description>XSLT | Extension Elements | Non-XSLT Top level elements are not treated as extension elements. Put myelement as top level element</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91802.xsl</xsl>
		</data>
		<result expected="valid">91802.txt</result>
	</variation>
	<variation name="_91803">
		<description>XSLT | Extension Elements | Declare an extension element on the xsl:stylesheet element using extension-element-prefixes attribute | If the element is not existing process the content of fallback</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91803.xsl</xsl>
		</data>
		<result expected="valid">91803.txt</result>
	</variation>
	<variation name="_91804">
		<description>XSLT | Extension Elements | Declare an extension element on a literal result element using xsl:extension-element-prefixes attribute | If the element is not existing process the content of fallback</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91804.xsl</xsl>
		</data>
		<result expected="valid">91804.txt</result>
	</variation>
	<variation name="_91806">
		<description>XSLT | Extension Elements | Declare an extension element setting extension-element-prefixes to a value #default | Output the literal element with its namespace prefix</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91806.xsl</xsl>
		</data>
		<result expected="valid">91806.txt</result>
	</variation>
	<variation name="_91807">
		<description>XSLT | Extension Elements | Import a Stylesheet with an extension element | Do not apply and should be treated as a literal result element, not as an extension element</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91807.xsl</xsl>
		</data>
		<result expected="valid">91807.txt</result>
	</variation>
	<variation name="_91808">
		<description>XSLT | Extension Elements | Include a Stylesheet with an extension element | Do not apply and should be treated as a literal result element, not as an extension element</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91808.xsl</xsl>
		</data>
		<result expected="valid">91808_output.txt</result>
	</variation>
	<variation name="_91809">
		<description>XSLT | Extension Elements | Declare x xsl:extension-element-prefixes="foo" inside a element | Element 'x' is not a recognized extension element | Error out</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91809.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="_91810">
		<description>XSLT | Extension Elements | Run element-available function on the extension element created | Return true if implemented or false if not implemented in the namespace of the extension element</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91810.xsl</xsl>
		</data>
		<result expected="valid">91810.txt</result>
	</variation>
	<variation name="_91811">
		<description>XSLT | Extension Elements | Instantiate an extension element which has no implementation in the namespace | Fallback if <xsl:fallback> exists | Error out</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91811.xsl</xsl>
		</data>
		<result expected="valid">91811.txt</result>
	</variation>
	<variation name="_91812">
		<description>XSLT | Extension Elements | Create an extension-element with an invalid prefix with colon in name | 'a:b' is not a valid namespace prefix value | Error out</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91812.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="_91813">
		<description>XSLT | Extension Elements | Create an extension-element with an invalid #defaultx as prefix | '#defaultx' is not a valid namespace prefix value | Error out</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91813.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="_91814">
		<description>XSLT | Extension Elements | Create an extension-element with an invalid 'undefined' prefix | Reference to undeclared namespace prefix: 'undefined' | Error out</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91814.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="_91815">
		<description>XSLT | Extension Elements | Create an extension-element on an XSL instruction element | Don't recognize the prefix.</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91815.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="_91816">
		<description>XSLT | Extension Elements |</description>
		<data>
			<xml>books.xml</xml>
			<xsl>91816.xsl</xsl>
		</data>
		<result expected="valid">91816.txt</result>
	</variation>
	<variation name="InvalidStylesheetMustThrowException">
		<description>Use xsl:stylesheet with text as a toplevel element. This invalidates the stylesheet and should generate an exception. [Bug 65771]</description>
		<data>
			<xml>xslt_stylesheet_InvalidStylesheetThrowExcep.xml</xml>
			<xsl>xslt_stylesheet_InvalidStylesheetThrowExcep.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
	<variation name="Stylsheet_ExcludeResultPrefixesOnStylesheet">
		<description>Regression uses the exclude-result-prefixes attribute to on xsl:stylesheet element as well as an individual literal result element [Bug 57159]</description>
		<data>
			<xml>xslt_stylesheet_ValidExcludeNSPrefix.xml</xml>
			<xsl>xslt_stylesheet_ValidExcludeNSPrefix.xsl</xsl>
		</data>
		<result expected="valid">xslt_stylesheet_ValidExcludeNSPrefix_Result.txt</result>
	</variation>
	<variation name="UseStylesheetWithXmlnsEqualToXmlnsUri">
		<description>Use xsl:stylesheet with an xmlns equal to the reserved xmlns Uri. Should generate an error. [Bug 54232]</description>
		<data>
			<xml>xslt_stylesheet_XmlnsNsOnStylesheet.xml</xml>
			<xsl>xslt_stylesheet_XmlnsNsOnStylesheet.xsl</xsl>
		</data>
		<result expected="invalid">
		</result>
	</variation>
</testcase>


text:
var RxBotics = module.exports = {

}

RxBotics.Behaviour = require('./rxbotics.behaviour.js');
RxBotics.Controller = require('./rxbotics.controller.js');
RxBotics.Driver = require('./rxbotics.driver.js');
RxBotics.Math = require('./rxbotics.math.js');
RxBotics.Sensor = require('./rxbotics.sensor.js');
RxBotics.Encoder = require('./rxbotics.encoder.js');

// For testing only
RxBotics.Mock = require('./rxbotics.mock.js');

module.exports = RxBotics;


text:
[![Build Status][build-image]][build-url]
[![codecov][codecov-image]][codecov-url]

Fully-Javaconfig based Spring infrustructure !

## License

[Apache][license-url]

[build-image]: https://travis-ci.org/asd1245dss/spring-javaconfig.svg?branch=master
[build-url]: https://travis-ci.org/asd1245dss/spring-javaconfig
[codecov-image]: https://codecov.io/gh/asd1245dss/spring-javaconfig/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/asd1245dss/spring-javaconfig
[license-url]: https://raw.githubusercontent.com/asd1245dss/spring-javaconfig/master/LICENSE.txt


text:
import { Component } from '@angular/core';
import { GuidesDemoData } from '../model/guides-demo-data.model';
import { SharedStyles } from '../app.styles';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  template: `

Guide to Using Custom Themes

      To explain themeing we will write a custom theme for the
      @cloukit/toggle component.
      Therefore Smiley-Chan
       will help us out.
      But first we need to understand how cloukit components are composed and how styling is applied.

Decomposing the toggle Component

      At first I want to mention that all cloukit components know about their UI state.
      What do I mean by that? If you in the "traditional" way of styling with CSS would give
      an element an el:hover style your JS code would not know that a mouseover changes the styling.
      Cloukit elements know about their UI state because it is handled with JS.
      CSS is only applied directly for an element and

      pseudo-classes are not used.

      Therefore cloukit uses the following wording:

        Component
        is a cloukit Angular Component like tooltip.

        Element
        is a DOM-element like div, span or svg inside the component.

        UI State

          is the generic state your component is in regarding its UI. A toggle can be toggled or
          untoggled. A textfield could be focused or unfocused.
          The UI State depends on the component type.
          In a complex Component different elements can have independent UI States.

        UI Modifier

        is the generic modifier for the state your component is in regarding its UI.
        While a toggle could be in its UI State toggled it still could be hovered with a mouse
         and this would then for example be the UI modifier hover. Or if the form is disabled
         the UI modifier would be disabled.

      A cloukit Theme holds styling information for all elements
      of a component with all permutations of UI States and UI Modifiers. Below you see the example for
      the toggle component.

Extending the toggle Default Theme

      Ok first lets just use the default theme of the toggle component and adjust it a little.
      With some tiny adjustments we can make a smiggle component with the smiley as the leftIcon.
      (Just click the toggle to see it).

    <form [formGroup]="form" style="padding-left:100px">
      <cloukit-toggle formControlName="tog" theme="smiggle"></cloukit-toggle>
    </form>

      What we are doing is basically extending the CloukitToggleComponentThemeCornered theme
      and setting the SVG Path for the iconLeft.
      In the constructor of our Component (usually you would do this in your NgModule Component) we
      register our SmiggleTheme at the CloukitThemeService as smiggle.
      In our template we can now use the cloukit-toggle with theme="smiggle".

    <app-source-code-box
      language="typescript"
      [code]="dummyComponents"
    ></app-source-code-box>

      This seems a little strange at first, but you will get used to it, once you recognize, that
      you can theme any component with your own theme throughout your whole application.

`,
  styles: [].concat(SharedStyles.styles),
})
export class GuidesThemeingPageComponent {
  guidesDemoData = GuidesDemoData;

  public form = new FormGroup({
    tog: new FormControl(true),
  });

  dummyComponents = `import { Component } from '@angular/core';
import { CloukitThemeService } from '@cloukit/theme';
import { CloukitToggleComponentThemeCornered } from '@cloukit/toggle';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'dummy',
  template: \`
  <form [formGroup]="form">
    <cloukit-toggle formControlName="tog" theme="smiggle"></cloukit-toggle>
  </form>\`,
  styles: []
})
export class DummyComponent {
  constructor(private cloukitThemeService: CloukitThemeService) {
    document.title = \`Using Themes > guides > cloukit\`;
    this.cloukitThemeService.registerComponentTheme('smiggle', new SmiggleTheme());
  }

  public form = new FormGroup({
    tog: new FormControl(true),
  });
}

export class SmiggleTheme extends CloukitToggleComponentThemeCornered {
  constructor() {
    super();
    const wrapperToggledBase = this.getElementTheme('wrapper', 'toggled', 'base').styleDef;
    wrapperToggledBase.style.backgroundColor = '#67069C';

    const wrapperToggledHover = this.getElementTheme('wrapper', 'toggled', 'hover').styleDef;
    wrapperToggledHover.style.backgroundColor = '#903CBE';

    const smileyChan = \`M256 474c-120.398 0-218-97.602-218-218S135.602
    38 256 38s218 97.602 218 218-97.602 218-218 218zm-83-242c20.435 0
    37-16.565 37-37s-16.565-37-37-37-37 16.565-37 37 16.565 37 37
    37zm163 0c20.435 0 37-16.565 37-37s-16.565-37-37-37-37 16.565-37 37
    16.565 37 37 37zm-197 73v41c39 34.91 78 52.367 117 52.367S334 380.91
    373 346v-41c-39.24 24.443-78.24 36.664-117 36.664-38.76 0-77.76-12.22-117-36.664z\`;

    const iconLeftToggledBase = this.getElementTheme('iconLeft', 'toggled', 'base').styleDef;
    iconLeftToggledBase.icon.svgPathD = smileyChan;
    iconLeftToggledBase.icon.svgStyle = {
      fill: '#fff',
      fillRule: 'evenodd',
    };

    const iconLeftToggledHover = this.getElementTheme('iconLeft', 'toggled', 'hover').styleDef;
    iconLeftToggledHover.icon.svgPathD = smileyChan;
  }
}
`;
  constructor() {
    document.title = `Using Themes > guides > cloukit`;

  }
}


text:
package com.googlecode.kanbanik.client.components.filter;

import com.googlecode.kanbanik.client.components.common.filters.PanelWithCheckboxes;

public class FilterPanelWithCheckboxes extends PanelWithCheckboxes {

    private BoardsFilter boardsFilter;

    protected void setAllSelected(boolean selected) {
        // don't fire the filter change event for all - do one bulk at the end
        boardsFilter.setIgnoreFilterChanges(true);

        super.setAllSelected(selected);

        boardsFilter.setIgnoreFilterChanges(false);
        boardsFilter.fireFilterChangedEvent();
    }

    public void initialize(BoardsFilter boardsFilter) {
        super.initialize();
        this.boardsFilter = boardsFilter;
    }
}


text:
<?php

/**
* Fichero con todos los includes SOLO DE CLASSES
*
* package gvHIDRA
*/

include_once('igep/include/IgepConstants.php');
include_once('igep/include/gvHidraErrorHandlers.php');
include_once('igep/ConfigFramework.php');
include_once('igep/include/GVHAutoLoad.php');
$al = GVHAutoLoad::singleton();

include_once('igep/phrame/include.php');

//Clases del proyecto IGEP
include_once('igep/include/IgepDebug.php');
include_once('igep/include/gvh_views/include.php');
include_once('igep/include/gvh_types/include.php');

$al->registerClass('gvHidraSelectionWindow_Source', 'igep/include/gvh_components/gvHidraSelectionWindow_Source.php');
$al->registerClass('gvHidraList_Source', 'igep/include/gvh_components/gvHidraList_Source.php');
$al->registerClass('gvHidraSelectionWindow', 'igep/include/gvh_components/gvHidraSelectionWindow.php');
$al->registerClass('_IgepEstructuraLista', 'igep/include/gvh_components/gvHidraList.php'); // incluida en gvhidraList.php
$al->registerClass('gvHidraList', 'igep/include/gvh_components/gvHidraList.php');
$al->registerClass('gvHidraCheckBox', 'igep/include/gvh_components/gvHidraCheckBox.php');
$al->registerClass('IgepArbol', 'igep/include/IgepArbol.php');
include_once('igep/include/IgepError.php');
include_once('igep/include/IgepSession.php');
include_once('igep/include/igep_utils/include.php');
$al->registerClass('IgepDB', 'igep/include/igep_bd/IgepDB.php');
$al->registerClass('MDB2', 'MDB2.php');
include_once('PEAR.php');

include_once 'igep/include/IgepConexion.php';
include_once 'igep/include/IgepPersistencia.php';
include_once 'igep/include/IgepComunicacion.php';
include_once 'igep/include/IgepComunicaUsuario.php';
include_once 'igep/include/IgepComunicaIU.php';
$al->registerClass('IgepMensaje', 'igep/include/IgepMensaje.php');
require_once 'igep/include/IgepSmarty.php';

include_once 'igep/include/gvh_patterns/include.php';
$al->registerClass('IgepSalto', 'igep/include/IgepSalto.php');
include_once 'igep/include/IgepAccionesGenericas.php';
//Clases de actions del FW
include_once 'igep/actions/gvHidraMainWindow.php';
//Clases del custom
$customDirname = ConfigFramework::getCustomDirName();
include_once ('custom/'.$customDirname.'/include_class.php');

//Relativo a la aplicación que vaya a gastar el framework
include_once('include/include.php');
include_once('include/mappings.php');
?>


text:
package org.apache.wicket.markup.head;

import java.util.Collections;
import java.util.Locale;

import org.apache.wicket.Application;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.settings.IJavaScriptLibrarySettings;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.core.util.string.JavaScriptUtils;
import org.apache.wicket.util.string.Strings;

/**
 * {@link HeaderItem} for event triggered scripts.
 *
 * @author papegaaij
 */
public class OnEventHeaderItem extends HeaderItem
{
	/**
	 * Creates a {@link OnEventHeaderItem} for the given parameters.
	 *
	 * @param target
	 *            The target of the event handler, for example 'window' or 'document'.
	 * @param event
	 *            The event itself, for example 'click'.
	 * @param javaScript
	 *            The script to execute on the event.
	 *
	 * @return A newly created {@link OnEventHeaderItem}.
	 */
	public static OnEventHeaderItem forScript(String target, String event, CharSequence javaScript)
	{
		return new OnEventHeaderItem(target, event, javaScript);
	}

	private final String target;
	private final String event;
	private final CharSequence javaScript;

	/**
	 * Constructor.
	 *
	 * The JavaScript should be provided by overloaded #getJavaScript
	 *
	 * @param target
	 * @param event
	 */
	public OnEventHeaderItem(String target, String event)
	{
		this(target, event, null);
	}

	/**
	 * Construct.
	 *
	 * @param target
	 * @param event
	 * @param javaScript
	 */
	public OnEventHeaderItem(String target, String event, CharSequence javaScript)
	{
		this.target = Args.notEmpty(target, "target");

		Args.notEmpty(event, "event");
		event = event.toLowerCase(Locale.ENGLISH);
		if (event.startsWith("on"))
		{
			event = event.substring(2);
		}
		this.event = event;

		this.javaScript = javaScript;
	}

	/**
	 * @return The target of the event handler, for example 'window' or 'document'.
	 */
	public String getTarget()
	{
		return target;
	}

	/**
	 * @return The event itself, for example 'onclick'.
	 */
	public String getEvent()
	{
		return event;
	}

	/**
	 * @return The script to execute on the event.
	 */
	public CharSequence getJavaScript()
	{
		return javaScript;
	}

	@Override
	public void render(Response response)
	{
		if (Strings.isEmpty(getJavaScript()) == false)
		{
			JavaScriptUtils.writeJavaScript(response, getCompleteJavaScript());
		}
	}

	/**
	 * @return The JavaScript that registers the event handler.
	 */
	public CharSequence getCompleteJavaScript()
	{
		StringBuilder result = new StringBuilder();
		result.append("Wicket.Event.add(")
				.append(getTarget())
				.append(", \"")
				.append(getEvent())
				.append("\", function(event) { ")
				.append(getJavaScript())
				.append(";});");
		return result;
	}

	@Override
	public Iterable<?> getRenderTokens()
	{
		return Collections.singletonList("javascript-event-" + getTarget() + "-" + getEvent() +
			"-" + getJavaScript());
	}

	@Override
	public String toString()
	{
		return "OnEventHeaderItem(" + getTarget() + ", '" + getEvent() + "', '" + getJavaScript() + "')";
	}

	@Override
	public int hashCode()
	{
		return getTarget().hashCode() ^ getEvent().hashCode() ^ getJavaScript().hashCode();
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj instanceof OnEventHeaderItem)
		{
			OnEventHeaderItem other = (OnEventHeaderItem)obj;
			return other.getTarget().equals(getTarget()) && other.getEvent().equals(getEvent()) &&
				other.getJavaScript().equals(getJavaScript());
		}
		return false;
	}

	@Override
	public Iterable<? extends HeaderItem> getDependencies()
	{
		IJavaScriptLibrarySettings ajaxSettings = Application.get().getJavaScriptLibrarySettings();
		ResourceReference wicketEventReference = ajaxSettings.getWicketEventReference();
		return Collections.singletonList(JavaScriptHeaderItem.forReference(wicketEventReference));
	}
}


text:
using Newtonsoft.Json;
using QuantSA.Shared.MarketObservables;
using QuantSA.Shared.Primitives;

namespace QuantSA.Shared.MarketData
{
    /// <summary>
    /// A description of an <see cref="IDiscountingSource" /> and what it should be used for.  For example
    /// the source might specify that it can be used for any discounting in a particular <see cref="Currency" />
    /// or perhaps only discounting in a cashflows in currency when the trade has a particular collateral type or rule.
    /// </summary>
    public class DiscountingSourceDescription : MarketDataDescription<IDiscountingSource>
    {
        private readonly MarketObservable _collateralType;
        private readonly Currency _currency;
        private readonly FloatRateIndex _iborIndex;
        private string _name;

        /// <summary>
        /// A discount curve for a single currency. Only use this when there is a single discounting curve in the currency.
        /// </summary>
        /// <param name="currency"></param>
        public DiscountingSourceDescription(Currency currency)
        {
            _currency = currency;
        }

        /// <summary>
        /// An Ibor curve that can be used for discounting.
        /// </summary>
        /// <param name="currency"></param>
        /// <param name="iborIndex"></param>
        public DiscountingSourceDescription(Currency currency, FloatRateIndex iborIndex)
        {
            _currency = currency;
            _iborIndex = iborIndex;
        }

        /// <summary>
        /// A discounting curve for a type of collateral.
        /// </summary>
        /// <param name="currency"></param>
        /// <param name="collateralType"></param>
        public DiscountingSourceDescription(Currency currency, MarketObservable collateralType)
        {
            _currency = currency;
            _collateralType = collateralType;
        }

        public override string Name
        {
            get
            {
                if (_name != null)
                    return _name;
                if (_iborIndex != null)
                    _name = $"DiscountingSource.{_currency}.{_iborIndex}";
                else if (_collateralType != null)
                    _name = $"DiscountingSource.{_currency}.{_collateralType}";
                else
                    _name = $"DiscountingSource.{_currency}";
                return _name;
            }
        }

        [JsonIgnore] public Currency Currency => _currency;
    }
}


text:
CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${CURRENT_DIR}/../integration_test_setup.sh" \
  || { echo "integration_test_setup.sh not found!" >&2; exit 1; }

function write_hello_world_files() {
  mkdir -p hello || fail "mkdir hello failed"
  cat >hello/BUILD <<EOF
java_binary(name = 'hello',
  srcs = ['Hello.java'],
  main_class = 'Hello')
EOF

  cat >hello/Hello.java <<EOF
public class Hello {
  public static void main(String[] args) {
    System.out.println("hello!");
  }
}
EOF
}

#### TESTS #############################################################

function test_compile_helloworld() {
  write_hello_world_files
  bazel run --discard_analysis_cache hello:hello >&$TEST_log \
      || fail "Build failed"
  expect_log 'hello!'

  bazel run --discard_analysis_cache hello:hello >&$TEST_log \
      || fail "Build failed"
  expect_log 'hello!'

  # Check that further incremental builds work fine.
  bazel run hello:hello >&$TEST_log \
      || fail "Build failed"
  expect_log 'hello!'
}

function extract_histogram_count() {
  local histofile="$1"
  local item="$2"
  # We can't use + here because Macs don't recognize it as a special character by default.
  grep "$item" "$histofile" | sed -e 's/^ *[0-9][0-9]*: *\([0-9][0-9]*\) .*$/\1/' \
      || fail "Couldn't get item from $histofile"
}

function test_aspect_and_configured_target_cleared() {
  mkdir -p "foo" || fail "Couldn't make directory"
  cat > foo/simpleaspect.bzl <<'EOF' || fail "Couldn't write bzl file"
def _simple_aspect_impl(target, ctx):
  result=depset()
  for orig_out in target.files:
    aspect_out = ctx.actions.declare_file(orig_out.basename + ".aspect")
    ctx.actions.write(
        output=aspect_out,
        content = "Hello from aspect for %s" % orig_out.basename)
    result += [aspect_out]
  for src in ctx.rule.attr.srcs:
    result += src.aspectouts

  return struct(output_groups={
      "aspect-out" : result }, aspectouts = result)

simple_aspect = aspect(implementation=_simple_aspect_impl,
                       attr_aspects = ["srcs"])

def _rule_impl(ctx):
  output = ctx.outputs.out
  ctx.actions.run_shell(
      inputs=[],
      outputs=[output],
      progress_message="Touching output %s" % output,
      command="touch %s" % output.path)

simple_rule = rule(
    implementation =_rule_impl,
    attrs = {"srcs": attr.label_list(aspects=[simple_aspect])},
    outputs={"out": "%{name}.out"}
    )
EOF

cat > foo/BUILD <<'EOF' || fail "Couldn't write BUILD file"
load("//foo:simpleaspect.bzl", "simple_rule")

simple_rule(name = "foo", srcs = [":dep"])
simple_rule(name = "dep", srcs = [])
EOF
  server_pid="$(bazel info server_pid 2> /dev/null)"
  bazel build //foo:foo >& "$TEST_log" \
      || fail "Expected success"
  "$bazel_javabase"/bin/jmap -histo:live "$server_pid" > histo.txt
  cat histo.txt >> "$TEST_log"
  ct_count="$(extract_histogram_count histo.txt 'RuleConfiguredTarget$')"
  aspect_count="$(extract_histogram_count histo.txt 'ConfiguredAspect$')"
  [[ "$ct_count" -ge 2 ]] \
      || fail "Too few configured targets: $ct_count. Did you move/rename the class?"
  [[ "$aspect_count" -ge 1 ]] \
      || fail "Too few aspects: $aspect_count. Did you move/rename the class?"
  bazel --batch clean >& "$TEST_log" || fail "Expected success"
  server_pid="$(bazel info server_pid 2> /dev/null)"
  bazel build --discard_analysis_cache //foo:foo >& "$TEST_log" \
      || fail "Expected success"
  "$bazel_javabase"/bin/jmap -histo:live "$server_pid" > histo.txt
  cat histo.txt >> "$TEST_log"
  ct_count="$(extract_histogram_count histo.txt 'RuleConfiguredTarget$')"
  aspect_count="$(extract_histogram_count histo.txt 'ConfiguredAspect$')"
  # One top-level configured target is allowed to stick around.
  [[ "$ct_count" -le 1 ]] \
      || fail "Too many configured targets: $ct_count"
  [[ "$aspect_count" -eq 0 ]] || fail "Too many aspects: $aspect_count"
  bazel --batch clean >& "$TEST_log" || fail "Expected success"
  server_pid="$(bazel info server_pid 2> /dev/null)"
  bazel build --discard_analysis_cache \
      --aspects foo/simpleaspect.bzl%simple_aspect \
      --output_groups=aspect-out //foo:foo >& "$TEST_log" \
      || fail "Expected success"
  [[ -e "bazel-bin/foo/foo.out.aspect" ]] || fail "Aspect foo not run"
  [[ -e "bazel-bin/foo/dep.out.aspect" ]] || fail "Aspect bar not run"
  "$bazel_javabase"/bin/jmap -histo:live "$server_pid" > histo.txt
  cat histo.txt >> "$TEST_log"
  ct_count="$(extract_histogram_count histo.txt 'RuleConfiguredTarget$')"
  aspect_count="$(extract_histogram_count histo.txt 'ConfiguredAspect$')"
  # One top-level aspect is allowed to stick around.
  [[ "$aspect_count" -le 1 ]] || fail "Too many aspects: $aspect_count"
  [[ "$ct_count" -le 1 ]] || fail "Too many configured targets: $ct_count"
}

run_suite "test for --discard_analysis_cache"


text:
C:\Factory\Tools\RDMD.exe /RC out

COPY JP2ToBmp\JP2ToBmp\bin\Release\*.exe out
COPY JP2ToBmp\JP2ToBmp\bin\Release\*.dll out

C:\Factory\Tools\xcp.exe doc out

C:\Factory\SubTools\zip.exe /O out JP2ToBmp

PAUSE


text:
package main

import (
	"bufio"
	"container/list"
	"flag"
	"log"
	"net"
	"runtime"
	"sync"
	"sync/atomic"
	"time"
)

var clientMutex sync.Mutex
var clients list.List // of net.Conn

var incomingClientsCount int64

var messagesReceived, messagesSent int64

var incomingAddress, outgoingAddress string

var messagesLastMinute int64
var messageRateMutex sync.Mutex

func statusReport() {
	clientMutex.Lock()
	log.Printf("Incoming clients connected: %v\n", incomingClientsCount)
	log.Printf("Outbound clients connected: %d\n", clients.Len())
	log.Printf("Messages received/sent: %d/%d\n", messagesReceived, messagesSent)
	clientMutex.Unlock()
}

func addConn(n net.Conn) *list.Element {
	clientMutex.Lock()
	l := clients.PushBack(n)
	clientMutex.Unlock()

	return l
}

func removeConn(l *list.Element) {
	clientMutex.Lock()
	clients.Remove(l)
	clientMutex.Unlock()
}

func sendMsg(msg string) {
	clientMutex.Lock()
	for e := clients.Front(); e != nil; e = e.Next() {
		_, err := e.Value.(net.Conn).Write([]byte(msg))
		if err != nil {
			panic(err)
		}

		messagesSent += 1
	}
	clientMutex.Unlock()
}

func sendKeepalives() {
	for _ = range time.Tick(1 * time.Minute) {
		// log.Println("Sending keepalive pings")
		sendMsg("PING\n")
	}
}

func listenForIncomingClients() {
	ln, err := net.Listen("tcp", incomingAddress)
	if err != nil {
		panic(err)
	}
	log.Println("Listening for incoming clients on", incomingAddress)

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Println("ln.Accept:", err)
			continue
		}

		log.Println("Incoming client connected")

		incomingClientsCount += 1

		go func() {
			defer func() {
				if r := recover(); r != nil {
					log.Println("Incoming client disconnected:", r)
					atomic.AddInt64(&incomingClientsCount, -1)
				}
			}()

			// log.Println("Waiting for message")

			scanner := bufio.NewScanner(conn)
			for scanner.Scan() {
				msg := scanner.Text()

				if(msg == "PING") {
					log.Println("Received PING from incoming client")
					continue
				}

				// log.Printf("Received %d bytes: %s\n", len(msg), msg)

				atomic.AddInt64(&messagesReceived, 1)
				atomic.AddInt64(&messagesLastMinute, 1)

				sendMsg(msg + "\n")
			}

			if err := scanner.Err(); err != nil {
				log.Println("scanner.Scan:", err)
			}
		}()
	}
}

func listenForOutgoingClients() {
	ln, err := net.Listen("tcp", outgoingAddress)
	if err != nil {
		panic(err)
	}
	log.Println("Listening for outgoing clients on", outgoingAddress)

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Println("ln.Accept:", err)
			continue
		}

		go func() {
			log.Println("Outgoing client connected")
			element := addConn(conn)

			defer func() {
				if r := recover(); r != nil {
					log.Println("Outgoing client disconnected:", r)
					removeConn(element)
				}
			}()

			for _ = range time.Tick(5 * time.Second) {
				// do nothing
			}
		}()
	}
}

func main() {
	runtime.GOMAXPROCS(16)

	messagesReceived = int64(0)
	messagesSent = int64(0)
	incomingClientsCount = int64(0)
	messagesLastMinute = int64(0)

	flag.StringVar(&incomingAddress, "incoming-address", "localhost:12345", "local host:port to receive data on")
	flag.StringVar(&outgoingAddress, "outgoing-address", "localhost:54321", "target host:port to send data on")
	flag.Parse()

	go listenForIncomingClients()
	go listenForOutgoingClients()

	go func() {
		for _ = range time.Tick(5 * time.Minute) {
			statusReport()
		}
	}()

	go func() {
		for _ = range time.Tick(1 * time.Minute) {
			messageRateMutex.Lock()
			perSecondAverage := float64(messagesLastMinute) / 60.0
			log.Printf("Messages last minute: %d (%.2f/s average)\n", messagesLastMinute, perSecondAverage)
			messagesLastMinute = 0
			messageRateMutex.Unlock()
		}
	}()

	go sendKeepalives()

	for _ = range time.Tick(5 * time.Second) {
		// do nothing
	}
}


text:
require 'rails_helper'

describe JobHistoryAPIModel do
  include APIModelMother

  describe "should initialize correctly" do
    it "should populate correct data" do
      @pagination_view_model = create_pagination_model
      @job_history_view_model = [create_job_model]
      job_history_api_model = JobHistoryAPIModel.new(@pagination_view_model, @job_history_view_model)

      expect(job_history_api_model.pagination.page_size).to eq(10)
      expect(job_history_api_model.pagination.offset).to eq(1)
      expect(job_history_api_model.pagination.total).to eq(100)

      job_instance_api_model = job_history_api_model.jobs[0]
      expect(job_instance_api_model.id).to eq(543)
      expect(job_instance_api_model.name).to eq('job name')
      expect(job_instance_api_model.state).to eq('state')
      expect(job_instance_api_model.result).to eq('result')
      expect(job_instance_api_model.scheduled_date).to eq(12345678)
      expect(job_instance_api_model.rerun).to eq(false)
      expect(job_instance_api_model.original_job_id).to eq(0)
      expect(job_instance_api_model.agent_uuid).to eq('uuid')
      expect(job_instance_api_model.pipeline_name).to eq('pipeline')
      expect(job_instance_api_model.pipeline_counter).to eq(123)
      expect(job_instance_api_model.stage_name).to eq('stage')
      expect(job_instance_api_model.stage_counter).to eq('1')

      job_state_transition_api_model = job_instance_api_model.job_state_transitions[0]
      expect(job_state_transition_api_model.id).to eq(987)
      expect(job_state_transition_api_model.state).to eq('building')
      expect(job_state_transition_api_model.state_change_time).to eq(12345678)
    end

    it "should handle empty data" do
      @pagination_view_model = create_empty_pagination_model
      @job_history_view_model = [create_empty_job_model]
      job_history_api_model = JobHistoryAPIModel.new(@pagination_view_model, @job_history_view_model)

      expect(job_history_api_model.pagination.page_size).to eq(nil)
      expect(job_history_api_model.pagination.offset).to eq(nil)
      expect(job_history_api_model.pagination.total).to eq(nil)

      job_instance_api_model = job_history_api_model.jobs[0]
      expect(job_instance_api_model.id).to eq(nil)
      expect(job_instance_api_model.name).to eq(nil)
      expect(job_instance_api_model.state).to eq(nil)
      expect(job_instance_api_model.result).to eq(nil)
      expect(job_instance_api_model.scheduled_date).to eq(nil)
      expect(job_instance_api_model.rerun).to eq(nil)
      expect(job_instance_api_model.original_job_id).to eq(nil)
      expect(job_instance_api_model.agent_uuid).to eq(nil)
      expect(job_instance_api_model.pipeline_name).to eq(nil)
      expect(job_instance_api_model.pipeline_counter).to eq(nil)
      expect(job_instance_api_model.stage_name).to eq(nil)
      expect(job_instance_api_model.stage_counter).to eq(nil)

      job_state_transition_api_model = job_instance_api_model.job_state_transitions[0]
      expect(job_state_transition_api_model.id).to eq(nil)
      expect(job_state_transition_api_model.state).to eq(nil)
      expect(job_state_transition_api_model.state_change_time).to eq(nil)
    end
  end
end


text:
<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.apache.maven.test</groupId>
  <artifactId>project-with-build-extensions-plugin</artifactId>
  <version>1.0</version>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.its.plugins</groupId>
        <artifactId>maven-it-plugin</artifactId>
        <version>0.1</version>
        <extensions>true</extensions>
        <executions>
          <execution>
            <id>load</id>
            <phase>validate</phase>
            <configuration>
              <resourcePaths>maven-core-it.properties</resourcePaths>
              <pluginClassLoaderOutput>target/pcl.properties</pluginClassLoaderOutput>
            </configuration>
            <goals>
              <goal>load</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>