text:
class AddIsGs1ToItems < ActiveRecord::Migration
  def self.up
    add_column :items, :is_gs1, :boolean, :default => false
  end

  def self.down
    remove_column :items, :is_gs1
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.tle.web.resources;

import com.google.inject.AbstractModule;

public class ResourcesModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(ResourcesService.class).asEagerSingleton();
  }
}


text:
BEGIN {
	base = File::dirname( File::dirname(File::expand_path(__FILE__)) )
	$LOAD_PATH.unshift "#{base}/lib"

	require "#{base}/utils.rb"
	include UtilityFunctions
}

require 'wordnet'

lex = WordNet::Lexicon.new
syn = lex.lookup_synsets_by_offset( "04456674%n" )

try( %{syn.pointerlist} )
try( %{syn.pointers} )


text:
#ifndef AMBROLIB_AT91SAM3X_PWM_H
#define AMBROLIB_AT91SAM3X_PWM_H

#include <stdint.h>
#include <stddef.h>
#include <sam/drivers/pmc/pmc.h>

#include <aprinter/base/Object.h>
#include <aprinter/meta/TypeListUtils.h>
#include <aprinter/meta/TypesAreEqual.h>
#include <aprinter/meta/ChooseInt.h>
#include <aprinter/meta/WrapValue.h>
#include <aprinter/meta/FuncUtils.h>
#include <aprinter/base/DebugObject.h>
#include <aprinter/base/Assert.h>
#include <aprinter/hal/at91/At91SamPins.h>

#include <aprinter/BeginNamespace.h>

template <uint8_t TPreA, uint8_t TDivA, uint8_t TPreB, uint8_t TDivB>
struct At91Sam3xPwmParams {
    static uint8_t const PreA = TPreA;
    static uint8_t const DivA = TDivA;
    static uint8_t const PreB = TPreB;
    static uint8_t const DivB = TDivB;
};

template <int TChan, char TSignal, typename TPin, typename TPerip>
struct At91Sam3xPwmConnn {
    static int const Chan = TChan;
    static char const Signal = TSignal;
    using Pin = TPin;
    using Periph = TPerip;
};

using At91Sam3xPwmConnections = MakeTypeList<
    At91Sam3xPwmConnn<0, 'H', At91SamPin<At91SamPioA, 8>, At91SamPeriphB>,
    At91Sam3xPwmConnn<0, 'H', At91SamPin<At91SamPioB, 12>, At91SamPeriphB>,
    At91Sam3xPwmConnn<0, 'H', At91SamPin<At91SamPioC, 3>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<0, 'H', At91SamPin<At91SamPioE, 15>, At91SamPeriphA>,
    At91Sam3xPwmConnn<1, 'H', At91SamPin<At91SamPioA, 19>, At91SamPeriphB>,
    At91Sam3xPwmConnn<1, 'H', At91SamPin<At91SamPioB, 13>, At91SamPeriphB>,
    At91Sam3xPwmConnn<1, 'H', At91SamPin<At91SamPioC, 5>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<1, 'H', At91SamPin<At91SamPioE, 16>, At91SamPeriphA>,
    At91Sam3xPwmConnn<2, 'H', At91SamPin<At91SamPioA, 13>, At91SamPeriphB>,
    At91Sam3xPwmConnn<2, 'H', At91SamPin<At91SamPioB, 14>, At91SamPeriphB>,
    At91Sam3xPwmConnn<2, 'H', At91SamPin<At91SamPioC, 7>, At91SamPeriphB>,
    At91Sam3xPwmConnn<3, 'H', At91SamPin<At91SamPioA, 9>, At91SamPeriphB>,
    At91Sam3xPwmConnn<3, 'H', At91SamPin<At91SamPioB, 15>, At91SamPeriphB>,
    At91Sam3xPwmConnn<3, 'H', At91SamPin<At91SamPioC, 3>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<3, 'H', At91SamPin<At91SamPioF, 3>, At91SamPeriphA>,
    At91Sam3xPwmConnn<4, 'H', At91SamPin<At91SamPioC, 20>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<4, 'H', At91SamPin<At91SamPioE, 20>, At91SamPeriphA>,
    At91Sam3xPwmConnn<5, 'H', At91SamPin<At91SamPioC, 19>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<5, 'H', At91SamPin<At91SamPioE, 22>, At91SamPeriphA>,
    At91Sam3xPwmConnn<6, 'H', At91SamPin<At91SamPioC, 18>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<6, 'H', At91SamPin<At91SamPioE, 24>, At91SamPeriphA>,
//    At91Sam3xPwmConnn<7, 'H', At91SamPin<At91SamPioE, 26>, At91SamPeriphA>,
    At91Sam3xPwmConnn<0, 'L', At91SamPin<At91SamPioA, 21>, At91SamPeriphB>,
    At91Sam3xPwmConnn<0, 'L', At91SamPin<At91SamPioB, 16>, At91SamPeriphB>,
    At91Sam3xPwmConnn<0, 'L', At91SamPin<At91SamPioC, 2>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<0, 'L', At91SamPin<At91SamPioE, 18>, At91SamPeriphA>,
    At91Sam3xPwmConnn<1, 'L', At91SamPin<At91SamPioA, 12>, At91SamPeriphB>,
    At91Sam3xPwmConnn<1, 'L', At91SamPin<At91SamPioB, 17>, At91SamPeriphB>,
    At91Sam3xPwmConnn<1, 'L', At91SamPin<At91SamPioC, 4>, At91SamPeriphB>,
    At91Sam3xPwmConnn<2, 'L', At91SamPin<At91SamPioA, 20>, At91SamPeriphB>,
    At91Sam3xPwmConnn<2, 'L', At91SamPin<At91SamPioB, 18>, At91SamPeriphB>,
    At91Sam3xPwmConnn<2, 'L', At91SamPin<At91SamPioC, 6>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<2, 'L', At91SamPin<At91SamPioE, 17>, At91SamPeriphA>,
    At91Sam3xPwmConnn<3, 'L', At91SamPin<At91SamPioA, 0>, At91SamPeriphB>,
    At91Sam3xPwmConnn<3, 'L', At91SamPin<At91SamPioB, 19>, At91SamPeriphB>,
    At91Sam3xPwmConnn<3, 'L', At91SamPin<At91SamPioC, 8>, At91SamPeriphB>,
    At91Sam3xPwmConnn<4, 'L', At91SamPin<At91SamPioC, 21>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<4, 'L', At91SamPin<At91SamPioE, 19>, At91SamPeriphA>,
    At91Sam3xPwmConnn<5, 'L', At91SamPin<At91SamPioC, 22>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<5, 'L', At91SamPin<At91SamPioE, 21>, At91SamPeriphA>,
    At91Sam3xPwmConnn<6, 'L', At91SamPin<At91SamPioC, 23>, At91SamPeriphB>,
//    At91Sam3xPwmConnn<6, 'L', At91SamPin<At91SamPioE, 23>, At91SamPeriphA>,
    At91Sam3xPwmConnn<7, 'L', At91SamPin<At91SamPioC, 24>, At91SamPeriphB>
//    At91Sam3xPwmConnn<7, 'L', At91SamPin<At91SamPioE, 25>, At91SamPeriphA>
>;

template <typename, typename, typename>
class At91Sam3xPwmChannel;

template <typename Context, typename ParentObject, typename Params>
class At91Sam3xPwm {
public:
    struct Object;

private:
    template <typename, typename, typename>
    friend class At91Sam3xPwmChannel;

    using TheDebugObject = DebugObject<Context, Object>;

    static_assert(Params::PreA <= 10, "");
    static_assert(Params::PreB <= 10, "");

public:
    static void init (Context c)
    {
        pmc_enable_periph_clk(ID_PWM);

        PWM->PWM_DIS = UINT32_MAX;
        PWM->PWM_IDR1 = UINT32_MAX;
        PWM->PWM_IDR2 = UINT32_MAX;
        PWM->PWM_SCM = 0;
        PWM->PWM_CLK = PWM_CLK_PREA(Params::PreA) | PWM_CLK_DIVA(Params::DivA) | PWM_CLK_PREB(Params::PreB) | PWM_CLK_DIVB(Params::DivB);

        TheDebugObject::init(c);
    }

    static void deinit (Context c)
    {
        TheDebugObject::deinit(c);

        PWM->PWM_CLK = 0;

        pmc_disable_periph_clk(ID_PWM);
    }

public:
    struct Object : public ObjBase<At91Sam3xPwm, ParentObject, MakeTypeList<TheDebugObject>> {};
};

template <typename Context, typename ParentObject, typename Params>
class At91Sam3xPwmChannel {
public:
    struct Object;

private:
    using TheDebugObject = DebugObject<Context, Object>;
    using ThePwm = typename Context::Pwm;
    static int const ChannelNumber = Params::ChannelNumber;
    static_assert(ChannelNumber >= 0 && ChannelNumber < 8, "");
    static_assert(Params::ChannelPrescaler >= 0 && Params::ChannelPrescaler <= 12, "");
    static_assert(Params::ChannelPeriod <= UINT32_C(0xFFFFFF), "");

    template <typename Conn>
    using ConnFilterFunc = WrapBool<(Conn::Chan == ChannelNumber && Conn::Signal == Params::Signal && TypesAreEqual<typename Conn::Pin, typename Params::Pin>::Value)>;
    using ConnSearchRes = FilterTypeList<At91Sam3xPwmConnections, TemplateFunc<ConnFilterFunc>>;
    static_assert(TypeListLength<ConnSearchRes>::Value >= 1, "No connection found for desired PWM channel config!");
    static_assert(TypeListLength<ConnSearchRes>::Value <= 1, "");
    using Conn = TypeListGet<ConnSearchRes, 0>;

public:
    using DutyCycleType = ChooseIntForMax<Params::ChannelPeriod, false>;
    static DutyCycleType const MaxDutyCycle = Params::ChannelPeriod;

    static void init (Context c)
    {
        ThePwm::TheDebugObject::access(c);

        PWM->PWM_CH_NUM[ChannelNumber].PWM_CPRD = PWM_CPRD_CPRD(Params::ChannelPeriod);
        PWM->PWM_CH_NUM[ChannelNumber].PWM_CDTY = 0;
        PWM->PWM_CH_NUM[ChannelNumber].PWM_CMR = Params::ChannelPrescaler | ((Conn::Signal == 'H') != Params::Invert ? PWM_CMR_CPOL : 0);
        PWM->PWM_ENA = (uint32_t)1 << ChannelNumber;

        Context::Pins::template setPeripheral<typename Conn::Pin>(c, typename Conn::Periph());

        TheDebugObject::init(c);
    }

    static void deinit (Context c)
    {
        TheDebugObject::deinit(c);

        PWM->PWM_DIS = (uint32_t)1 << ChannelNumber;
    }

    template <typename ThisContext>
    static void setDutyCycle (ThisContext c, DutyCycleType duty_cycle)
    {
        AMBRO_ASSERT(duty_cycle <= MaxDutyCycle)

        PWM->PWM_CH_NUM[ChannelNumber].PWM_CDTYUPD = duty_cycle;
    }

    static void emergencySetOff ()
    {
        PWM->PWM_CH_NUM[ChannelNumber].PWM_CDTYUPD = 0;
    }

public:
    struct Object : public ObjBase<At91Sam3xPwmChannel, ParentObject, MakeTypeList<TheDebugObject>> {};
};

template <int TChannelPrescaler, uint32_t TChannelPeriod, int TChannelNumber, typename TPin, char TSignal, bool TInvert>
struct At91Sam3xPwmChannelService {
    static int const ChannelPrescaler = TChannelPrescaler;
    static uint32_t const ChannelPeriod = TChannelPeriod;
    static int const ChannelNumber = TChannelNumber;
    using Pin = TPin;
    static char const Signal = TSignal;
    static bool const Invert = TInvert;

    template <typename Context, typename ParentObject>
    using Pwm = At91Sam3xPwmChannel<Context, ParentObject, At91Sam3xPwmChannelService>;
};

#include <aprinter/EndNamespace.h>

#endif


text:
import sqlite3
import re
import sys

reload(sys)
sys.setdefaultencoding('utf8')

data = "download/tvOS.docset/Contents/Resources/docSet.dsidx"

url = "https://developer.apple.com/library/content/"

def generate_output(result):
    abstract_format = "{name}\tA\t\t\t\t\t\t\t\t\t\t{abstract}\t{path}\n"
    redirect_format = "{alt_name}\tR\t{name}\t\t\t\t\t\t\t\t\t\t\n"

    f = open('output.txt', 'a')

    for r in result:
        if r['redirect']:
            for alt_name in r['alt_names']:
                r['alt_name'] = alt_name
                f.write(redirect_format.format(**r))
        f.write(abstract_format.format(**r))

    f.close()

def create_fathead(database):
    # Connect to the documentation's sqlite database.
    conn = sqlite3.connect(database)
    c = conn.cursor()

    # Variables that we need for later.
    result = []

    seen_list = {}

    # This long SQL query just gets the details about each class and method.
    # ZLANGUAGE = 3 means Swift
    # Note: The SQL query is different between different docsets.
    for row in c.execute('''SELECT ZTOKENNAME, ZABSTRACT, ZTOKENMETAINFORMATION.ZANCHOR, ZDECLARATION, ZNODEURL.ZPATH, ZTOKENUSR, ZTOKEN.ZTOKENTYPE
                            FROM ZTOKEN, ZTOKENMETAINFORMATION, ZNODEURL
                            WHERE ZLANGUAGE=3
                            AND ZTOKENTYPE IN (1, 4, 5, 7, 8, 12, 14, 17)
                            AND ZTOKENMETAINFORMATION.ZTOKEN=ZTOKEN.Z_PK
                            AND ZTOKENNAME IS NOT NULL
                            AND ZABSTRACT IS NOT NULL
                            AND ZTOKENMETAINFORMATION.ZANCHOR IS NOT NULL
                            AND ZDECLARATION IS NOT NULL
                            AND ZTOKENUSR IS NOT NULL
                            AND ZNODEURL.ZPATH IS NOT NULL
                            AND ZNODEURL.ZNODE=ZTOKEN.ZPARENTNODE
                            ORDER BY ZTOKENNAME'''):
        name, abstract, anchor, snippet, path, usr, tokentype = row

        # This is the meta data that we're going to attach later.
        pack = {
            "name": name,
            "abstract": abstract or "",
            "path": url + path + "#" + anchor,
            "original": abstract or "",
            "platform": "tvOS",
            "snippet": snippet or "",
        }

        # Remove all the tags inside the pre tags.
        snippet = re.sub(r'<[^>]*>', '', snippet)
        pack['snippet'] = "
" + snippet + "
"

        # Process the abstract
        # Classes have irrelevant snippets so we're not adding that in
        if tokentype != 12:
            pack['abstract'] = pack['abstract'] + " " + pack['snippet']
        pack['abstract'] = pack['abstract'].replace("\n", "\\n")

        # Remove function parenthesis
        p = re.compile('\(.*?\)')
        pack['name'] = re.sub(p, '', pack['name'])

        # Have we seen this before?
        if not pack['name'] in seen_list:
            seen_list[pack['name']] = True
        else:
            continue

        # ----------------
        # Create Redirects
        # ----------------
        #
        # This is where the variable `usr` will come in handy. It has information on whether a certain
        # method or variable belongs to a class which makes it useful for queries like "length nsstring",
        # "nsstring length", or "nsstring.length"

        p = re.compile('c:objc\(..\)([a-zA-Z]+)\(..\)([a-zA-Z]+)')
        if p.match(usr):
            pack['redirect'] = p.findall(usr)
            cl = pack['redirect'][0][0]
            prop = pack['redirect'][0][1]
            pack['name'] = cl + "." + prop

            pack['alt_names'] = [cl + " " + prop, prop + " " + cl, prop]
        else:
            pack['redirect'] = None

        print pack['name']

        result.append(pack)

    conn.close()
    generate_output(result)

create_fathead(data)


text:
#include "third_party/blink/renderer/platform/wtf/threading.h"

#include "build/build_config.h"

#if defined(OS_POSIX) || defined(OS_FUCHSIA)

#include <errno.h>
#include <limits.h>
#include <sched.h>
#include <sys/time.h>
#include "base/threading/scoped_blocking_call.h"
#include "third_party/blink/renderer/platform/wtf/date_math.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/thread_specific.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"

#if defined(OS_MAC)
#include <objc/objc-auto.h>
#endif

#if defined(OS_LINUX) || defined(OS_CHROMEOS)
#include <sys/syscall.h>
#endif

#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID)
#include <unistd.h>
#endif

namespace WTF {

MutexBase::MutexBase(bool recursive) {
  pthread_mutexattr_t attr;
  pthread_mutexattr_init(&attr);
  pthread_mutexattr_settype(
      &attr, recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_NORMAL);

  int result = pthread_mutex_init(&mutex_.internal_mutex_, &attr);
  DCHECK_EQ(result, 0);
#if DCHECK_IS_ON()
  mutex_.recursion_count_ = 0;
#endif

  pthread_mutexattr_destroy(&attr);
}

MutexBase::~MutexBase() {
  int result = pthread_mutex_destroy(&mutex_.internal_mutex_);
  DCHECK_EQ(result, 0);
}

void MutexBase::lock() {
  int result = pthread_mutex_lock(&mutex_.internal_mutex_);
  DCHECK_EQ(result, 0);
#if DCHECK_IS_ON()
  DCHECK(!mutex_.recursion_count_)
      << "WTF does not support recursive mutex acquisition!";
  ++mutex_.recursion_count_;
#endif
}

void MutexBase::unlock() {
#if DCHECK_IS_ON()
  DCHECK(mutex_.recursion_count_);
  --mutex_.recursion_count_;
#endif
  int result = pthread_mutex_unlock(&mutex_.internal_mutex_);
  DCHECK_EQ(result, 0);
}

// There is a separate tryLock implementation for the Mutex and the
// RecursiveMutex since on Windows we need to manually check if tryLock should
// succeed or not for the non-recursive mutex. On Linux the two implementations
// are equal except we can assert the recursion count is always zero for the
// non-recursive mutex.
bool Mutex::TryLock() {
  int result = pthread_mutex_trylock(&mutex_.internal_mutex_);
  if (result == 0) {
#if DCHECK_IS_ON()
    // The Mutex class is not recursive, so the recursionCount should be
    // zero after getting the lock.
    DCHECK(!mutex_.recursion_count_)
        << "WTF does not support recursive mutex acquisition!";
    ++mutex_.recursion_count_;
#endif
    return true;
  }
  if (result == EBUSY)
    return false;

  NOTREACHED();
  return false;
}

bool RecursiveMutex::TryLock() {
  int result = pthread_mutex_trylock(&mutex_.internal_mutex_);
  if (result == 0) {
#if DCHECK_IS_ON()
    DCHECK(!mutex_.recursion_count_)
        << "WTF does not support recursive mutex acquisition!";
    ++mutex_.recursion_count_;
#endif
    return true;
  }
  if (result == EBUSY)
    return false;

  NOTREACHED();
  return false;
}

ThreadCondition::ThreadCondition(Mutex& mutex) : mutex_(mutex.Impl()) {
  pthread_cond_init(&condition_, nullptr);
}

ThreadCondition::~ThreadCondition() {
  pthread_cond_destroy(&condition_);
}

void ThreadCondition::Wait() {
  base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
                                                base::BlockingType::MAY_BLOCK);
#if DCHECK_IS_ON()
  --mutex_.recursion_count_;
#endif
  int result = pthread_cond_wait(&condition_, &mutex_.internal_mutex_);
  DCHECK_EQ(result, 0);
#if DCHECK_IS_ON()
  ++mutex_.recursion_count_;
#endif
}

void ThreadCondition::Signal() {
  int result = pthread_cond_signal(&condition_);
  DCHECK_EQ(result, 0);
}

void ThreadCondition::Broadcast() {
  int result = pthread_cond_broadcast(&condition_);
  DCHECK_EQ(result, 0);
}

}  // namespace WTF

#endif  // defined(OS_POSIX) || defined(OS_FUCHSIA)


text:
package com.github.open96.jypm.settings;

import com.github.open96.jypm.thread.TASK_TYPE;
import com.github.open96.jypm.thread.ThreadManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.SystemUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class SettingsManager {
    //File which stores Playlist objects in form of JSON
    private final static String JSON_FILE_NAME = "settings.json";
    //This object is a singleton thus storing instance of it is needed
    private volatile static SettingsManager singletonInstance;
    //Initialize log4j logger for later use in this class
    private static final Logger LOG = LogManager.getLogger(SettingsManager.class.getName());
    //Pojo object where settings are stored during the runtime
    private Settings settings;

    private SettingsManager() {
        init();
    }

    /**
     * Method that ensures object will be initialized only once.
     * For reasoning behind using this design pattern look into init() method.
     *
     * @return Singleton instance of SettingsManager.
     */
    public static SettingsManager getInstance() {
        if (singletonInstance == null) {
            synchronized (SettingsManager.class) {
                if (singletonInstance == null) {
                    LOG.debug("Instance is null, initializing...");
                    singletonInstance = new SettingsManager();
                }
            }
        }
        return singletonInstance;
    }

    /**
     * Method that initializes whole object and loads data from .json file to it if one exists.
     * Singleton design pattern ensures class won't load that data more than once during application runtime
     * and possibly cause desync between what is stored in RAM and what is stored in JSON.
     */
    private void init() {
        LOG.trace("Initializing SettingsManager");
        settings = new Settings();
        //Read data from file, if it exists.
        try (FileReader fileReader = new FileReader(JSON_FILE_NAME)) {
            GsonBuilder gsonBuilder = new GsonBuilder();
            Gson gson = gsonBuilder.create();
            Type type = new TypeToken<Settings>() {
            }.getType();
            Settings loadedSettings = gson.fromJson(fileReader, type);
            if (loadedSettings != null) {
                settings = loadedSettings;
            }
        } catch (FileNotFoundException e) {
            LOG.info(JSON_FILE_NAME + " has not been found, assuming it's a first run of application...");
        } catch (IOException e) {
            LOG.error("Unable to initialize FileReader...", e);
        }
        determineHostOS();
        setDefaultFileManagerIfNotSet();
        setFfmpegExecutableIfPossibleAndNotSet();
        saveToJson();
        LOG.debug("SettingsManager has been successfully initialized");
    }

    /**
     * Stores settings object's state to a JSON file.
     */
    private void saveToJson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        try (FileWriter fileWriter = new FileWriter(JSON_FILE_NAME)) {
            fileWriter.write(gson.toJson(settings));
            fileWriter.flush();
        } catch (IOException e) {
            LOG.error("Could not save settings to " + JSON_FILE_NAME, e);
        }
    }

    /**
     * @return Path to youtube-dl executable stored in SettingsManager in form of String object
     */
    public String getYoutubeDlExecutable() {

        Callable<String> settingsGetterThread = () -> settings.getYoutubeDlExecutable();
        Future<String> settingsFuture = ThreadManager
                .getInstance()
                .sendTask(settingsGetterThread, TASK_TYPE.SETTING);

        try {
            return settingsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Failed to retrieve setting", e);
        }
        return null;
    }

    /**
     * Sets path to youtube-dl executable and saves it in SettingsManager
     *
     * @param executableLocation path to youtube-dl executable
     */
    public void setYoutubeDlExecutable(String executableLocation) {

        ThreadManager
                .getInstance()
                .sendVoidTask(new Thread(() -> {
                    settings.setYoutubeDlExecutable(executableLocation);
                    if (ThreadManager.getExecutionPermission()) {
                        saveToJson();
                    }
                }), TASK_TYPE.SETTING);
    }

    /**
     * @return Path to ffmpeg executable stored in SettingsManager in form of String object
     */
    public String getFfmpegExecutable() {

        Callable<String> settingsGetterThread = () -> settings.getFfmpegExecutable();
        Future<String> settingsFuture = ThreadManager
                .getInstance()
                .sendTask(settingsGetterThread, TASK_TYPE.SETTING);

        try {
            return settingsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Failed to retrieve setting", e);
        }
        return null;
    }

    /**
     * Sets path to ffmpeg executable and saves it in SettingsManager
     *
     * @param executableLocation path to youtube-dl executable
     */
    public void setFfmpegExecutable(String executableLocation) {

        ThreadManager
                .getInstance()
                .sendVoidTask(new Thread(() -> {
                    settings.setFfmpegExecutable(executableLocation);
                    if (ThreadManager.getExecutionPermission()) {
                        saveToJson();
                    }
                }), TASK_TYPE.SETTING);
    }

    /**
     * @return Type of OS application is running on
     */
    public OS_TYPE getOS() {
        return settings.getOsType();
    }

    /**
     * @return File manager command stored in SettingsManager in form of String object
     */
    public String getFileManagerCommand() {

        Callable<String> settingsGetterThread = () -> settings.getFileManagerCommand();
        Future<String> settingsFuture = ThreadManager
                .getInstance()
                .sendTask(settingsGetterThread, TASK_TYPE.SETTING);

        try {
            return settingsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Failed to retrieve setting", e);
        }
        return null;
    }

    /**
     * Sets file manager command and saves it in SettingsManager
     *
     * @param fileManagerCommand path to youtube-dl executable
     */
    public void setFileManagerCommand(String fileManagerCommand) {

        //Create a Runnable thread that will download needed playlist and video data
        ThreadManager
                .getInstance()
                .sendVoidTask(new Thread(() -> {
                    settings.setFileManagerCommand(fileManagerCommand);
                    saveToJson();
                }), TASK_TYPE.SETTING);
    }

    /**
     * @return Notification policy stored in SettingsManager in form of Boolean object
     */
    public Boolean getNotificationPolicy() {

        Callable<Boolean> settingsGetterThread = () -> settings.getNotificationPolicy();
        Future<Boolean> settingsFuture = ThreadManager
                .getInstance()
                .sendTask(settingsGetterThread, TASK_TYPE.SETTING);

        try {
            return settingsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Failed to retrieve setting", e);
        }
        return null;
    }

    /**
     * Sets notification policy and saves it in SettingsManager
     *
     * @param isEnabled Should notifications be enabled
     */
    public void setNotificationPolicy(Boolean isEnabled) {

        //Create a Runnable thread that will download needed playlist and video data
        ThreadManager
                .getInstance()
                .sendVoidTask(new Thread(() -> {
                    settings.setNotificationPolicy(isEnabled);
                    if (ThreadManager.getExecutionPermission()) {
                        saveToJson();
                    }
                }), TASK_TYPE.SETTING);
    }

    /**
     * @return youtube-dl version stored in SettingsManager in form of String object
     */
    public String getYoutubeDlVersion() {

        Callable<String> settingsGetterThread = () -> settings.getYoutubeDlVersion();
        Future<String> settingsFuture = ThreadManager
                .getInstance()
                .sendTask(settingsGetterThread, TASK_TYPE.SETTING);

        try {
            return settingsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Failed to retrieve setting", e);
        }
        return null;
    }

    /**
     * Sets youtube-dl version and saves it in SettingsManager
     *
     * @param version Version of youtube-dl
     */
    public void setYoutubeDlVersion(String version) {

        //Create a Runnable thread that will download needed playlist and video data
        ThreadManager
                .getInstance()
                .sendVoidTask(new Thread(() -> {
                    settings.setYoutubeDlVersion(version);
                    if (ThreadManager.getExecutionPermission()) {
                        saveToJson();
                    }
                }), TASK_TYPE.SETTING);
    }

    /**
     * @return runtime version stored in SettingsManager in form of String object
     */
    public String getRuntimeVersion() {

        Callable<String> settingsGetterThread = () -> settings.getRuntimeVersion();
        Future<String> settingsFuture = ThreadManager
                .getInstance()
                .sendTask(settingsGetterThread, TASK_TYPE.SETTING);

        try {
            return settingsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Failed to retrieve setting", e);
        }
        return null;
    }

    /**
     * Sets runtime version and saves it in SettingsManager
     *
     * @param version Runtime version
     */
    public void setRuntimeVersion(String version) {

        //Create a Runnable thread that will download needed playlist and video data
        ThreadManager
                .getInstance()
                .sendVoidTask(new Thread(() -> {
                    settings.setRuntimeVersion(version);
                    if (ThreadManager.getExecutionPermission()) {
                        saveToJson();
                    }
                }), TASK_TYPE.SETTING);
    }

    /**
     * @return maximum number of allowed ffmpeg  concurrent tasks
     */
    public Integer getFfmpegThreadLimit() {

        Callable<Integer> settingsGetterThread = () -> settings.getFfmpegThreadLimit();
        Future<Integer> settingsFuture = ThreadManager
                .getInstance()
                .sendTask(settingsGetterThread, TASK_TYPE.SETTING);

        try {
            return settingsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Failed to retrieve setting", e);
        }
        return null;
    }

    /**
     * Sets maximum number of allowed ffmpeg  concurrent tasks
     *
     * @param ffmpegThreadLimit Number of desired allowed concurrent tasks
     */
    public void setFfmpegThreadLimit(Integer ffmpegThreadLimit) {

        //Create a Runnable thread that will download needed playlist and video data
        ThreadManager
                .getInstance()
                .sendVoidTask(new Thread(() -> {
                    settings.setFfmpegThreadLimit(ffmpegThreadLimit);
                    if (ThreadManager.getExecutionPermission()) {
                        saveToJson();
                    }
                }), TASK_TYPE.SETTING);
    }

    /**
     * @return boolean that specifies if youtube-dl should be ran in "fallback" mode
     */
    public Boolean getYoutubeDlFallback() {

        Callable<Boolean> settingsGetterThread = () -> settings.getYoutubeDlFallback();
        Future<Boolean> settingsFuture = ThreadManager
                .getInstance()
                .sendTask(settingsGetterThread, TASK_TYPE.SETTING);

        try {
            return settingsFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            LOG.error("Failed to retrieve setting", e);
        }
        return null;
    }

    /**
     * Sets youtubedl fallback boolean
     *
     * @param youtubeDlFallback Number of desired allowed concurrent tasks
     */
    public void setYoutubeDlFallback(Boolean youtubeDlFallback) {

        //Create a Runnable thread that will download needed playlist and video data
        ThreadManager
                .getInstance()
                .sendVoidTask(new Thread(() -> {
                    settings.setYoutubeDlFallback(youtubeDlFallback);
                    if (ThreadManager.getExecutionPermission()) {
                        saveToJson();
                    }
                }), TASK_TYPE.SETTING);
    }

    private void determineHostOS() {
        if (SystemUtils.IS_OS_WINDOWS) {
            settings.setOsType(OS_TYPE.WINDOWS);
        } else if (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_FREE_BSD
                || SystemUtils.IS_OS_NET_BSD || SystemUtils.IS_OS_OPEN_BSD) {
            settings.setOsType(OS_TYPE.OPEN_SOURCE_UNIX);
        } else if (SystemUtils.IS_OS_MAC) {
            settings.setOsType(OS_TYPE.MAC_OS);
        } else {
            settings.setOsType(OS_TYPE.UNKNOWN);
            LOG.warn("Unsupported OS, you are on your own...");
        }
    }

    private void setDefaultFileManagerIfNotSet() {
        if (getFileManagerCommand().equals("")) {
            if (getOS() == OS_TYPE.WINDOWS) {
                setFileManagerCommand("explorer");
            } else if (getOS() == OS_TYPE.OPEN_SOURCE_UNIX) {
                setFileManagerCommand("xdg-open");
            }
        }
    }

    private void setFfmpegExecutableIfPossibleAndNotSet() {
        if (getOS() != OS_TYPE.WINDOWS && getFfmpegExecutable().equals("")) {
            setFfmpegExecutable("ffmpeg");
            LOG.warn("FFmpeg has been assumed to be available via \"ffmpeg\" command. Make sure it is available" +
                    "via command line or download it from page/via your package manager.");
        }
        if (getOS() == OS_TYPE.WINDOWS && getFfmpegExecutable().equals("")) {
            LOG.warn("Ffmpeg is not set, download one and set it in settings to make video conversion possible.");
        }
        ThreadManager.getInstance().overrideConversionQueueSize(settings.getFfmpegThreadLimit());
    }

}


text:
module AhoyEmail
  class Processor
    attr_reader :message, :mailer, :ahoy_message

    UTM_PARAMETERS = %w(utm_source utm_medium utm_term utm_content utm_campaign)

    def initialize(message, mailer = nil)
      @message = message
      @mailer = mailer
    end

    def process
      action_name = mailer.action_name.to_sym
      if options[:message] && (!options[:only] || options[:only].include?(action_name)) && !options[:except].to_a.include?(action_name)
        @ahoy_message = AhoyEmail.message_model.new
        ahoy_message.token = generate_token
        ahoy_message.to = message.to.join(", ") if ahoy_message.respond_to?(:to=)
        ahoy_message.user = options[:user]

        track_open if options[:open]
        track_links if options[:utm_params] || options[:click]

        ahoy_message.mailer = options[:mailer] if ahoy_message.respond_to?(:mailer=)
        ahoy_message.subject = message.subject if ahoy_message.respond_to?(:subject=)
        ahoy_message.content = message.to_s if ahoy_message.respond_to?(:content=)

        UTM_PARAMETERS.each do |k|
          ahoy_message.send("#{k}=", options[k.to_sym]) if ahoy_message.respond_to?("#{k}=")
        end

        ahoy_message.assign_attributes(options[:extra] || {})

        ahoy_message.save
        message["Ahoy-Message-Id"] = ahoy_message.id.to_s
      end
    rescue => e
      report_error(e)
    end

    def track_send
      if (message_id = message["Ahoy-Message-Id"])
        ahoy_message = AhoyEmail.message_model.where(id: message_id.to_s).first
        if ahoy_message
          ahoy_message.sent_at = Time.now
          ahoy_message.save
        end
        message["Ahoy-Message-Id"] = nil
      end
    rescue => e
      report_error(e)
    end

    protected

    def options
      @options ||= begin
        options = AhoyEmail.options.merge(mailer.class.ahoy_options)
        if mailer.ahoy_options
          options = options.except(:only, :except).merge(mailer.ahoy_options)
        end
        options.each do |k, v|
          if v.respond_to?(:call)
            options[k] = v.call(message, mailer)
          end
        end
        options
      end
    end

    def generate_token
      SecureRandom.urlsafe_base64(32).gsub(/[\-_]/, "").first(32)
    end

    def track_open
      if html_part?
        raw_source = (message.html_part || message).body.raw_source
        regex = /<\/body>/i
        url =
          url_for(
            controller: "ahoy/messages",
            action: "open",
            id: ahoy_message.token,
            format: "gif"
          )
        pixel = ActionController::Base.helpers.image_tag(url, size: "1x1", alt: nil)

        # try to add before body tag
        if raw_source.match(regex)
          raw_source.gsub!(regex, "#{pixel}\\0")
        else
          raw_source << pixel
        end
      end
    end

    def track_links
      if html_part?
        body = (message.html_part || message).body

        doc = Nokogiri::HTML(body.raw_source)
        doc.css("a[href]").each do |link|
          # utm params first
          if options[:utm_params] && !skip_attribute?(link, "utm-params")
            uri = Addressable::URI.parse(link["href"])
            params = uri.query_values || {}
            UTM_PARAMETERS.each do |key|
              params[key] ||= options[key.to_sym] if options[key.to_sym]
            end
            uri.query_values = params
            link["href"] = uri.to_s
          end

          if options[:click] && !skip_attribute?(link, "click")
            signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new("sha1"), AhoyEmail.secret_token, link["href"])
            link["href"] =
              url_for(
                controller: "ahoy/messages",
                action: "click",
                id: ahoy_message.token,
                url: link["href"],
                signature: signature
              )
          end
        end

        # hacky
        body.raw_source.sub!(body.raw_source, doc.to_s)
      end
    end

    def html_part?
      (message.html_part || message).content_type =~ /html/
    end

    def skip_attribute?(link, suffix)
      attribute = "data-skip-#{suffix}"
      if link[attribute]
        # remove it
        link.remove_attribute(attribute)
        true
      elsif link["href"].to_s =~ /unsubscribe/i
        # try to avoid unsubscribe links
        true
      elsif link["href"].to_s.start_with?("mailto:")
        # mailto's shouldn't go through a redirect
        true
      else
        false
      end
    end

    def url_for(opt)
      opt = (ActionMailer::Base.default_url_options || {})
            .merge(options[:url_options])
            .merge(opt)
      AhoyEmail::Engine.routes.url_helpers.url_for(opt)
    end

    # not a fan of quiet errors
    # but tracking should *not* break
    # email delivery in production
    def report_error(e)
      if Rails.env.production?
        $stderr.puts e
      else
        raise e
      end
    end
  end
end


text:
__author__ = 'purg'

def get_descriptor_element_impls():
    """
    Discover and return Descriptor implementation classes found in the plugin
    directory. Keys in the returned map are the names of the discovered classes
    and the paired values are the actual class type objects.

    We look for modules (directories or files) that start with and alphanumeric
    character ('_' prefixed files/directories are hidden, but not recommended).

    Within a module, we first look for a helper variable by the name
    ``DESCRIPTOR_ELEMENT_CLASS``, which can either be a single class object or
    an iterable of class objects, to be exported. If the variable is set to
    None, we skip that module and do not import anything. If the variable is not
    present, we look for a class by the same na e and casing as the module's
    name. If neither are found, the module is skipped.

    :return: Map of discovered class objects of type ``DescriptorElement`` whose
        keys are the string names of the classes.
    :rtype: dict[str, type]

    """
    import os
    from smqtk.data_rep import DescriptorElement
    from smqtk.utils.plugin import get_plugins

    this_dir = os.path.abspath(os.path.dirname(__file__))
    helper_var = "DESCRIPTOR_ELEMENT_CLASS"
    return get_plugins(__name__, this_dir, helper_var, DescriptorElement)


text:
"""blogghar URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('allauth.urls')),
    url(r'^simplemde/', include('simplemde.urls', namespace='simplemde')),
    url(r'^comments/', include('comments.urls', namespace='comments')),
    url(r'^', include('authapp.urls', namespace='authapp')),
    url(r'^', include('blog.urls', namespace='blog')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  # noqa


text:
/**
 * Core classes that provide JavaFX support for JFreeChart.
 */
package org.jfree.chart.fx;


text:
using namespace mx::core;
using namespace std;
using namespace mxtest;

TEST( Test01, Interchangeable )
{
	Interchangeable object;
	stringstream expected;
	streamLine( expected, 1, R"(<interchangeable>)" );
	streamLine( expected, 2, R"(<beats></beats>)" );
	streamLine( expected, 2, R"(<beat-type></beat-type>)" );
	streamLine( expected, 1, R"(</interchangeable>)", false );
	stringstream actual;
	// object.toStream( std::cout, 1 );
	object.toStream( actual, 1 );
	CHECK_EQUAL( expected.str(), actual.str() )
	CHECK( ! object.hasAttributes() )
	CHECK( object.hasContents() )
}
TEST( Test02, Interchangeable )
{
	Interchangeable object;
    object.getAttributes()->hasSeparator = true;
    object.getAttributes()->separator = TimeSeparator::horizontal;
    object.getAttributes()->hasSymbol = true;
    object.getAttributes()->symbol = TimeSymbol::cut;
    object.getBeats()->setValue( XsString{ "Weird" } );
    object.getBeatType()->setValue( XsString{ "to be a string" } );
    object.setHasTimeRelation( true );
    object.getTimeRelation()->setValue( TimeRelationEnum::hyphen );
	stringstream expected;
	streamLine( expected, 1, R"(<interchangeable symbol="cut" separator="horizontal">)" );
	streamLine( expected, 2, R"(<time-relation>hyphen</time-relation>)" );
	streamLine( expected, 2, R"(<beats>Weird</beats>)" );
	streamLine( expected, 2, R"(<beat-type>to be a string</beat-type>)" );
	streamLine( expected, 1, R"(</interchangeable>)", false );
	stringstream actual;
	// object.toStream( std::cout, 1 );
	object.toStream( actual, 1 );
	CHECK_EQUAL( expected.str(), actual.str() )
	CHECK( object.hasAttributes() )
	CHECK( object.hasContents() )
}

#endif


text:
extern crate bindgen;

use std::env;
use std::path::PathBuf;
use bindgen::callbacks::{ParseCallbacks, IntKind};

fn main() {
    // We don't need to link to any library
    println!("cargo:rustc-link-lib=sqlite3");

    // The bindgen::Builder is the main entry point
    // to bindgen, and lets you build up options for
    // the resulting bindings.
    let bindings = bindgen::Builder::default()
        // The input header we would like to generate
        // bindings for.
        .header("wrapper.h")
        // This makes initializing structs less verbose
        .derive_default(true)
        // This makes debugging easier
        .derive_debug(true)
        .impl_debug(true)
        // Guess SQLite's macros
        .parse_callbacks(Box::new(SQLiteEnums()))
        // Finish the builder and generate the bindings.
        .generate()
        // Unwrap the Result and panic on failure.
        .expect("Unable to generate bindings");

    // Write the bindings to the $OUT_DIR/bindings.rs file.
    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}

#[derive(Debug)]
struct SQLiteEnums();
impl ParseCallbacks for SQLiteEnums {
    fn int_macro(&self, name: &str, _value: i64) -> Option<IntKind> {
        if name.starts_with("SQLITE_INDEX_CONSTRAINT") { Some(IntKind::U8) }
        else if name.starts_with("SQLITE_SERIES_CONSTRAINT") { Some(IntKind::U8) }
        else {Some(IntKind::I32)}
    }
}


text:
<?php

namespace Pimcore\Model\Metadata;

use Pimcore\Model;
use Pimcore\Model\Element;

class Predefined extends Model\AbstractModel {

    /**
     * @var integer
     */
    public $id;

    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $description;

    /**
     * @var string
     */
    public $key;

    /**
     * @var string
     */
    public $type;

    /**
     * @var string
     */
    public $targetSubtype;

    /**
     * @var string
     */
    public $data;

    /**
     * @var string
     */
    public $config;

    /**
     * @var string
     */
    public $ctype;

    /**
     * @var string
     */
    public $language;

    /**
     * @var integer
     */
    public $creationDate;

    /**
     * @var integer
     */
    public $modificationDate;

    /**
     * @param integer $id
     * @return self
     */
    public static function getById($id) {
        $metadata = new self();
        $metadata->setId($id);
        $metadata->getResource()->getById();

        return $metadata;
    }

    /**
     * @param string $key
     * @return self
     */
    public static function getByName($name, $language = "") {

        $metadata = new self();
        $metadata->setName($name);
        $metadata->getResource()->getByNameAndLanguage($name, $language);

        return $metadata;
    }

    /**
     * @return self
     */
    public static function create() {
        $type = new self();
        $type->save();

        return $type;
    }

    /**
     * @return string
     */
    public function getName() {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getType() {
        return $this->type;
    }

    /**
     * @return string
     */
    public function getData() {
        return $this->data;
    }

    /**
     * @param string $name
     * @return void
     */
    public function setName($name) {
        $this->name = $name;
        return $this;
    }

    /**
     * @param string $type
     * @return void
     */
    public function setType($type) {
        $this->type = $type;
        return $this;
    }

    /**
     * @param string $data
     * @return void
     */
    public function setData($data) {
        $this->data = $data;
        return $this;
    }

    /**
     * @return integer
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @param integer $id
     * @return void
     */
    public function setId($id) {
        $this->id = (int) $id;
        return $this;
    }

    /**
     * @param string $description
     * @return void
     */
    public function setDescription($description)
    {
        $this->description = $description;
        return $this;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param $creationDate
     * @return $this
     */
    public function setCreationDate($creationDate)
    {
        $this->creationDate = (int) $creationDate;
        return $this;
    }

    /**
     * @return int
     */
    public function getCreationDate()
    {
        return $this->creationDate;
    }

    /**
     * @param $modificationDate
     * @return $this
     */
    public function setModificationDate($modificationDate)
    {
        $this->modificationDate = (int) $modificationDate;
        return $this;
    }

    /**
     * @return int
     */
    public function getModificationDate()
    {
        return $this->modificationDate;
    }

    /**
     * @param string $language
     */
    public function setLanguage($language)
    {
        $this->language = $language;
    }

    /**
     * @return string
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * @param string $targetSubtype
     */
    public function setTargetSubtype($targetSubtype)
    {
        $this->targetSubtype = $targetSubtype;
    }

    /**
     * @return string
     */
    public function getTargetSubtype()
    {
        return $this->targetSubtype;
    }

    /**
     * @return string
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @param string $config
     */
    public function setConfig($config)
    {
        $this->config = $config;
    }

    /**
     *
     */
    public function minimize() {
        switch ($this->type) {
            case "document":
            case "asset":
            case "object":
                {
                    $element = Element\Service::getElementByPath($this->type, $this->data);
                    if ($element) {
                        $this->data = $element->getId();
                    } else {
                        $this->data = "";
                    }
                }
                break;
            case "date":
            {
                if ($this->data && !is_numeric($this->data)) {
                    $this->data = strtotime($this->data);
                }
            }
            default:
                //nothing to do
        }
    }

    /**
     *
     */
    public function expand() {
        switch ($this->type) {
            case "document":
            case "asset":
            case "object":
                {
                if (is_numeric($this->data)) {
                    $element = Element\Service::getElementById($this->type, $this->data);
                }
                if ($element) {
                    $this->data = $element->getFullPath();
                } else {
                    $this->data = "";
                }
            }

            break;
            default:
        //nothing to do
        }
    }
}


text:
package gobblin.metrics.event;

import java.util.Map;

import com.google.common.collect.Maps;

/**
 * Event to time actions in the program. Automatically reports start time, end time, and duration from the time
 * the {@link gobblin.metrics.event.TimingEvent} was created to the time {@link #stop} is called.
 */
public class TimingEvent {

  public static class LauncherTimings {
    public static final String FULL_JOB_EXECUTION = "FullJobExecutionTimer";
    public static final String WORK_UNITS_CREATION = "WorkUnitsCreationTimer";
    public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer";
    public static final String JOB_PREPARE = "JobPrepareTimer";
    public static final String JOB_START = "JobStartTimer";
    public static final String JOB_RUN = "JobRunTimer";
    public static final String JOB_COMMIT = "JobCommitTimer";
    public static final String JOB_CLEANUP = "JobCleanupTimer";
    public static final String JOB_CANCEL = "JobCancelTimer";
    public static final String JOB_COMPLETE = "JobCompleteTimer";
    public static final String JOB_FAILED = "JobFailedTimer";
  }

  public static class RunJobTimings {
    public static final String JOB_LOCAL_SETUP = "JobLocalSetupTimer";
    public static final String WORK_UNITS_RUN = "WorkUnitsRunTimer";
    public static final String WORK_UNITS_PREPARATION = "WorkUnitsPreparationTimer";
    public static final String MR_STAGING_DATA_CLEAN = "JobMrStagingDataCleanTimer";
    public static final String MR_DISTRIBUTED_CACHE_SETUP = "JobMrDistributedCacheSetupTimer";
    public static final String MR_JOB_SETUP = "JobMrSetupTimer";
    public static final String MR_JOB_RUN = "JobMrRunTimer";
    public static final String HELIX_JOB_SUBMISSION= "JobHelixSubmissionTimer";
    public static final String HELIX_JOB_RUN = "JobHelixRunTimer";
  }

  public static final String METADATA_START_TIME = "startTime";
  public static final String METADATA_END_TIME = "endTime";
  public static final String METADATA_DURATION = "durationMillis";
  public static final String METADATA_TIMING_EVENT = "timingEvent";

  private final String name;
  private final Long startTime;
  private final EventSubmitter submitter;
  private boolean stopped;

  public TimingEvent(EventSubmitter submitter, String name) {
    this.stopped = false;
    this.name = name;
    this.submitter = submitter;
    this.startTime = System.currentTimeMillis();
  }

  /**
   * Stop the timer and submit the event. If the timer was already stopped before, this is a no-op.
   */
  public void stop() {
    stop(Maps.<String, String> newHashMap());
  }

  /**
   * Stop the timer and submit the event, along with the additional metadata specified. If the timer was already stopped
   * before, this is a no-op.
   *
   * @param additionalMetadata a {@link Map} of additional metadata that should be submitted along with this event
   */
  public void stop(Map<String, String> additionalMetadata) {
    if (this.stopped) {
      return;
    }
    this.stopped = true;
    long endTime = System.currentTimeMillis();
    long duration = endTime - this.startTime;

    Map<String, String> finalMetadata = Maps.newHashMap();
    finalMetadata.putAll(additionalMetadata);
    finalMetadata.put(EventSubmitter.EVENT_TYPE, METADATA_TIMING_EVENT);
    finalMetadata.put(METADATA_START_TIME, Long.toString(this.startTime));
    finalMetadata.put(METADATA_END_TIME, Long.toString(endTime));
    finalMetadata.put(METADATA_DURATION, Long.toString(duration));

    this.submitter.submit(this.name, finalMetadata);
  }
}


text:
package org.commcare.tasks;

/**
 * @author Will Pride (wpride@dimagi.com)
 */
public interface RetrieveParseVerifyMessageListener {
    void downloadLinkReceived(String url);

    void downloadLinkReceivedAutoInstall(String url);

    void exceptionReceived(Exception e, boolean notify);
}


text:
package androidx.core.view;

import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;

import androidx.annotation.NonNull;
import androidx.core.R;
import androidx.core.view.ViewCompat.ScrollAxis;

/**
 * Helper for accessing features in {@link ViewGroup}.
 */
public final class ViewGroupCompat {

    /**
     * This constant is a {@link #setLayoutMode(ViewGroup, int) layoutMode}.
     * Clip bounds are the raw values of {@link android.view.View#getLeft() left},
     * {@link android.view.View#getTop() top},
     * {@link android.view.View#getRight() right} and {@link android.view.View#getBottom() bottom}.
     */
    public static final int LAYOUT_MODE_CLIP_BOUNDS = 0;

    /**
     * This constant is a {@link #setLayoutMode(ViewGroup, int) layoutMode}.
     * Optical bounds describe where a widget appears to be. They sit inside the clip
     * bounds which need to cover a larger area to allow other effects,
     * such as shadows and glows, to be drawn.
     */
    public static final int LAYOUT_MODE_OPTICAL_BOUNDS = 1;

    /*
     * Hide the constructor.
     */
    private ViewGroupCompat() {}

    /**
     * Called when a child has requested sending an {@link AccessibilityEvent} and
     * gives an opportunity to its parent to augment the event.
     *

     * If an {@link AccessibilityDelegateCompat} has been specified via calling
     * {@link ViewCompat#setAccessibilityDelegate(View, AccessibilityDelegateCompat)} its
     * {@link AccessibilityDelegateCompat#onRequestSendAccessibilityEvent(ViewGroup, View,
     * AccessibilityEvent)} is responsible for handling this call.
     *

     *
     * @param group The group whose method to invoke.
     * @param child The child which requests sending the event.
     * @param event The event to be sent.
     * @return True if the event should be sent.
     *
     * @deprecated Use {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)}
     * directly.
     */
    @Deprecated
    public static boolean onRequestSendAccessibilityEvent(ViewGroup group, View child,
            AccessibilityEvent event) {
        return group.onRequestSendAccessibilityEvent(child, event);
    }

    /**
     * Enable or disable the splitting of MotionEvents to multiple children during touch event
     * dispatch. This behavior is enabled by default for applications that target an
     * SDK version of 11 (Honeycomb) or newer. On earlier platform versions this feature
     * was not supported and this method is a no-op.
     *
     *
When this option is enabled MotionEvents may be split and dispatched to different child
     * views depending on where each pointer initially went down. This allows for user interactions
     * such as scrolling two panes of content independently, chording of buttons, and performing
     * independent gestures on different pieces of content.
     *
     * @param group ViewGroup to modify
     * @param split true to allow MotionEvents to be split and dispatched to multiple
     *              child views. false to only allow one child view to be the target of
     *              any MotionEvent received by this ViewGroup.
     *
     * @deprecated Use {@link ViewGroup#setMotionEventSplittingEnabled(boolean)} directly.
     */
    @Deprecated
    public static void setMotionEventSplittingEnabled(ViewGroup group, boolean split) {
        group.setMotionEventSplittingEnabled(split);
    }

    /**
     * Returns the basis of alignment during layout operations on this ViewGroup:
     * either {@link #LAYOUT_MODE_CLIP_BOUNDS} or {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
     *

     * If no layoutMode was explicitly set, either programmatically or in an XML resource,
     * the method returns the layoutMode of the view's parent ViewGroup if such a parent exists,
     * otherwise the method returns a default value of {@link #LAYOUT_MODE_CLIP_BOUNDS}.
     *
     * @return the layout mode to use during layout operations
     *
     * @see #setLayoutMode(ViewGroup, int)
     */
    public static int getLayoutMode(@NonNull ViewGroup group) {
        if (Build.VERSION.SDK_INT >= 18) {
            return group.getLayoutMode();
        }
        return LAYOUT_MODE_CLIP_BOUNDS;
    }

    /**
     * Sets the basis of alignment during the layout of this ViewGroup.
     * Valid values are either {@link #LAYOUT_MODE_CLIP_BOUNDS} or
     * {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
     *
     * @param mode the layout mode to use during layout operations
     *
     * @see #getLayoutMode(ViewGroup)
     */
    public static void setLayoutMode(@NonNull ViewGroup group, int mode) {
        if (Build.VERSION.SDK_INT >= 18) {
            group.setLayoutMode(mode);
        }
    }

    /**
     * Changes whether or not this ViewGroup should be treated as a single entity during
     * Activity Transitions.
     * @param isTransitionGroup Whether or not the ViewGroup should be treated as a unit
     *                          in Activity transitions. If false, the ViewGroup won't transition,
     *                          only its children. If true, the entire ViewGroup will transition
     *                          together.
     */
    public static void setTransitionGroup(@NonNull ViewGroup group, boolean isTransitionGroup) {
        if (Build.VERSION.SDK_INT >= 21) {
            group.setTransitionGroup(isTransitionGroup);
        } else {
            group.setTag(R.id.tag_transition_group, isTransitionGroup);
        }
    }

    /**
     * Returns true if this ViewGroup should be considered as a single entity for removal
     * when executing an Activity transition. If this is false, child elements will move
     * individually during the transition.
     */
    public static boolean isTransitionGroup(@NonNull ViewGroup group) {
        if (Build.VERSION.SDK_INT >= 21) {
            return group.isTransitionGroup();
        }
        Boolean explicit = (Boolean) group.getTag(R.id.tag_transition_group);
        return (explicit != null && explicit)
                || group.getBackground() != null
                || ViewCompat.getTransitionName(group) != null;
    }

    /**
     * Return the current axes of nested scrolling for this ViewGroup.
     *
     *
A ViewGroup returning something other than {@link ViewCompat#SCROLL_AXIS_NONE} is
     * currently acting as a nested scrolling parent for one or more descendant views in
     * the hierarchy.

     *
     * @return Flags indicating the current axes of nested scrolling
     * @see ViewCompat#SCROLL_AXIS_HORIZONTAL
     * @see ViewCompat#SCROLL_AXIS_VERTICAL
     * @see ViewCompat#SCROLL_AXIS_NONE
     */
    @ScrollAxis
    @SuppressWarnings("RedundantCast") // Intentionally invoking interface method.
    public static int getNestedScrollAxes(@NonNull ViewGroup group) {
        if (Build.VERSION.SDK_INT >= 21) {
            return group.getNestedScrollAxes();
        }
        if (group instanceof NestedScrollingParent) {
            return ((NestedScrollingParent) group).getNestedScrollAxes();
        }
        return ViewCompat.SCROLL_AXIS_NONE;
    }
}


text:
<resources>
    <string name="app_name">GimmeLayouts</string>
</resources>


text:
var common = require('../common');
var assert = require('assert');
var fs = require('fs');

var openFd;
fs.open(__filename, 'r', function(err, fd) {
  if (err) {
    throw err;
  }

  openFd = fd;
});

process.addListener('exit', function() {
  assert.ok(openFd);
});


text:
title: 19.3.2016
layout: post
author: jeremiah.puren
permalink: /19.3.2016/
source-id: 1vTyOZbYe1tAzzTqnT1-9Xfmuv6iMPU2k0QgfvJsIthg
published: true
---
This lesson, we learnt about Prezi, a presentation assisting software. We got to play around with it and use all of the functions to test them out, it was really fun and it taught us a fair amount as well. For homework we had to play around more.


text:
FileList = [
	"lib/eventer.js"
	, "helpers/application.js"
	, "helpers/images.js"
	, "helpers/user.js"
	, "ui/ui.js"
	, "ui/button_group.js"
	, "ui/sub_tabs.js"
	, "ui/gallery.js"
	, "lib/file_cache.js"
	, "lib/authenticator.js"
	, "lib/validation_errors.js"
	, "lib/geolocator.js"
	, "layouts/application.js"
	, "layouts/login.js"
	, "controllers/capsules.js"
	, "controllers/application.js"
	, "controllers/accounts.js"
	, "controllers/authentications.js"
	, "controllers/followings.js"
	, "controllers/omniauth_callbacks.js"
	, "controllers/tags.js"
	, "controllers/sharings.js"
	, "controllers/websnippets.js"
	, "controllers/users.js"
	, "views/accounts/init.js"
	, "views/capsules/index.js"
	, "views/capsules/show.js"
	, "views/capsules/create.js"
	, "views/capsules/mosaic.js"
	, "views/capsules/top_bar.js"
	, "views/capsules/update.js"
	, "views/capsules/feed_row.js"
	, "views/capsules/eight_photos.js"
	, "views/capsules/four_photos.js"
	, "views/capsules/two_photos.js"
	, "views/capsules/two_comments.js"
	, "views/capsules/video_screenshot.js"
	, "views/comments/create.js"
	, "views/comments/show.js"
	, "views/photos/create.js"
	, "views/photos/show.js"
	, "views/videos/create.js"
	, "views/videos/show.js"
	, "views/tags/create.js"
	, "views/sharings/init.js"
	, "views/websnippets/init.js"
	, "views/websnippets/show.js"
	, "views/users/show.js"
]


text:
'use strict';

const EventEmitter = require('events');
const Promise = require('bluebird');
const AwsSqsClient = require('./aws-sqs-client');

const DEFAULT_POLLING_INTERVAL = 20;
const DEFAULT_WAIT_TIME = 100;
const DEFAULT_MAX_MESSAGES = 3;

class SQSTransport extends EventEmitter {
	constructor(options) {
		super();

		this.awsSqsClient = AwsSqsClient.create({
			accessKeyId: options.accessKeyId,
			secretAccessKey: options.secretAccessKey,
			region: options.region,
			QueueUrl: options.QueueUrl,
			WaitTimeSeconds: typeof options.WaitTimeSeconds === 'number' ? options.WaitTimeSeconds : DEFAULT_WAIT_TIME,
			MaxNumberOfMessages: typeof options.MaxNumberOfMessages === 'number' ? options.MaxNumberOfMessages : DEFAULT_MAX_MESSAGES
		});

		this.pollingInterval = typeof options.pollingInterval === 'number' ?
			options.pollingInterval : DEFAULT_POLLING_INTERVAL;

		this.handler = null;
		this.closeHandler = null;

		this.initialized = false;
	}

	initialize() {
		if (this.initialized) {
			return this;
		}
		this.initialized = true;
		this.pollForMessages();
		return this;
	}

	pollForMessages() {
		return this.awsSqsClient.receiveMessage().then(messages => {
			if (messages.length === 0) {
				return this.pollAgain();
			}

			const promises = messages.map(this.handleIncomingMessage.bind(this));

			return Promise.all(promises).catch(err => {
				this.emit('error', err);
				return this.pollAgain();
			});
		});
	}

	deleteMessage(message) {
		return this.awsSqsClient.deleteMessage(message.ReceiptHandle).catch(err => {
			this.emit('error', err);
			return null;
		});
	}

	pollAgain() {
		return Promise.delay(this.pollingInterval * 1000).then(() => {
			// If there is a closeHandler we are done and need to break the loop.
			if (this.closeHandler) {
				this.closeHandler();
			} else {
				this.pollForMessages();
			}

			// Don't return the result of pollForMessages() (which is a Promise). If we do, we'll end
			// up with an infinite stack that will never unwind.
			return null;
		});
	}

	handleIncomingMessage(message) {
		this.emit('log', {level: 'info', message: 'received sqs message', context: {message}});

		let payload;
		let pattern;
		try {
			payload = JSON.parse(message.Body);
			pattern = JSON.parse(message.MessageAttributes.pattern.StringValue);
		} catch (err) {
			this.emit('error', new Error(`Oddcast message JSON parsing error: ${err.message}`));
			return;
		}

		return this.handler({pattern, payload})
			.catch(() => {
				// Oddcast will have already reported the error, so we can skip it here.
				return false;
			})
			.then(success => {
				if (success) {
					return this.deleteMessage(message.ReceiptHandle);
				}
				return null;
			});
	}

	write(message) {
		const pattern = message.pattern;
		const payload = typeof message.payload === 'undefined' ? null : message.payload;

		return this.awsSqsClient.sendMessage(pattern, payload).then(() => {
			this.emit('log', {level: 'info', message: 'SQS transport message sent', context: {pattern, payload}});
			return null;
		});
		// If we return a promise here, oddcast will catch errors itself.
		// .catch(err => {
		// 	this.emit('error', err);
		// });
	}

	setHandler(handler) {
		this.handler = handler;
	}

	close(callback) {
		callback = typeof callback === 'function' ? callback : function () {};
		this.closeHandler = callback;
		return true;
	}

	// options.accessKeyId - String
	// options.secretAccessKey - String
	// options.region - AWS region String
	// options.QueueUrl - AWS SQS queue URL String.
	// options.WaitTimeSeconds - Number of seconds to wait for new messages when polling (default=100).
	// options.MaxNumberOfMessages - Number of messages to retreive at once (default=3).
	// options.pollingInterval - Number of seconds to wait between polling tries (default=20).
	static create(options) {
		return new SQSTransport(options);
	}
}

module.exports = SQSTransport;


text:
<!doctype html>

	<meta charset="utf-8">

	<link rel="stylesheet" href="../../../../docs/style.css">

timelinefx:timelinefx.tlParticleManager.New

Method New:Void( particles:Int=tlPARTICLE_LIMIT, layers:Int=1 )

Constructor for tlParticleManager.
See also CreateParticleManager


text:
package com.xiangli.coolweather;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;

/**
 * Created by Administrator on 2017/2/23.
 */

public interface RequestSerice {
   @POST("add/index.html")
   @GET("WWW")
   Call<User> getName(@Path("NAME")String userName);
    Call<String> getString(@Query("userName")String userName,@Query("password")String password);
}


text:
#pragma once

#ifndef __SWIFT_FACTORY_H__
#define __SWIFT_FACTORY_H__

namespace Swift {
  class iSection;
  class iBlock;

  typedef SharedPtr<class Factory> oFactory;

  class Factory : public SharedObject<iSharedObject, LockableObject<iSharedObject, FastMutex>> {
    /* Class version */
    STAMINA_OBJECT_CLASS_VERSION(Factory, iSharedObject, Version(1,0,0,0));

  public:
    typedef iSection* (__stdcall *fCallback)(iBlock* parent);
    typedef tHashMap<string, fCallback> tCallbacks;

  private:
    Factory(const Factory& copy) { }
    Factory() { }

  public:
    static inline Factory* get() {
      if (!_instance/*.isValid()*/) {
        _instance = new Factory;
      }
      return _instance.get();
    }
    static inline iSection* get(const string& name, iBlock* parent = 0) {
      return get()->getInstance(name, parent);
    }

  public:
    iSection* getInstance(const string& name, iBlock* parent);

    inline void bind(const string& name, fCallback callback) {
      _callbacks[name] = callback;
    }
    inline void unbind(const string& name) {
      tCallbacks::iterator it = _callbacks.find(name);
      if (it != _callbacks.end()) {
        _callbacks.erase(it);
      }
    }
    inline bool isBinded(const string& name) {
      return _callbacks.find(name) != _callbacks.end();
    }

  protected:
    tCallbacks _callbacks;

  private:
    static oFactory _instance;
  };

  __declspec(selectany) oFactory Factory::_instance;
}

#endif // __SWIFT_FACTORY_H__


text:
package com.nifty.cloud.mb.core;

import java.util.ArrayList;

/**
 * Interface for callback after push notification search
 */
public interface SearchPushCallback extends CallbackBase{
    /**
     * Override this method with the code you want to run after getting push
     * @param push found push
     * @param e exception sdk internal or NIFTY Cloud mobile backend
     */
    void done(ArrayList<NCMBPush> push, NCMBException e);
}


text:
#import "EC2CreateTagsResponse.h"
#import "EC2ResponseUnmarshaller.h"

@interface EC2CreateTagsResponseUnmarshaller:EC2ResponseUnmarshaller
{
    EC2CreateTagsResponse *response;
}

@property (nonatomic, readonly) EC2CreateTagsResponse *response;

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;

-(EC2CreateTagsResponse *)response;

@end


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.twelvemonkeys.common</groupId>
        <artifactId>common</artifactId>
        <version>3.10.0-SNAPSHOT</version>
    </parent>
    <artifactId>common-lang</artifactId>
    <packaging>jar</packaging>
    <name>TwelveMonkeys :: Common :: Language support</name>
    <description>
        The TwelveMonkeys Common Language support
    </description>

    <properties>
        <project.jpms.module.name>com.twelvemonkeys.common.lang</project.jpms.module.name>
    </properties>

</project>


text:
/**
 * @author  Cenk Gündoğan <cnkgndgn@gmail.com>
 */

#ifndef COAP_COMMON_H
#define COAP_COMMON_H

#include <coap.h>

#ifdef __cplusplus
extern "C" {
#endif

#define MAX_RESPONSE_LEN    500

extern uint8_t response[MAX_RESPONSE_LEN];
extern const coap_endpoint_t endpoints[];

int handle_get_well_known_core(coap_rw_buffer_t *scratch, const coap_packet_t *inpkt,
                               coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo);

void *microcoap_server(void *);

#ifdef __cplusplus
}
#endif
#endif /* COAP_COMMON_H */
/** @} */


text:
WSO2 Complex Event Processor (CEP)
==================================
V 4.0.0

If snapshot versions of dependent jars are not available or out of date, to build this repository please build the following repositories first.

* siddhi - https://github.com/wso2/siddhi
* carbon-commons - https://github.com/wso2/carbon-commons
* carbon-event-processing - https://github.com/wso2/carbon-event-processing
* jaggery - https://github.com/wso2/jaggery/tree/branch-for-kernel4.3.0


text:
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

SOCIALACCOUNT_ENABLED = 'allauth.socialaccount' in settings.INSTALLED_APPS

if SOCIALACCOUNT_ENABLED:
    if 'allauth.socialaccount.context_processors.socialaccount' \
            not in settings.TEMPLATE_CONTEXT_PROCESSORS:
        raise ImproperlyConfigured("socialaccount context processor "
                    "not found in settings.TEMPLATE_CONTEXT_PROCESSORS."
                    "See settings.py instructions here: "
                    "https://github.com/pennersr/django-allauth#installation")

LOGIN_REDIRECT_URL = getattr(settings, 'LOGIN_REDIRECT_URL', '/')


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    This file is part of LexLauncher, licensed under the MIT License (MIT).

    Copyright (c) 2014-2017, Jamie Mansfield <https://github.com/jamierocks>

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

<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%d{HH:mm:ss}] [%logger{1}/%level]: %msg%n"/>
        </Console>

        <RollingFile name="File" fileName="logs/latest.log" filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="[%d{HH:mm:ss}] [%logger{1}/%level]: %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <OnStartupTriggeringPolicy />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="all">
            <AppenderRef ref="Console" level="info"/>
            <AppenderRef ref="File" level="info"/>
        </Root>
    </Loggers>
</Configuration>


text:
var ModuleTest<<REPOSITORY_NAME>> = (function(global) {

var test = new Test(["<<REPOSITORY_NAME>>"], { // Add the ModuleName to be tested here (if necessary).
        disable:    false, // disable all tests.
        browser:    true,  // enable browser test.
        worker:     true,  // enable worker test.
        node:       true,  // enable node test.
        nw:         true,  // enable nw.js test.
        el:         true,  // enable electron (render process) test.
        button:     true,  // show button.
        both:       true,  // test the primary and secondary modules.
        ignoreError:false, // ignore error.
        callback:   function() {
        },
        errorback:  function(error) {
            console.error(error.message);
        }
    });

if (IN_BROWSER || IN_NW || IN_EL || IN_WORKER || IN_NODE) {
    test.add([
        test<<REPOSITORY_NAME>>_method,
        test<<REPOSITORY_NAME>>_accessor,
    ]);
}
if (IN_BROWSER || IN_NW || IN_EL) {
    test.add([
    ]);
}
if (IN_WORKER) {
    test.add([
    ]);
}
if (IN_NODE) {
    test.add([
    ]);
}

// --- test cases ------------------------------------------
function test<<REPOSITORY_NAME>>_method(test, pass, miss) {

    var result = {
            0: new WebModule.<<REPOSITORY_NAME>>().method("a", "b") === "ab", // true
        };

    if ( /false/.test(JSON.stringify(result)) ) {
        test.done(miss());
    } else {
        test.done(pass());
    }
}

function test<<REPOSITORY_NAME>>_accessor(test, pass, miss) {

    var instance = new WebModule.<<REPOSITORY_NAME>>();
    instance.value = "a"; // setter

    if (instance.value === "a") { // getter
        test.done(pass());
    } else {
        test.done(miss());
    }
}

return test.run();

})(GLOBAL);


text:
#include <string>
#include <unordered_set>
#include <utility>

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"

namespace tensorflow {
template <typename T>
class ListDiffOp : public OpKernel {
 public:
  explicit ListDiffOp(OpKernelConstruction* context) : OpKernel(context) {
    const DataType dt = DataTypeToEnum<T>::v();
    OP_REQUIRES_OK(context, context->MatchSignature({dt, dt}, {dt, DT_INT32}));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& x = context->input(0);
    const Tensor& y = context->input(1);

    OP_REQUIRES(context, TensorShapeUtils::IsVector(x.shape()),
                errors::InvalidArgument("x should be a 1D vector."));

    OP_REQUIRES(context, TensorShapeUtils::IsVector(y.shape()),
                errors::InvalidArgument("y should be a 1D vector."));

    std::unordered_set<T> y_set;
    const auto Ty = y.vec<T>();
    const int y_size = Ty.size();
    y_set.reserve(y_size);
    for (int i = 0; i < y_size; ++i) {
      y_set.insert(Ty(i));
    }

    // Compute the size of the output.
    const auto Tx = x.vec<T>();
    const int x_size = Tx.size();

    int out_size = 0;
    for (int i = 0; i < x_size; ++i) {
      if (y_set.count(Tx(i)) == 0) {
        ++out_size;
      }
    }

    // Allocate and populate outputs.
    Tensor* out = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, {out_size}, &out));
    auto Tout = out->vec<T>();

    Tensor* indices = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(1, {out_size}, &indices));
    auto Tindices = indices->vec<int32>();

    for (int i = 0, p = 0; i < x_size; ++i) {
      if (y_set.count(Tx(i)) == 0) {
        OP_REQUIRES(context, p < out_size,
                    errors::OutOfRange(
                        "Tried to set output index ", p,
                        " when output Tensor only had ", out_size,
                        " elements. Check that your "
                        "input tensors are not being concurrently mutated."));
        Tout(p) = Tx(i);
        Tindices(p) = i;
        p++;
      }
    }
  }
};

#define REGISTER_LISTDIFF(type)                                      \
  REGISTER_KERNEL_BUILDER(                                           \
      Name("ListDiff").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      ListDiffOp<type>)

TF_CALL_REAL_NUMBER_TYPES(REGISTER_LISTDIFF);
REGISTER_LISTDIFF(string);
#undef REGISTER_LISTDIFF

}  // namespace tensorflow


text:
package cz.jan.maly.model.planing;

import cz.jan.maly.model.knowledge.WorkingMemory;
import cz.jan.maly.model.metadata.DesireParameters;

/**
 * Interface with template for reaction on change strategy
 * Created by Jan on 10-May-17.
 */
public interface ReactionOnChangeStrategy {

    /**
     * Strategy to update beliefs
     * @param memory
     * @param desireParameters
     */
    void updateBeliefs(WorkingMemory memory, DesireParameters desireParameters);

}


text:
namespace boost { namespace spirit { namespace karma { namespace detail
{
    template <typename Modifiers, bool case_modifier = false>
    struct get_casetag : mpl::identity<unused_type> {};

    template <typename Modifiers>
    struct get_casetag<Modifiers, true>
      : mpl::if_<has_modifier<Modifiers, tag::char_code_base<tag::lower> >
          , tag::lower, tag::upper> {};
}}}}

#endif


text:
package com.amazonaws.services.ec2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * DescribeFlowLogsRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeFlowLogsRequestMarshaller implements Marshaller<Request<DescribeFlowLogsRequest>, DescribeFlowLogsRequest> {

    public Request<DescribeFlowLogsRequest> marshall(DescribeFlowLogsRequest describeFlowLogsRequest) {

        if (describeFlowLogsRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<DescribeFlowLogsRequest> request = new DefaultRequest<DescribeFlowLogsRequest>(describeFlowLogsRequest, "AmazonEC2");
        request.addParameter("Action", "DescribeFlowLogs");
        request.addParameter("Version", "2016-11-15");
        request.setHttpMethod(HttpMethodName.POST);

        com.amazonaws.internal.SdkInternalList<Filter> describeFlowLogsRequestFilterList = (com.amazonaws.internal.SdkInternalList<Filter>) describeFlowLogsRequest
                .getFilter();
        if (!describeFlowLogsRequestFilterList.isEmpty() || !describeFlowLogsRequestFilterList.isAutoConstruct()) {
            int filterListIndex = 1;

            for (Filter describeFlowLogsRequestFilterListValue : describeFlowLogsRequestFilterList) {

                if (describeFlowLogsRequestFilterListValue.getName() != null) {
                    request.addParameter("Filter." + filterListIndex + ".Name", StringUtils.fromString(describeFlowLogsRequestFilterListValue.getName()));
                }

                com.amazonaws.internal.SdkInternalList<String> filterValuesList = (com.amazonaws.internal.SdkInternalList<String>) describeFlowLogsRequestFilterListValue
                        .getValues();
                if (!filterValuesList.isEmpty() || !filterValuesList.isAutoConstruct()) {
                    int valuesListIndex = 1;

                    for (String filterValuesListValue : filterValuesList) {
                        if (filterValuesListValue != null) {
                            request.addParameter("Filter." + filterListIndex + ".Value." + valuesListIndex, StringUtils.fromString(filterValuesListValue));
                        }
                        valuesListIndex++;
                    }
                }
                filterListIndex++;
            }
        }

        com.amazonaws.internal.SdkInternalList<String> describeFlowLogsRequestFlowLogIdsList = (com.amazonaws.internal.SdkInternalList<String>) describeFlowLogsRequest
                .getFlowLogIds();
        if (!describeFlowLogsRequestFlowLogIdsList.isEmpty() || !describeFlowLogsRequestFlowLogIdsList.isAutoConstruct()) {
            int flowLogIdsListIndex = 1;

            for (String describeFlowLogsRequestFlowLogIdsListValue : describeFlowLogsRequestFlowLogIdsList) {
                if (describeFlowLogsRequestFlowLogIdsListValue != null) {
                    request.addParameter("FlowLogId." + flowLogIdsListIndex, StringUtils.fromString(describeFlowLogsRequestFlowLogIdsListValue));
                }
                flowLogIdsListIndex++;
            }
        }

        if (describeFlowLogsRequest.getMaxResults() != null) {
            request.addParameter("MaxResults", StringUtils.fromInteger(describeFlowLogsRequest.getMaxResults()));
        }

        if (describeFlowLogsRequest.getNextToken() != null) {
            request.addParameter("NextToken", StringUtils.fromString(describeFlowLogsRequest.getNextToken()));
        }

        return request;
    }

}


text:
#region Foreign-License

#endregion
using System;
namespace Tcl.Lang
{

    /// <summary> This class implements the built-in "incr" command in Tcl.</summary>
    class IncrCmd : ICommand
    {
        /// <summary> This procedure is invoked to process the "incr" Tcl command.
        /// See the user documentation for details on what it does.
        /// </summary>
        /// <exception cref=""> TclException if wrong # of args or increment is not an
        /// integer.
        /// </exception>

        public TCL.CompletionCode CmdProc(Interp interp, TclObject[] objv)
        {
            int incrAmount;
            TclObject newValue;

            if ((objv.Length != 2) && (objv.Length != 3))
            {
                throw new TclNumArgsException(interp, 1, objv, "varName ?increment?");
            }

            // Calculate the amount to increment by.

            if (objv.Length == 2)
            {
                incrAmount = 1;
            }
            else
            {
                try
                {
                    incrAmount = TclInteger.Get(interp, objv[2]);
                }
                catch (TclException e)
                {
                    interp.AddErrorInfo("\n    (reading increment)");
                    throw;
                }
            }

            // Increment the variable's value.

            newValue = Var.incrVar(interp, objv[1], null, incrAmount, TCL.VarFlag.LEAVE_ERR_MSG);

            // FIXME: we need to look at this exception throwing problem again
            /*
            if (newValue == null) {
            return TCL_ERROR;
            }
            */

            // Set the interpreter's object result to refer to the variable's new
            // value object.

            interp.SetResult(newValue);
            return TCL.CompletionCode.RETURN;
        }
    }
}


text:
var Book = require('../models/book');
var BookInstance = require('../models/bookinstance');

// Display list of all BookInstances
// Display list of all BookInstances
exports.bookinstance_list = function(req, res, next) {

  BookInstance.find()
    .populate('book')
    .exec(function (err, list_bookinstances) {
      if (err) { return next(err); }
      //Successful, so render
      res.render('bookinstance_list', { title: 'Book Instance List', bookinstance_list: list_bookinstances });
    });

};

// Display detail page for a specific BookInstance
// Display detail page for a specific BookInstance
exports.bookinstance_detail = function(req, res, next) {

  BookInstance.findById(req.params.id)
    .populate('book')
    .exec(function (err, bookinstance) {
      if (err) { return next(err); }
      //Successful, so render
      res.render('bookinstance_detail', { title: 'Book:', bookinstance: bookinstance });
    });

};

// Display BookInstance create form on GET
// Display BookInstance create form on GET
exports.bookinstance_create_get = function(req, res, next) {

    Book.find({},'title')
    .exec(function (err, books) {
      if (err) { return next(err); }
      //Successful, so render
      res.render('bookinstance_form', {title: 'Create BookInstance', book_list:books});
    });

};

// Handle BookInstance create on POST
// Handle BookInstance create on POST
exports.bookinstance_create_post = function(req, res, next) {

    req.checkBody('book', 'Book must be specified').notEmpty(); //We won't force Alphanumeric, because book titles might have spaces.
    req.checkBody('imprint', 'Imprint must be specified').notEmpty();
    req.checkBody('due_back', 'Invalid date').optional({ checkFalsy: true }).isDate();

    req.sanitize('book').escape();
    req.sanitize('imprint').escape();
    req.sanitize('status').escape();
    req.sanitize('book').trim();
    req.sanitize('imprint').trim();
    req.sanitize('status').trim();
    req.sanitize('due_back').toDate();

    var bookinstance = new BookInstance({
        book: req.body.book,
        imprint: req.body.imprint,
        status: req.body.status,
        due_back: req.body.due_back
    });

    var errors = req.validationErrors();
    if (errors) {

        Book.find({},'title')
        .exec(function (err, books) {
          if (err) { return next(err); }
          //Successful, so render
          res.render('bookinstance_form', { title: 'Create BookInstance', book_list : books, selected_book : bookinstance.book._id , errors: errors, bookinstance:bookinstance });
        });
        return;
    }
    else {
    // Data from form is valid

        bookinstance.save(function (err) {
            if (err) { return next(err); }
               //successful - redirect to new book-instance record.
               res.redirect(bookinstance.url);
            });
    }

};

// Display BookInstance delete form on GET
exports.bookinstance_delete_get = function(req, res) {
    res.send('NOT IMPLEMENTED: BookInstance delete GET');
};

// Handle BookInstance delete on POST
exports.bookinstance_delete_post = function(req, res) {
    res.send('NOT IMPLEMENTED: BookInstance delete POST');
};

// Display BookInstance update form on GET
exports.bookinstance_update_get = function(req, res) {
    res.send('NOT IMPLEMENTED: BookInstance update GET');
};

// Handle bookinstance update on POST
exports.bookinstance_update_post = function(req, res) {
    res.send('NOT IMPLEMENTED: BookInstance update POST');
};


text:
<?xml version="1.0" encoding="utf-8"?>
<doc>
  <assembly>
    <name>SharpGit</name>
  </assembly>
  <members>
    <member name="M:SharpGit.GitTools.PathCombine(System.String,System.String)">
      Long path capable version of <see cref="M:System.IO.Path.Combine(System.String,System.String)" />
    </member>
    <member name="M:SharpGit.GitTools.GetNormalizedDirectoryName(System.String)">
      Gets the normalized directory name of path (Long path enabled version of <see cref="M:System.IO.Path.GetDirectoryName(System.String)" />, always returning full paths)
      <returns>Directory information for path, or null if path denotes a root directory or is null. Returns String.Empty if path does not contain directory information.</returns>
    </member>
    <member name="M:SharpGit.GitTools.IsAbsolutePath(System.String)">

Checks whether the specified path is an absolute path that doesn't end in an unneeded '\'

    </member>
    <member name="M:SharpGit.GitTools.IsNormalizedFullPath(System.String)">

Checks whether normalization is required

      <remarks>This method does not verify the casing of invariant parts</remarks>
    </member>
    <member name="M:SharpGit.GitTools.GetNormalizedFullPath(System.String)">

Normalizes the path to a full path

      This normalizes drive letters to upper case and hostnames to lowercase to match Subversion 1.6 behavior
    </member>
    <member name="M:SharpGit.GitTools.IsBelowManagedPath(System.String)">
      Gets a boolean indicating whether at least one of the
parent paths or the path (file/directory) itself is a working copy.

    </member>
    <member name="M:SharpGit.GitTools.IsManagedPath(System.String)">
      Gets a boolean indicating whether the path could contain a Subversion Working Copy
      <remarks>Assumes path is a directory</remarks>
    </member>
    <member name="M:SharpGit.GitTools.GetTruePath(System.String,System.Boolean)">
      Gets the absolute pathname exactly like it is on disk (fixing casing).
For not existing paths, if bestEffort is TRUE, returns a path based on existing parents. Otherwise return NULL for not existing paths
    </member>
    <member name="M:SharpGit.GitTools.GetTruePath(System.String)">
      Gets the absolute pathname exactly like it is on disk (fixing casing); returns NULL for non existing paths
    </member>
    <member name="P:SharpGit.GitMergeAnalysis.IsUnborn">

The HEAD of the current repository is "unborn" and does not point to
a valid commit.  No merge can be performed, but the caller may wish
to simply set HEAD to the target commit(s).

    </member>
    <member name="P:SharpGit.GitMergeAnalysis.CanFastForward">

The given merge input is a fast-forward from HEAD and no merge
needs to be performed.  Instead, the client can check out the
given merge input.

    </member>
    <member name="P:SharpGit.GitMergeAnalysis.IsUpToDate">

All given merge inputs are reachable from HEAD, meaning the
repository is up-to-date and no merge needs to be performed.

    </member>
    <member name="P:SharpGit.GitMergeAnalysis.CanMergeNormal">

A "normal" merge; both HEAD and the given merge input have diverged
from their common ancestor.  The divergent commits must be merged.

    </member>
    <member name="T:SharpGit.GitCheckOutConflictStrategy">

Enum specifying what content checkout should write to disk
for conflicts.

      <threadsafety static="true" instance="false" />
    </member>
    <member name="F:SharpGit.GitCheckOutConflictStrategy.Diff3">

Write diff3 formated files for conflicts.

    </member>
    <member name="F:SharpGit.GitCheckOutConflictStrategy.Merge">

Write normal merge files for conflicts.

    </member>
    <member name="F:SharpGit.GitCheckOutConflictStrategy.UseTheirs">

For conflicting files, checkout the "theirs" (stage 3) version of
the file from the index.

    </member>
    <member name="F:SharpGit.GitCheckOutConflictStrategy.UseOurs">

For conflicting files, checkout the "ours" (stage 2)  version of
the file from the index.

    </member>
    <member name="F:SharpGit.GitCheckOutConflictStrategy.Default">

Use the default behavior for handling file conflicts. This is
controlled by the merge.conflictstyle config option, and is "Merge"
if no option is explicitly set.

    </member>
    <member name="M:SharpGit.Plumbing.GitBranch.RecordAsHeadBranch(SharpGit.GitClientArgs)">
      Marks this branch as the currently checked out HEAD branch
    </member>
    <member name="P:SharpGit.Plumbing.GitCommit.AncestorsAndSelf">
      Get an enumerator over this nodes ancestors, starting by this node itself
    </member>
    <member name="P:SharpGit.Plumbing.GitCommit.Ancestors">
      Get an enumerator over this nodes ancestors, starting by the parent of this commit
    </member>
    <member name="P:SharpGit.Plumbing.GitCommit.Ancestor">
      Get the first ancestor/first parent of this commit
    </member>
    <member name="P:SharpGit.GitException.Error">
      Gets the raw subversion error code
    </member>
    <member name="F:SharpGit.Plumbing.GitObjectKind.DeltaOffset">
      GIT_OBJ_OFS_DELTA
    </member>
    <member name="F:SharpGit.Plumbing.GitObjectKind.Ext5">
      Reserved
    </member>
    <member name="F:SharpGit.Plumbing.GitObjectKind.Ext0">
      Reserved
    </member>
    <member name="F:SharpGit.Plumbing.GitObjectKind.Bad">
      Object is invalid
    </member>
    <member name="F:SharpGit.Plumbing.GitObjectKind.Any">
      Object can be any of the following
    </member>
    <member name="P:SharpGit.Plumbing.GitIndexEntry.Id">
      Id of blob
    </member>
    <member name="T:SharpGit.Plumbing.GitIndexStage">
      Disambiguates the different versions of an index entry during a merge.
      <threadsafety static="true" instance="false" />
    </member>
    <member name="F:SharpGit.Plumbing.GitIndexStage.Theirs">
      Version of the entry as it is in the commit being merged.
    </member>
    <member name="F:SharpGit.Plumbing.GitIndexStage.Ours">
      Version of the entry as it is in the commit of the Head.
    </member>
    <member name="F:SharpGit.Plumbing.GitIndexStage.Ancestor">
      Version of the entry as it was in the common base merge commit.
    </member>
    <member name="F:SharpGit.Plumbing.GitIndexStage.Normal">
      The standard fully merged state for an index entry.
    </member>
    <member name="P:SharpGit.GitStatusArgs.GenerateVersionedDirs">
      Generates reports for versioned directories
    </member>
    <member name="P:SharpGit.Plumbing.GitRemote.DefaultBranch">
      When connected: Provides the default branch
    </member>
    <member name="M:SharpGit.Plumbing.GitRepository.CleanupState(SharpGit.GitArgs)">
      Remove all the metadata associated with an ongoing command like merge, revert, cherry-pick, etc.
    </member>
    <member name="M:SharpGit.Plumbing.GitRepository.CleanupState">
      Remove all the metadata associated with an ongoing command like merge, revert, cherry-pick, etc.
    </member>
    <member name="M:SharpGit.Plumbing.GitRepository.Open(System.String)">
      Opens the repository at REPOSITORYPATH
    </member>
    <member name="M:SharpGit.Plumbing.GitRepository.Locate(System.String)">
      Opens the repository containing PATH
    </member>
    <member name="M:SharpGit.Plumbing.GitRepository.#ctor(System.String)">
      Creates an unopened repository and then calls Open(REPOSITORYPATH)
    </member>
    <member name="M:SharpGit.Plumbing.GitRepository.#ctor">
      Creates an unopened repository
    </member>
    <member name="P:SharpGit.GitClient.SharpGitVersion">
      Gets the SharpGit version
    </member>
    <member name="P:SharpGit.GitClient.Version">
      Gets the libgit2 version
    </member>
    <member name="M:SharpGit.GitClient.Add(System.String,SharpGit.GitStageArgs)">
      Alias for .Stage()
    </member>
    <member name="M:SharpGit.GitClient.Add(System.String)">
      Alias for .Stage()
    </member>
    <member name="T:SharpGit.GitClient">
      Git client instance; main entrance to the SharpGit Client api
      <threadsafety static="true" instance="false" />
    </member>
    <member name="P:SharpGit.GitSignature.EmailAddress">
      The email address. When using for commit preparation NULL represents the configured value
    </member>
    <member name="P:SharpGit.GitSignature.Name">
      The user name. When using for commit preparation NULL represents the configured value
    </member>
    <member name="P:SharpGit.GitSignature.When">
      When the signature was added (as/auto-converted as GMT DateTime)
    </member>
  </members>
</doc>