text:
package org.wildfly.swarm.undertow.descriptors;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.jboss.shrinkwrap.api.asset.NamedAsset;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.javaee7.ListenerType;
import org.jboss.shrinkwrap.descriptor.api.javaee7.ParamValueType;
import org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor;
import org.jboss.shrinkwrap.descriptor.api.webcommon31.LoginConfigType;
import org.jboss.shrinkwrap.descriptor.api.webcommon31.SecurityConstraintType;
import org.jboss.shrinkwrap.descriptor.api.webcommon31.ServletType;

import static org.wildfly.swarm.spi.api.ClassLoading.withTCCL;

/**
 * @author Ken Finnigan
 */
public class WebXmlAsset implements NamedAsset {

    public static final String NAME = "WEB-INF/web.xml";

    public WebXmlAsset() {
        this.descriptor =
                withTCCL(Descriptors.class.getClassLoader(),
                         () -> Descriptors.create(WebAppDescriptor.class));
    }

    public WebXmlAsset(InputStream fromStream) {
        this.descriptor =
                withTCCL(Descriptors.class.getClassLoader(),
                         () -> Descriptors.importAs(WebAppDescriptor.class)
                                 .fromStream(fromStream));
    }

    public void setContextParam(String name, String... values) {
        this.descriptor.createContextParam()
                .paramName(name)
                .paramValue(convert(values));
    }

    public String getContextParam(String name) {
        if (name == null || name.length() == 0) {
            return null;
        }

        Optional<ParamValueType<WebAppDescriptor>> paramValue = this.descriptor.getAllContextParam().stream().filter(p -> p.getParamName().equals(name)).findFirst();

        return paramValue.isPresent() ? paramValue.get().getParamValue() : null;
    }

    public Servlet addServlet(String servletName, String servletClass) {
        Servlet servlet = new Servlet(servletName, servletClass);
        this.servlets.add(servlet);
        return servlet;
    }

    public Servlet getServlet(String servletClass) {
        ServletType<WebAppDescriptor> descriptorServlet = this.descriptor.getAllServlet()
                .stream()
                .filter(s -> s.getServletClass().equals(servletClass))
                .findFirst().get();

        return convert(descriptorServlet);
    }

    public void setLoginConfig(String authMethod, String realmName) {
        this.descriptor.getOrCreateLoginConfig()
                .authMethod(authMethod)
                .realmName(realmName);
    }

    public void setFormLoginConfig(String realmName, String loginPage, String errorPage) {
        this.descriptor.getOrCreateLoginConfig()
                .authMethod("FORM")
                .realmName(realmName)
                .getOrCreateFormLoginConfig()
                .formLoginPage(loginPage)
                .formErrorPage(errorPage);
    }

    public String getLoginRealm(String authMethod) {
        if (authMethod == null || authMethod.length() == 0) {
            return null;
        }

        Optional<LoginConfigType<WebAppDescriptor>> loginConfig = this.descriptor.getAllLoginConfig().stream().filter(l -> l.getAuthMethod().equals(authMethod)).findFirst();

        return loginConfig.isPresent() ? loginConfig.get().getRealmName() : null;
    }

    public void addListener(String listener) {
        this.descriptor.createListener()
                .listenerClass(listener);
    }

    public List<String> allListenersClasses() {
        return this.descriptor.getAllListener().stream().map(ListenerType::getListenerClass).collect(Collectors.toList());
    }

    public SecurityConstraint protect() {
        SecurityConstraint constraint = new SecurityConstraint();
        this.constraints.add(constraint);
        return constraint;
    }

    public SecurityConstraint protect(String urlPattern) {
        SecurityConstraint constraint = new SecurityConstraint(urlPattern);
        this.constraints.add(constraint);
        return constraint;
    }

    public List<SecurityConstraint> allConstraints() {
        return constraints;
    }

    /**
     *
     * @param servletName
     * @return the list of url-pattern elements or an empty list if no mapping is present
     */
    public List<String> getServletMapping(String servletName) {
        return this.descriptor.getAllServletMapping().stream().filter((mapping) -> mapping.getServletName().equals(servletName)).findFirst()
                .map(m -> m.getAllUrlPattern()).orElse(Collections.emptyList());
    }

    @Override
    public InputStream openStream() {
        // Add Security Constraints
        Set<String> allRoles = new HashSet<>();

        for (SecurityConstraint each : this.constraints) {
            SecurityConstraintType<WebAppDescriptor> sc = this.descriptor.createSecurityConstraint()
                    .createWebResourceCollection()
                    .urlPattern(each.urlPattern())
                    .httpMethod(each.methods().toArray(new String[each.methods().size()]))
                    .up();
            if (!each.isPermitAll()) {
                sc.getOrCreateAuthConstraint()
                        .roleName(each.roles().toArray(new String[each.roles().size()]))
                        .up();
            }

            allRoles.addAll(each.roles());
        }

        for (String eachRole : allRoles) {
            this.descriptor.getOrCreateSecurityRole()
                    .roleName(eachRole);
        }

        // Add Servlets
        for (Servlet each : this.servlets) {
            ServletType<WebAppDescriptor> servlet =
                    this.descriptor.createServlet()
                            .servletName(each.servletName())
                            .servletClass(each.servletClass())
                            .displayName(each.displayName())
                            .enabled(each.enabled());

            if (each.asyncSupported() != null) {
                servlet.asyncSupported(each.asyncSupported());
            }

            if (each.loadOnStartup() != null) {
                servlet.loadOnStartup(each.loadOnStartup());
            }

            for (Map.Entry<String, String> init : each.initParams().entrySet()) {
                servlet.createInitParam()
                        .paramName(init.getKey())
                        .paramValue(init.getValue());
            }

            if (each.urlPatterns().size() > 0) {
                this.descriptor.createServletMapping()
                        .servletName(each.servletName())
                        .urlPattern(each.urlPatterns().stream().toArray(String[]::new));
            }
        }

        return new ByteArrayInputStream(this.descriptor.exportAsString().getBytes());
    }

    @Override
    public String getName() {
        return NAME;
    }

    private String convert(String... values) {
        StringBuilder builder = new StringBuilder();
        boolean addedFirst = false;

        for (String value : values) {
            if (addedFirst) {
                builder.append(',');
            }
            builder.append(value);
            addedFirst = true;
        }

        return builder.toString();
    }

    private Servlet convert(ServletType<WebAppDescriptor> descriptorServlet) {
        Servlet servlet = new Servlet(descriptorServlet.getServletName(), descriptorServlet.getServletClass());

        List<String> dispNames = descriptorServlet.getAllDisplayName();
        if (dispNames.size() > 0) {
            servlet.withDisplayName(dispNames.get(0));
        }
        List<String> descriptions = descriptorServlet.getAllDescription();
        if (descriptions.size() > 0) {
            servlet.withDescription(descriptions.get(0));
        }
        servlet.withEnabled(descriptorServlet.isEnabled());
        servlet.withAsyncSupported(descriptorServlet.isAsyncSupported());
        servlet.withLoadOnStartup(descriptorServlet.getLoadOnStartup());
        servlet.withInitParams(
                descriptorServlet.getAllInitParam()
                        .stream()
                        .collect(Collectors.toMap(
                                ParamValueType::getParamName,
                                ParamValueType::getParamValue)
                        )
        );
        servlet.withUrlPatterns(this.descriptor.getAllServletMapping()
                                        .stream()
                                        .filter(mapping -> mapping.getServletName().equals(servlet.servletName()))
                                        .findFirst().get().getAllUrlPattern());
        return servlet;
    }

    private final WebAppDescriptor descriptor;

    private List<SecurityConstraint> constraints = new ArrayList<>();

    private List<Servlet> servlets = new ArrayList<>();
}


text:
<?php

/**
 * Dutch language file for iDEAL by Mollie
 */

// Text
$_['heading_title']             = 'Betaling via Mollie';
$_['ideal_title']               = 'Uw betaling';
$_['text_title']                = 'Online betalen';
$_['text_redirected']           = 'De klant is doorgestuurd naar het betaalscherm';
$_['text_issuer_ideal']         = 'Kies uw bank';
$_['text_issuer_giftcard']      = 'Kies uw giftcard';
$_['text_issuer_kbc']           = 'Kies uw betaalknop';
$_['text_issuer_voucher']       = 'Kies uw merk';
$_['text_card_details']         = 'Voer uw creditcardgegevens in.';
$_['text_mollie_payments']      = 'Veilige betalingen geleverd door %s';
$_['text_recurring_desc']       = 'Bestelling %s, %s - %s, elke %s voor %s';
$_['text_recurring']		    = '%s elke %s %s';
$_['text_length']			    = ' voor %s betalingen';
$_['text_trial']			    = '%s elke %s %s voor %s betalingen dan ';
$_['text_error_report_success']	= 'De fout is met succes gerapporteerd!';

// Button
$_['button_retry']          = 'Opnieuw proberen af te rekenen';
$_['button_report']         = 'Report Error';
$_['button_submit']         = 'Verzenden';

// Entry
$_['entry_card_holder']     	= 'Kaarthouder naam';
$_['entry_card_number']     	= 'Kaartnummer';
$_['entry_expiry_date']     	= 'Vervaldatum';
$_['entry_verification_code']	= 'CVV';

// Error
$_['error_card']				= 'Controleer uw kaartgegevens.';
$_['error_missing_field']	    = 'Vereiste informatie ontbreekt. Controleer of er basisadresgegevens zijn verstrekt.';

// Status page: payment failed (e.g. cancelled).
$_['heading_failed']     = 'Uw betaling is niet voltooid';
$_['msg_failed']         = 'Helaas is de betaling mislukt. Klik op onderstaande knop om terug te keren naar het afrekenscherm.';

// Status page: payment pending.
$_['heading_unknown']    = 'We wachten nog op uw betaling';
$_['msg_unknown']        = 'We hebben uw betaling nog niet ontvangen. Wij zullen een bevestigingsmail versturen op het moment dat de betaling binnen is.';

// Status page: API failure.
$_['heading_error']      = 'Er is een fout opgetreden bij het opzetten van de betaling';
$_['text_error']         = 'Er is een fout opgetreden bij het opzetten van de betaling bij Mollie. Klik op onderstaande knop om terug te keren naar het afrekenscherm.';

// Response
$_['response_success']   = 'De betaling is ontvangen';
$_['response_none']      = 'We wachten nog op de betaling. U krijgt een email zodra de status van de betaling bij ons bekend is.';
$_['response_cancelled'] = 'De klant heeft de betaling geannuleerd';
$_['response_failed']    = 'De betaling is helaas mislukt. Probeer het alstublieft opnieuw.';
$_['response_expired']   = 'De betaling is verlopen';
$_['response_unknown']   = 'Er is een onbekende fout opgetreden';
$_['shipment_success']   = 'Zending is gemaakt';
$_['refund_cancelled']   = 'Restitutie is geannuleerd.';
$_['refund_success'] 	 = 'Terugbetaling is succesvol verwerkt!';

// Methods
$_['method_ideal']          = 'iDEAL';
$_['method_creditcard']     = 'Creditcard';
$_['method_bancontact']     = 'Bancontact';
$_['method_banktransfer']   = 'Overboeking';
$_['method_belfius']        = 'Belfius Direct Net';
$_['method_kbc']            = 'KBC/CBC-Betaalknop';
$_['method_sofort']         = 'SOFORT Banking';
$_['method_paypal']         = 'PayPal';
$_['method_paysafecard']    = 'paysafecard';
$_['method_giftcard']       = 'Giftcard';
$_['method_eps']            = 'EPS';
$_['method_giropay']        = 'Giropay';
$_['method_klarnapaylater'] = 'Klarna Pay Later';
$_['method_klarnapaynow']   = 'Klarna Pay Now';
$_['method_klarnasliceit']  = 'Klarna Betaal in 3 delen';
$_['method_przelewy24']  	= 'P24';
$_['method_applepay']    	= 'Apple Pay';
$_['method_voucher']    	= 'Voucher';
$_['method_in3']    	    = 'IN3';

//Round Off Description
$_['roundoff_description']  = 'Afrondingsverschil door valutaomrekening';

//Warning
$_['warning_secure_connection']  = 'Zorg ervoor dat u een veilige verbinding gebruikt.';

redpajama_set_name: RedPajamaGithub


text:
namespace base {
class DictionaryValue;
}

namespace extensions {

// A simplified version of ExternalPrefLoader that loads the dictionary
// from json data specified in a string.
class ExternalTestingLoader : public ExternalLoader {
 public:
  ExternalTestingLoader(const std::string& json_data,
                        const base::FilePath& fake_base_path);
  ExternalTestingLoader(const ExternalTestingLoader&) = delete;
  ExternalTestingLoader& operator=(const ExternalTestingLoader&) = delete;

  // ExternalLoader:
  const base::FilePath GetBaseCrxFilePath() override;

  void StartLoading() override;

 private:
  friend class base::RefCountedThreadSafe<ExternalLoader>;

  ~ExternalTestingLoader() override;

  base::FilePath fake_base_path_;
  std::unique_ptr<base::DictionaryValue> testing_prefs_;
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_EXTERNAL_TESTING_LOADER_H_


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE ViewPatterns #-}
module Test.Hspec.Core.Formatters.Diff (
  Diff (..)
, diff
#ifdef TEST
, partition
, breakList
#endif
) where

import           Prelude ()
import           Test.Hspec.Core.Compat hiding (First)

import           Data.Char
import qualified Data.Algorithm.Diff as Diff

data Diff = First String | Second String | Both String | Omitted Int
  deriving (Eq, Show)

-- |
-- Split a string at line boundaries.
--
-- >>> splitLines "foo\nbar\nbaz"
-- ["foo\n","bar\n","baz"]
--
-- prop> concat (splitLines xs) == xs
splitLines :: String -> [String]
splitLines = go
  where
    go xs = case break (== '\n') xs of
      (ys, '\n' : zs) -> (ys ++ ['\n']) : go zs
      ("", "") -> []
      _ -> [xs]

data TrimMode = FirstChunck | Chunck | LastChunck

trim :: Int -> [Diff] -> [Diff]
trim context = \ chunks -> case chunks of
  [] -> []
  x : xs -> trimChunk FirstChunck x (go xs)
  where
    omitThreshold = 3

    go chunks = case chunks of
      [] -> []
      [x] -> trimChunk LastChunck x []
      x : xs -> trimChunk Chunck x (go xs)

    trimChunk mode chunk = case chunk of
      Both xs | omitted >= omitThreshold -> keep start . (Omitted omitted :) . keep end
        where
          omitted :: Int
          omitted = n - keepStart - keepEnd

          keepStart :: Int
          keepStart = case mode of
            FirstChunck -> 0
            _ -> succ context

          keepEnd :: Int
          keepEnd = case mode of
            LastChunck -> 0
            _ -> if xs `endsWith` "\n" then context else succ context

          n :: Int
          n = length allLines

          allLines :: [String]
          allLines = splitLines xs

          start :: [String]
          start = take keepStart allLines

          end :: [String]
          end = drop (keepStart + omitted) allLines
      _ -> (chunk :)

    keep xs
      | null xs = id
      | otherwise = (Both (concat xs) :)

diff :: Maybe Int -> String -> String -> [Diff]
diff context expected actual = maybe id trim context $ map (toDiff . fmap concat) $ Diff.getGroupedDiff (partition expected) (partition actual)

toDiff :: Diff.Diff String -> Diff
toDiff d = case d of
  Diff.First xs -> First xs
  Diff.Second xs -> Second xs
  Diff.Both xs _ -> Both xs

partition :: String -> [String]
partition = filter (not . null) . mergeBackslashes . breakList isAlphaNum
  where
    mergeBackslashes :: [String] -> [String]
    mergeBackslashes xs = case xs of
      ['\\'] : (splitEscape -> Just (escape, ys)) : zs -> ("\\" ++ escape) : ys : mergeBackslashes zs
      z : zs -> z : mergeBackslashes zs
      [] -> []

breakList :: (a -> Bool) -> [a] -> [[a]]
breakList _ [] = []
breakList p xs = case break p xs of
  (y, ys) -> map return y ++ case span p ys of
    (z, zs) -> z `cons` breakList p zs
  where
    cons x
      | null x = id
      | otherwise = (x :)

splitEscape :: String -> Maybe (String, String)
splitEscape xs = splitNumericEscape xs <|> (msum $ map split escapes)
  where
    split :: String -> Maybe (String, String)
    split escape = (,) escape <$> stripPrefix escape xs

splitNumericEscape :: String -> Maybe (String, String)
splitNumericEscape xs = case span isDigit xs of
  ("", _) -> Nothing
  r -> Just r

escapes :: [String]
escapes = [
    "ACK"
  , "CAN"
  , "DC1"
  , "DC2"
  , "DC3"
  , "DC4"
  , "DEL"
  , "DLE"
  , "ENQ"
  , "EOT"
  , "ESC"
  , "ETB"
  , "ETX"
  , "NAK"
  , "NUL"
  , "SOH"
  , "STX"
  , "SUB"
  , "SYN"
  , "EM"
  , "FS"
  , "GS"
  , "RS"
  , "SI"
  , "SO"
  , "US"
  , "a"
  , "b"
  , "f"
  , "n"
  , "r"
  , "t"
  , "v"
  , "&"
  , "'"
  , "\""
  , "\\"
  ]


text:
namespace PCU.Web {

    public partial class ViewSwitcher {
    }
}


text:
![alt tag](https://dl.dropboxusercontent.com/u/21000833/Bitsend/Website/Splash.png)

 http://www.bitsend.info
 Bitcointalk https://bitcointalk.org/index.php?topic=1370307

Release 21.03.2017
----------------
Update BitSend 1.2.7.1
- add the command `shrinkdebuginterval` (new feature which allows shrinking the debug file periodically)
- getblocktemplate fix
- add new Help File "Create build-ubuntu-1404.md"

What is Bitsend?
----------------

Bitsend is an experimental and new digital currency that enables anonymous, instant
payments to anyone, anywhere in the world. Bitsend uses peer-to-peer technology
to operate without a central authority: transaction management and money subsidy
are carried out collectively by the network. Bitsend Core is the name of open
source software which enables the use of this currency.

For more information, as well as an immediately useable, binary version of
the Bitsend Core software, see http://www.bitsend.info

License
-------

Bitsend Core is released under the terms of the MIT license. See [COPYING](COPYING) for more
information or see https://opensource.org/licenses/MIT.

Development Process
-------------------

The `master` branch is meant to be stable. Development is normally done in separate branches.
[Tags](https://github.com/LIMXTEC/BitSend/tags) are created to indicate new official,
stable release versions of BitSend Core.

The contribution workflow is described in [CONTRIBUTING.md](CONTRIBUTING.md).

Building process
-----------------

**compiling Bitsend from git**

Use the autogen script to prepare the build environment.

    ./autogen.sh
    ./configure
    make

**precompiled binaries**

Precompiled binaries are available at GitHub, see
http://sourceforge.net/projects/bitsend/files/?source=navbar

Always verify the signatures and checksums.

Development tips and tricks
---------------------------

**compiling for debugging**

Run configure with the --enable-debug option, then make. Or run configure with
CXXFLAGS="-g -ggdb -O0" or whatever debug flags you need.

**debug.log**

If the code is behaving strangely, take a look in the debug.log file in the data directory;
error and debugging message are written there.

The -debug=... command-line option controls debugging; running with just -debug will turn
on all categories (and give you a very large debug.log file).

The Qt code routes qDebug() output to debug.log under category "qt": run with -debug=qt
to see it.

**testnet and regtest modes**

Run with the -testnet option to run with "play bitsends" on the test network, if you
are testing multi-machine code that needs to operate across the internet.

If you are testing something that can run on one machine, run with the -regtest option.
In regression test mode blocks can be created on-demand; see qa/rpc-tests/ for tests
that run in -regtest mode.

**DEBUG_LOCKORDER**

Bitsend Core is a multithreaded application, and deadlocks or other multithreading bugs
can be very difficult to track down. Compiling with -DDEBUG_LOCKORDER (configure
CXXFLAGS="-DDEBUG_LOCKORDER -g") inserts run-time checks to keep track of what locks
are held, and adds warning to the debug.log file if inconsistencies are detected.


text:
package com.sandwish.site.service.dao;

import com.sandwish.site.entity.User;

public interface UserService {
	public User getUser(String userID);
}


text:
module EbayTrading # :nodoc:
  module Requests # :nodoc:
    # == Attributes
    #  value_array_node :alert_ids, 'AlertIDs', 'AlertID', :default_value => []
    #  value_array_node :message_ids, 'MessageIDs', 'MessageID', :default_value => []
    class DeleteMyMessages < Abstract
      include XML::Mapping
      include Initializer
      root_element_name 'DeleteMyMessagesRequest'
      value_array_node :alert_ids, 'AlertIDs', 'AlertID', :default_value => []
      value_array_node :message_ids, 'MessageIDs', 'MessageID', :default_value => []
    end
  end
end


text:
package org.apache.servicemix.nmr.api.internal;

import org.apache.servicemix.nmr.api.service.ServiceRegistry;

/**
 * @version $Revision: $
 * @since 4.0
 */
public interface FlowRegistry extends Flow, ServiceRegistry<Flow> {

}


text:
namespace mocores
{
    class Config
    {
    public:
        virtual void openConfig(const std::string &path) = 0;

        virtual void saveConfig(const std::string& path) = 0;
    };
}

#endif


text:
layout: post
title: "HTML is Boring"
author: "Dave Jacoby"
date: "2020-05-14 22:15:11 -0400"
categories: ""
---

## "HTML is Boring"

This is a message my friend tweeted, then immediately deleted, as he decided to not "stir the pot".

I'm game. HTML is Boring.

By and large, it is a good thing. I mean, writing (or in this current case, typing) is boring, because the thing you're ending up with is what's cool.

I mean, the first passes of HTML is to give us a quick and easy way to do the same things as we got from Word — **bold**, _italics_, paragraphs, lists and the like — and designers and developers trying to turn HTML into a pixel-perfect thing, despite going to different browsers on different screens with different resolutions on different operating systems.

That HTML is boring because it is _simple_: solving problems we've solved before. We want the useful technologies to be boring, because if they're not, it's hard to build upon them. Routing emails is boring because we don't have to deal with bang paths and such. Internal combustion is boring. These are good things.

But there's more.

There's lots to make things work for different languages, for accessability, and grids for responsive design across several platforms, and beyond. And y'know, I see why it's considered important and all, but honestly, I find it tedious.

Largely, when I touch it, I use templates and automate it as much as possible.

HTML _is_ boring. I stand by that statement.

#### If you have any questions or comments, I would be glad to hear it. Ask me on [Twitter](https://twitter.com/jacobydave) or [make an issue on my blog repo.](https://github.com/jacoby/jacoby.github.io)


text:
package com.betahikaru.aws.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;

public class ConfigProvider {

	private static Properties credentialsProperty = null;

	public static void loadConfigure(InputStream inputStream) {
		credentialsProperty = new Properties();
		try {
			credentialsProperty.load(inputStream);
		} catch (IOException e) {
			System.err.println("load property");
		}
	}

	private static Region defaultRegion = Region.getRegion(Regions.AP_NORTHEAST_1);

	public static Region getDefaultRegion() {
		if (defaultRegion == null && credentialsProperty != null) {
			String regionKey = credentialsProperty.getProperty("aws.region");
			if (regionKey != null) {
				defaultRegion = Region.getRegion(Regions.valueOf(regionKey));
			}
		}
		return defaultRegion;
	}

	private static AWSCredentials credentials = null;

	public static AWSCredentials getCredential() {
		if (credentials == null && credentialsProperty != null) {
			String accessKey = credentialsProperty.getProperty("aws.access_key_id");
			String secretKey = credentialsProperty.getProperty("aws.secret_access_key");
			credentials = new BasicAWSCredentials(accessKey, secretKey);
		}
		return credentials;
	}

}


text:
using System;
using System.IO;
using System.Xml.Linq;
using log4net;
using log4net.Appender;
using log4net.Repository.Hierarchy;
using StructureMap;

namespace FloydPink.Flickr.Downloadr.Bootstrap
{
  public static class Bootstrapper
  {
    private const string AppenderName = "XmlSchemaFileAppender";
    private const string LogFileName = "flickrdownloadr.log";
    private const string LogConfigFileName = "flickrdownloadr.log4net";
    private static readonly ILog Log = LogManager.GetLogger(typeof(Bootstrapper));
    private static Container _container;
    private static string _logLevel;
    private static string _logFile;

    public static void Initialize()
    {
      Log.Debug("Initialize");
      _container = new Container(expression =>
      {
        expression.AddRegistry<CommonsRegistry>();
        expression.AddRegistry<OAuthRegistry>();
        expression.AddRegistry<RepositoryRegistry>();
        expression.AddRegistry<LogicRegistry>();
        expression.AddRegistry<PresentationRegistry>();
      });
      ReadLoggingConfiguration();
    }

    public static T GetInstance<T>()
    {
      Log.Debug("GetInstance<T>");
      return _container.GetInstance<T>();
    }

    public static TPresenter GetPresenter<TView, TPresenter>(TView view)
    {
      Log.Debug("GetPresenter<TView, TPresenter>");
      return _container.With(view).GetInstance<TPresenter>();
    }

    public static FileInfo GetLogFile()
    {
      Log.Debug("GetLogFile");
      return GetAppDirectoryFile(LogFileName);
    }

    public static FileInfo GetLogConfigFile()
    {
      Log.Debug("GetLogConfigFile");
      var writableLogConfigFile = GetAppDataDirectoryFile(LogConfigFileName);
      if (!writableLogConfigFile.Exists)
      {
        GetAppDirectoryFile(LogConfigFileName).CopyTo(writableLogConfigFile.FullName);
      }
      return writableLogConfigFile;
    }

    public static void ReconfigureLogging(string level, string logFolder)
    {
      Log.Debug("ReconfigureLogging");
      var logLevel = level.ToUpperInvariant();
      var logFile = Path.Combine(logFolder, LogFileName);

      if ((logLevel != _logLevel) || (logFile != _logFile))
      {
        _logLevel = logLevel;
        _logFile = logFile;

        var log4NetConfig = XDocument.Load(GetLogConfigFile().FullName);

        var fileElement = log4NetConfig.Root.Element("appender").Element("file");
        fileElement.Attribute("value").SetValue(logFile);

        var levelElement = log4NetConfig.Root.Element("root").Element("level");
        levelElement.Attribute("value").SetValue(logLevel);

        log4NetConfig.Save(GetLogConfigFile().FullName);

        Log.Debug(string.Format("Reconfigured log4net to the level '{0}' and the file '{1}'", logLevel, logFile));
      }
    }

    private static FileInfo GetAppDirectoryFile(string filename)
    {
      Log.Debug("GetAppDirectoryFile");
      return new FileInfo(Path.Combine(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory), filename));
    }

    private static FileInfo GetAppDataDirectoryFile(string filename)
    {
      Log.Debug("GetAppDataDirectoryFile");
      var appDataDirectoryFile = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        "flickr-downloadr", filename));
      appDataDirectoryFile.Directory.Create();
      return appDataDirectoryFile;
    }

    private static void ReadLoggingConfiguration()
    {
      Log.Debug("ReadLoggingConfiguration");
      var hierarchy = (Hierarchy) LogManager.GetRepository();
      var rootLogger = hierarchy.Root;

      _logLevel = rootLogger.Level.ToString();

      var appender = rootLogger.GetAppender(AppenderName) as FileAppender;
      if (appender != null)
      {
        _logFile = appender.File;
      }
    }
  }
}


text:
#pragma once

#define DEF_SYSCALL(num, ret, name, ...) SYS_## name = num,

enum{
#include <sysmaster/syscalls.inc>
};


text:
      Age
      Client
      Flow URN
      Flow Name
      Message

      <nobr>{$ ::item.age * 1000 | date:'medium' $}</nobr>
      <grr-client-urn value="::item.value.client_id.value" />
      {$ ::item.shortUrn.value $}
      {$ ::item.value.flow_name.value $}
      {$ ::item.value.log_message.value $}


text:
package org.apache.click.examples.page.tree;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.click.Context;
import org.apache.click.control.Checkbox;
import org.apache.click.control.FieldSet;
import org.apache.click.control.Form;
import org.apache.click.control.Submit;
import org.apache.click.examples.page.BorderPage;
import org.apache.click.examples.util.ExampleUtils;
import org.apache.click.extras.tree.Tree;
import org.apache.click.extras.tree.TreeListener;
import org.apache.click.extras.tree.TreeNode;

/**
 * Example usage of some extra functionality of the {@link Tree} control.
 */
public class AdvancedTreePage extends BorderPage implements TreeListener {

    private static final long serialVersionUID = 1L;

    public static final String TREE_NODES_SESSION_KEY = "advancedTreeNodes";

    private Tree tree;

    // Event Handlers ---------------------------------------------------------

    /**
     * @see org.apache.click.Page#onInit()
     */
    @Override
    public void onInit() {
        super.onInit();

        //Create the tree and tree model and add it to the page
        tree = buildTree();
        tree.addListener(this);
        addControl(tree);

        //Build the options user interface for users to interactively
        //change the tree values.
        buildOptionsUI();
    }

    /**
     * Called when user submits the options form.
     */
    public boolean onApplyOptionsClick() {
        //Reset the tree and nodes to default values
        resetTree();

        //Store the users options in the session
        TreeOptions options = new TreeOptions();
        options.javascriptEnabled = jsEnabled.isChecked();
        options.rootNodeDisplayed = rootNodeDisplayed.isChecked();
        ExampleUtils.setSessionObject(options);

        //Apply users new options
        applyOptions();

        return true;
    }

    // Public Methods ---------------------------------------------------------

    /**
     * Creates and return a new tree instance.
     */
    public Tree createTree() {
        return new Tree("advancedTree" );
    }

    /**
     * Build the tree model and stores it in the session.
     */
    public Tree buildTree() {
        tree = createTree();

        //Try and load the already stored nodes from the session.
        //If this is the first time we access the page, this method
        //will return null, indicating no nodes is stored.
        TreeNode existingRootNode = loadNodesFromSession();

        if(existingRootNode != null) {
            //OK we had already nodes stored in the session, so no need
            //to rebuild them. We attach the root node and return.
            tree.setRootNode(existingRootNode);

            return tree;
        }

        // Create a node representing the root directory with the specified
        // parameter as the value. Because an id is not specified, a random
        // one will be generated by the node. By default the root node is
        // not rendered by the tree. This can be changed by calling
        // tree.setRootNodeDisplayed(true).
        TreeNode root = new TreeNode("c:");

        // Create a new directory, setting the root directory as its parent. Here
        // we do specify a id as the 2nd argument, so no id is generated.
        TreeNode dev = new TreeNode("dev","1");
        root.add(dev);

        // The following 3 nodes represent files in the directory as children of
        // the dev node. Note the false argument to the constructor.
        // This means that the specific node does not support child nodes, and
        // it will be rendered as a leaf icon. If children are supported (the
        // default value) then even  if the node is a leaf, it will still be rendered
        // as a collapsed icon. In the example a default leaf node will be
        // rendered as a directory, and a node that does not support children is
        // rendered as a file.
        // Also note the node with the long text, will cause the tree to overflow
        // and add scrollbars
        dev.add(new TreeNode("java.pdf", "1.1", false));
        dev.add(new TreeNode("JEE 6 - the new fantastic approach to write better software (apparently)", "1.2", false));
        dev.add(new TreeNode("ruby.pdf", "1.3", false));

        //We continue constructing the rest of the tree
        TreeNode programFiles = new TreeNode("program files", "2");
        root.add(programFiles);
        programFiles.add(new TreeNode("Adobe", "2.1"));

        TreeNode download = new TreeNode("downloads","3");
        root.add(download);

        TreeNode web = new TreeNode("web", "3.1");
        download.add(web);
        web.add(new TreeNode("html.pdf", "3.1.1", false));
        web.add(new TreeNode("css.html", "3.1.2", false));

        TreeNode databases = new TreeNode("databases", "3.2");
        download.add(databases);
        TreeNode relationalDb = new TreeNode("relational", "3.2.1");
        databases.add(relationalDb);

        relationalDb.add(new TreeNode("mysql.html", "3.2.1.1", false));
        relationalDb.add(new TreeNode("oracle.pdf", "3.2.1.2", false));
        relationalDb.add(new TreeNode("postgres", "3.2.1.3", false));

        TreeNode objectDb = new TreeNode("object", "3.2.2");
        databases.add(objectDb);
        objectDb.add(new TreeNode("db4o.html", "3.2.2.1", false));

        //Attach the root node containing all the other nodes to the tree
        tree.setRootNode(root);

        //By default root node is not displayed in browser. Here we expand it,
        //so that the root's children are visible.
        expandRoot();

        //Store the tree nodes in the session so on the next request we do not
        //have to rebuild it. Also because we keep the tree nodes in the session
        //the nodes will keep their state between requests.
        storeNodesInSession(root);

        return tree;
    }

    // TreeListener Support ---------------------------------------------------

    /**
     * This method, which implements TreeListener, is called when a node is selected
     */
    public void nodeSelected(Tree tree, TreeNode node, Context context, boolean oldValue) {
        List list = getModelValue("selected");
        list.add(node);
    }

    /**
     * This method, which implements TreeListener, is called when a node is deselected
     */
    public void nodeDeselected(Tree tree, TreeNode node, Context context, boolean oldValue) {
        List list = getModelValue("deselected");
        list.add(node);
    }

    /**
     * This method, which implements TreeListener, is called when a node is expanded
     */
    public void nodeExpanded(Tree tree, TreeNode node, Context context, boolean oldValue) {
        List list = getModelValue("expanded");
        list.add(node);
    }

    /**
     * This method, which implements TreeListener, is called when a node is collapsed
     */
    public void nodeCollapsed(Tree tree, TreeNode node, Context context, boolean oldValue) {
        List list = getModelValue("collapsed");
        list.add(node);
    }

    /**
     * Returns the value for the specified name from the page's model.
     * If a value is not found, a new ArrayList is created and added to the model.
     */
    private List getModelValue(String name) {
        List list = (List) getModel().get(name);
        if(list == null) {
            list = new ArrayList();
            addModel(name, list);
        }
        return list;
    }

    // ------------------------------------------------------------------- NOTE
    //The code below is not specific to the tree control. It was moved here
    //so as not to distract the user from the use of the tree control.

    private Form optionsForm;
    private Checkbox jsEnabled = new Checkbox("jsEnabled", "JavaScript Enabled");
    private Checkbox rootNodeDisplayed = new Checkbox("rootNodeDisplayed", "Display root node");
    private Submit applyOptions = new Submit("apply", "Apply Options", this, "onApplyOptionsClick");

    /**
     * Builds the user interface for users to change the tree options interactively.
     */
    public void buildOptionsUI() {
        //Form to handle user selected options
        optionsForm = new Form("optionForm");
        FieldSet fieldSet = new FieldSet("options", "Form Options");
        fieldSet.add(jsEnabled);
        fieldSet.add(rootNodeDisplayed);
        optionsForm.add(fieldSet);

        addControl(optionsForm);
        optionsForm.add(applyOptions);

        //Apply users existing options
        applyOptions();
    }

    /** Form options holder. */
    public static class TreeOptions implements Serializable {
        private static final long serialVersionUID = 1L;
        boolean javascriptEnabled= false;
        boolean rootNodeDisplayed = false;
    }

    /**
     * Reset the tree to initial state
     */
    private void resetTree() {
        // Remove any Session entries made by Tree
        tree.cleanupSession();

        //Temporarily disable notification to any tree listeners while we reset the tree
        tree.setNotifyListeners(false);

        //Clear all current selections so the tree can start afresh with new options enabled
        tree.deselectAll();
        tree.collapseAll();

        //Enable notification to any tree listeners again
        tree.setNotifyListeners(true);

        if(!rootNodeDisplayed.isChecked()) {
            //If rootNodeDisplayed is false, the root node is not displayed in browser. Here we
            //expand it,  so that the root's children are visible.
            expandRoot();
        }
    }

    /**
     * Store the tree nodes in the session
     */
    private void storeNodesInSession(TreeNode rootNode) {
        if (tree.getRootNode() == null) {
            return;
        }

        getContext().getSession().setAttribute(TREE_NODES_SESSION_KEY, rootNode);
    }

    /**
     * Retrieve the tree nodes from the session if available. Otherwise we return
     * null.
     */
    private TreeNode loadNodesFromSession() {
        return (TreeNode) getContext().getSession().getAttribute(TREE_NODES_SESSION_KEY);
    }

    /**
     * Enable javascript so that there are no round trips to server
     * when expand and collapsing nodes.
     */
    private void enableJavascript(boolean enable) {
        //This call enables the client side javascript functionality
        tree.setJavascriptEnabled(enable);
    }

    /**
     * Applies the user selected options to the tree like enabling javascript,
     * displaying the root node etc.
     */
    private void applyOptions() {

        //We retrieve our stored options from the session and set the controls state
        TreeOptions options = (TreeOptions)
            ExampleUtils.getSessionObject(TreeOptions.class);

        jsEnabled.setChecked(options.javascriptEnabled);
        rootNodeDisplayed.setChecked(options.rootNodeDisplayed);

        //Enable or disable javascript functionality based on users current option
        enableJavascript(options.javascriptEnabled);

        //Indicates if we want to display the root node or not.
        tree.setRootNodeDisplayed(options.rootNodeDisplayed);
    }

    /**
     * Expand the root but do not notify any tree listeners of the change.
     */
    private void expandRoot() {
        //Temporarily disable notification to any tree listeners while we expand the root node
        tree.setNotifyListeners(false);

        tree.expand(tree.getRootNode());

        //Enable notification to any tree listeners again
        tree.setNotifyListeners(true);
    }

}


text:
package org.eigenbase.rel.rules;

import java.util.*;

import org.eigenbase.rel.*;
import org.eigenbase.relopt.*;
import org.eigenbase.rex.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.util.*;
import org.eigenbase.util.mapping.IntPair;

import com.google.common.collect.Lists;

/**
 * Rule which converts a {@link JoinRel} into a {@link CorrelatorRel}, which can
 * then be implemented using nested loops.
 *
 *
For example,

 *
 *
select * from emp join dept on emp.deptno =
 * dept.deptno

 *
 *
becomes a CorrelatorRel which restarts TableAccessRel("DEPT") for each row
 * read from TableAccessRel("EMP").

 *
 *
This rule is not applicable if for certain types of outer join. For
 * example,

 *
 *
select * from emp right join dept on emp.deptno =
 * dept.deptno

 *
 *
would require emitting a NULL emp row if a certain department contained no
 * employees, and CorrelatorRel cannot do that.

 */
public class NestedLoopsJoinRule extends RelOptRule {
  //~ Static fields/initializers ---------------------------------------------

  public static final NestedLoopsJoinRule INSTANCE =
      new NestedLoopsJoinRule();

  //~ Constructors -----------------------------------------------------------

  /**
   * Private constructor; use singleton {@link #INSTANCE}.
   */
  private NestedLoopsJoinRule() {
    super(operand(JoinRel.class, any()));
  }

  //~ Methods ----------------------------------------------------------------

  public boolean matches(RelOptRuleCall call) {
    JoinRel join = call.rel(0);
    switch (join.getJoinType()) {
    case INNER:
    case LEFT:
      return true;
    case FULL:
    case RIGHT:
      return false;
    default:
      throw Util.unexpected(join.getJoinType());
    }
  }

  public void onMatch(RelOptRuleCall call) {
    assert matches(call);
    final JoinRel join = call.rel(0);
    RelNode right = join.getRight();
    final RelNode left = join.getLeft();
    final JoinInfo joinInfo = join.analyzeCondition();
    final List<Correlation> correlationList = Lists.newArrayList();
    final RelOptCluster cluster = join.getCluster();
    final RexBuilder rexBuilder = cluster.getRexBuilder();
    final List<RexNode> conditions = Lists.newArrayList();
    for (IntPair p : joinInfo.pairs()) {
      final String dynInIdStr = cluster.getQuery().createCorrel();
      final int dynInId = RelOptQuery.getCorrelOrdinal(dynInIdStr);

      // Create correlation to say 'each row, set variable #id
      // to the value of column #leftKey'.
      correlationList.add(new Correlation(dynInId, p.source));
      conditions.add(
          rexBuilder.makeCall(SqlStdOperatorTable.EQUALS,
              rexBuilder.makeInputRef(right, p.target),
              rexBuilder.makeCorrel(
                  left.getRowType().getFieldList().get(p.source).getType(),
                  dynInIdStr)));
    }
    final RelNode filteredRight = RelOptUtil.createFilter(right, conditions);
    RelNode newRel =
        new CorrelatorRel(
            join.getCluster(),
            left,
            filteredRight,
            joinInfo.getRemaining(join.getCluster().getRexBuilder()),
            correlationList,
            join.getJoinType());
    call.transformTo(newRel);
  }
}

// End NestedLoopsJoinRule.java


text:
using org.xmlvm;
namespace org.xml.sax {
public class SAXNotRecognizedException: global::org.xml.sax.SAXException {
new public void @this(){
//XMLVM_BEGIN_WRAPPER[org.xml.sax.SAXNotRecognizedException: void <init>()]
    global::System.Object _r0_o = null;
    _r0_o = this;
    ((global::org.xml.sax.SAXException) _r0_o).@this();
    return;
//XMLVM_END_WRAPPER[org.xml.sax.SAXNotRecognizedException: void <init>()]
}

new public void @this(global::java.lang.String n1){
//XMLVM_BEGIN_WRAPPER[org.xml.sax.SAXNotRecognizedException: void <init>(java.lang.String)]
    global::System.Object _r0_o = null;
    global::System.Object _r1_o = null;
    _r0_o = this;
    _r1_o = n1;
    ((global::org.xml.sax.SAXException) _r0_o).@this((global::java.lang.String) _r1_o);
    return;
//XMLVM_END_WRAPPER[org.xml.sax.SAXNotRecognizedException: void <init>(java.lang.String)]
}

//XMLVM_BEGIN_WRAPPER[org.xml.sax.SAXNotRecognizedException]
//XMLVM_END_WRAPPER[org.xml.sax.SAXNotRecognizedException]

} // end of class: SAXNotRecognizedException

} // end of namespace: org.xml.sax


text:
"""
__init__.py: Package definition for the dataCommander DBAL.

Copyright (c) 2015 Pyrus <pyrus at coffee dash break dot at>
See the file LICENSE for copying permission.
"""

from .common import Session, Base, engine


text:
//
//  GDataContactElements.h
//

#if !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_CONTACTS_SERVICE

#import "GDataObject.h"
#import "GDataValueConstruct.h"
#import "GDataContactLink.h"

#undef _EXTERN
#undef _INITIALIZE_AS
#ifdef GDATACONTACTELEMENTS_DEFINE_GLOBALS
#define _EXTERN
#define _INITIALIZE_AS(x) =x
#else
#define _EXTERN GDATA_EXTERN
#define _INITIALIZE_AS(x)
#endif

// gender
_EXTERN NSString* kGDataContactGenderFemale         _INITIALIZE_AS(@"female");
_EXTERN NSString* kGDataContactGenderMale           _INITIALIZE_AS(@"male");

// calendarLink rel
_EXTERN NSString* kGDataContactCalendarLinkHome     _INITIALIZE_AS(@"home");
_EXTERN NSString* kGDataContactCalendarLinkWork     _INITIALIZE_AS(@"work");
_EXTERN NSString* kGDataContactCalendarLinkFreeBusy _INITIALIZE_AS(@"free-busy");

// websiteLink rel
_EXTERN NSString* kGDataContactWebsiteLinkBlog     _INITIALIZE_AS(@"blog");
_EXTERN NSString* kGDataContactWebsiteLinkFTP      _INITIALIZE_AS(@"ftp");
_EXTERN NSString* kGDataContactWebsiteLinkHome     _INITIALIZE_AS(@"home");
_EXTERN NSString* kGDataContactWebsiteLinkHomePage _INITIALIZE_AS(@"home-page");
_EXTERN NSString* kGDataContactWebsiteLinkOther    _INITIALIZE_AS(@"other");
_EXTERN NSString* kGDataContactWebsiteLinkProfile  _INITIALIZE_AS(@"profile");
_EXTERN NSString* kGDataContactWebsiteLinkWork     _INITIALIZE_AS(@"work");

// billing, like <gContact:billingInformation>Blah</gContact:billingInformation>
@interface GDataContactBillingInformation : GDataValueElementConstruct <GDataExtension>
@end

// birthday, like <gContact:birthday when="1-Jan-1992" />
@interface GDataContactBirthday : GDataValueConstruct <GDataExtension>
@end

// related calendar link
@interface GDataContactCalendarLink : GDataContactLink <GDataExtension>
@end

// directory server, like <gContact:directoryServer>directory.domain.com</gContact:directoryServer>
@interface GDataContactDirectoryServer : GDataValueElementConstruct <GDataExtension>
@end

// gender, like <gContact:gender value="female" />
@interface GDataContactGender : GDataValueConstruct <GDataExtension>
@end

// hobby, like <gContact:hobby>eating crackers</gContact:hobby> // TODO - sure it's an element, not an attribute?
@interface GDataContactHobby : GDataValueElementConstruct <GDataExtension>
@end

// initials, like <gContact:initials>I.M.</gContact:initials> // TODO - sure it's an element, not an attribute?
@interface GDataContactInitials : GDataValueElementConstruct <GDataExtension>
@end

// maiden name, like <gContact:maidenName>Sosnick</gContact:maidenName>
@interface GDataContactMaidenName : GDataValueElementConstruct <GDataExtension>
@end

// mileage, like <gContact:mileage>20 km/l</gContact:mileage>
@interface GDataContactMileage : GDataValueElementConstruct <GDataExtension>
@end

// nickname, like <gContact:nickname>Freddy</gContact:nickname>
@interface GDataContactNickname : GDataValueElementConstruct <GDataExtension>
@end

// occupation, like <gContact:occupation>Chef</gContact:occupation>
@interface GDataContactOccupation : GDataValueElementConstruct <GDataExtension>
@end

// short name, like <gContact:shortName>Fred</gContact:shortName>
@interface GDataContactShortName : GDataValueElementConstruct <GDataExtension>
@end

// subject, like <gContact:subject>data</gContact:subject>
@interface GDataContactSubject : GDataValueElementConstruct <GDataExtension>
@end

// related website link
@interface GDataContactWebsiteLink : GDataContactLink <GDataExtension>
@end

#endif // !GDATA_REQUIRE_SERVICE_INCLUDES || GDATA_INCLUDE_CONTACTS_SERVICE


text:
namespace vkpp::ext
{

enum class DebugReportFlagBits
{
    eInformation        = VK_DEBUG_REPORT_INFORMATION_BIT_EXT,
    eWarning            = VK_DEBUG_REPORT_WARNING_BIT_EXT,
    ePerformanceWarning = VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
    eError              = VK_DEBUG_REPORT_ERROR_BIT_EXT,
    eDebug              = VK_DEBUG_REPORT_DEBUG_BIT_EXT
};

VKPP_ENUM_BIT_MASK_FLAGS_EXT(DebugReport)

class DebugReportCallbackCreateInfo : public internal::VkTrait<DebugReportCallbackCreateInfo, VkDebugReportCallbackCreateInfoEXT>
{
private:
    const internal::Structure sType = internal::Structure::eDebugReportCallback;

public:
    const void*                     pNext{ nullptr };
    DebugReportFlags                flags;
    PFN_vkDebugReportCallbackEXT    pfnCallback{ nullptr };
    void*                           pUserData{ nullptr };

    DEFINE_CLASS_MEMBER(DebugReportCallbackCreateInfo)

    DebugReportCallbackCreateInfo(const DebugReportFlags& aFlags, PFN_vkDebugReportCallbackEXT apfnCallback, void* apUserData = nullptr) noexcept
        : flags(aFlags), pfnCallback(apfnCallback), pUserData(apUserData)
    {
        assert(flags != DefaultFlags);              // flags must not be 0.
    }

    DebugReportCallbackCreateInfo& SetNext(const void* apNext) noexcept
    {
        pNext = apNext;

        return *this;
    }

    DebugReportCallbackCreateInfo& SetFlags(const DebugReportFlags& aFlags) noexcept
    {
        assert(flags != DefaultFlags);

        flags = aFlags;

        return *this;
    }

    DebugReportCallbackCreateInfo& SetCallback(PFN_vkDebugReportCallbackEXT apfnCallback, void* apUserData = nullptr) noexcept
    {
        pfnCallback = apfnCallback;
        pUserData   = apUserData;

        return *this;
    }
};

ConsistencyCheck(DebugReportCallbackCreateInfo, pNext, flags, pfnCallback, pUserData)

class DebugReportCallback : public internal::VkTrait<DebugReportCallback, VkDebugReportCallbackEXT>
{
private:
    VkDebugReportCallbackEXT mDebugReportCallback{ VK_NULL_HANDLE };

public:
    DebugReportCallback(void) noexcept = default;

    DebugReportCallback(std::nullptr_t) noexcept
    {}

    explicit DebugReportCallback(VkDebugReportCallbackEXT aDebugReportCallback) noexcept : mDebugReportCallback(aDebugReportCallback)
    {}
};

StaticSizeCheck(DebugReportCallback)

}                   // End of namespace vkpp::ext.

#endif              // __VKPP_TYPE_DEBUG_REPORT_CALLBACK_H__


text:
import { Observable } from '../../internal/Observable';
import { expand } from '../../internal/patching/operator/expand';

Observable.prototype.expand = expand;

declare module '../../internal/Observable' {
  interface Observable<T> {
    expand: typeof expand;
  }
}


text:
@interface ViewController () <CLLocationManagerDelegate>

@property (nonatomic, assign) CLLocationCoordinate2D origin;

@property (strong, nonatomic) CLLocationManager *locationManager;

@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;
@property (weak, nonatomic) IBOutlet UIView *originView;
@property (weak, nonatomic) IBOutlet UILabel *originLabel;
@property (weak, nonatomic) IBOutlet UIView *destinationView;
@property (weak, nonatomic) IBOutlet UILabel *destinationLabel;
@property (weak, nonatomic) IBOutlet UIView *geometryDistanceView;
@property (weak, nonatomic) IBOutlet UILabel *geometryDistanceLabel;
@property (weak, nonatomic) IBOutlet UIView *realDistanceView;
@property (weak, nonatomic) IBOutlet UILabel *realDistanceLabel;

@end

@implementation ViewController

#pragma mark - VIEW LIFECYCLE

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Apple
    self.origin = CLLocationCoordinate2DMake(37.332064, -122.028570);
    self.originLabel.text = @"Apple, Infinite Loop";

    // Start getting current location
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    self.locationManager.distanceFilter = 100;
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager startUpdatingLocation];

    // Customize UI
    [self customizeUI];
}

- (void)customizeUI
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    // Black background
    self.originView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.35];
    self.destinationView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.35];
    self.geometryDistanceView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.35];
    self.realDistanceView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.35];

    // Show camera on real device for nice effect
    BOOL hasCamera = ([[AVCaptureDevice devices] count] > 0);
    if (hasCamera)
    {
        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        session.sessionPreset = AVCaptureSessionPresetHigh;

        AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
        [captureVideoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        [captureVideoPreviewLayer setFrame:self.backgroundImageView.bounds];
        [self.backgroundImageView.layer addSublayer:captureVideoPreviewLayer];

        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        NSError *error = nil;
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
        [session addInput:input];
        [session startRunning];
    }
    else
    {
        self.backgroundImageView.image = [UIImage imageNamed:@"background"];
    }
}

#pragma mark - LOCATION MANAGER

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    CGFloat geometryDistance = [LMDistanceCalculator geometryDistanceFromOrigin:self.origin destination:location.coordinate];

    // Update UI
    self.destinationLabel.text = [NSString stringWithFormat:@"%.6f, %.6f", location.coordinate.latitude, location.coordinate.longitude];
    self.geometryDistanceLabel.text = [NSString stringWithFormat:@"%dm", (int)geometryDistance];

    // Start to reverse
    [[LMDistanceCalculator sharedInstance] cancelCalculator];
    [[LMDistanceCalculator sharedInstance] realDistanceFromOrigin:self.origin
                                                      destination:location.coordinate
                                                completionHandler:^(NSNumber * _Nullable result, NSError * _Nullable error) {

                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                if (result && !error) {
                                                    self.realDistanceLabel.text = [NSString stringWithFormat:@"%dm", [result intValue]];
                                                }
                                                else {
                                                    self.realDistanceLabel.text = @"-";
                                                }
                                            });
                                        }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Updating location failed");
}

@end


text:
var Mongoose = require('mongoose');

var Schema = new Mongoose.Schema({
    name : { type: String, match: /[a-zA-Z0-9_\-]+/, unique: true },
    game : { type: Mongoose.Schema.ObjectId, ref: 'Game' }
});

var Model = Mongoose.model('Room', Schema);

module.exports = function(App){
    return {
        Model: Model,
        SyncModel: {
            read: function(params, callback){
                Model.findOne(params).populate('game').exec(function(error, room){
                    if (error) {
                        return callback(App.createError('FATAL', 'QUERY_ERROR', error));
                    } else if (!room) {
                        return callback(App.createError('FATAL', 'NOT_FOUND'));
                    }

                    callback(null, room);
                });
            }
        }
    };
};


text:
var gblPhotoShufflerDivId = "screenshot-slide";
var gblPhotoShufflerImgId = "screenshot-slide-image";

var gblRotations = 40;
var gblFPS = 20;

// End Customization section

var gblOpacity = 100;
var gblOnDeck = 0;
var gblStartImg;

function photoShufflerLaunch()
{
    var theimg = document.getElementById(gblPhotoShufflerImgId);
    gblStartImg = theimg.src; // save away to show as final image

    document.getElementById(gblPhotoShufflerDivId).style.backgroundImage='url(' + gblImg[gblOnDeck] + ')';
    setTimeout("photoShufflerFade()",gblPauseSeconds*1000);
}

function photoShufflerFade()
{
    var theimg = document.getElementById(gblPhotoShufflerImgId);

    // determine delta based on number of fade seconds
    // the slower the fade the more increments needed
    var fadeDelta = 100 / (gblFPS * gblFadeSeconds);

    // fade top out to reveal bottom image
    if (gblOpacity < 2*fadeDelta)  {
        gblOpacity = 100;
        // stop the rotation if we're done
        if (gblImageRotations < 1) return;
        photoShufflerShuffle();
        // pause before next fade
        setTimeout("photoShufflerFade()",gblPauseSeconds*1000);
    } else {
        gblOpacity -= fadeDelta;
        setOpacity(theimg,gblOpacity);
        setTimeout("photoShufflerFade()",1000/gblFPS);
    }
}

var finished = false;
function photoShufflerShuffle()
{
    var thediv = document.getElementById(gblPhotoShufflerDivId);
    var theimg = document.getElementById(gblPhotoShufflerImgId);

    // copy div background-image to img.src
    theimg.src = gblImg[gblOnDeck];
    // set img opacity to 100
    setOpacity(theimg,100);

    // shuffle the deck
    gblOnDeck = ++gblOnDeck % gblDeckSize;
    // decrement rotation counter
    if (--gblImageRotations < 1) {
        finished = true;
        // insert start/final image if we're done
        gblImg[gblOnDeck] = gblStartImg;
    }

    // slide next image underneath
    thediv.style.backgroundImage='url(' + gblImg[gblOnDeck] + ')';
}

function setOpacity(obj, opacity)
{
    if (finished)
        return;

    opacity = (opacity == 100)?99.999:opacity;

    // IE/Win
    obj.style.filter = "alpha(opacity:"+opacity+")";

    // Safari<1.2, Konqueror
    obj.style.KHTMLOpacity = opacity/100;

    // Older Mozilla and Firefox
    obj.style.MozOpacity = opacity/100;

    // Safari 1.2, newer Firefox and Mozilla, CSS3
    obj.style.opacity = opacity/100;
}


text:
#import "SequencerKeyframe.h"
#import "SequencerNodeProperty.h"
#import "SequencerKeyframeEasing.h"

NSString * kClipboardKeyFrames          = @"com.cocosbuilder.keyframes";
NSString * kClipboardChannelKeyframes   = @"com.cocosbuilder.channelkeyframes";

@implementation SequencerKeyframe

@synthesize value;
@synthesize type;
@synthesize name;

@synthesize time;
@synthesize timeAtDragStart;
@synthesize selected;

@synthesize parent;
@synthesize easing;

- (id) init
{
    self = [super init];
    if (!self) return NULL;

    self.easing = [SequencerKeyframeEasing easing];

    return self;
}

- (id) initWithSerialization:(id)ser
{
    self = [super init];
    if (!self) return NULL;

    self.value = [ser valueForKey:@"value"];
    self.type = [[ser valueForKey:@"type"] intValue];
    self.name = [ser valueForKey:@"name"];
    self.time = [[ser valueForKey:@"time"] floatValue];
    self.easing = [[SequencerKeyframeEasing alloc] initWithSerialization:[ser objectForKey:@"easing"]];
    // fix possible broken easing/type combinations
    if (![self supportsFiniteTimeInterpolations]) {
        easing.type = kCCBKeyframeEasingInstant;
    }

	//Fixup Callback Sequencers to not have 'None' selector type.
	if(self.type == kCCBKeyframeTypeCallbacks)
	{
		NSMutableArray * callbackProperties = self.value;
		if(callbackProperties.count >= 2)
		{
			//If it equals None, fixup to @""
			if([callbackProperties[1] integerValue] == 0)
			{
				callbackProperties[0] = @"";
				callbackProperties[1] = @(1);
			}
		}
	}

    return self;
}

- (id) serialization
{
    NSMutableDictionary* ser = [NSMutableDictionary dictionaryWithCapacity:4];

    [ser setValue:value forKey:@"value"];
    [ser setValue:[NSNumber numberWithInt:type] forKey:@"type"];
    [ser setValue:name forKey:@"name"];
    [ser setValue:[NSNumber numberWithFloat:time] forKey:@"time"];
    [ser setValue:[easing serialization] forKey:@"easing"];

    return ser;
}

+ (kCCBKeyframeType) keyframeTypeFromPropertyType:(NSString*)type
{
    if ([type isEqualToString:@"Degrees"])
    {
        return kCCBKeyframeTypeDegrees;
    }
    else if ([type isEqualToString:@"Position"])
    {
        return kCCBKeyframeTypePosition;
    }
    else if ([type isEqualToString:@"ScaleLock"])
    {
        return kCCBKeyframeTypeScaleLock;
    }
    else if ([type isEqualToString:@"Check"])
    {
        return kCCBKeyframeTypeToggle;
    }
    else if ([type isEqualToString:@"Byte"])
    {
        return kCCBKeyframeTypeByte;
    }
    else if ([type isEqualToString:@"Color3"])
    {
        return kCCBKeyframeTypeColor3;
    }
    else if ([type isEqualToString:@"SpriteFrame"])
    {
        return kCCBKeyframeTypeSpriteFrame;
    }
    else if ([type isEqualToString:@"FloatXY"])
    {
        return kCCBKeyframeTypeFloatXY;
    }
    else if([type isEqualToString:@"Float"])
    {
        return kCCBKeyframeTypeFloat;
    }
    else if ([type isEqualToString:@"String"])
    {
		NSAssert(false, @"Need to handle");//TODO
        return kCCBKeyframeTypeUndefined;
    }
    else
    {
        return kCCBKeyframeTypeUndefined;
    }
}

- (NSComparisonResult) compareTime:(id)cmp
{
    SequencerKeyframe* keyframe = cmp;

    if (keyframe.time > self.time) return NSOrderedAscending;
    else if (keyframe.time < self.time) return NSOrderedDescending;
    else return NSOrderedSame;
}

- (void) setTime:(float)t
{
    time = t;
    [parent sortKeyframes];
}

- (BOOL) valueIsEqualTo:(SequencerKeyframe*)keyframe
{
    if (type != keyframe.type)
    {
        return NO;
    }

    if (type == kCCBKeyframeTypeDegrees)
    {
        return ([value floatValue] == [keyframe.value floatValue]);
    }
    else if (type == kCCBKeyframeTypePosition
             || type == kCCBKeyframeTypeScaleLock)
    {
        return ([[value objectAtIndex:0] floatValue] == [[keyframe.value objectAtIndex:0] floatValue]
                && [[value objectAtIndex:1] floatValue] == [[keyframe.value objectAtIndex:1] floatValue]);
    }
    else if (type == kCCBKeyframeTypeByte || type == kCCBKeyframeTypeFloat)
    {
        return ([value intValue] == [keyframe.value intValue]);
    }
    else if (type == kCCBKeyframeTypeColor3)
    {
        int r0 = [[value objectAtIndex:0] intValue];
        int g0 = [[value objectAtIndex:1] intValue];
        int b0 = [[value objectAtIndex:2] intValue];

        int r1 = [[keyframe.value objectAtIndex:0] intValue];
        int g1 = [[keyframe.value objectAtIndex:1] intValue];
        int b1 = [[keyframe.value objectAtIndex:2] intValue];

        return (r0 == r1 && g0 == g1 && b0 == b1);
    }
    return NO;
}

- (BOOL) supportsFiniteTimeInterpolations
{
    return (type != kCCBKeyframeTypeToggle && type != kCCBKeyframeTypeUndefined && type != kCCBKeyframeTypeSpriteFrame);
}

@end


text:
/* @option Slide show effect */
sdSS.effect = 'scrollRight';


text:
/* global describe, it, expect, beforeEach, jasmine, afterEach */
/* eslint camelcase: 0, no-invalid-this: 0 */

const _ = require('underscore');

const SerJaimeLannister = require('../../../../../server/game/cards/characters/01/serjaimelannister.js');

describe('SerJaimeLannister', function() {
    beforeEach(function() {
        this.gameSpy = jasmine.createSpyObj('game', ['on', 'removeListener', 'addPower', 'addMessage', 'raiseEvent', 'once', 'addEffect']);
        this.playerSpy = jasmine.createSpyObj('player', ['standCard']);
        this.otherPlayerSpy = jasmine.createSpyObj('player2', ['standCard']);

        this.playerSpy.game = this.gameSpy;
        this.otherPlayerSpy.game = this.gameSpy;

        this.character = new SerJaimeLannister(this.playerSpy, {});

        this.challenge = jasmine.createSpyObj('challenge', ['isAttacking']);
        this.challenge.attackingPlayer = this.playerSpy;
        this.challenge.challengeType = 'military';
    });

    describe('when attackers are declared', function() {
        describe('and this card is in play', function() {
            beforeEach(function() {
                this.character.kneeled = true;
            });

            describe('and the attacker is not my owner', function() {
                beforeEach(function() {
                    this.challenge.attackingPlayer = this.otherPlayerSpy;
                    this.character.onAttackersDeclared({}, this.challenge);
                });

                it('should not stand the card', function() {
                    expect(this.playerSpy.standCard).not.toHaveBeenCalled();
                });
            });

            describe('and the attacker is my owner', function() {
                beforeEach(function() {
                    this.character.onAttackersDeclared({}, this.challenge);
                });

                describe('and this card is blank', function() {
                    beforeEach(function() {
                        this.character.setBlank();
                        this.character.onAttackersDeclared({}, this.challenge);
                    });

                    afterEach(function() {
                        this.character.clearBlank();
                    });

                    it('should not stand the card', function() {
                        expect(this.character.kneeled).toBe(true);
                    });
                });

                describe('and this card is not in the challenge', function() {
                    beforeEach(function() {
                        this.challenge.isAttacking.and.returnValue(false);
                    });

                    it('should not stand the card', function() {
                        expect(this.character.kneeled).toBe(true);
                    });
                });

                describe('and this card is in the challenge', function() {
                    beforeEach(function() {
                        this.challenge.isAttacking.and.returnValue(true);

                        this.character.onAttackersDeclared({}, this.challenge);
                    });

                    it('should stand the card', function() {
                        expect(this.playerSpy.standCard).toHaveBeenCalled();
                    });

                    describe('and the challenge type is not military', function() {
                        beforeEach(function() {
                            this.character.kneeled = true;
                            this.character.keywords['renown'] = 0;
                            this.challenge = 'intrigue';
                            this.character.onAttackersDeclared({}, this.challenge);
                        });

                        it('should not stand the card', function() {
                            expect(this.character.kneeled).toBe(true);
                        });
                    });
                });
            });
        });
    });
});


text:
package io.cattle.platform.servicediscovery.deployment;

import io.cattle.platform.core.model.Service;
import io.cattle.platform.servicediscovery.deployment.impl.DeploymentManagerImpl.DeploymentServiceContext;
import io.cattle.platform.servicediscovery.deployment.impl.unit.DeploymentUnit;

import java.util.List;
import java.util.Map;

public interface DeploymentUnitInstanceFactory {

    /**
     * Creates deployment unit instance based on the service, its type and instanceName
     * @param context TODO
     * @param uuid
     * @param service
     * @param instanceName
     * @param instanceObj TODO
     * @param labels TODO
     * @param launchConfigName TODO
     * @return
     */
    public DeploymentUnitInstance createDeploymentUnitInstance(DeploymentServiceContext context, String uuid,
            Service service, String instanceName, Object instanceObj, Map<String, String> labels, String launchConfigName);

    /**
     * @param service TODO
     * @param context TODO
     * @return list of deployment units per service
     */
    public List<DeploymentUnit> collectDeploymentUnits(List<Service> service, DeploymentServiceContext context);
}


text:
<?php

namespace FOD\Instruct\TypeChecker;

use InvalidArgumentException;

abstract class AbstractTypeChecker implements TypeCheckerInterface
{
    /**
     * @var mixed
     */
    private $lastInvalidValue;

    /**
     * {@inheritdoc}
     */
    public function check($value, $name = 'value')
    {
        if (!$this->doCheck($value)) {
            $this->lastInvalidValue = $value;

            throw new InvalidArgumentException(sprintf(
                "%s should be %s %s. '%s' given.",
                ucfirst($name),
                $this->getTypeNameArticle(),
                $this->getTypeName(),
                trim(var_export($value, true), "'")
            ));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getLastInvalidValue()
    {
        return $this->lastInvalidValue;
    }

    /**
     * static version of the check method.
     *
     * @param  mixed $value
     *
     * @throws InvalidArgumentException
     *
     * @return null
     */
    public static function scheck($value, $name = 'value')
    {
        return (new static())->check($value, $name);
    }

    /**
     * Perform the actual checks.
     *
     * @param  mixed $value
     *
     * @return bool
     */
    abstract protected function doCheck($value);

    /**
     * Return the type name.
     *
     * @return string
     */
    abstract protected function getTypeName();

    /**
     * Return the type name article.
     *
     * @return string
     */
    protected function getTypeNameArticle()
    {
        return 'an';
    }
}


text:
package com.example.loglifecycle;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.support.v4.app.Fragment;

import com.github.stephanenicolas.loglifecycle.LogLifeCycle;

@LogLifeCycle
public class MainFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container);
    }
}


text:
<?php

// ROBOT ACTIONS : SORT ROBOTS

// Include the necessary database files
require(MMRPG_CONFIG_ROOTDIR.'database/types.php');
require(MMRPG_CONFIG_ROOTDIR.'database/robots.php');
//
// Collect the ability variables from the request header, if they exist
$temp_token = !empty($_REQUEST['token']) ? $_REQUEST['token'] : '';
$temp_order = !empty($_REQUEST['order']) ? $_REQUEST['order'] : '';
$temp_player = !empty($_REQUEST['player']) ? $_REQUEST['player'] : '';
$temp_robots = !empty($_REQUEST['robots']) ? $_REQUEST['robots'] : '';
$temp_token_order = $temp_token.'_'.$temp_order;
// If key variables are not provided, kill the script in error
if (empty($temp_token) || empty($temp_order) || empty($temp_player)){
    die('error|request-error|'.preg_replace('/\s+/', ' ', print_r($_REQUEST, true)));
}

// Ensure this player's robots exist in the current game session
if (!empty($_SESSION[$session_token]['values']['battle_settings'][$temp_player]['player_robots'])
    && !empty($_SESSION[$session_token]['values']['battle_rewards'][$temp_player]['player_robots'])){

        // Make a copy of the player robots array
        $temp_player_robots = $_SESSION[$session_token]['values']['battle_settings'][$temp_player]['player_robots'];
        $temp_player_robots_rewards = $_SESSION[$session_token]['values']['battle_rewards'][$temp_player]['player_robots'];
        if (!empty($temp_player_robots)){
            foreach ($temp_player_robots AS $token => $info){
                // Update the current and session arrays to make absolutely sure the robot token is in the right place
                if (empty($info['robot_token'])){ $_SESSION[$session_token]['values']['battle_settings'][$temp_player]['player_robots'][$token]['robot_token'] = $temp_player_robots[$token]['robot_token'] = $token; }
                $temp_player_robots[$token]['robot_core'] = !empty($mmrpg_database_robots[$token]['robot_core']) ? $mmrpg_database_robots[$token]['robot_core'] : '';
            }
        }

        // Define a temporarily function for sorting the robots
        $mmrpg_database_robots_keys = array_keys($mmrpg_database_robots);
        $mmrpg_database_types_keys = array_keys($mmrpg_database_types);

        // If the sort token was by number and asc
        if ($temp_token_order == 'number_asc'){
            // Define the sort function that uses these keys
            function temp_player_robots_sort($r1, $r2){
                global $mmrpg_database_robots_keys;
                if (empty($r1) || empty($r2)){ return 0; }
                $robot1_number_position = array_search($r1['robot_token'], $mmrpg_database_robots_keys);
                $robot2_number_position = array_search($r2['robot_token'], $mmrpg_database_robots_keys);
                if ($robot1_number_position === false && $robot2_number_position !== false){ return -1; }
                elseif ($robot1_number_position !== false && $robot2_number_position === false){ return 1; }
                elseif ($robot1_number_position < $robot2_number_position){ return -1; }
                elseif ($robot1_number_position > $robot2_number_position){ return 1; }
                else { return 0; }
            }
        }
        // Else if the sort token was by number and desc
        elseif ($temp_token_order == 'number_desc'){
            // Define the sort function that uses these keys
            function temp_player_robots_sort($r1, $r2){
                global $mmrpg_database_robots_keys;
                if (empty($r1) || empty($r2)){ return 0; }
                $robot1_number_position = array_search($r1['robot_token'], $mmrpg_database_robots_keys);
                $robot2_number_position = array_search($r2['robot_token'], $mmrpg_database_robots_keys);
                if ($robot1_number_position === false && $robot2_number_position !== false){ return 1; }
                elseif ($robot1_number_position !== false && $robot2_number_position === false){ return -1; }
                elseif ($robot1_number_position < $robot2_number_position){ return 1; }
                elseif ($robot1_number_position > $robot2_number_position){ return -1; }
                else { return 0; }
            }
        }
        // Else if the sort token was by level and asc
        elseif ($temp_token_order == 'level_asc'){
            // Define the sort function that uses these keys
            function temp_player_robots_sort($r1, $r2){
                global $mmrpg_database_robots_keys, $temp_player_robots_rewards;
                if (empty($r1) || empty($r2)){ return 0; }
                $robot1_number_position = array_search($r1['robot_token'], $mmrpg_database_robots_keys);
                $robot2_number_position = array_search($r2['robot_token'], $mmrpg_database_robots_keys);
                $r1['robot_level'] = $temp_player_robots_rewards[$r1['robot_token']]['robot_level'];
                $r2['robot_level'] = $temp_player_robots_rewards[$r2['robot_token']]['robot_level'];
                if ($robot1_number_position === false && $robot2_number_position !== false){ return -1; }
                elseif ($robot1_number_position !== false && $robot2_number_position === false){ return 1; }
                elseif ($r1['robot_level'] < $r2['robot_level']){ return -1; }
                elseif ($r1['robot_level'] > $r2['robot_level']){ return 1; }
                elseif ($robot1_number_position < $robot2_number_position){ return -1; }
                elseif ($robot1_number_position > $robot2_number_position){ return 1; }
                else { return 0; }
            }
        }
        // Else if the sort token was by level and desc
        elseif ($temp_token_order == 'level_desc'){
            // Define the sort function that uses these keys
            function temp_player_robots_sort($r1, $r2){
                global $mmrpg_database_robots_keys, $temp_player_robots_rewards;
                if (empty($r1) || empty($r2)){ return 0; }
                $robot1_number_position = array_search($r1['robot_token'], $mmrpg_database_robots_keys);
                $robot2_number_position = array_search($r2['robot_token'], $mmrpg_database_robots_keys);
                $r1['robot_level'] = $temp_player_robots_rewards[$r1['robot_token']]['robot_level'];
                $r2['robot_level'] = $temp_player_robots_rewards[$r2['robot_token']]['robot_level'];
                if ($robot1_number_position === false && $robot2_number_position !== false){ return 1; }
                elseif ($robot1_number_position !== false && $robot2_number_position === false){ return -1; }
                elseif ($r1['robot_level'] < $r2['robot_level']){ return 1; }
                elseif ($r1['robot_level'] > $r2['robot_level']){ return -1; }
                elseif ($robot1_number_position < $robot2_number_position){ return 1; }
                elseif ($robot1_number_position > $robot2_number_position){ return -1; }
                else { return 0; }
            }
        }
        // If the sort token was by core and asc
        elseif ($temp_token_order == 'core_asc'){
            //die($temp_token_order.'
'.print_r(implode(',', $mmrpg_database_types_keys), true).'
');
            // Define the sort function that uses these keys
            function temp_player_robots_sort($r1, $r2){
                global $temp_token_order, $mmrpg_database_types_keys, $mmrpg_database_robots_keys;
                if (empty($r1) || empty($r2)){ return 0; }
                $robot1_core = !empty($r1['robot_core']) ? $r1['robot_core'] : 'none';
                $robot2_core = !empty($r2['robot_core']) ? $r2['robot_core'] : 'none';
                $robot1_token = !empty($r1['robot_token']) ? $r1['robot_token'] : 'robot';
                $robot2_token = !empty($r2['robot_token']) ? $r2['robot_token'] : 'robot';
                $robot1_core_position = array_search($robot1_core, $mmrpg_database_types_keys);
                $robot2_core_position = array_search($robot2_core, $mmrpg_database_types_keys);
                $robot1_number_position = array_search($robot1_token, $mmrpg_database_robots_keys);
                $robot2_number_position = array_search($robot2_token, $mmrpg_database_robots_keys);
                //die($temp_token_order.' ('.$robot1_token.' vs '.$robot2_token.') ('.$robot1_core.' vs '.$robot2_core.')
'.print_r(implode(',', $mmrpg_database_types_keys), true).'
');
                if ($robot1_core_position === false && $robot2_core_position !== false){ return -1; }
                elseif ($robot1_core_position !== false && $robot2_core_position === false){ return 1; }
                elseif ($robot1_core_position < $robot2_core_position){ return -1; }
                elseif ($robot1_core_position > $robot2_core_position){ return 1; }
                elseif ($robot1_number_position === false && $robot2_number_position !== false){ return -1; }
                elseif ($robot1_number_position !== false && $robot2_number_position === false){ return 1; }
                elseif ($robot1_number_position < $robot2_number_position){ return -1; }
                elseif ($robot1_number_position > $robot2_number_position){ return 1; }
                else { return 0; }
            }
        }
        // Else if the sort token was by core and desc
        elseif ($temp_token_order == 'core_desc'){
            //die($temp_token_order.'
'.print_r(implode(',', $mmrpg_database_types_keys), true).'
');
            // Define the sort function that uses these keys
            function temp_player_robots_sort($r1, $r2){
                global $temp_token_order, $mmrpg_database_types_keys, $mmrpg_database_robots_keys;
                if (empty($r1) || empty($r2)){ return 0; }
                $robot1_core = !empty($r1['robot_core']) ? $r1['robot_core'] : 'none';
                $robot2_core = !empty($r2['robot_core']) ? $r2['robot_core'] : 'none';
                $robot1_token = !empty($r1['robot_token']) ? $r1['robot_token'] : 'robot';
                $robot2_token = !empty($r2['robot_token']) ? $r2['robot_token'] : 'robot';
                $robot1_core_position = array_search($robot1_core, $mmrpg_database_types_keys);
                $robot2_core_position = array_search($robot2_core, $mmrpg_database_types_keys);
                $robot1_number_position = array_search($robot1_token, $mmrpg_database_robots_keys);
                $robot2_number_position = array_search($robot2_token, $mmrpg_database_robots_keys);
                //die($temp_token_order.' ('.$robot1_token.' vs '.$robot2_token.') ('.$robot1_core.' vs '.$robot2_core.')
'.print_r(implode(',', $mmrpg_database_types_keys), true).'
');
                if ($robot1_core_position === false && $robot2_core_position !== false){ return 1; }
                elseif ($robot1_core_position !== false && $robot2_core_position === false){ return -1; }
                elseif ($robot1_core_position < $robot2_core_position){ return 1; }
                elseif ($robot1_core_position > $robot2_core_position){ return -1; }
                elseif ($robot1_number_position === false && $robot2_number_position !== false){ return 1; }
                elseif ($robot1_number_position !== false && $robot2_number_position === false){ return -1; }
                elseif ($robot1_number_position < $robot2_number_position){ return 1; }
                elseif ($robot1_number_position > $robot2_number_position){ return -1; }
                else { return 0; }
            }
        }
        // Else if the sort token was a manual drag
        elseif ($temp_token_order == 'manual_auto'){

            // Explode the provided robot keys, assuming there were...
            $mmrpg_manual_robots_keys = !empty($temp_robots) ? explode(',', $temp_robots) : array();

            // Define the sort function that uses these keys
            function temp_player_robots_sort($r1, $r2){
                global $mmrpg_manual_robots_keys, $mmrpg_database_robots_keys;
                if (empty($r1) || empty($r2)){ return 0; }

                $robot1_token = !empty($r1['robot_token']) ? $r1['robot_token'] : 'robot';
                $robot2_token = !empty($r2['robot_token']) ? $r2['robot_token'] : 'robot';
                $robot1_manual_position = array_search($robot1_token, $mmrpg_manual_robots_keys);
                $robot2_manual_position = array_search($robot2_token, $mmrpg_manual_robots_keys);
                $robot1_number_position = array_search($robot1_token, $mmrpg_database_robots_keys);
                $robot2_number_position = array_search($robot2_token, $mmrpg_database_robots_keys);

                if ($robot1_manual_position === false && $robot2_manual_position !== false){ return -1; }
                elseif ($robot1_manual_position !== false && $robot2_manual_position === false){ return 1; }
                elseif ($robot1_number_position === false && $robot2_number_position !== false){ return -1; }
                elseif ($robot1_number_position !== false && $robot2_number_position === false){ return 1; }
                elseif ($robot1_manual_position < $robot2_manual_position){ return -1; }
                elseif ($robot1_manual_position > $robot2_manual_position){ return 1; }
                elseif ($robot1_number_position < $robot2_number_position){ return -1; }
                elseif ($robot1_number_position > $robot2_number_position){ return 1; }
                else { return 0; }

            }
        }

        // Sort the robots and maintain index association
        uasort($temp_player_robots, 'temp_player_robots_sort');

        // Ensure nothing went wrong with the array before copying
        if (!empty($temp_player_robots)){
            $temp_robot_tokens = implode(',', array_keys($temp_player_robots));
            $_SESSION[$session_token]['values']['battle_settings'][$temp_player]['player_robots'] = $temp_player_robots;
            exit('success|array-sorted|'.$temp_robot_tokens);
        }
        // Otherwise produce an error
        else {
            // Produce the error message
            exit('error|array-corrupted|false');
        }

    }
// Otherwise, produce an error
else {

    // Produce the error message
    exit('error|robots-undefined|false');

}

?>


text:
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Deployment.Application;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using CodeExecutor;
using NuGet;
using NuGetPackageExplorer.Types;
using PackageExplorer.Properties;
using PackageExplorerViewModel;

namespace PackageExplorer
{
    public partial class App : Application
    {
        private CompositionContainer _container;

        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        internal CompositionContainer Container
        {
            get
            {
                if (_container == null)
                {
                    var catalog1 = new AssemblyCatalog(typeof(App).Assembly);
                    var catalog2 = new AssemblyCatalog(typeof(PackageViewModel).Assembly);
                    var catalog = new AggregateCatalog(catalog1, catalog2);

                    _container = new CompositionContainer(catalog);

                    // add PluginManager instance to be available as export to the rest of the app.
                    _container.ComposeParts(new PluginManager(catalog));
                }

                return _container;
            }
        }

        private async void Application_Startup(object sender, StartupEventArgs e)
        {
            MigrateSettings();

            var window = Container.GetExportedValue<MainWindow>();
            window.Show();

            CheckWindows8AndDisplayUpsellDialog();

            if (e.Args.Length > 0)
            {
                string file = e.Args[0];
                bool successful = await LoadFile(window, file);
                if (successful)
                {
                    return;
                }
            }

            // activation via ClickOnce url
            if (ApplicationDeployment.IsNetworkDeployed &&
                ApplicationDeployment.CurrentDeployment != null &&
                ApplicationDeployment.CurrentDeployment.ActivationUri != null)
            {
                string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
                var arguments = HttpUtility.ParseQueryString(queryString);

                string downloadUrl = arguments["url"];
                Uri uri;

                if (!String.IsNullOrEmpty(downloadUrl) && Uri.TryCreate(downloadUrl, UriKind.Absolute, out uri))
                {
                    string id = arguments["id"];
                    string versionString = arguments["version"];
                    SemanticVersion version = null;
                    SemanticVersion.TryParse(versionString, out version);

                    await window.DownloadAndOpenDataServicePackage(downloadUrl, id, version);
                    return;
                }
            }

            if (AppDomain.CurrentDomain.SetupInformation != null &&
                AppDomain.CurrentDomain.SetupInformation.ActivationArguments != null)
            {
                // click-once deployment
                string[] activationData = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData;
                if (activationData != null && activationData.Length > 0)
                {
                    string file = activationData[0];
                    await LoadFile(window, file);
                    return;
                }
            }
        }

        private void CheckWindows8AndDisplayUpsellDialog()
        {
            if (NativeMethods.IsWindows8OrLater && Settings.Default.SolicitInstallNpeForWin8)
            {
                bool isInstalled = RemoteCodeExecutor.IsNpeMetroInstalled;
                if (!isInstalled)
                {
                    IUIServices uiServices = Container.GetExportedValue<IUIServices>();
                    bool? result = uiServices.AskToInstallNpeOnWindows8();

                    // if result == null, remind user next time
                    Settings.Default.SolicitInstallNpeForWin8 = (result != false);

                    if (result == true)
                    {
                        Process.Start("ms-windows-store:PDP?PFN=50582LuanNguyen.NuGetPackageExplorer_w6y2tyx5bpzwa");
                    }
                }
            }
        }

        private static void MigrateSettings()
        {
            Settings settings = Settings.Default;
            if (settings.IsFirstTime)
            {
                settings.Upgrade();
                settings.IsFirstTime = false;
                settings.Save();
            }
        }

        private static async Task<bool> LoadFile(MainWindow window, string file)
        {
            if (FileUtility.IsSupportedFile(file) && File.Exists(file))
            {
                await window.OpenLocalPackage(file);
                return true;
            }
            else
            {
                return false;
            }
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            if (_container != null)
            {
                _container.Dispose();
            }

            // IMPORTANT: Call this after calling _container.Dispose(). Some exports relies on Dispose()
            // being called to save settings values.
            Settings.Default.IsFirstTimeAfterMigrate = false;
            Settings.Default.Save();
        }
    }
}