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

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    /// <summary>
    /// Abstract base class for mutable and immutable type maps.
    /// </summary>
    internal abstract class AbstractTypeMap
    {
        /// <summary>
        /// Substitute for a type declaration.  May use alpha renaming if the container is substituted.
        /// </summary>
        private NamedTypeSymbol SubstituteMemberType(NamedTypeSymbol previous)
        {
            Debug.Assert((object)previous.ConstructedFrom == (object)previous);

            NamedTypeSymbol newContainingType = SubstituteNamedType(previous.ContainingType);
            if ((object)newContainingType == null)
            {
                return previous;
            }

            return previous.OriginalDefinition.AsMember(newContainingType);
        }

        /// <summary>
        /// SubstType, but for NamedTypeSymbols only.  This is used for concrete types, so no alpha substitution appears in the result.
        /// </summary>
        internal NamedTypeSymbol SubstituteNamedType(NamedTypeSymbol previous)
        {
            if (ReferenceEquals(previous, null))
                return null;

            if (previous.IsUnboundGenericType)
                return previous;

            if (previous.IsAnonymousType)
            {
                ImmutableArray<TypeSymbol> oldFieldTypes = AnonymousTypeManager.GetAnonymousTypePropertyTypes(previous);
                ImmutableArray<TypeSymbol> newFieldTypes = SubstituteTypes(oldFieldTypes);
                return (oldFieldTypes == newFieldTypes) ? previous : AnonymousTypeManager.ConstructAnonymousTypeSymbol(previous, newFieldTypes);
            }

            // TODO: we could construct the result's ConstructedFrom lazily by using a "deep"
            // construct operation here (as VB does), thereby avoiding alpha renaming in most cases.
            // Aleksey has shown that would reduce GC pressure if substitutions of deeply nested generics are common.
            NamedTypeSymbol oldConstructedFrom = previous.ConstructedFrom;
            NamedTypeSymbol newConstructedFrom = SubstituteMemberType(oldConstructedFrom);

            ImmutableArray<TypeSymbol> oldTypeArguments = previous.TypeArgumentsNoUseSiteDiagnostics;
            ImmutableArray<TypeSymbol> newTypeArguments = SubstituteTypes(oldTypeArguments);

            if (ReferenceEquals(oldConstructedFrom, newConstructedFrom) && oldTypeArguments == newTypeArguments)
            {
                return previous;
            }

            return newConstructedFrom.ConstructIfGeneric(newTypeArguments);
        }

        /// <summary>
        /// Perform the substitution on the given type.  Each occurrence of the type parameter is
        /// replaced with its corresponding type argument from the map.
        /// </summary>
        /// <param name="previous">The type to be rewritten.</param>
        /// <returns>The type with type parameters replaced with the type arguments.</returns>
        internal TypeSymbol SubstituteType(TypeSymbol previous)
        {
            if (ReferenceEquals(previous, null))
                return null;

            switch (previous.Kind)
            {
                case SymbolKind.NamedType:
                    return SubstituteNamedType((NamedTypeSymbol)previous);
                case SymbolKind.TypeParameter:
                    return SubstituteTypeParameter((TypeParameterSymbol)previous);
                case SymbolKind.ArrayType:
                    return SubstituteArrayType((ArrayTypeSymbol)previous);
                case SymbolKind.PointerType:
                    return SubstitutePointerType((PointerTypeSymbol)previous);
                case SymbolKind.DynamicType:
                    return SubstituteDynamicType();
                case SymbolKind.ErrorType:
                    return ((ErrorTypeSymbol)previous).Substitute(this);
                default:
                    return previous;
            }
        }

        protected virtual TypeSymbol SubstituteDynamicType()
        {
            return DynamicTypeSymbol.Instance;
        }

        protected virtual TypeSymbol SubstituteTypeParameter(TypeParameterSymbol typeParameter)
        {
            return typeParameter;
        }

        private ArrayTypeSymbol SubstituteArrayType(ArrayTypeSymbol t)
        {
            TypeSymbol element = SubstituteType(t.ElementType);
            if (ReferenceEquals(element, t.ElementType))
            {
                return t;
            }

            ImmutableArray<NamedTypeSymbol> interfaces = t.InterfacesNoUseSiteDiagnostics();
            Debug.Assert(0 <= interfaces.Length && interfaces.Length <= 2);

            if (interfaces.Length == 1)
            {
                Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T>
                interfaces = ImmutableArray.Create<NamedTypeSymbol>((NamedTypeSymbol)SubstituteType(interfaces[0]));
            }
            else if (interfaces.Length == 2)
            {
                Debug.Assert(interfaces[0] is NamedTypeSymbol); // IList<T>
                interfaces = ImmutableArray.Create<NamedTypeSymbol>((NamedTypeSymbol)SubstituteType(interfaces[0]), (NamedTypeSymbol)SubstituteType(interfaces[1]));
            }

            return new ArrayTypeSymbol(
                element,
                t.Rank,
                t.BaseTypeNoUseSiteDiagnostics,
                interfaces,
                t.CustomModifiers);
        }

        private PointerTypeSymbol SubstitutePointerType(PointerTypeSymbol t)
        {
            TypeSymbol pointedAtType = SubstituteType(t.PointedAtType);
            if (ReferenceEquals(pointedAtType, t.PointedAtType))
            {
                return t;
            }

            return new PointerTypeSymbol(pointedAtType, t.CustomModifiers);
        }

        internal ImmutableArray<TypeSymbol> SubstituteTypes(ImmutableArray<TypeSymbol> original)
        {
            if (original.IsDefault)
            {
                return original;
            }

            TypeSymbol[] result = null;

            for (int i = 0; i < original.Length; i++)
            {
                var t = original[i];
                var substituted = SubstituteType(t);
                if (!Object.ReferenceEquals(substituted, t))
                {
                    if (result == null)
                    {
                        result = new TypeSymbol[original.Length];
                        for (int j = 0; j < i; j++)
                        {
                            result[j] = original[j];
                        }
                    }
                }

                if (result != null)
                {
                    result[i] = substituted;
                }
            }

            return result != null ? result.AsImmutableOrNull() : original;
        }

        /// <summary>
        /// Substitute types, and return the results without duplicates, preserving the original order.
        /// </summary>
        internal void SubstituteTypesDistinct(ImmutableArray<TypeSymbol> original, ArrayBuilder<TypeSymbol> result)
        {
            if (original.Length == 0)
            {
                return;
            }
            else if (original.Length == 1)
            {
                result.Add(SubstituteType(original[0]));
            }
            else
            {
                var set = new HashSet<TypeSymbol>();
                foreach (var type in original)
                {
                    var substituted = SubstituteType(type);
                    if (set.Add(substituted))
                    {
                        result.Add(substituted);
                    }
                }
            }
        }

        internal ImmutableArray<TypeParameterSymbol> SubstituteTypeParameters(ImmutableArray<TypeParameterSymbol> original)
        {
            return original.SelectAsArray((tp, m) => (TypeParameterSymbol)m.SubstituteTypeParameter(tp), this);
        }

        /// <summary>
        /// Like SubstTypes, but for NamedTypeSymbols.
        /// </summary>
        internal ImmutableArray<NamedTypeSymbol> SubstituteNamedTypes(ImmutableArray<NamedTypeSymbol> original)
        {
            NamedTypeSymbol[] result = null;

            for (int i = 0; i < original.Length; i++)
            {
                var t = original[i];
                var substituted = SubstituteNamedType(t);
                if (!Object.ReferenceEquals(substituted, t))
                {
                    if (result == null)
                    {
                        result = new NamedTypeSymbol[original.Length];
                        for (int j = 0; j < i; j++)
                        {
                            result[j] = original[j];
                        }
                    }
                }

                if (result != null)
                {
                    result[i] = substituted;
                }
            }

            return result != null ? result.AsImmutableOrNull() : original;
        }
    }
}


text:
header{
   margin:0px;
   background-color:cadetblue;
   padding: 55px;
   font-weight:bolder;
   font-family:  sans-serif, 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', 'Geneva', Verdana;
   border-radius:0px;
   color:whitesmoke;
}

#container-table{
    margin:10px;
}
section{
    background-color: lightgray;
    margin:0px;

}

body{
    background-color: lightgray;
    margin:10px;
}

table, thead, tbody, th, tr, td{
     border:1px solid;
     text-align: center;
 }

#tbl{
    margin: 50px 10px;

 }

 #btn{
     margin:8px;
 }

 ol{
     margin:10px;
 }

redpajama_set_name: RedPajamaGithub


text:
extern llvm::cl::OptionCategory SlicingOpts;

// Object representing options for slicer
struct SlicerOptions {
    dg::llvmdg::LLVMDependenceGraphOptions dgOptions{};

    // FIXME: get rid of this once we got the secondary SC
    std::vector<std::string> additionalSlicingCriteria{};

    // bodies of these functions will not be sliced
    std::vector<std::string> preservedFunctions{};

    // slice away also the slicing criteria nodes
    // (if they are not dependent on themselves)
    bool removeSlicingCriteria{false};

    // do we perform forward slicing?
    bool forwardSlicing{false};

    // string describing the slicing criteria
    std::string slicingCriteria{};
    // SC string in the old format
    std::string legacySlicingCriteria{};
    // legacy secondary SC
    std::string legacySecondarySlicingCriteria{};

    std::string inputFile{};
    std::string outputFile{};
};

///
// Return filled SlicerOptions structure.
SlicerOptions parseSlicerOptions(int argc, char *argv[],
                                 bool requireCrit = false,
                                 bool inputFileRequired = true);

std::vector<const llvm::Value *>
getSlicingCriteriaValues(llvm::Module &M, const std::string &slicingCriteria,
                         const std::string &legacyslicingCriteria,
                         const std::string &legacySecondaryCriteria,
                         bool criteria_are_next_instr = false);

bool getSlicingCriteriaNodes(dg::LLVMDependenceGraph &dg,
                             const std::string &slicingCriteria,
                             const std::string &legacySlicingCriteria,
                             const std::string &legacySecondarySlicingCriteria,
                             std::set<dg::LLVMNode *> &criteria_nodes,
                             bool criteria_are_next_instr = false);

#endif // DG_TOOLS_LLVM_SLICER_OPTS_H_


text:
require 'mkalias/version'
require 'set'

# Module to manage alias
module Mkalias
  module_function

  SIGNAL_NAME = 'USR1'.freeze
  BASHRC_PATH = "#{File.expand_path('~')}/.bashrc".freeze

  def new_alias(alias_name, commands, file_path = BASHRC_PATH)
    alias_names = Mkalias.list_alias(file_path)
    return false if alias_names.include?(alias_name)

    commands = Mkalias.prepare_commands(commands)

    function_name = "mkalias_#{alias_name}"
    bash_function = "function #{function_name}(){ #{commands}; }"
    bash_alias = "alias #{alias_name}='#{function_name}'"

    open(file_path, 'a') do |file|
      file.puts("\n#{bash_alias}\n#{bash_function}")
    end

    true
  end

  def list_alias(file_path = BASHRC_PATH)
    alias_regex = /mkalias_(.*?)\(/

    file_text = File.open(file_path, &:read)
    alias_names = file_text.scan(alias_regex).flatten

    alias_names
  end

  def show_alias(alias_names, file_path = BASHRC_PATH)
    alias_names = [alias_names] unless alias_names.is_a?(Array)

    alias_commands = {}
    alias_names.each do |alias_name|
      alias_commands[alias_name] = Mkalias.get_alias_command(alias_name,
                                                             file_path)
    end

    alias_commands.select! { |_, value| !value.nil? }
    alias_commands
  end

  def remove_alias(alias_names, file_path = BASHRC_PATH)
    alias_names = [alias_names] unless alias_names.is_a?(Array)

    removed_alias = []
    alias_names.each do |alias_name|
      removed = Mkalias.remove_one_alias(alias_name, file_path)
      removed_alias << alias_name if removed
    end

    removed_alias
  end

  def add_signal(file_path = BASHRC_PATH)
    return false if Mkalias.signal?(file_path)

    trap_command = "trap 'source #{file_path}' #{SIGNAL_NAME}"
    open(file_path, 'a') do |file|
      file.puts("\n")
      file.puts(trap_command)
    end

    true
  end

  def remove_signal(file_path = BASHRC_PATH)
    return false unless signal?(file_path)

    trap_regex = /\btrap\s'source\s(.*)\sUSR1/

    lines = File.readlines(file_path).reject { |line| line =~ trap_regex }
    File.open(file_path, 'w') { |f| lines.each { |line| f.puts line } }

    true
  end

  def signal?(file_path = BASHRC_PATH)
    trap_regex = /\btrap\s'source\s(.*)\sUSR1/
    !File.foreach(file_path).grep(trap_regex).empty?
  end

  def get_alias_command(alias_name, file_path = BASHRC_PATH)
    alias_names = Mkalias.list_alias(file_path)
    return nil unless alias_names.include?(alias_name)

    command_regex = /mkalias_#{alias_name}\(\)[{](.+)[;]/

    file_text = File.open(file_path, &:read)
    commands = file_text.scan(command_regex).flatten.first
    commands = commands.split(';').each(&:strip!) if commands

    commands
  end

  def remove_one_alias(alias_name, file_path = BASHRC_PATH)
    alias_names = Mkalias.list_alias(file_path)
    return false unless alias_names.include?(alias_name)

    alias_regex = /\bmkalias_#{alias_name}[(']/

    lines = File.readlines(file_path).reject { |line| line =~ alias_regex }

    File.open(file_path, 'w') { |f| lines.each { |line| f.puts line } }
  end

  def prepare_commands(commands)
    commands = commands.join('; ') if commands.is_a?(Array)
    unless commands.include?(';') || commands.include?('#')
      commands = "#{commands} $@"
    end
    commands = commands.tr('#', '$')

    commands
  end
end


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>MNE-CPP: D:/Users/Christoph/GitHub/mne-cpp/applications/mne_x_libs/xDisp/helpers/frequencyspectrumsettingswidget.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

MNE-CPP
    beta 1.0

Main Page

Related Pages

Modules

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

applications

mne_x_libs

xDisp

helpers

frequencyspectrumsettingswidget.h

Go to the documentation of this file.

    1 //=============================================================================================================

   36 #ifndef FREQUENCYSPECTRUMSETTINGSWIDGET_H

   37 #define FREQUENCYSPECTRUMSETTINGSWIDGET_H

   38

   39 //*************************************************************************************************************

   40 //=============================================================================================================

   41 // INCLUDES

   42 //=============================================================================================================

   43

   44

   45

   46 //*************************************************************************************************************

   47 //=============================================================================================================

   48 // QT INCLUDES

   49 //=============================================================================================================

   50

   51 #include <QWidget>

   52 #include <QSlider>

   53

   54

   55 //*************************************************************************************************************

   56 //=============================================================================================================

   57 // DEFINE NAMESPACE XDISPLIB

   58 //=============================================================================================================

   59

   60 namespace XDISPLIB

   61 {

   62

   63

   64 //*************************************************************************************************************

   65 //=============================================================================================================

   66 // FORWARD DECLARATIONS

   67 //=============================================================================================================

   68

   69 class FrequencySpectrumWidget;

   70

   71

   72 //=============================================================================================================

   78 class FrequencySpectrumSettingsWidget : public QWidget

   79 {

   80     Q_OBJECT

   81

   82     friend class FrequencySpectrumWidget;

   83

   84 public:

   85     //=========================================================================================================

   91     FrequencySpectrumSettingsWidget(FrequencySpectrumWidget *toolbox);

   92

   93     //=========================================================================================================

   99     void updateValue(qint32 value);

  100

  101 signals:

  102     void settingsChanged();

  103

  104 private:

  105     FrequencySpectrumWidget * m_pFrequencySpectrumWidget;

  107     QSlider* m_pSliderLowerBound;

  108     QSlider* m_pSliderUpperBound;

  109 };

  110

  111 } // NAMESPACE

  112

  113 #endif // FREQUENCYSPECTRUMSETTINGSWIDGET_H

XDISPLIB::FrequencySpectrumSettingsWidget::updateValue

void updateValue(qint32 value)

Definition: frequencyspectrumsettingswidget.cpp:104

XDISPLIB::FrequencySpectrumSettingsWidget::FrequencySpectrumSettingsWidget

FrequencySpectrumSettingsWidget(FrequencySpectrumWidget *toolbox)

Definition: frequencyspectrumsettingswidget.cpp:70

XDISPLIB::FrequencySpectrumSettingsWidget

The FrequencySpectrumWidget class provides the settings widget.

Definition: frequencyspectrumsettingswidget.h:78

XDISPLIB

Definition: frequencyspectrumwidget.h:82

XDISPLIB::FrequencySpectrumWidget

The FrequencySpectrumWidget class provides a equalizer display.

Definition: frequencyspectrumwidget.h:121

<address class="footer">
Generated on Fri Mar 27 2015 22:54:29 for MNE-CPP by

 1.8.9.1
</address>


text:
package opus.gwt.management.console.client.overlays;

import com.google.gwt.core.client.JavaScriptObject;

public class DependencyData extends JavaScriptObject {                              // [1]
  // Overlay types always have protected, zero argument constructors.
  protected DependencyData() {}                                              // [2]

  // JSNI methods to get stock data.
  public final native String getName() /*-{ return this.name; }-*/; // [3]
  public final native String getVersion() /*-{ return this.version_number; }-*/;

}


text:
/**
 */
package anyfeatureadapted.impl;

import anyfeatureadapted.AnyfeatureadaptedPackage;
import anyfeatureadapted.Element1;
import anyfeatureadapted.Properties;
import anyfeatureadapted.RootElementType;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

/**
 *
 * An implementation of the model object 'Root Element Type'.
 *
 *

 * The following features are implemented:
 *

 *
{@link anyfeatureadapted.impl.RootElementTypeImpl#getElement1 Element1}

 *
{@link anyfeatureadapted.impl.RootElementTypeImpl#getProperties Properties}

 *

 *

 *
 * @generated
 */
public class RootElementTypeImpl extends MinimalEObjectImpl.Container implements RootElementType {
	/**
	 * The cached value of the '{@link #getElement1() Element1}' containment reference.
	 *
	 *
	 * @see #getElement1()
	 * @generated
	 * @ordered
	 */
	protected Element1 element1;

	/**
	 * The cached value of the '{@link #getProperties() Properties}' containment reference.
	 *
	 *
	 * @see #getProperties()
	 * @generated
	 * @ordered
	 */
	protected Properties properties;

	/**
	 *
	 *
	 * @generated
	 */
	protected RootElementTypeImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return AnyfeatureadaptedPackage.Literals.ROOT_ELEMENT_TYPE;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Element1 getElement1() {
		return element1;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetElement1(Element1 newElement1, NotificationChain msgs) {
		Element1 oldElement1 = element1;
		element1 = newElement1;
		if (eNotificationRequired()) {
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1, oldElement1, newElement1);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setElement1(Element1 newElement1) {
		if (newElement1 != element1) {
			NotificationChain msgs = null;
			if (element1 != null)
				msgs = ((InternalEObject)element1).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1, null, msgs);
			if (newElement1 != null)
				msgs = ((InternalEObject)newElement1).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1, null, msgs);
			msgs = basicSetElement1(newElement1, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1, newElement1, newElement1));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Properties getProperties() {
		return properties;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetProperties(Properties newProperties, NotificationChain msgs) {
		Properties oldProperties = properties;
		properties = newProperties;
		if (eNotificationRequired()) {
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES, oldProperties, newProperties);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setProperties(Properties newProperties) {
		if (newProperties != properties) {
			NotificationChain msgs = null;
			if (properties != null)
				msgs = ((InternalEObject)properties).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES, null, msgs);
			if (newProperties != null)
				msgs = ((InternalEObject)newProperties).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES, null, msgs);
			msgs = basicSetProperties(newProperties, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES, newProperties, newProperties));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1:
				return basicSetElement1(null, msgs);
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES:
				return basicSetProperties(null, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1:
				return getElement1();
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES:
				return getProperties();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1:
				setElement1((Element1)newValue);
				return;
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES:
				setProperties((Properties)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1:
				setElement1((Element1)null);
				return;
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES:
				setProperties((Properties)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__ELEMENT1:
				return element1 != null;
			case AnyfeatureadaptedPackage.ROOT_ELEMENT_TYPE__PROPERTIES:
				return properties != null;
		}
		return super.eIsSet(featureID);
	}

} //RootElementTypeImpl


text:
package hwo.kurjatturskat.core.message;

public class MessageCarData extends CarIdentifier {

    public final String gameId;
    public final int gameTick;

    public MessageCarData(String name, String color, String gameId, int gameTick) {
        super(name, color);
        this.gameId = gameId;
        this.gameTick = gameTick;
    }
}


text:
Backgrid.Extensions
====================

### Table column class

```javascript

columns: [
    {
        className: "name-col",
        name: 'name',
        cell: 'string'
    }
]

```

### Cell handler function

```javascript

columns: [
    {
        name: 'name',
        cell: 'string',
        handler: function (model, cell) {
            var highlight = model.get("highlight");
            if (highlight) {
                cell.addClass("HighlightCell");
            }
        }
    }
]

```

### HTML Cell

```javascript

columns: [
    {
        label: "",
        name: 'Id',
        cell: 'html',
        editable: false,
        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
            fromRaw: function (rawValue, model) {
                return "<a href='#products/" + rawValue + "' >Details</a>";
            }
        })
    }
]

```

### Dropdown Cell

```javascript

columns: [
    {
        name: 'Type',
        cell: 'dropdown',
        editable: false,
        formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
            fromRaw: function(rawValue, model) {
                return '<select class="form-control">' +
                    '<option>String</option>' +
                    '<option>Int</option>' +
                    '<option>Double</option>' +
                    '<option>Decimal</option>' +
                    '<option>DateTime</option>' +
                    '<option>Bool</option>' +
                    '</select>';
            },
            toRaw: function($select) {
                return $select.val();
            }
        })
    }
]

```


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Collections;
using System.Diagnostics.CodeAnalysis;

namespace Squidex.Infrastructure.Collections;

public class ReadonlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>, IEquatable<ReadonlyDictionary<TKey, TValue>> where TKey : notnull
{
    private static readonly Dictionary<TKey, TValue> EmptyInner = new Dictionary<TKey, TValue>();
    private readonly IDictionary<TKey, TValue> inner;

    public TValue this[TKey key]
    {
        get
        {
            if (!TryGetValue(key, out var value))
            {
                throw new KeyNotFoundException();
            }

            return value;
        }
    }

    public IEnumerable<TKey> Keys
    {
        get => inner.Keys;
    }

    public IEnumerable<TValue> Values
    {
        get => inner.Values;
    }

    public int Count
    {
        get => inner.Count;
    }

    public ReadonlyDictionary()
        : this(EmptyInner)
    {
    }

    public ReadonlyDictionary(IDictionary<TKey, TValue> inner)
    {
        Guard.NotNull(inner);

        this.inner = inner;
    }

    public bool ContainsKey(TKey key)
    {
        return inner.ContainsKey(key);
    }

    public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
    {
        return inner.TryGetValue(key, out value);
    }

    IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
    {
        return GetEnumerable(inner).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return inner.GetEnumerator();
    }

    private static IEnumerable<TItem> GetEnumerable<TItem>(IEnumerable<TItem> collection)
    {
        return collection;
    }

    public override bool Equals(object? obj)
    {
        return Equals(obj as ReadonlyDictionary<TKey, TValue>);
    }

    public bool Equals(ReadonlyDictionary<TKey, TValue>? other)
    {
        return this.EqualsDictionary(other);
    }

    public override int GetHashCode()
    {
        return this.DictionaryHashCode();
    }
}


text:
package com.RSen.Commandr.builtincommands;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

import com.RSen.Commandr.R;

public class RootCommandActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final String[] commands = getIntent().getStringArrayExtra("command");
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Process proc = Runtime.getRuntime().exec(commands);
                    proc.waitFor();
                } catch (Exception ex) {
                    (RootCommandActivity.this).runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(RootCommandActivity.this, getString(R.string.root_command_failed), Toast.LENGTH_SHORT).show();
                        }
                    });
                    ex.printStackTrace();
                }
                (RootCommandActivity.this).runOnUiThread(new Runnable() {
                    public void run() {
                        finish();
                    }
                });
            }
        }, "RestartNowRootOnly ").start();

    }

}


text:
/**
 * @fileoverview Rule to check multiple var declarations per line
 * @author Alberto Rodríguez
 */
"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "require or disallow newlines around variable declarations",
            recommended: false,
            url: "https://eslint.org/docs/rules/one-var-declaration-per-line"
        },

        schema: [
            {
                enum: ["always", "initializations"]
            }
        ],

        fixable: "whitespace",

        messages: {
            expectVarOnNewline: "Expected variable declaration to be on a new line."
        }
    },

    create(context) {

        const always = context.options[0] === "always";

        //--------------------------------------------------------------------------
        // Helpers
        //--------------------------------------------------------------------------

        /**
         * Determine if provided keyword is a variant of for specifiers
         * @private
         * @param {string} keyword keyword to test
         * @returns {boolean} True if `keyword` is a variant of for specifier
         */
        function isForTypeSpecifier(keyword) {
            return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement";
        }

        /**
         * Checks newlines around variable declarations.
         * @private
         * @param {ASTNode} node `VariableDeclaration` node to test
         * @returns {void}
         */
        function checkForNewLine(node) {
            if (isForTypeSpecifier(node.parent.type)) {
                return;
            }

            const declarations = node.declarations;
            let prev;

            declarations.forEach(current => {
                if (prev && prev.loc.end.line === current.loc.start.line) {
                    if (always || prev.init || current.init) {
                        context.report({
                            node,
                            messageId: "expectVarOnNewline",
                            loc: current.loc,
                            fix: fixer => fixer.insertTextBefore(current, "\n")
                        });
                    }
                }
                prev = current;
            });
        }

        //--------------------------------------------------------------------------
        // Public
        //--------------------------------------------------------------------------

        return {
            VariableDeclaration: checkForNewLine
        };

    }
};


text:
<?php

namespace AppBundle;

use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class AppBundle extends Bundle
{
    public function __construct()
    {
        AnnotationReader::addGlobalIgnoredName('ODM\Collection');
        AnnotationReader::addGlobalIgnoredName('ODM\Field');
    }
}


text:
'''
The MIT License (MIT)
Copyright (c) 2016 Nordeus LLC

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.
'''
import time
import os

from pushkin.sender.nordifier import constants
from pushkin import config, context
from collections import defaultdict

from pushkin.database import model
from sqlalchemy.orm import sessionmaker, contains_eager
from sqlalchemy import create_engine, func, text, update, bindparam, and_, pool

import psycopg2 as dbapi2
import psycopg2.extras

from alembic.config import Config as AlembicConfig
from alembic import command as alembic_command
from alembic.script import ScriptDirectory as AlembicScriptDirectory
from alembic.migration import MigrationContext as AlembicMigrationContext
from pushkin.sender.nordifier.gcm_push_sender import GCM2
from contextlib import contextmanager

"""Module containing database wrapper calls."""

ENGINE = None
SESSION = None
ALEMBIC_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'alembic.ini')

def init_db():
    global ENGINE
    global SESSION
    if ENGINE is None:
        ENGINE = create_engine(config.sqlalchemy_url, poolclass=pool.NullPool)

def create_database():
    """Create database by executing db_create.sql"""
    db_create_sql_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'db_create.sql')
    with open(db_create_sql_path, 'r') as fd:
        sql_create_commands = fd.read()
        ENGINE.execute(sql_create_commands)
        ENGINE.execute(text("INSERT INTO alembic_version VALUES (:version_num)"), {"version_num": get_head_revision()})

def upgrade_database():
    alembic_cfg = AlembicConfig(ALEMBIC_CONFIG)
    alembic_command.upgrade(alembic_cfg, "head")

def get_head_revision():
    alembic_cfg = AlembicConfig(ALEMBIC_CONFIG)
    script = AlembicScriptDirectory.from_config(alembic_cfg)
    head_revision = script.get_current_head()
    return head_revision

def get_current_revision():
    alembic_context = AlembicMigrationContext.configure(ENGINE.connect())
    current_revision = alembic_context.get_current_revision()
    return current_revision

def execute_query(query):
    '''
    Execute a specific query.
    '''
    with dbapi2.connect('host={db_host} user={db_user} password={db_pass} port={db_port} dbname={db_name}'.format(
            db_host=config.db_host, db_port=config.db_port, db_user=config.db_user, db_pass=config.db_pass, db_name=config.db_name)) as conn:
        with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
            cur.execute(query)

def execute_query_with_results(query):
    '''
    Execute a specific query and return results.
    '''
    with dbapi2.connect('host={db_host} user={db_user} password={db_pass} port={db_port} dbname={db_name}'.format(
            db_host=config.db_host, db_port=config.db_port, db_user=config.db_user, db_pass=config.db_pass, db_name=config.db_name)) as conn:
        with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
            cur.execute(query)
            rows = cur.fetchall()
    return rows

@contextmanager
def session_scope():
    """Provide a transactional scope around a series of operations."""
    global ENGINE
    global SESSION
    if SESSION is None:
        SESSION = sessionmaker(bind=ENGINE)
    session = SESSION()
    try:
        yield session
    except:
        session.rollback()
        raise
    finally:
        session.close()

def get_device_tokens(login_id):
    '''
    Get device tokens for a given login. Removes duplicates per provider.
    '''
    with session_scope() as session:
        result = session.query(model.Device.platform_id,
                    func.coalesce(model.Device.device_token_new, model.Device.device_token).label('device_token')).\
                    filter(model.Device.login_id == login_id).filter(model.Device.unregistered_ts.is_(None)).all()

    # only return unique device tokens per provider (gcm, apn) to avoid sending duplicates
    devices = set()
    provider_tokens = set()
    for device in sorted(result): # sorting to make unit tests easier
        platform_id, device_token = device
        provider_id = (constants.PLATFORM_BY_PROVIDER.get(platform_id, 0)
                       or platform_id)
        # NOTE: Use unique tokens per *provider* only for known providers,
        #       and unique tokens per *platform* in other cases, since
        #       it is hard to verify providers for custom senders
        provider_token = (provider_id, device_token)
        if provider_token not in provider_tokens:
            devices.add(device)
            provider_tokens.add(provider_token)
    return list(devices)

def get_raw_messages(login_id, title, content, screen, game, world_id, dry_run, message_id=0, event_ts_bigint=None,
                     expiry_millis=None, priority=GCM2.PRIORITY_NORMAL, filter_platform_id=None, filter_device_token=None):
    '''
    Get message dictionaries for a login id and message params.
    '''
    if expiry_millis is not None and event_ts_bigint is not None:
        time_to_live_ts_bigint = event_ts_bigint + expiry_millis
    else:
        time_to_live_ts_bigint = int(round(time.time() * 1000)) + constants.TIME_TO_LIVE_HOURS * 60 * 60 * 1000
    raw_messages = []
    base_notification = {
        'login_id': login_id,
        'title': title,
        'content': content,
        'game': game,
        'world_id': world_id,
        'screen': screen,
        'time': int(round(time.time() * 1000)),
        'time_to_live_ts_bigint': time_to_live_ts_bigint,
        'status': constants.NOTIFICATION_READY,
        'message_id': message_id,
        'campaign_id': 1,
        'sending_id': 0,
        'dry_run': dry_run,
        'priority': priority
    }
    if filter_platform_id is not None and filter_device_token is not None:
        devices = [(filter_platform_id, filter_device_token)]
    else:
        devices = get_device_tokens(login_id)
    if len(devices) > 0:
        for platform_id, device_token in devices:
            notification = base_notification.copy()
            notification['receiver_id'] = device_token
            notification['platform'] = platform_id
            raw_messages.append(notification)
    else:
        context.main_logger.debug("User with login_id={login_id} doesn't have any device.".format(login_id=login_id))
    return raw_messages

def update_canonicals(canonicals):
    '''
    Update canonical data for android devices.
    '''
    global ENGINE
    binding = [{"p_{}".format(k): v for k, v in canonical.items()} for canonical in canonicals]
    device_table = model.metadata.tables['device']
    stmt = update(device_table).\
        values(device_token_new=bindparam('p_new_token')).\
        where(and_(device_table.c.login_id == bindparam('p_login_id'),
                   func.coalesce(device_table.c.device_token_new, device_table.c.device_token) == bindparam('p_old_token')))
    ENGINE.execute(stmt, binding)

    with session_scope() as session:
        query = text('SELECT keep_max_users_per_device( \
                     (:platform_id)::int2, :device_token, (:max_users_per_device)::int2)')
        for canonical in canonicals:
            session.execute(query,
                            {'platform_id': constants.PLATFORM_ANDROID,
                             'device_token': canonical['new_token'],
                             'max_users_per_device': config.max_users_per_device
                            })
            session.execute(query,
                            {'platform_id': constants.PLATFORM_ANDROID_TABLET,
                             'device_token': canonical['new_token'],
                             'max_users_per_device': config.max_users_per_device
                            })
        session.commit()

def update_unregistered_devices(unregistered):
    '''
    Update data for unregistered Android devices.

    Unregistered device will not receive notifications and will be deleted when number of devices exceeds maximum.
    '''
    global ENGINE
    binding = [{"p_{}".format(k): v for k, v in u.items()} for u in unregistered]
    device_table = model.metadata.tables['device']
    stmt = update(device_table).\
        values(unregistered_ts=func.now()).\
        where(and_(device_table.c.login_id == bindparam('p_login_id'),
                   func.coalesce(device_table.c.device_token_new, device_table.c.device_token) == bindparam('p_device_token')))
    ENGINE.execute(stmt, binding)

def process_user_login(login_id, language_id, platform_id, device_token, application_version):
    '''
    Add or update device and login data. Also deletes oldest device if number of devices exceeds maximum.
    '''
    with session_scope() as session:
        session.execute(text('SELECT process_user_login(:login_id, (:language_id)::int2, \
                             (:platform_id)::int2,:device_token, :application_version, \
                             (:max_devices_per_user)::int2, (:max_users_per_device)::int2)'),
                    {
                    'login_id': login_id,
                    'language_id': language_id,
                    'platform_id': platform_id,
                    'device_token': device_token,
                    'application_version': application_version,
                    'max_devices_per_user': config.max_devices_per_user,
                    'max_users_per_device': config.max_users_per_device
                    })
        session.commit()

def upsert_login(login_id, language_id):
    '''
    Add or update a login entity. Returns new or updated login.
    '''
    with session_scope() as session:
        login = session.query(model.Login).filter(model.Login.id == login_id).one_or_none()
        if login is not None:
            login.language_id = language_id
        else:
            login = model.Login(id=login_id, language_id=language_id)
            session.add(login)
        session.commit()
        session.refresh(login)
    return login

def upsert_device(login_id, platform_id, device_token, application_version, unregistered_ts=None):
    '''
    Add or update a device entity. Returns new or updated device with relation to login preloaded.
    '''
    with session_scope() as session:
        login = session.query(model.Login).filter(model.Login.id == login_id).one()
        device = session.query(model.Device).\
            filter(model.Device.login == login).\
            filter(model.Device.platform_id == platform_id).\
            filter(func.coalesce(model.Device.device_token_new, model.Device.device_token) == device_token).\
            one_or_none()
        if device is not None:
            device.application_version = application_version
            device.unregistered_ts = unregistered_ts
        else:
            device = model.Device(login=login, platform_id=platform_id, device_token=device_token,
                                  application_version=application_version, unregistered_ts=unregistered_ts)
            session.add(device)
        session.commit()
        session.refresh(device)
        session.refresh(device.login)
    return device

def get_all_logins():
    '''
    Get list of all logins.
    '''
    with session_scope() as session:
        logins = session.query(model.Login).all()
        return logins

def get_all_message_blacklist():
    '''
    Get list of all message blacklists
    '''
    with session_scope() as session:
        blacklists = session.query(model.MessageBlacklist).all()
    return blacklists

def upsert_message_blacklist(login_id, blacklist):
    '''
    Add or update a message. Returns new or updated message.
    '''
    with session_scope() as session:
        entity = session.query(model.MessageBlacklist).filter(model.MessageBlacklist.login_id == login_id).one_or_none()
        if entity is not None:
            entity.blacklist = blacklist
        else:
            entity = model.MessageBlacklist(login_id=login_id, blacklist=blacklist)
            session.add(entity)
        session.commit()
        session.refresh(entity)
    return entity

def get_login(login_id):
    '''
    Get a specific login by id.
    '''
    with session_scope() as session:
        login = session.query(model.Login).filter(model.Login.id == login_id).one_or_none()
        return login

def get_devices(login):
    '''
    Get devices of a specific login.
    '''
    with session_scope() as session:
        reloaded_login = session.query(model.Login).filter(model.Login.id == login.id).one()
        devices = reloaded_login.devices
    return devices

def delete_login(login):
    '''
    Delete a specific login together with all devices of that user.
    '''
    with session_scope() as session:
        reloaded_login = session.query(model.Login).filter(model.Login.id == login.id).one()
        for device in reloaded_login.devices:
            session.delete(device)
        session.delete(reloaded_login)
        session.commit()

def delete_device(device):
    '''
    Delete a specific device.
    '''
    with session_scope() as session:
        reloaded_device = session.query(model.Device).filter(model.Device.id == device.id).one()
        session.delete(reloaded_device)
        session.commit()

def get_localized_message(login_id, message_id):
    '''
    Get message localization for language of a specific user.

    If translation for language of a user doesn't exist English translation is given.
    '''
    with session_scope() as session:
        localized_message = session.query(model.MessageLocalization).\
        from_statement(text("select lm.*, m.* from get_localized_message(:login_id, :message_id) lm inner join message m on lm.message_id = m.id")).\
        params(login_id=login_id, message_id=message_id).\
        options(contains_eager(model.MessageLocalization.message)).\
        one_or_none()
    return localized_message

def upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority):
    '''
    Add or update a message. Returns new or updated message.
    '''
    with session_scope() as session:
        message = session.query(model.Message).filter(model.Message.name == message_name).one_or_none()
        if message is not None:
            message.cooldown_ts = cooldown_ts
            message.trigger_event_id = trigger_event_id
            message.screen = screen
            message.expiry_millis = expiry_millis
            message.priority = priority
        else:
            message = model.Message(name=message_name, cooldown_ts=cooldown_ts, trigger_event_id=trigger_event_id,
                                    screen=screen, expiry_millis=expiry_millis, priority=priority)
            session.add(message)
        session.commit()
        session.refresh(message)
    return message

def upsert_message_localization(message_name, language_id, message_title, message_text):
    '''
    Add or update a message localization. Returns new or updated localization with relation to message preloaded.
    '''
    with session_scope() as session:
        message = session.query(model.Message).filter(model.Message.name == message_name).one()
        message_localization = session.query(model.MessageLocalization).\
            filter(model.MessageLocalization.message == message).\
            filter(model.MessageLocalization.language_id == language_id).\
            one_or_none()
        if message_localization is not None:
            message_localization.message_title = message_title
            message_localization.message_text = message_text
        else:
            message_localization = model.MessageLocalization(message=message, language_id=language_id,
                                                             message_title=message_title, message_text=message_text)
            session.add(message_localization)
        session.commit()
        session.refresh(message_localization)
        session.refresh(message_localization.message)
    return message_localization

def add_message(message_name, language_id, message_title, message_text, trigger_event_id=None, cooldown_ts=None,
                screen='', expiry_millis=None, priority=GCM2.PRIORITY_NORMAL):
    '''
    Add or update a message with localization for one language.
    '''
    message = upsert_message(message_name, cooldown_ts, trigger_event_id, screen, expiry_millis, priority)
    message_localization = upsert_message_localization(message_name, language_id, message_title, message_text)
    return message_localization

def get_all_messages():
    '''
    Get list of all messages from database.
    '''
    with session_scope() as session:
        messages = session.query(model.Message).all()
    return messages

def get_message(message_name):
    '''
    Get a specific message.
    '''
    with session_scope() as session:
        message = session.query(model.Message).filter(model.Message.name == message_name).one_or_none()
    return message

def get_message_localizations(message):
    '''
    Get all localizations for a specific message.
    '''
    with session_scope() as session:
        reloaded_message = session.query(model.Message).filter(model.Message.id == message.id).one()
        localizations = reloaded_message.localizations
    return localizations

def delete_message(message):
    '''
    Delete a specific message with all localizations.
    '''
    with session_scope() as session:
        reloaded_message = session.query(model.Message).filter(model.Message.id == message.id).one()
        for message_localization in reloaded_message.localizations:
            session.delete(message_localization)
        session.delete(reloaded_message)
        session.commit()

def delete_message_localization(message_localization):
    '''
    Delete a specific message localization.
    '''
    with session_scope() as session:
        reloaded_message_localization = session.query(model.MessageLocalization).filter(model.MessageLocalization.id == message_localization.id).one()
        session.delete(reloaded_message_localization)
        session.commit()

def get_event_to_message_mapping():
    '''
    Return a mapping of event ids to messages ids in format {event_id: [message_ids]}.
    '''
    with session_scope() as session:
        messages_with_event = session.query(model.Message.trigger_event_id, model.Message.id).filter(model.Message.trigger_event_id.isnot(None)).all()
        mapping = defaultdict(list)
        for trigger_event_id, id in messages_with_event:
            mapping[trigger_event_id].append(id)
    return mapping

def get_and_update_messages_to_send(user_message_set):
    '''
    Update last time a message id was send for a user.

    Expects a set of (login_id, message_id) tuples.
    '''
    # collect user messages in a dictionary for easier processing
    user_dict = defaultdict(set)
    for login_id, message_id in user_message_set:
        user_dict[login_id].add(message_id)
    with session_scope() as session:
        joined_login_ids = ','.join([str(login_id) for login_id in user_dict.keys()])
        array_login_ids = "'{{{}}}'".format(joined_login_ids)
        query = "select * from get_non_elligible_user_message_pairs({})".format(array_login_ids)
        non_eligible_messages = session.query(model.UserMessageLastTimeSent).\
            from_statement(text(query)).all()
        for non_eligible_message in non_eligible_messages:
            user_dict[non_eligible_message.login_id].discard(non_eligible_message.message_id)

        # update user_message_last_time_sent
        return_tuple = []
        for user, messages in user_dict.iteritems():
            for message in messages:
                return_tuple.append({str(user): str(message)})
                session.execute(text(
                    'SELECT upsert_user_message_last_time_sent((:login_id)::bigint, :message_id)'),
                                {
                                    'login_id': user,
                                    'message_id': message
                                })
        session.commit()
    return return_tuple


text:
Site Code for [BASKA-Sweden.co.za](https://baska-sweden.co.za)

[Facebook Page](https://www.facebook.com/Baska-Sweden-2018-1427271897380852/)

Theme: [Minimal Mistakes](https://mmistakes.github.io/minimal-mistakes/) ([GitHub repo](https://github.com/mmistakes/minimal-mistakes))


text:
<template name="deviceSubmit">

    {{#autoForm id="deviceEdit" collection=Collections.Devices class="main form project-detail"}}

Create My New Device

        {{> projectItemSimple _id=project_id}}

        {{> afQuickField name='project_id' value=project_id type='hidden'}}
        {{> afQuickField name='name'}}
        {{> afQuickField name='desc' type="textarea"}}

        <button type="submit" class="btn btn-primary">
             Save
        </button>
    {{/autoForm}}

</template>


text:
/* */
"format cjs";
/* Copyright (c) 2011 by The Authors.
 * Published under the LGPL 2.1 license.
 * See /license-notice.txt for the full text of the license notice.
 * See /license.txt for the full text of the license.
 */

/**
 * Contains information about the nature and location of a {@link Geometry}
 * validation error
 *
 * @version 1.7
 */

/**
 *
 * Creates a validation error with the given type and location
 *
 * @param errorType
 *          the type of the error.
 *
 * @param pt
 *          the location of the error.
 *
 */
jsts.operation.valid.TopologyValidationError = function(errorType, pt) {
  this.errorType = errorType;
  this.pt = null;

  if (pt != null) {
    this.pt = pt.clone();
  }
};

/**
 *
 * Indicates that a hole of a polygon lies partially or completely in the
 * exterior of the shell
 *
 */
jsts.operation.valid.TopologyValidationError.HOLE_OUTSIDE_SHELL = 2;

/**
 *
 * Indicates that a hole lies in the interior of another hole in the same
 * polygon
 *
 */
jsts.operation.valid.TopologyValidationError.NESTED_HOLES = 3;

/**
 *
 * Indicates that the interior of a polygon is disjoint
 *
 * (often caused by set of contiguous holes splitting the polygon into two
 * parts)
 *
 */
jsts.operation.valid.TopologyValidationError.DISCONNECTED_INTERIOR = 4;

/**
 *
 * Indicates that two rings of a polygonal geometry intersect
 *
 */
jsts.operation.valid.TopologyValidationError.SELF_INTERSECTION = 5;

/**
 *
 * Indicates that a ring self-intersects
 *
 */
jsts.operation.valid.TopologyValidationError.RING_SELF_INTERSECTION = 6;

/**
 *
 * Indicates that a polygon component of a MultiPolygon lies inside another
 * polygonal component
 *
 */
jsts.operation.valid.TopologyValidationError.NESTED_SHELLS = 7;

/**
 *
 * Indicates that a polygonal geometry contains two rings which are identical
 *
 */
jsts.operation.valid.TopologyValidationError.DUPLICATE_RINGS = 8;

/**
 *
 * Indicates that either
 *

 *
a LineString contains a single point
 *
a LinearRing contains 2 or 3 points
 *

 *
 */
jsts.operation.valid.TopologyValidationError.TOO_FEW_POINTS = 9;

/**
 *
 * Indicates that the X or Y ordinate of
 * a Coordinate is not a valid numeric value (e.g. {@link Double#NaN} )
 *
 */
jsts.operation.valid.TopologyValidationError.INVALID_COORDINATE = 10;

/**
 *
 * Indicates that a ring is not correctly closed
 * (the first and the last coordinate are different)
 *
 */
jsts.operation.valid.TopologyValidationError.RING_NOT_CLOSED = 11;

/**
 *
 * Messages corresponding to error codes
 *
 */
jsts.operation.valid.TopologyValidationError.prototype.errMsg = [
'Topology Validation Error',
'Repeated Point',
'Hole lies outside shell',
'Holes are nested',
'Interior is disconnected',
'Self-intersection',
'Ring Self-intersection',
'Nested shells',
'Duplicate Rings',
'Too few distinct points in geometry component',
'Invalid Coordinate',
'Ring is not closed'
];

/**
 * Creates a validation error of the given type with a null location
 *
 * @param errorType
 *          the type of the error
 *
 * jsts.operation.valid.TopologyValidationError(int errorType) // cannot
 * overload constructors, use above with null as arg 2
 *  {
 * this(errorType, null);
 *  }
 */

/**
 *
 * Returns the location of this error (on the {@link Geometry} containing the
 * error).
 *
 *
 *
 * @return a {@link Coordinate} on the input geometry.
 *
 */
jsts.operation.valid.TopologyValidationError.prototype.getCoordinate = function() {
  return this.pt;
};

/**
 *
 * Gets the type of this error.
 * @return the error type.
 *
 */
jsts.operation.valid.TopologyValidationError.prototype.getErrorType = function() {
  return this.errorType;
};

/**
 *
 * Gets an error message describing this error.
 * The error message does not describe the location of the error.
 * @return the error message.
 *
 */
jsts.operation.valid.TopologyValidationError.prototype.getMessage = function() {
  return this.errMsg[this.errorType];
};

/**
 *
 * Gets a message describing the type and location of this error.
 * @return the error message.
 *
 */
jsts.operation.valid.TopologyValidationError.prototype.toString = function() {
  var locStr = '';
  if (this.pt != null) {
    locStr = ' at or near point ' + this.pt;
    return this.getMessage() + locStr;
  }
  return locStr;
};


text:
class Course < ActiveRecord::Base
  extend FriendlyId

  belongs_to :unit

  has_one :forum

  has_many :subjects, dependent: :destroy

  has_many :teachings
  has_many :teachers, through: :teachings

  has_many :enrollments
  has_many :students, through: :enrollments, source: :user

  has_many :links, -> { uniq }, through: :subjects

  has_and_belongs_to_many :library_files

  validates :name, :slug, presence: true
  validates :name, :slug, uniqueness: {scope: :unit}

  friendly_id :slug, use: :history

  before_validation :ensure_slug

  after_create :create_forum

  def self.find_by_teacher(teacher)
    includes(:users).where(users: { id: teacher.id })
  end

  def self.with_files
    includes(:library_files).where.not( library_files: { id: nil })
  end

  def ensure_slug
    if name.present? and slug.blank?
      self.slug = name.parameterize
    end
  end

  protected
    def create_forum
      Forum.create!(name: self.name, description: self.subname, course: self)
    end
end


text:
<?php
/**
 * @author Tomáš Blatný
 */

namespace Learn\Security;

use Nette\Object;

class Passwords extends Object
{
	public static function hashPassword($password, $username, $salt)
	{
		return self::mutliHash($username . '@' . $password, $salt, 5, 'sha512');
	}

	protected static function mutliHash($password, $salt, $count = 1, $hashType = 'md5')
	{
		$hashed = self::hash($password, $salt, $hashType);
		return $count <= 1 ? $hashed : self::mutliHash($hashed, $salt, --$count, $hashType);
	}

	protected static function hash($password, $salt, $hashType = 'md5')
	{
		return hash($hashType, $salt . $password . $salt);
	}
}


text:
'use strict';

const path = require('path');
const electron = require('electron');
const ipcMain = electron.ipcMain;
const objectsRegistry = require('./objects-registry');
const v8Util = process.atomBinding('v8_util');
const IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap;

var slice = [].slice;

// Convert a real value into meta data.
var valueToMeta = function(sender, value, optimizeSimpleObject) {
  var el, field, i, len, meta, name;
  if (optimizeSimpleObject == null) {
    optimizeSimpleObject = false;
  }
  meta = {
    type: typeof value
  };
  if (Buffer.isBuffer(value)) {
    meta.type = 'buffer';
  }
  if (value === null) {
    meta.type = 'value';
  }
  if (Array.isArray(value)) {
    meta.type = 'array';
  }
  if (value instanceof Error) {
    meta.type = 'error';
  }
  if (value instanceof Date) {
    meta.type = 'date';
  }
  if ((value != null ? value.constructor.name : void 0) === 'Promise') {
    meta.type = 'promise';
  }

  // Treat simple objects as value.
  if (optimizeSimpleObject && meta.type === 'object' && v8Util.getHiddenValue(value, 'simple')) {
    meta.type = 'value';
  }

  // Treat the arguments object as array.
  if (meta.type === 'object' && (value.hasOwnProperty('callee')) && (value.length != null)) {
    meta.type = 'array';
  }
  if (meta.type === 'array') {
    meta.members = [];
    for (i = 0, len = value.length; i < len; i++) {
      el = value[i];
      meta.members.push(valueToMeta(sender, el));
    }
  } else if (meta.type === 'object' || meta.type === 'function') {
    meta.name = value.constructor.name;

    // Reference the original value if it's an object, because when it's
    // passed to renderer we would assume the renderer keeps a reference of
    // it.
    meta.id = objectsRegistry.add(sender.getId(), value);
    meta.members = (function() {
      var results;
      results = [];
      for (name in value) {
        field = value[name];
        results.push({
          name: name,
          type: typeof field
        });
      }
      return results;
    })();
  } else if (meta.type === 'buffer') {
    meta.value = Array.prototype.slice.call(value, 0);
  } else if (meta.type === 'promise') {
    meta.then = valueToMeta(sender, value.then.bind(value));
  } else if (meta.type === 'error') {
    meta.members = plainObjectToMeta(value);

    // Error.name is not part of own properties.
    meta.members.push({
      name: 'name',
      value: value.name
    });
  } else if (meta.type === 'date') {
    meta.value = value.getTime();
  } else {
    meta.type = 'value';
    meta.value = value;
  }
  return meta;
};

// Convert object to meta by value.
var plainObjectToMeta = function(obj) {
  return Object.getOwnPropertyNames(obj).map(function(name) {
    return {
      name: name,
      value: obj[name]
    };
  });
};

// Convert Error into meta data.
var exceptionToMeta = function(error) {
  return {
    type: 'exception',
    message: error.message,
    stack: error.stack || error
  };
};

// Convert array of meta data from renderer into array of real values.
var unwrapArgs = function(sender, args) {
  var metaToValue;
  metaToValue = function(meta) {
    var i, len, member, ref, rendererReleased, returnValue;
    switch (meta.type) {
      case 'value':
        return meta.value;
      case 'remote-object':
        return objectsRegistry.get(meta.id);
      case 'array':
        return unwrapArgs(sender, meta.value);
      case 'buffer':
        return new Buffer(meta.value);
      case 'date':
        return new Date(meta.value);
      case 'promise':
        return Promise.resolve({
          then: metaToValue(meta.then)
        });
      case 'object':
        let ret = v8Util.createObjectWithName(meta.name);
        ref = meta.members;
        for (i = 0, len = ref.length; i < len; i++) {
          member = ref[i];
          ret[member.name] = metaToValue(member.value);
        }
        return ret;
      case 'function-with-return-value':
        returnValue = metaToValue(meta.value);
        return function() {
          return returnValue;
        };
      case 'function':
        // Cache the callbacks in renderer.
        if (!sender.callbacks) {
          sender.callbacks = new IDWeakMap;
          sender.on('render-view-deleted', function() {
            return this.callbacks.clear();
          });
        }

        if (sender.callbacks.has(meta.id))
          return sender.callbacks.get(meta.id);

        // Prevent the callback from being called when its page is gone.
        rendererReleased = false;
        sender.once('render-view-deleted', function() {
          rendererReleased = true;
        });

        let callIntoRenderer = function(...args) {
          if (rendererReleased)
            throw new Error(`Attempting to call a function in a renderer window that has been closed or released. Function provided here: ${meta.location}.`);
          sender.send('ATOM_RENDERER_CALLBACK', meta.id, valueToMeta(sender, args));
        };
        v8Util.setDestructor(callIntoRenderer, function() {
          if (!rendererReleased)
            sender.send('ATOM_RENDERER_RELEASE_CALLBACK', meta.id);
        });
        sender.callbacks.set(meta.id, callIntoRenderer);
        return callIntoRenderer;
      default:
        throw new TypeError("Unknown type: " + meta.type);
    }
  };
  return args.map(metaToValue);
};

// Call a function and send reply asynchronously if it's a an asynchronous
// style function and the caller didn't pass a callback.
var callFunction = function(event, func, caller, args) {
  var e, error1, funcMarkedAsync, funcName, funcPassedCallback, ref, ret;
  funcMarkedAsync = v8Util.getHiddenValue(func, 'asynchronous');
  funcPassedCallback = typeof args[args.length - 1] === 'function';
  try {
    if (funcMarkedAsync && !funcPassedCallback) {
      args.push(function(ret) {
        return event.returnValue = valueToMeta(event.sender, ret, true);
      });
      return func.apply(caller, args);
    } else {
      ret = func.apply(caller, args);
      return event.returnValue = valueToMeta(event.sender, ret, true);
    }
  } catch (error1) {
    e = error1;

    // Catch functions thrown further down in function invocation and wrap
    // them with the function name so it's easier to trace things like
    // `Error processing argument -1.`
    funcName = (ref = func.name) != null ? ref : "anonymous";
    throw new Error("Could not call remote function `" + funcName + "`. Check that the function signature is correct. Underlying error: " + e.message);
  }
};

// Send by BrowserWindow when its render view is deleted.
process.on('ATOM_BROWSER_RELEASE_RENDER_VIEW', function(id) {
  return objectsRegistry.clear(id);
});

ipcMain.on('ATOM_BROWSER_REQUIRE', function(event, module) {
  var e, error1;
  try {
    return event.returnValue = valueToMeta(event.sender, process.mainModule.require(module));
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_GET_BUILTIN', function(event, module) {
  var e, error1;
  try {
    return event.returnValue = valueToMeta(event.sender, electron[module]);
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_GLOBAL', function(event, name) {
  var e, error1;
  try {
    return event.returnValue = valueToMeta(event.sender, global[name]);
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_CURRENT_WINDOW', function(event) {
  var e, error1;
  try {
    return event.returnValue = valueToMeta(event.sender, event.sender.getOwnerBrowserWindow());
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_CURRENT_WEB_CONTENTS', function(event) {
  return event.returnValue = valueToMeta(event.sender, event.sender);
});

ipcMain.on('ATOM_BROWSER_CONSTRUCTOR', function(event, id, args) {
  var constructor, e, error1, obj;
  try {
    args = unwrapArgs(event.sender, args);
    constructor = objectsRegistry.get(id);

    // Call new with array of arguments.
    // http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible
    obj = new (Function.prototype.bind.apply(constructor, [null].concat(args)));
    return event.returnValue = valueToMeta(event.sender, obj);
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_FUNCTION_CALL', function(event, id, args) {
  var e, error1, func;
  try {
    args = unwrapArgs(event.sender, args);
    func = objectsRegistry.get(id);
    return callFunction(event, func, global, args);
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_MEMBER_CONSTRUCTOR', function(event, id, method, args) {
  var constructor, e, error1, obj;
  try {
    args = unwrapArgs(event.sender, args);
    constructor = objectsRegistry.get(id)[method];

    // Call new with array of arguments.
    obj = new (Function.prototype.bind.apply(constructor, [null].concat(args)));
    return event.returnValue = valueToMeta(event.sender, obj);
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_MEMBER_CALL', function(event, id, method, args) {
  var e, error1, obj;
  try {
    args = unwrapArgs(event.sender, args);
    obj = objectsRegistry.get(id);
    return callFunction(event, obj[method], obj, args);
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_MEMBER_SET', function(event, id, name, value) {
  var e, error1, obj;
  try {
    obj = objectsRegistry.get(id);
    obj[name] = value;
    return event.returnValue = null;
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_MEMBER_GET', function(event, id, name) {
  var e, error1, obj;
  try {
    obj = objectsRegistry.get(id);
    return event.returnValue = valueToMeta(event.sender, obj[name]);
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_DEREFERENCE', function(event, id) {
  return objectsRegistry.remove(event.sender.getId(), id);
});

ipcMain.on('ATOM_BROWSER_GUEST_WEB_CONTENTS', function(event, guestInstanceId) {
  var e, error1, guestViewManager;
  try {
    guestViewManager = require('./guest-view-manager');
    return event.returnValue = valueToMeta(event.sender, guestViewManager.getGuest(guestInstanceId));
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});

ipcMain.on('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', function() {
  var args, e, error1, event, guest, guestInstanceId, guestViewManager, method;
  event = arguments[0], guestInstanceId = arguments[1], method = arguments[2], args = 4 <= arguments.length ? slice.call(arguments, 3) : [];
  try {
    guestViewManager = require('./guest-view-manager');
    guest = guestViewManager.getGuest(guestInstanceId);
    return guest[method].apply(guest, args);
  } catch (error1) {
    e = error1;
    return event.returnValue = exceptionToMeta(e);
  }
});


text:
import TouchPan from '../../directives/touch-pan.js'
import { css, cssTransform } from '../../utils/dom.js'
import { between } from '../../utils/format.js'
import ModelToggleMixin from '../../mixins/model-toggle.js'
import PreventScroll from '../../mixins/prevent-scroll.js'

const
  bodyClass = 'u-body-drawer-toggle',
  duration = 150

export default {
  name: 'ULayoutDrawer',
  inject: {
    layout: {
      default () {
        console.error('ULayoutDrawer needs to be child of ULayout')
      }
    }
  },
  mixins: [ ModelToggleMixin, PreventScroll ],
  directives: {
    TouchPan
  },
  props: {
    overlay: Boolean,
    side: {
      type: String,
      default: 'left',
      validator: v => ['left', 'right'].includes(v)
    },
    width: {
      type: Number,
      default: process.env.THEME === 'mat' ? 300 : 280
    },
    mini: Boolean,
    miniWidth: {
      type: Number,
      default: 60
    },
    breakpoint: {
      type: Number,
      default: 992
    },
    behavior: {
      type: String,
      validator: v => ['default', 'desktop', 'mobile'].includes(v),
      default: 'default'
    },
    contentStyle: Object,
    contentClass: [String, Object, Array],
    noHideOnRouteChange: Boolean,
    noSwipeOpen: Boolean,
    noSwipeClose: Boolean
  },
  data () {
    const
      largeScreenState = this.value !== void 0 ? this.value : true,
      showing = this.behavior !== 'mobile' && this.breakpoint < this.layout.width && !this.overlay
        ? largeScreenState
        : false

    if (this.value !== void 0 && this.value !== showing) {
      this.$emit('input', showing)
    }

    return {
      showing,
      belowBreakpoint: (
        this.behavior === 'mobile' ||
        (this.behavior !== 'desktop' && this.breakpoint >= this.layout.width)
      ),
      largeScreenState,
      mobileOpened: false
    }
  },
  watch: {
    belowBreakpoint (val, old) {
      if (this.mobileOpened) {
        return
      }

      if (val) { // from lg to xs
        if (!this.overlay) {
          this.largeScreenState = this.showing
        }
        // ensure we close it for small screen
        this.hide(false)
      }
      else if (!this.overlay) { // from xs to lg
        this[this.largeScreenState ? 'show' : 'hide'](false)
      }
    },
    behavior (val) {
      this.__updateLocal('belowBreakpoint', (
        val === 'mobile' ||
        (val !== 'desktop' && this.breakpoint >= this.layout.width)
      ))
    },
    breakpoint (val) {
      this.__updateLocal('belowBreakpoint', (
        this.behavior === 'mobile' ||
        (this.behavior !== 'desktop' && val >= this.layout.width)
      ))
    },
    'layout.width' (val) {
      this.__updateLocal('belowBreakpoint', (
        this.behavior === 'mobile' ||
        (this.behavior !== 'desktop' && this.breakpoint >= val)
      ))
    },
    offset (val) {
      this.__update('offset', val)
    },
    onLayout (val) {
      this.__update('space', val)
    },
    $route () {
      if (this.noHideOnRouteChange) {
        return
      }

      if (this.mobileOpened || this.onScreenOverlay) {
        this.hide()
      }
    },
    rightSide () {
      this.applyPosition()
    },
    size (val) {
      this.applyPosition()
      this.__update('size', val)
    },
    '$uloc.i18n.rtl' () {
      this.applyPosition()
    },
    mini () {
      if (this.value) {
        this.layout.__animate()
      }
    }
  },
  computed: {
    rightSide () {
      return this.side === 'right'
    },
    offset () {
      return this.showing && !this.mobileOpened && !this.overlay
        ? this.size
        : 0
    },
    size () {
      return this.isMini ? this.miniWidth : this.width
    },
    fixed () {
      return this.overlay || this.layout.view.indexOf(this.rightSide ? 'R' : 'L') > -1
    },
    onLayout () {
      return this.showing && !this.mobileView && !this.overlay
    },
    onScreenOverlay () {
      return this.showing && !this.mobileView && this.overlay
    },
    backdropClass () {
      return {
        'no-pointer-events': !this.showing || !this.mobileView
      }
    },
    mobileView () {
      return this.belowBreakpoint || this.mobileOpened
    },
    headerSlot () {
      return this.overlay
        ? false
        : (this.rightSide
          ? this.layout.rows.top[2] === 'r'
          : this.layout.rows.top[0] === 'l'
        )
    },
    footerSlot () {
      return this.overlay
        ? false
        : (this.rightSide
          ? this.layout.rows.bottom[2] === 'r'
          : this.layout.rows.bottom[0] === 'l'
        )
    },
    belowClass () {
      return {
        'fixed': true,
        'on-top': true,
        'u-layout-drawer-delimiter': this.fixed && this.showing,
        'u-layout-drawer-mobile': true,
        'top-padding': true
      }
    },
    aboveClass () {
      return {
        'fixed': this.fixed || !this.onLayout,
        'u-layout-drawer-mini': this.isMini,
        'u-layout-drawer-normal': !this.isMini,
        'u-layout-drawer-delimiter': this.fixed && this.showing,
        'top-padding': this.headerSlot
      }
    },
    aboveStyle () {
      const css = {}

      if (this.layout.header.space && !this.headerSlot) {
        if (this.fixed) {
          css.top = `${this.layout.header.offset}px`
        }
        else if (this.layout.header.space) {
          css.top = `${this.layout.header.size}px`
        }
      }

      if (this.layout.footer.space && !this.footerSlot) {
        if (this.fixed) {
          css.bottom = `${this.layout.footer.offset}px`
        }
        else if (this.layout.footer.space) {
          css.bottom = `${this.layout.footer.size}px`
        }
      }

      return css
    },
    computedStyle () {
      return [this.contentStyle, { width: `${this.size}px` }, this.mobileView ? '' : this.aboveStyle]
    },
    computedClass () {
      return [this.contentClass, this.mobileView ? this.belowClass : this.aboveClass]
    },
    stateDirection () {
      return (this.$uloc.i18n.rtl ? -1 : 1) * (this.rightSide ? 1 : -1)
    },
    isMini () {
      return this.mini && !this.mobileView
    },
    onNativeEvents () {
      if (!this.mobileView) {
        return {
          '!click': e => { this.$emit('click', e) },
          mouseover: e => { this.$emit('mouseover', e) },
          mouseout: e => { this.$emit('mouseout', e) }
        }
      }
    }
  },
  methods: {
    applyPosition (position) {
      if (position === void 0) {
        this.$nextTick(() => {
          position = this.showing
            ? 0
            : (this.$uloc.i18n.rtl ? -1 : 1) * (this.rightSide ? 1 : -1) * this.size

          this.applyPosition(position)
        })
        return
      }
      this.$refs.content && css(this.$refs.content, cssTransform(`translateX(${position}px)`))
    },
    applyBackdrop (x) {
      this.$refs.backdrop && css(this.$refs.backdrop, { backgroundColor: `rgba(0,0,0,${x * 0.4})` })
    },
    __openByTouch (evt) {
      if (!this.belowBreakpoint) {
        return
      }

      const
        width = this.size,
        position = between(evt.distance.x, 0, width)

      if (evt.isFinal) {
        const
          el = this.$refs.content,
          opened = position >= Math.min(75, width)

        el.classList.remove('no-transition')

        if (opened) {
          this.show()
        }
        else {
          this.layout.__animate()
          this.applyBackdrop(0)
          this.applyPosition(this.stateDirection * width)
          el.classList.remove('u-layout-drawer-delimiter')
        }

        return
      }

      this.applyPosition(
        (this.$uloc.i18n.rtl ? !this.rightSide : this.rightSide)
          ? Math.max(width - position, 0)
          : Math.min(0, position - width)
      )
      this.applyBackdrop(
        between(position / width, 0, 1)
      )

      if (evt.isFirst) {
        const el = this.$refs.content
        el.classList.add('no-transition')
        el.classList.add('u-layout-drawer-delimiter')
      }
    },
    __closeByTouch (evt) {
      if (!this.mobileOpened) {
        return
      }

      const
        width = this.size,
        dir = evt.direction === this.side,
        position = (this.$uloc.i18n.rtl ? !dir : dir)
          ? between(evt.distance.x, 0, width)
          : 0

      if (evt.isFinal) {
        const opened = Math.abs(position) < Math.min(75, width)
        this.$refs.content.classList.remove('no-transition')

        if (opened) {
          this.layout.__animate()
          this.applyBackdrop(1)
          this.applyPosition(0)
        }
        else {
          this.hide()
        }

        return
      }

      this.applyPosition(this.stateDirection * position)
      this.applyBackdrop(between(1 - position / width, 0, 1))

      if (evt.isFirst) {
        this.$refs.content.classList.add('no-transition')
      }
    },
    __show (animate = true) {
      animate && this.layout.__animate()
      this.applyPosition(0)

      const otherSide = this.layout.instances[this.rightSide ? 'left' : 'right']
      if (otherSide && otherSide.mobileOpened) {
        otherSide.hide()
      }

      if (this.belowBreakpoint) {
        this.mobileOpened = true
        this.applyBackdrop(1)
        this.__preventScroll(true)
      }
      else {
        document.body.classList.add(bodyClass)
      }

      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        if (this.showPromise) {
          this.showPromise.then(() => {
            document.body.classList.remove(bodyClass)
          })
          this.showPromiseResolve()
        }
      }, duration)
    },
    __hide (animate = true) {
      animate && this.layout.__animate()

      if (this.mobileOpened) {
        this.__preventScroll(false)
        this.mobileOpened = false
      }

      this.applyPosition((this.$uloc.i18n.rtl ? -1 : 1) * (this.rightSide ? 1 : -1) * this.size)
      this.applyBackdrop(0)

      document.body.classList.remove(bodyClass)

      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.hidePromise && this.hidePromiseResolve()
      }, duration)
    },

    __update (prop, val) {
      if (this.layout[this.side][prop] !== val) {
        this.layout[this.side][prop] = val
      }
    },
    __updateLocal (prop, val) {
      if (this[prop] !== val) {
        this[prop] = val
      }
    }
  },
  created () {
    this.layout.instances[this.side] = this
    this.__update('size', this.size)
    this.__update('space', this.onLayout)
    this.__update('offset', this.offset)
  },
  mounted () {
    if (this.showing) {
      this.applyPosition(0)
    }
  },
  beforeDestroy () {
    clearTimeout(this.timer)
    if (this.layout.instances[this.side] === this) {
      this.layout.instances[this.side] = null
      this.__update('size', 0)
      this.__update('offset', 0)
      this.__update('space', false)
    }
  },
  render (h) {
    const child = [
      this.mobileView && !this.noSwipeOpen
        ? h('div', {
          staticClass: `u-layout-drawer-opener fixed-${this.side}`,
          directives: [{
            name: 'touch-pan',
            modifiers: { horizontal: true },
            value: this.__openByTouch
          }]
        })
        : null,
      h('div', {
        ref: 'backdrop',
        staticClass: 'fullscreen u-layout-backdrop u-layout-transition',
        'class': this.backdropClass,
        on: { click: this.hide },
        directives: [{
          name: 'touch-pan',
          modifiers: { horizontal: true },
          value: this.__closeByTouch
        }]
      })
    ]

    return h('div', {
      staticClass: 'u-drawer-container'
    }, child.concat([
      h('aside', {
        ref: 'content',
        staticClass: `u-layout-drawer u-layout-transition u-layout-drawer-${this.side} scroll`,
        'class': this.computedClass,
        style: this.computedStyle,
        attrs: this.$attrs,
        on: this.onNativeEvents,
        directives: this.mobileView && !this.noSwipeClose ? [{
          name: 'touch-pan',
          modifiers: { horizontal: true },
          value: this.__closeByTouch
        }] : null
      },
      this.isMini && this.$slots.mini
        ? [ this.$slots.mini ]
        : this.$slots.default
      )
    ]))
  }
}


text:
__version__ = '0.3'

'''
https://github.com/Chive/django-multiupload

The MIT License (MIT)

Copyright (c) 2014 Chive - Kim Thoenen (kim@smuzey.ch)

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.
'''

from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

class MultiFileInput(forms.FileInput):
    def render(self, name, value, attrs=None):
        attrs['multiple'] = 'multiple'
        return super(MultiFileInput, self).render(name, value, attrs)

    def value_from_datadict(self, data, files, name):
        if hasattr(files, 'getlist'):
            return files.getlist(name)
        else:
            return [files.get(name)]

class MultiFileField(forms.FileField):
    widget = MultiFileInput
    default_error_messages = {
        'min_num': _(u'Ensure at least %(min_num)s files are uploaded (received %(num_files)s).'),
        'max_num': _(u'Ensure at most %(max_num)s files are uploaded (received %(num_files)s).'),
        'file_size': _(u'File %(uploaded_file_name)s exceeded maximum upload size.'),
    }

    def __init__(self, *args, **kwargs):
        self.min_num = kwargs.pop('min_num', 0)
        self.max_num = kwargs.pop('max_num', None)
        self.maximum_file_size = kwargs.pop('max_file_size', None)
        super(MultiFileField, self).__init__(*args, **kwargs)

    def to_python(self, data):
        ret = []
        for item in data:
            i = super(MultiFileField, self).to_python(item)
            if i:
                ret.append(i)
        return ret

    def validate(self, data):
        super(MultiFileField, self).validate(data)
        num_files = len(data)
        if len(data) and not data[0]:
            num_files = 0
        if num_files < self.min_num:
            raise ValidationError(self.error_messages['min_num'] % {'min_num': self.min_num, 'num_files': num_files})
        elif self.max_num and num_files > self.max_num:
            raise ValidationError(self.error_messages['max_num'] % {'max_num': self.max_num, 'num_files': num_files})
        for uploaded_file in data:
            if self.maximum_file_size and uploaded_file.size > self.maximum_file_size:
                raise ValidationError(self.error_messages['file_size'] % {'uploaded_file_name': uploaded_file.name})


text:
package org.foxbpm.kernel.test;

import org.foxbpm.kernel.ProcessDefinitionBuilder;
import org.foxbpm.kernel.process.KernelProcessDefinition;
import org.foxbpm.kernel.runtime.KernelProcessInstance;
import org.foxbpm.kernel.test.behavior.AutomaticBehavior;
import org.foxbpm.kernel.test.behavior.TestEndBehavior;
import org.foxbpm.kernel.test.behavior.TestParallelGatewayBehavior;

public class KernelParallelTest extends KernelTestCase {

	public void testParallel(){

			KernelProcessDefinition processDefinition = new ProcessDefinitionBuilder()
		    .createFlowNode("start")
		      .initial()
		      .behavior(new AutomaticBehavior())
		      .sequenceFlow("fork","sequenceFlow_1")
		    .endFlowNode()
		    .createFlowNode("fork")
		      .behavior(new TestParallelGatewayBehavior("Diverging"))
		      .sequenceFlow("c1","sequenceFlow_2")
		      .sequenceFlow("c2","sequenceFlow_3")
		    .endFlowNode()
		    .createFlowNode("c1")
		      .behavior(new AutomaticBehavior())
		      .sequenceFlow("join","sequenceFlow_4")
		    .endFlowNode()
		    .createFlowNode("c2")
		      .behavior(new AutomaticBehavior())
		      .sequenceFlow("join","sequenceFlow_5")
		    .endFlowNode()
		    .createFlowNode("join")
		      .behavior(new TestParallelGatewayBehavior("Converging"))
		      .sequenceFlow("end","sequenceFlow_6")
		    .endFlowNode()
		    .createFlowNode("end")
		      .behavior(new TestEndBehavior())
		    .endFlowNode()
		  .buildProcessDefinition();

		  KernelProcessInstance processInstance = processDefinition.createProcessInstance();
		  processInstance.start();

		  assertTrue(processInstance.isEnded());

	}

	/**
	 *                   +----+
	 *              +--->|end1|
	 *              |    +----+
	 *              |
	 * +-----+   +----+
	 * |start|-->|fork|
	 * +-----+   +----+
	 *              |
	 *              |    +----+
	 *              +--->|end2|
	 *                   +----+
	 */
	public void testParallelEnd() {
		KernelProcessDefinition processDefinition = new ProcessDefinitionBuilder()
	    .createFlowNode("start")
	      .initial()
	      .behavior(new AutomaticBehavior())
	      .sequenceFlow("fork","sequenceFlow_1")
	    .endFlowNode()
	    .createFlowNode("fork")
	      .behavior(new TestParallelGatewayBehavior("Diverging"))
	      .sequenceFlow("end1","sequenceFlow_2")
	      .sequenceFlow("end2","sequenceFlow_3")
	    .endFlowNode()
	    .createFlowNode("end1")
	      .behavior(new TestEndBehavior())
	    .endFlowNode()
	    .createFlowNode("end2")
	      .behavior(new TestEndBehavior())
	    .endFlowNode()
	  .buildProcessDefinition();

	  KernelProcessInstance processInstance = processDefinition.createProcessInstance();
	  processInstance.start();

	  assertTrue(processInstance.isEnded());
	}

}


text:
'''
A general map/reduce style salt runner for aggregating results
returned by several different minions.

.. versionadded:: 2014.7.0

Aggregated results are sorted by the size of the minion pools which returned
matching results.

Useful for playing the game: " some of these things are not like the others... "
when identifying discrepancies in a large infrastructure managed by salt.
'''

from __future__ import print_function

from __future__ import absolute_import

import salt.client
from salt.ext.six.moves import range
from salt.exceptions import SaltClientError

def hash(*args, **kwargs):
    '''
    Return the MATCHING minion pools from the aggregated and sorted results of
    a salt command

    .. versionadded:: 2014.7.0

    This command is submitted via a salt runner using the
    general form:

        salt-run survey.hash [survey_sort=up/down] <target>
                  <salt-execution-module> <salt-execution-module parameters>

    Optionally accept a "survey_sort=" parameter. Default: "survey_sort=down"

    CLI Example #1: ( functionally equivalent to "salt-run manage.up" )

    .. code-block:: bash

        salt-run survey.hash "*" test.ping

    CLI Example #2: ( find an "outlier" minion config file )

    .. code-block:: bash

        salt-run survey.hash "*" file.get_hash /etc/salt/minion survey_sort=up
    '''

    return _get_pool_results(*args, **kwargs)

def diff(*args, **kwargs):
    '''
    Return the DIFFERENCE of the result sets returned by each matching minion
    pool

    .. versionadded:: 2014.7.0

    These pools are determined from the aggregated and sorted results of
    a salt command.
    This command displays the "diffs" as a series of 2-way differences-- namely
    the difference between the FIRST displayed minion pool
    (according to sort order) and EACH SUBSEQUENT minion pool result set.
    Differences are displayed according to the Python "difflib.unified_diff()"
    as in the case of the salt execution module "file.get_diff".

    This command is submitted via a salt runner using the general form:

        salt-run survey.diff [survey_sort=up/down] <target>
                     <salt-execution-module> <salt-execution-module parameters>

    Optionally accept a "survey_sort=" parameter. Default: "survey_sort=down"

    CLI Example #1: ( Example to display the "differences of files" )

    .. code-block:: bash

        salt-run survey.diff survey_sort=up "*" cp.get_file_str file:///etc/hosts
    '''
    # TODO: The salt execution module "cp.get_file_str file:///..." is a
    # non-obvious way to display the differences between files using
    # survey.diff .  A more obvious method needs to be found or developed.

    import difflib

    bulk_ret = _get_pool_results(*args, **kwargs)

    is_first_time = True
    for k in bulk_ret:
        print('minion pool :\n'
              '------------')
        print(k['pool'])
        print('pool size :\n'
              '----------')
        print('    ' + str(len(k['pool'])))
        if is_first_time:
            is_first_time = False
            print('pool result :\n'
                  '------------')
            print('    ' + bulk_ret[0]['result'])
            print()
            continue

        outs = ('differences from "{0}" results :').format(
            bulk_ret[0]['pool'][0])
        print(outs)
        print('-' * (len(outs) - 1))
        from_result = bulk_ret[0]['result'].splitlines()
        for i in range(0, len(from_result)):
            from_result[i] += '\n'
        to_result = k['result'].splitlines()
        for i in range(0, len(to_result)):
            to_result[i] += '\n'
        outs = ''
        outs += ''.join(difflib.unified_diff(from_result,
                                             to_result,
                                             fromfile=bulk_ret[0]['pool'][0],
                                             tofile=k['pool'][0],
                                             n=0))
        print(outs)
        print()

    return bulk_ret

def _get_pool_results(*args, **kwargs):
    '''
    A helper function which returns a dictionary of minion pools along with
    their matching result sets.
    Useful for developing other "survey style" functions.
    Optionally accepts a "survey_sort=up" or "survey_sort=down" kwargs for
    specifying sort order.
    Because the kwargs namespace of the "salt" and "survey" command are shared,
    the name "survey_sort" was chosen to help avoid option conflicts.
    '''
    # TODO: the option "survey.sort=" would be preferred for namespace
    # separation but the kwargs parser for the salt-run command seems to
    # improperly pass the options containing a "." in them for later modules to
    # process. The "_" is used here instead.

    import hashlib

    tgt = args[0]
    cmd = args[1]
    ret = {}

    sort = kwargs.get('survey_sort', 'down')
    direction = sort != 'up'

    expr_form = kwargs.get('expr_form', 'compound')
    if expr_form not in ['compound', 'pcre']:
        expr_form = 'compound'

    client = salt.client.get_local_client(__opts__['conf_file'])
    try:
        minions = client.cmd(tgt, cmd, args[2:], timeout=__opts__['timeout'], expr_form=expr_form)
    except SaltClientError as client_error:
        print(client_error)
        return ret

    # hash minion return values as a string
    for minion in sorted(minions):
        digest = hashlib.sha256(str(minions[minion])).hexdigest()
        if digest not in ret:
            ret[digest] = {}
            ret[digest]['pool'] = []
            ret[digest]['result'] = str(minions[minion])

        ret[digest]['pool'].append(minion)

    sorted_ret = []
    for k in sorted(ret, key=lambda k: len(ret[k]['pool']), reverse=direction):
        # return aggregated results, sorted by size of the hash pool

        sorted_ret.append(ret[k])

    return sorted_ret


text:
ScrubRub
========

An experiment in touch-oriented playback control for Netflix


text:
    <title>My Angular App!</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

        <ui-view></ui-view>


text:
(function() {

    var app = angular.module('userFactory', []);

    app.factory('UserFactory', [function() {

        var factory = {};

        return factory;
    }]);
})();