text:
//package org.jasig.cas.web.init;

//import java.io.IOException;

//import javax.servlet.ServletConfig;
//import javax.servlet.ServletContext;
//import javax.servlet.ServletException;
//import javax.servlet.ServletRequest;
//import javax.servlet.ServletResponse;
//import javax.servlet.http.HttpServlet;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.context.ApplicationContextException;
//import org.springframework.web.servlet.DispatcherServlet;

/**
 * This servlet wraps the Spring DispatchServlet, catching any exceptions it
 * throws on init() to guarantee that servlet initialization succeeds. This
 * allows our application context to succeed in initializing so that we can
 * display a friendly "CAS is not available" page to the deployer (an
 * appropriate use of the page in development) or to the end user (an
 * appropriate use of the page in production). The error page associated with
 * this deployment failure is configured in the web.xml via the standard error
 * handling mechanism.
 *

 * If the underlying Spring DispatcherServlet failed to init(), this
 * SafeDispatcherServlet will throw an
 * org.springframework.context.ApplicationContextException on
 * service().
 *

 * The exception thrown by the underlying Spring DispatcherServlet init() and
 * caught in the SafeDispatcherServlet init() is exposed as a Servlet Context
 * attribute under the key "exceptionCaughtByServlet".
 *
 * @author Andrew Petro
 * @version $Revision$ $Date$
 * @see DispatcherServlet
 */
//public  class SafeDispatcherServlet : HttpServlet {

//    /** Unique Id for serialization. */
//    private static  long serialVersionUID = 1L;

//    /** Key under which we will store the exception in the ServletContext. */
//    public static  string CAUGHT_THROWABLE_KEY = "exceptionCaughtByServlet";

//    /** Instance of Commons Logging. */
//    private static  Logger log = LoggerFactory.getLogger(SafeDispatcherServlet.class);

//    /** The actual DispatcherServlet to which we will delegate to. */
//    private DispatcherServlet delegate = new DispatcherServlet();

//    /** bool to determine if the application deployed successfully. */
//    private bool initSuccess = true;

//    public void init( ServletConfig config) {
//        try {
//            this.delegate.init(config);

//        } catch ( Exception t) {
//            // let the service method know initialization failed.
//            this.initSuccess = false;

//            /*
//             * no matter what went wrong, our role is to capture this error and
//             * prevent it from blocking initialization of the servlet. logging
//             * overkill so that our deployer will find a record of this problem
//             * even if unfamiliar with Commons Logging and properly configuring
//             * it.
//             */

//             string message = "SafeDispatcherServlet: \n"
//                + "The Spring DispatcherServlet we wrap threw on init.\n"
//                + "But for our having caught this error, the servlet would not have initialized.";

//            // log it via Commons Logging
//            log.error(message, t);

//            // log it to System.err
//            System.err.println(message);
//            t.printStackTrace();

//            // log it to the ServletContext
//            ServletContext context = config.getServletContext();
//            context.log(message, t);

//            /*
//             * record the error so that the application has access to later
//             * display a proper error message based on the exception.
//             */
//            context.setAttribute(CAUGHT_THROWABLE_KEY, t);

//        }
//    }

//    /**
//     * @throws ApplicationContextException if the DispatcherServlet does not
//     * initialize properly, but the servlet attempts to process a request.
//     */
//    public void service( ServletRequest req,  ServletResponse resp)
//        throws ServletException, IOException {
//        /*
//         * Since our container calls only this method and not any of the other
//         * HttpServlet runtime methods, such as doDelete(), etc., delegating
//         * this method is sufficient to delegate all of the methods in the
//         * HttpServlet API.
//         */
//        if (this.initSuccess) {
//            this.delegate.service(req, resp);
//        } else {
//            throw new ApplicationContextException(
//                "Unable to initialize application context.");
//        }
//    }
//}

using System;
using System.Web;

namespace NCAS.jasig.web.init
{
    ///
    /// ÔÚjavaÖРʹÓÃhttpServlet , ÔÚC# ÖÐʹÓà IhttpHandler
    ///
    public class SafeDispatcherServlet : IHttpHandler
    {

        /** Unique Id for serialization. */
        private static long serialVersionUID = 1L;

        /** Key under which we will store the exception in the ServletContext. */
        public static string CAUGHT_THROWABLE_KEY = "exceptionCaughtByServlet";

        /** Instance of Commons Logging. */
        //private static  Logger log = LoggerFactory.getLogger(SafeDispatcherServlet.class);

        ///** The actual DispatcherServlet to which we will delegate to. */
        //private DispatcherServlet delegate = new DispatcherServlet();

        /** bool to determine if the application deployed successfully. */
        private bool initSuccess = true;

        //public void init( ServletConfig config) {
        //    try {
        //        this.delegate.init(config);

        //    } catch ( Exception t) {
        //        // let the service method know initialization failed.
        //        this.initSuccess = false;

        //        /*
        //         * no matter what went wrong, our role is to capture this error and
        //         * prevent it from blocking initialization of the servlet. logging
        //         * overkill so that our deployer will find a record of this problem
        //         * even if unfamiliar with Commons Logging and properly configuring
        //         * it.
        //         */

        //         string message = "SafeDispatcherServlet: \n"
        //            + "The Spring DispatcherServlet we wrap threw on init.\n"
        //            + "But for our having caught this error, the servlet would not have initialized.";

        //        // log it via Commons Logging
        //        log.error(message, t);

        //        // log it to System.err
        //        System.err.println(message);
        //        t.printStackTrace();

        //        // log it to the ServletContext
        //        ServletContext context = config.getServletContext();
        //        context.log(message, t);

        //        /*
        //         * record the error so that the application has access to later
        //         * display a proper error message based on the exception.
        //         */
        //        context.setAttribute(CAUGHT_THROWABLE_KEY, t);

        //    }
        //}

        /**
     * @throws ApplicationContextException if the DispatcherServlet does not
     * initialize properly, but the servlet attempts to process a request.
     */
        public void service(HttpRequest req, HttpResponse resp)
        {
            /*
         * Since our container calls only this method and not any of the other
         * HttpServlet runtime methods, such as doDelete(), etc., delegating
         * this method is sufficient to delegate all of the methods in the
         * HttpServlet API.
         */
            //if (this.initSuccess) {
            //    this.delegate.service(req, resp);
            //} else {
            //    throw new ApplicationContextException(
            //        "Unable to initialize application context.");
            //}
        }
        public void ProcessRequest(HttpContext context)
        {
            //throw new NotImplementedException();

            this.service(context.Request, context.Response);
        }

        public bool IsReusable { get; private set; }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Int. J. Syst. Evol. Microbiol. 56(2): 485 (2005)

#### Original name
Neosartorya coreana S.B. Hong, Frisvad & Samson

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package com.aerospike.benchmarks;

import java.util.Map;
import java.util.Random;

import com.aerospike.client.AerospikeClient;
import com.aerospike.client.AerospikeException;
import com.aerospike.client.Bin;
import com.aerospike.client.Key;
import com.aerospike.client.Record;
import com.aerospike.client.ResultCode;
import com.aerospike.client.policy.GenerationPolicy;
import com.aerospike.client.policy.WritePolicy;
import com.aerospike.client.util.Util;

/**
 * Random Read/Write workload task.
 */
public abstract class RWTask implements Runnable {

	final AerospikeClient client;
	final Arguments args;
	final CounterStore counters;
	final Random random;
	final WritePolicy writePolicyGeneration;
	ExpectedValue[] expectedValues;
	final double readPct;
	final double readMultiBinPct;
	final double writeMultiBinPct;
	final int keyStart;
	final int keyCount;

	public RWTask(AerospikeClient client, Arguments args, CounterStore counters, int keyStart, int keyCount) {
		this.client = client;
		this.args = args;
		this.counters = counters;
		this.keyStart = keyStart;
		this.keyCount = keyCount;

		// Use default constructor which uses a different seed for each invocation.
		// Do not use System.currentTimeMillis() for a seed because it is often
		// the same across concurrent threads, thus causing hot keys.
		random = new Random();

		writePolicyGeneration = new WritePolicy();
		writePolicyGeneration.timeout = args.writePolicy.timeout;
		writePolicyGeneration.maxRetries = args.writePolicy.maxRetries;
		writePolicyGeneration.sleepBetweenRetries = args.writePolicy.sleepBetweenRetries;
		writePolicyGeneration.generationPolicy = GenerationPolicy.EXPECT_GEN_EQUAL;
		writePolicyGeneration.generation = 0;

		readPct = (double)args.readPct / 100.0;
		readMultiBinPct = (double)args.readMultiBinPct / 100.0;
		writeMultiBinPct = (double)args.writeMultiBinPct / 100.0;
	}

	public void run() {
		// Load data if we're going to be validating.
		if (args.validate) {
			setupValidation();
		}

		while (true) {
			// Get random key
			int key = random.nextInt(keyCount);

			try {
				switch (args.workload) {
				case READ_UPDATE:
					readUpdate(key);
					break;

				case READ_MODIFY_UPDATE:
					readModifyUpdate(key);
					break;

				case READ_MODIFY_INCREMENT:
					readModifyIncrement(key);
					break;

				case READ_MODIFY_DECREMENT:
					readModifyDecrement(key);
					break;
				}
			}
			catch (Exception e) {
				if (args.debug) {
					e.printStackTrace();
				}
				else {
					System.out.println("Exception - " + e.toString());
				}
			}

			// Throttle throughput
			if (args.throughput > 0) {
				int transactions = counters.write.count.get() + counters.read.count.get();

				if (transactions > args.throughput) {
					long millis = counters.periodBegin.get() + 1000L - System.currentTimeMillis();

					if (millis > 0) {
						Util.sleep(millis);
					}
				}
			}
		}
	}

	private void readUpdate(int key) {
		if (random.nextDouble() < this.readPct) {
			boolean isMultiBin = random.nextDouble() < readMultiBinPct;
			doRead(key, isMultiBin);
		}
		else {
			boolean isMultiBin = random.nextDouble() < writeMultiBinPct;
			doWrite(key, isMultiBin);
		}
	}

	private void readModifyUpdate(int key) {
		// Read all bins.
		doRead(key, true);
		// Write one bin.
		doWrite(key, false);
	}

	private void readModifyIncrement(int key) {
		// Read all bins.
		doRead(key, true);
		// Increment one bin.
		doIncrement(key, 1);
	}

	private void readModifyDecrement(int key) {
		// Read all bins.
		doRead(key, true);
		// Decrement one bin.
		doIncrement(key, -1);
	}

	/**
	 * Read existing values from the database, save them away in our validation arrays.
	 */
	private void setupValidation() {
		expectedValues = new ExpectedValue[keyCount];

		// Load starting values
		for (int i = 0; i < keyCount; i++) {
			Bin[] bins = null;
			int generation = 0;

			try {
				Key key = new Key(args.namespace, args.setName, Utils.genKey(keyStart + i, args.keySize));
				Record record = client.get(args.readPolicy, key);

				if (record != null && record.bins != null) {
					Map<String,Object> map = record.bins;
					int max = map.size();
					bins = new Bin[max];

					for (int j = 0; j < max; j++) {
						String name = Integer.toString(j);
						bins[j] = new Bin(name, map.get(name));
					}
					generation = record.generation;
				}
				counters.read.count.getAndIncrement();
			}
			catch (Exception e) {
				readFailure(e);
			}
			expectedValues[i] = new ExpectedValue(bins, generation);
		}

		// Tell the global counter that this task is finished loading
		this.counters.loadValuesFinishedTasks.incrementAndGet();

		// Wait for all tasks to be finished loading
		while (! this.counters.loadValuesFinished.get()) {
			try {
				Thread.sleep(10);
			} catch (Exception e) {
				System.out.println("Can't sleep while waiting for all values to load");
			}
		}
	}

	/**
	 * Write the key at the given index
	 */
	protected void doWrite(int keyIdx, boolean multiBin) {
		String key = Utils.genKey(keyStart + keyIdx, args.keySize);
		int binCount = multiBin ? args.nBins : 1;
		Bin[] bins;

		if (args.validate) {
			bins = Utils.genBins(random, binCount, args.objectSpec, this.expectedValues[keyIdx].generation+1);
		} else {
			bins = Utils.genBins(random, binCount, args.objectSpec, 0);
		}

		try {
			put(new Key(args.namespace, args.setName, key), bins);

			if (args.validate) {
				this.expectedValues[keyIdx].write(bins);
			}
		}
		catch (AerospikeException ae) {
			writeFailure(ae);
		}
		catch (Exception e) {
			writeFailure(e);
		}
	}

	/**
	 * Increment (or decrement, if incrValue is negative) the key at the given index.
	 */
	protected void doIncrement(int keyIdx, int incrValue) {
		// get key
		String key = Utils.genKey(keyStart + keyIdx, args.keySize);

		// set up bin for increment
		Bin[] bins = new Bin[] {new Bin("", incrValue)};

		try {
			add(new Key(args.namespace, args.setName, key), bins);

			if (args.validate) {
				this.expectedValues[keyIdx].add(bins, incrValue);
			}
		}
		catch (AerospikeException ae) {
			writeFailure(ae);
		}
		catch (Exception e) {
			writeFailure(e);
		}
	}

	/**
	 * Read the key at the given index.
	 */
	protected void doRead(int keyIdx, boolean multiBin) {
		String key = Utils.genKey(keyStart + keyIdx, args.keySize);

		try {
			if (multiBin) {
				// Read all bins, maybe validate
				get(keyIdx, new Key(args.namespace, args.setName, key));
			}
			else {
				// Read one bin, maybe validate
				get(keyIdx, new Key(args.namespace, args.setName, key), Integer.toString(0));
			}
		}
		catch (AerospikeException ae) {
			readFailure(ae);
		}
		catch (Exception e) {
			readFailure(e);
		}
	}

	protected void validateRead(int keyIdx, Record record) {
		if (! this.expectedValues[keyIdx].validate(record)) {
			this.counters.valueMismatchCnt.incrementAndGet();
		}
	}

	protected void writeFailure(AerospikeException ae) {
		if (ae.getResultCode() == ResultCode.TIMEOUT) {
			counters.write.timeouts.getAndIncrement();
		}
		else {
			counters.write.errors.getAndIncrement();

			if (args.debug) {
				ae.printStackTrace();
			}
		}
	}

	protected void writeFailure(Exception e) {
		counters.write.errors.getAndIncrement();

		if (args.debug) {
			e.printStackTrace();
		}
	}

	protected void readFailure(AerospikeException ae) {
		if (ae.getResultCode() == ResultCode.TIMEOUT) {
			counters.read.timeouts.getAndIncrement();
		}
		else {
			counters.read.errors.getAndIncrement();

			if (args.debug) {
				ae.printStackTrace();
			}
		}
	}

	protected void readFailure(Exception e) {
		counters.read.errors.getAndIncrement();

		if (args.debug) {
			e.printStackTrace();
		}
	}

	protected abstract void put(Key key, Bin[] bins) throws AerospikeException;
	protected abstract void add(Key key, Bin[] bins) throws AerospikeException;
	protected abstract void get(int keyIdx, Key key, String binName) throws AerospikeException;
	protected abstract void get(int keyIdx, Key key) throws AerospikeException;
}


text:
/****************************************************************************************/
/*                                                                                */
/*                                       Pegasus                                        */
/*                                                                                */
/****************************************************************************************/

//! \file	MultiCopyOperator.h
//! \author	Kleber Garcia
//! \date	May 21th 2017
//! \brief	MultiCopyOperator

#ifndef PEGASUS_MULTI_COPY_OPERATOR_H
#define PEGASUS_MULTI_COPY_OPERATOR_H

#include "Pegasus/Mesh/MeshOperator.h"
#include "Pegasus/Math/Vector.h"
#include "Pegasus/Math/Matrix.h"

namespace Pegasus
{

namespace Mesh
{

//! Mesh cube generator. Generates a cube
class MultiCopyOperator : public MeshOperator
{
    DECLARE_MESH_OPERATOR_NODE(MultiCopyOperator)

    //! Property declarations
    BEGIN_DECLARE_PROPERTIES(MultiCopyOperator, MeshOperator)
        DECLARE_PROPERTY(int, MultiCopyFactor, 1)
        DECLARE_PROPERTY(Math::Vec3, TranslationOffset, Math::Vec3(0.0f, 0.0f, 0.0f))
        DECLARE_PROPERTY(Math::Vec3, ScaleOffset, Math::Vec3(1.0f, 1.0f, 1.0f))
        DECLARE_PROPERTY(Math::Vec4, QuaternionRotOffset, Math::Vec4(0.0f, 1.0f, 0.0f, 0.0f))
    END_DECLARE_PROPERTIES()

public:

    //! constructor
    MultiCopyOperator(Pegasus::Alloc::IAllocator* nodeAllocator,
                  Pegasus::Alloc::IAllocator* nodeDataAllocator);

    virtual ~MultiCopyOperator();

    virtual unsigned int GetMinNumInputNodes() const override { return 1; }

    virtual unsigned int GetMaxNumInputNodes() const override { return 1; }

protected:

    //! Generate the content of the data associated with the texture generator
    virtual void GenerateData();

};
}

}

#endif//PEGASUS_CUBE_GENERATOR_H


text:
using System.Web.Mvc;

namespace NewEmployeeBuddy.Web.Areas.Account
{
    public class AccountAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Account";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Account_default",
                "{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


text:
Just a few code snippets I have in my Xcode arsenal. In [dotfiles](http://dotfiles.org/) fashion, I thought it'd be cool to put these out in the ether.

## Using Snippets

In Xcode 4, open a workspace and toggle the right sidebar to be visible. On the bottom, there is a panel with four icons in the header. Click on the `{ }` icon to open the Code Snippets Library.

Now copy-paste the code from one of these snippets, highlight the code block you just pasted and drag it to the Code Snippet panel. Make sure to match the suggested platform, language, and completion scope. The completion shortcut corresponds to the filename of the code snippet.


text:
from __future__ import unicode_literals
import json

# Django
from django.conf import settings as _settings

def settings(request):
    return {
        'DEBUG': _settings.DEBUG,
    }


text:
ActiveRecord::Schema.define(version: 20151212175007) do

  create_table "songs", force: :cascade do |t|
    t.string   "nid",        null: false
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "authentication_token"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["authentication_token"], name: "index_users_on_authentication_token", unique: true
  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Guitar32.Database;
using TechByte;

namespace TechByte.Configs
{
    public class DatabaseCredentialsFile
    {
        public static DatabaseCredentials databaseCredentials;

        /// <summary>
        /// Create a new database credentials and load it to current instance
        /// </summary>
        /// <param name="creds">The new DatabaseCredentials object to be created and loaded</param>
        /// <returns>If creation and loading is success</returns>
        public static bool CreateNew(DatabaseCredentials creds) {
            if (File.Exists(TechByte.Values.FileSystem.DatabaseCredentialsFile)) {
                File.Delete(TechByte.Values.FileSystem.DatabaseCredentialsFile);
            }
            bool isSuccess = creds.Dump(TechByte.Values.FileSystem.DatabaseCredentialsFile);
            if (isSuccess) {
                isSuccess = Load();
            }
            return isSuccess;
        }

        public static bool Exists() {
            // Check if Database credentials file exists
            bool dbCredentialsExist = true;
            if (!File.Exists(TechByte.Values.FileSystem.DatabaseCredentialsFile)) {
                dbCredentialsExist = false;
            }
            else {
                // Verify validity of file
                Console.WriteLine(TechByte.Values.FileSystem.DatabaseCredentialsFile);
                FileStream fs = new FileStream(TechByte.Values.FileSystem.DatabaseCredentialsFile, FileMode.OpenOrCreate);
                BinaryReader binReader = new BinaryReader(fs);
                byte[] contents = new byte[fs.Length];
                binReader.Read(contents, 0, (int)fs.Length);
                binReader.Close();
                fs.Close();
                try {
                    DatabaseCredentials.Deserialize(contents);
                }
                catch (InvalidCredentialsFileException exception) {
                    File.Delete(TechByte.Values.FileSystem.DatabaseCredentialsFile);
                    dbCredentialsExist = false;
                }
            }
            return dbCredentialsExist;
        }

        public static bool Load() {
            if (Exists()) {
                String path = TechByte.Values.FileSystem.DatabaseCredentialsFile;
                databaseCredentials = new DatabaseCredentials(path);
                // Set `dbtechbyte` as default database
                databaseCredentials.setDatabase("dbtechbyte");
                return true;
            }
            else {
                return false;
            }
        }

    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace IppDotNetSdkQuickBooksApiV3SampleWebFormsApp {

    public partial class CustomerList {

        /// <summary>
        /// customersView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ListView customersView;

        /// <summary>
        /// A1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlAnchor A1;

        /// <summary>
        /// A4 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlAnchor A4;

        /// <summary>
        /// A2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlAnchor A2;
    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * ``thrashview'' is a program that reads a binary stream of addresses
 * from stdin and displays the pattern graphically in a window.
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <fstream>
#include <getopt.h>

#define GET_DISPLAY_FD(display_) ConnectionNumber(display_)

static bool opt_working_set = false;
static bool opt_fixed = false;

static Display *display;
static Window window;
static GC gc;
static XColor colors[256];
const unsigned int cellsize = 4;
static unsigned int width = 64 * cellsize;
static unsigned int height = 64 * cellsize;

#define PAGESIZE 4096
#define MAXPAGES 4096  // should hold 16MB worth of code
static unsigned int minpage = static_cast<unsigned int>(-1);
static unsigned int maxpage = 0;
static unsigned char pages[MAXPAGES];

/**
 * Create a simple window and the X objects we'll need to talk with it.
 */
static int
init()
{
    display = XOpenDisplay(0);
    if (! display)
        return 0;

    window =
        XCreateSimpleWindow(display,
                            RootWindow(display, 0),
                            1, 1, width, height,
                            0,
                            BlackPixel(display, 0),
                            BlackPixel(display, 0));

    if (! window)
        return 0;

    gc = XCreateGC(display, window, 0, 0);
    if (! gc)
        return 0;

    // Set up a grayscale
    const unsigned int ncolors = sizeof colors / sizeof colors[0];
    const unsigned short step = 65536 / ncolors;
    unsigned short brightness = 0;

    XColor *color = colors;
    XColor *limit = colors + ncolors;
    for (; color < limit; ++color, brightness += step) {
        color->red   = brightness;
        color->green = brightness;
        color->blue  = brightness;
        XAllocColor(display, DefaultColormap(display, 0), color);
    }

    // We want exposes and resizes.
    XSelectInput(display, window, ExposureMask | StructureNotifyMask);

    XMapWindow(display, window);
    XFlush(display);

    return 1;
}

/**
 * Age pages that haven't been recently touched.
 */
static void
decay()
{
    int ws_immediate = 0, ws_longterm = 0;

    unsigned char *page = pages;
    unsigned char *limit = pages + (maxpage - minpage) + 1;
    for (; page < limit; ++page) {
        if (opt_working_set) {
            if (*page == 255)
                ++ws_immediate;
            if (*page)
                ++ws_longterm;
        }

        if (*page) {
            *page /= 8;
            *page *= 7;
        }
    }

    if (opt_working_set) {
        dec(cout);
        cout << "immediate: " << ws_immediate << " pages, ";
        cout << "longterm: " << ws_longterm << " pages, ";
        cout << "mapped: " << ((maxpage - minpage) + 1) << " pages";
        cout << endl;
    }
}

/**
 * Blast the state of our pages to the screen.
 */
static int
handle_expose(const XExposeEvent& event)
{
    //printf("handle_expose(%d, %d, %d, %d)\n", event.x, event.y, event.width, event.height);

    int i = event.x / cellsize;
    int imost = i + event.width / cellsize + 1;

    int j = event.y / cellsize;
    int jmost = j + event.height / cellsize + 1;

    unsigned char *last_cell = pages + maxpage - minpage;
    unsigned char *row = pages + j;
    for (int y = j * cellsize, ymost = jmost * cellsize;
         y < ymost;
         y += cellsize, row += width / cellsize) {
        unsigned char *cell = row + i;
        for (int x = i * cellsize, xmost = imost * cellsize;
             x < xmost;
             x += cellsize, ++cell) {
            unsigned int pixel = (cell <= last_cell) ? colors[*cell].pixel : colors[0].pixel;
            XSetForeground(display, gc, pixel);
            XFillRectangle(display, window, gc, x, y, cellsize - 1, cellsize - 1);
        }
    }

    XFlush(display);

    return 1;
}

/**
 * Invalidate the entire window.
 */
static void
invalidate_window()
{
    XExposeEvent event;
    event.x = event.y = 0;
    event.width = width;
    event.height = height;

    handle_expose(event);
}

/**
 * Handle a configure event.
 */
static int
handle_configure(const XConfigureEvent& event)
{
    //printf("handle_resize(%d, %d)\n", event.width, event.height);
    width = event.width - event.width % cellsize;
    height = event.height;
    return 1;
}

/**
 * Filter to select any message.
 */
static Bool
any_event(Display *display, XEvent *event, XPointer arg)
{
    return 1;
}

/**
 * An X event occurred. Process it and flush the queue.
 */
static int
handle_xevents()
{
    int ok;

    XEvent event;
    XNextEvent(display, &event);
    do {
        switch (event.type) {
        case Expose:
            ok = handle_expose(reinterpret_cast<const XExposeEvent&>(event));
            break;

        case ConfigureNotify:
            ok = handle_configure(reinterpret_cast<const XConfigureEvent&>(event));
            break;

        default:
            ok = 1;
        }
    } while (ok && XCheckIfEvent(display, &event, any_event, 0));

    return ok;
}

/**
 * Read address data from stdin.
 */
static int
read_addrs()
{
    unsigned int buf[1024];
    ssize_t count;
    while ((count = read(0, buf, sizeof buf)) > 0) {
        if (count % sizeof(unsigned int))
            cerr << "truncating unaligned read" << endl;

        count /= sizeof buf[0];

        unsigned int *addr = reinterpret_cast<unsigned int *>(buf);
        unsigned int *limit = addr + count;

        for (; addr < limit; ++addr) {
            // map the address to a page
            unsigned int page = *addr / PAGESIZE;

            // XXX Don't let stray addresses bring us down. Should
            // really fix this by knowing what the ranges of addresses
            // we ought to expect are (e.g., by reading the symtab)
            if (maxpage && page > maxpage && page - maxpage > MAXPAGES)
                continue;

            if (! opt_fixed) {
                // Potentially adjust minpage and maxpage to
                // accomodate an out-of-bounds address.
                if (page < minpage) {
                    if (maxpage) {
                        // everything needs to shift.
                        unsigned int shift = minpage - page;
                        memmove(pages + shift, pages, maxpage - minpage);
                        memset(pages, 0, shift);
                    }
                    minpage = page;
                }

                if (page > maxpage)
                    maxpage = page;
            }

            page -= minpage;
            pages[page] = 255;
        }
    }

    if (count < 0 && errno != EWOULDBLOCK) {
        perror("read");
        return 0;
    }

    return 1;
}

/**
 * Run the program
 */
static void
run()
{
    // We want non-blocking I/O on stdin so we can select on it.
    fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);

    // The last time we refreshed the window.
    struct timeval last;
    gettimeofday(&last, 0);

    int ok;

    do {
        // Select on stdin and the connection to the X server.
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(STDIN_FILENO, &fds);
        FD_SET(GET_DISPLAY_FD(display), &fds);

        struct timeval tv;
        tv.tv_sec  = 1;
        tv.tv_usec = 0;

        ok = select(GET_DISPLAY_FD(display) + 1, &fds, 0, 0, &tv);
        if (ok < 0)
            break;

        if (maxpage) {
            // See if we've waited long enough to refresh the window.
            struct timeval now;
            gettimeofday(&now, 0);

            if (now.tv_sec != last.tv_sec) {
                // At least a second has gone by. Decay and refresh.
                last = now;
                decay();
                invalidate_window();
            }
            else if (now.tv_usec - last.tv_usec > 100000) {
                // At least 100msec have gone by. Refresh.
                last.tv_usec = now.tv_usec;
                invalidate_window();
            }
        }

        // Now check for X events and input.
        ok = 1;

        if (FD_ISSET(GET_DISPLAY_FD(display), &fds))
            ok = handle_xevents();

        if (FD_ISSET(STDIN_FILENO, &fds))
            ok = read_addrs();
    } while (ok);
}

/**
 * Tear down our window and stuff.
 */
static void
finish()
{
    if (window) {
        XUnmapWindow(display, window);
        XDestroyWindow(display, window);
    }

    if (display)
        XCloseDisplay(display);
}

static struct option opts[] = {
    { "working-set", no_argument,       0, 'w' },
    { "min",         required_argument, 0, 'm' },
    { "size",        required_argument, 0, 's' },
    { "max",         required_argument, 0, 'x' },
    { 0,             0,                 0, 0   }
};

static void
usage()
{
    cerr << "thrashview [--working-set] [--min=<min>] [--max=<max>] [--size=<size>]" << endl;
}

/**
 * Program starts here.
 */
int
main(int argc, char *argv[])
{
    int size = 0;

    while (1) {
        int option_index = 0;
        int c = getopt_long(argc, argv, "wm:x:s:", opts, &option_index);

        if (c < 0)
            break;

        switch (c) {
        case 'w':
            opt_working_set = true;
            break;

        case 'm':
            minpage = strtol(optarg, 0, 0) / PAGESIZE;
            opt_fixed = true;
            break;

        case 's':
            size = strtol(optarg, 0, 0) / PAGESIZE;
            break;

        case 'x':
            maxpage = strtol(optarg, 0, 0) / PAGESIZE;
            opt_fixed = true;
            break;

        default:
            usage();
            return 1;
        }
    }

    if (minpage && !maxpage) {
        if (!size) {
            cerr << argv[0] << ": minpage specified without maxpage or size" << endl;
            return 1;
        }

        maxpage = minpage + size;
    }

    if (opt_fixed && minpage > maxpage) {
        cerr << argv[0] << ": invalid page range" << endl;
        return 1;
    }

    if (init())
        run();

    finish();

    return 0;
}


text:
package org.apache.slide.event;

import org.apache.slide.common.SlideToken;
import org.apache.slide.common.Namespace;
import org.apache.slide.structure.ObjectNode;

import java.util.EventListener;
import java.util.EventObject;

/**
 * Structure event class
 *
 * @version $Revision: 1.2 $
 */
public class StructureEvent extends EventObject {
    public final static Retrieve RETRIEVE = new Retrieve();
    public final static Store STORE = new Store();
    public final static Create CREATE = new Create();
    public final static Remove REMOVE = new Remove();
    public final static CreateLink CREATE_LINK = new CreateLink();
    public final static AddBinding ADD_BINDING = new AddBinding();
    public final static RemoveBinding REMOVE_BINDING = new RemoveBinding();

    public final static String GROUP = "structure";
    public final static AbstractEventMethod[] methods = new AbstractEventMethod[] { RETRIEVE, STORE, CREATE, REMOVE, CREATE_LINK, ADD_BINDING, REMOVE_BINDING };

    private SlideToken token;
    private ObjectNode objectNode = null;
    private String uri = null;
    private Namespace namespace;

    public StructureEvent(Object source, SlideToken token, Namespace namespace, String uri) {
        super(source);
        this.uri = uri;
        this.token = token;
        this.namespace = namespace;
    }

    public StructureEvent(Object source, SlideToken token, Namespace namespace, ObjectNode objectNode) {
        super(source);
        this.token = token;
        this.objectNode = objectNode;
        this.namespace = namespace;
    }

    public StructureEvent(Object source, SlideToken token, ObjectNode objectNode, String uri) {
        super(source);
        this.token = token;
        this.objectNode = objectNode;
        this.uri = uri;
    }

    public String toString() {
        StringBuffer buffer = new StringBuffer(256);
        buffer.append(getClass().getName()).append("[uri=").append(uri);
        buffer.append(", objectNode=").append(objectNode);
        buffer.append("]");
        return buffer.toString();
    }

    public SlideToken getToken() {
        return token;
    }

    public ObjectNode getObjectNode() {
        return objectNode;
    }

    public String getUri() {
        return uri;
    }

    public Namespace getNamespace() {
        return namespace;
    }

    public final static class Create extends VetoableEventMethod {
        public Create() {
            super(GROUP, "create");
        }

        public void fireVetaoableEvent(EventListener listener, EventObject event) throws VetoException  {
            if ( listener instanceof StructureListener ) ((StructureListener)listener).create((StructureEvent)event);
        }
    }

    public final static class CreateLink extends VetoableEventMethod {
        public CreateLink() {
            super(GROUP, "create-link");
        }

        public void fireVetaoableEvent(EventListener listener, EventObject event) throws VetoException  {
            if ( listener instanceof StructureListener ) ((StructureListener)listener).createLink((StructureEvent)event);
        }
    }

    public final static class Remove extends VetoableEventMethod {
        public Remove() {
            super(GROUP, "remove");
        }

        public void fireVetaoableEvent(EventListener listener, EventObject event) throws VetoException  {
            if ( listener instanceof StructureListener ) ((StructureListener)listener).remove((StructureEvent)event);
        }
    }

    public final static class AddBinding extends VetoableEventMethod {
        public AddBinding() {
            super(GROUP, "add-binding");
        }

        public void fireVetaoableEvent(EventListener listener, EventObject event) throws VetoException  {
            if ( listener instanceof StructureListener ) ((StructureListener)listener).addBinding((StructureEvent)event);
        }
    }

    public final static class RemoveBinding extends VetoableEventMethod {
        public RemoveBinding() {
            super(GROUP, "remove-binding");
        }

        public void fireVetaoableEvent(EventListener listener, EventObject event) throws VetoException  {
            if ( listener instanceof StructureListener ) ((StructureListener)listener).removeBinding((StructureEvent)event);
        }
    }

    public final static class Store extends VetoableEventMethod {
        public Store() {
            super(GROUP, "store");
        }

        public void fireVetaoableEvent(EventListener listener, EventObject event) throws VetoException  {
            if ( listener instanceof StructureListener ) ((StructureListener)listener).store((StructureEvent)event);
        }
    }

    public final static class Retrieve extends VetoableEventMethod {
        public Retrieve() {
            super(GROUP, "retrieve");
        }

        public void fireVetaoableEvent(EventListener listener, EventObject event) throws VetoException  {
            if ( listener instanceof StructureListener ) ((StructureListener)listener).retrieve((StructureEvent)event);
        }
    }
}


text:
// source:

package nl.esciencecenter.ptk.web.content;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import nl.esciencecenter.ptk.io.FSPath;
import nl.esciencecenter.ptk.web.PutMonitor;

import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.content.AbstractContentBody;

/**
 * File Body which uses FSNodes. <br>
 * Based on Apache FileBody. Example how to upload custom Object types. Since FSNode can be
 * sub-classed, any file type can be uploaded using this Content Body Type.
 */
public class FSNodeBody extends AbstractContentBody {

    private final FSPath fsNode;

    private long totalWritten = 0;

    private PutMonitor putMonitor = null;

    private int defaultChunkSize = 4096;

    public FSNodeBody(final FSPath node, final String mimeType, PutMonitor putMonitor) {
        super(mimeType);
        this.putMonitor = putMonitor;

        if (node == null) {
            throw new IllegalArgumentException("File may not be null");
        }

        this.fsNode = node;
    }

    public FSNodeBody(final FSPath node) {
        this(node, "application/octet-stream", null);
    }

    public FSNodeBody(final FSPath node, PutMonitor putMonitor) {
        this(node, "application/octet-stream", putMonitor);
    }

    public InputStream getInputStream() throws IOException {
        return fsNode.getFSInterface().createInputStream(fsNode);
    }

    @Override
    public void writeTo(final OutputStream out) throws IOException {
        if (out == null) {
            throw new IllegalArgumentException("Output stream may not be null");
        }

        InputStream in = fsNode.getFSInterface().createInputStream(fsNode);

        try {
            byte[] tmp = new byte[defaultChunkSize];

            int numRead = 0;

            while ((numRead = in.read(tmp)) >= 0) {
                out.write(tmp, 0, numRead);

                if (numRead == 0) {
                    // micro sleep: allow IO to happen when thread sleeps.
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                totalWritten += numRead;
                logPrintf("Total written=%d\n", totalWritten);

                if (putMonitor != null) {
                    putMonitor.bytesWritten(totalWritten);
                }
            }

            out.flush();

            if (putMonitor != null) {
                putMonitor.bytesWritten(totalWritten);
                putMonitor.putDone();
            }

            logPrintf("Done: Total written=%d\n", totalWritten);
        } finally {
            in.close();
        }
    }

    public String getTransferEncoding() {
        return MIME.ENC_BINARY;
    }

    public String getCharset() {
        return null;
    }

    public long getContentLength() {
        try {
            return this.fsNode.getFileSize();
        } catch (IOException e) {
            return 0;
        }
    }

    public String getFilename() {
        return this.fsNode.getBasename();
    }

    public long getProgress() {
        return totalWritten;
    }

    protected void logPrintf(String format, Object... args) {
        // Delegate to monitor:
    }

}


text:
FROM alpine:3.1

RUN echo "@edge http://nl.alpinelinux.org/alpine/edge/main" >> /etc/apk/repositories
RUN apk update
RUN apk add rsyslog curl "postgresql@edge>9.4"
RUN apk add bash vim
RUN mkdir -p /run/openrc && echo "" > /run/openrc/softlevel
RUN apk add openssh
RUN curl -o /usr/local/bin/gosu -sSL "https://github.com/tianon/gosu/releases/download/1.2/gosu-amd64"
RUN chmod +x /usr/local/bin/gosu

ENV LANG en_US.utf8
ENV PGDATA /var/lib/postgresql/data
VOLUME /var/lib/postgresql/data

COPY docker-entrypoint.sh /
RUN chmod a+x /docker-entrypoint.sh
ENTRYPOINT ["/docker-entrypoint.sh"]

EXPOSE 5432
CMD ["postgres"]


text:
MongoDB\Driver\BulkWrite::delete() with invalid options
--FILE--
<?php

require_once __DIR__ . '/../utils/basic.inc';

$bulk = new MongoDB\Driver\BulkWrite;

echo throws(function() use ($bulk) {
    $bulk->delete(['x' => 1], ['collation' => 1]);
}, 'MongoDB\Driver\Exception\InvalidArgumentException'), "\n\n";

echo throws(function() use ($bulk) {
    $bulk->delete(['x' => 1], ['hint' => 1]);
}, 'MongoDB\Driver\Exception\InvalidArgumentException'), "\n";

?>
===DONE===
<?php exit(0); ?>
--EXPECTF--
OK: Got MongoDB\Driver\Exception\InvalidArgumentException
Expected "collation" option to be array or object, int%S given

OK: Got MongoDB\Driver\Exception\InvalidArgumentException
Expected "hint" option to be string, array, or object, int%S given
===DONE===


text:
import {Map} from 'immutable';
import partial from 'lodash-es/partial';
import tap from 'lodash-es/tap';
import test from 'tape-catch';

import {
  accountMigrationComplete,
  accountMigrationError,
  accountMigrationNeeded,
  accountMigrationUndoPeriodExpired,
  dismissAccountMigration,
  identityLinked,
  identityUnlinked,
  startAccountMigration,
  userAuthenticated,
  userLoggedOut,
} from '../../../src/actions/user';
import {AccountMigrationState, LoginState} from '../../../src/enums';
import {
  AccountMigration,
  User,
  UserAccount,
  UserIdentityProvider,
} from '../../../src/records';
import reducer from '../../../src/reducers/user';
import {userCredential} from '../../helpers/factory';
import reducerTest from '../../helpers/reducerTest';
import {user as states} from '../../helpers/referenceStates';

const userCredentialIn = userCredential();

const loggedOutState = new User({
  loginState: LoginState.ANONYMOUS,
});

const loggedInState = new User({
  loginState: LoginState.AUTHENTICATED,
  account: new UserAccount({
    id: userCredentialIn.user.uid,
    displayName: userCredentialIn.user.displayName,
    avatarUrl: userCredentialIn.user.photoURL,
    identityProviders: new Map({
      'google.com': new UserIdentityProvider({
        accessToken: userCredentialIn.credential.idToken,
        avatarUrl: userCredentialIn.user.photoURL,
        displayName: userCredentialIn.user.displayName,
      }),
    }),
  }),
});

test(
  'userAuthenticated',
  reducerTest(
    reducer,
    states.initial,
    partial(userAuthenticated, userCredentialIn.user, [
      userCredentialIn.credential,
    ]),
    loggedInState,
  ),
);

test(
  'identityLinked',
  reducerTest(
    reducer,
    loggedInState,
    partial(
      identityLinked,
      {
        displayName: 'Popcode User',
        photoURL: null,
        providerData: [
          {
            displayName: 'Popcode User',
            photoURL: null,
            providerId: 'github.com',
          },
        ],
      },
      {providerId: 'github.com', accessToken: 'abc'},
    ),
    loggedInState.setIn(
      ['account', 'identityProviders', 'github.com'],
      new UserIdentityProvider({
        displayName: 'Popcode User',
        accessToken: 'abc',
      }),
    ),
  ),
);

test(
  'identityUnlinked',
  reducerTest(
    reducer,
    loggedInState.setIn(
      ['account', 'identityProviders', 'github.com'],
      new UserIdentityProvider({
        displayName: 'Popcode User',
        accessToken: 'abc',
      }),
    ),
    partial(identityUnlinked, 'github.com'),
    loggedInState,
  ),
);

tap(
  [
    {name: 'Popcode User', avatar_url: 'https://github.com/popcodeuser.jpg'},
    {
      providerData: [
        {
          photoURL: 'https://google.com/face.jpg',
          displayName: 'Google User',
          providerId: 'google.com',
        },
        {
          photoURL: 'https://github.com/face.jpg',
          displayName: 'GitHub User',
          providerId: 'github.com',
        },
      ],
    },
    {providerId: 'github.com', accessToken: 'abc123'},
  ],

  ([githubProfile, firebaseUser, credential]) => {
    const proposedState = loggedInState.set(
      'currentMigration',
      new AccountMigration({
        userAccountToMerge: new UserAccount({
          avatarUrl: 'https://github.com/popcodeuser.jpg',
          displayName: 'Popcode User',
          identityProviders: new Map({
            'github.com': new UserIdentityProvider({
              accessToken: 'abc123',
              avatarUrl: 'https://github.com/popcodeuser.jpg',
              displayName: 'Popcode User',
            }),
          }),
        }),
        firebaseCredential: credential,
      }),
    );

    const undoGracePeriodState = proposedState.setIn(
      ['currentMigration', 'state'],
      AccountMigrationState.UNDO_GRACE_PERIOD,
    );

    const inProgressState = undoGracePeriodState.setIn(
      ['currentMigration', 'state'],
      AccountMigrationState.IN_PROGRESS,
    );

    const completeState = undoGracePeriodState
      .setIn(['currentMigration', 'state'], AccountMigrationState.COMPLETE)
      .setIn(
        ['account', 'identityProviders', 'github.com'],
        new UserIdentityProvider({
          accessToken: credential.accessToken,
          avatarUrl: 'https://github.com/face.jpg',
          displayName: 'GitHub User',
        }),
      );

    const errorState = undoGracePeriodState.setIn(
      ['currentMigration', 'state'],
      AccountMigrationState.ERROR,
    );

    test(
      'accountMigrationNeeded',
      reducerTest(
        reducer,
        loggedInState,
        partial(accountMigrationNeeded, githubProfile, credential),
        proposedState,
      ),
    );

    test(
      'startAccountMigration',
      reducerTest(
        reducer,
        proposedState,
        startAccountMigration,
        undoGracePeriodState,
      ),
    );

    test(
      'dismissAccountMigration',
      reducerTest(
        reducer,
        proposedState,
        dismissAccountMigration,
        loggedInState,
      ),
    );

    test(
      'accountMigrationUndoPeriodExpired',
      reducerTest(
        reducer,
        undoGracePeriodState,
        accountMigrationUndoPeriodExpired,
        inProgressState,
      ),
    );

    test(
      'accountMigrationComplete',
      reducerTest(
        reducer,
        inProgressState,
        partial(accountMigrationComplete, firebaseUser, credential, []),
        completeState,
      ),
    );

    test(
      'accountMigrationError',
      reducerTest(
        reducer,
        inProgressState,
        partial(accountMigrationError, new Error('Error')),
        errorState,
      ),
    );
  },
);

test(
  'userLoggedOut',
  reducerTest(reducer, loggedInState, userLoggedOut, loggedOutState),
);


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link th:href="@{/webjars/font-awesome/4.3.0/css/font-awesome.css}" rel="stylesheet" />
<link th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap.min.css}" rel="stylesheet" media="screen" />
<link th:href="@{/css/styles.css}" rel="stylesheet" media="screen" />
<title layout:title="$title">OAuth 2</title>

				<button type="button" class="navbar-toggle" data-toggle="collapse"
					data-target="#bs-example-navbar-collapse-1">
					Toggle Navigation

				</button>

					OAuth2 Authentication Tool

???


text:
@implementation XBAMPString

- (NSData *)encodeObject:(id)object
{
    NSString *string = object;
    return [string dataUsingEncoding:NSUTF8StringEncoding];
}

- (id)decodeData:(NSData *)data
{
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

@end


text:
{% extends 'base.html' %}

{% block page_title %}Add A Transaction{% endblock %}

{% block content %}

Add A Transaction

    <form method="post" action=".">

            {{ form.as_table }}

                    <input type="submit" name="confirmed" value="Save">
                    or
                    Cancel

    </form>
{% endblock %}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="Refractored.Xam.Settings.NUnitTest.Android" android:versionCode="1" android:versionName="1.0">
	<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21" />
	<application android:label="Refractored.Xam.Settings.NUnitTest.Android" android:icon="@drawable/Icon"></application>
</manifest>


text:
GW2 Bounty Hunter
=================

*Due to the implementation of megaservers and changes to the API, this app no longer functions.*

`compass watch --sass-dir app/styles/sass --css-dir app/styles/css -I app/styles/imports`

`app/build/build.sh`


text:
package com.keygenteam.mamiferosenpeligro;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;

public class Info_Profile5 extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_info__profile5);

		WebView WV = (WebView) findViewById(R.id.wv_profile5);
		WV.getSettings().setBuiltInZoomControls(true);
		WV.loadUrl("file:///android_asset/ArmadilloZorro.html");
	}

}


text:
module MongoidShortener
  VERSION = "1.1.0"
end


text:
using System;
using System.Linq;

namespace Vsts.Cli
{
    public static class ReservedNames
    {
        public static readonly string[] UserStory = new[] { "userstory", "user story", "user-story" };
        public static readonly string[] TestCase = new[] { "testcase", "test case", "test-case" };
        public static readonly string[] TestSuite = new[] { "testsuite", "test suite", "test-suite" };
        public static readonly string[] Epic = new[] { "epic", "epics", "epci", "epcis" };
        public static readonly string[] Bug = new[] { "bug", "bugs", "bgu", "bgus" };
        public static readonly string[] Feature = new[] { "feature", "features", "featuer", "featuers" };
        public static readonly string[] Issue = new[] { "issue", "issues", "isseu", "isseus" };

        public static readonly string[] PullRequestCommands = new[] { "pullrequest", "pr", "pullrequets" };
        public static readonly string[] WorkItemCommands = new[] { "workitem", "wi", "workitme", "workitmes" };
        public static readonly string[] BuildCommands = new[] { "build", "biuld" };
        public static readonly string[] LogCommands = new[] { "log", "logs", "lgo", "lgos" };
        public static readonly string[] ReleaseCommands = new[] { "release", "releases", "rel", "releaes" };
        public static readonly string[] TestManagmentCommands = new[] { "test", "tests", "testmanagemnet", "tets", "tetss" };

        public static string Normalize(this string source)
        {
            if (string.IsNullOrWhiteSpace(source)) return source;
            source = source.Replace(" ", string.Empty).Replace("-", string.Empty);

            if (UserStory.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return WorkItemType.UserStory;

            if (TestCase.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return WorkItemType.TestCase;

            if (TestSuite.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return WorkItemType.TestSuite;

            if (Epic.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return WorkItemType.Epic;

            if (Bug.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return WorkItemType.Bug;

            if (Feature.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return WorkItemType.Feature;

            if (Issue.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return WorkItemType.Issue;

            if (PullRequestCommands.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return CommandName.PullRequests;

            if (WorkItemCommands.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return CommandName.WorkItems;

            if (BuildCommands.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return CommandName.Builds;

            if (LogCommands.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return CommandName.Logs;

            if (ReleaseCommands.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return CommandName.Releases;

            if (TestManagmentCommands.Any(x => x.Equals(source, StringComparison.OrdinalIgnoreCase)))
                return CommandName.TestManagement;

            return source;
        }
    }
}


text:
#include "FooService.h"

#include "cppmicroservices/BundleActivator.h"
#include "cppmicroservices/BundleContext.h"
#include "cppmicroservices/ServiceRegistration.h"

#include <iostream>

namespace cppmicroservices {

class FooServiceImpl : public FooService
{

public:
  void foo() {}
};

class ActivatorSL4 : public BundleActivator
{

public:
  ~ActivatorSL4() {}

  void Start(BundleContext context)
  {
    sr =
      context.RegisterService<FooService>(std::make_shared<FooServiceImpl>());
  }

  void Stop(BundleContext /*context*/) {}

private:
  ServiceRegistration<FooService> sr;
};
}

CPPMICROSERVICES_EXPORT_BUNDLE_ACTIVATOR(cppmicroservices::ActivatorSL4)


text:
require 'shrine'
require 'shrine/storage/file_system'
require 'ckeditor/backend/shrine'

# Choose your favorite image processor
require 'image_processing/mini_magick'
SHRINE_PICTURE_PROCESSOR = ImageProcessing::MiniMagick

# require 'image_processing/vips'
# SHRINE_PICTURE_PROCESSOR = ImageProcessing::Vips

Shrine.storages = {
  cache: Shrine::Storage::FileSystem.new('public', prefix: 'uploads/cache'),
  store: Shrine::Storage::FileSystem.new('public', prefix: 'system')
}

Shrine.plugin :determine_mime_type
Shrine.plugin :mongoid
Shrine.plugin :instrumentation

Shrine.plugin :validation_helpers
Shrine.plugin :processing
Shrine.plugin :versions


text:
package suonos.services.player.events;

import suonos.services.player.PlayerItem;

public class PositionUpdated {

    private PlayerItem itemPlaying;
    private long position;

    public PositionUpdated(PlayerItem itemPlaying, long position) {
        this.itemPlaying = itemPlaying;
        this.position = position;
    }

    public PlayerItem getItemPlaying() {
        return itemPlaying;
    }

    public long getPosition() {
        return position;
    }
}


text:
<html>

Hi,

Congratulation!
Your image has been downloaded

</html>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/alarm_activity_dialog"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <RelativeLayout
        android:id="@+id/alarm_layout_top"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/blue_500">

        <TextView
            android:id="@+id/alarm_mainTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginBottom="15dp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="15dp"
            android:text="@string/alarm"
            android:textColor="@android:color/white"
            android:textIsSelectable="false"
            android:textSize="25sp" />

        <ImageButton
            android:id="@+id/alarm_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="20dp"
            android:background="?android:selectableItemBackgroundBorderless"
            android:src="@drawable/ic_delete_white_24dp" />
    </RelativeLayout>

    <TextView
        android:id="@+id/alarm_set_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/alarm_layout_top"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginTop="15dp"
        android:text="@string/no_alarm_set"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <LinearLayout
        android:id="@+id/alarm_date_and_time_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/alarm_set_tv"
        android:layout_marginTop="15dp">

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:clickable="false"
            android:text="" />

        <TextView
            android:id="@+id/date_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:gravity="center"
            android:background="?android:selectableItemBackground"
            android:clickable="true"
            android:text="@string/null_date"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:clickable="false"
            android:text="" />

        <TextView
            android:id="@+id/time_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:gravity="center"
            android:background="?android:selectableItemBackground"
            android:clickable="true"
            android:text="@string/null_time"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:clickable="false"
            android:text="" />
    </LinearLayout>

    <View
        android:id="@+id/div"
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:layout_below="@id/alarm_date_and_time_layout"
        android:background="@android:color/darker_gray" />

    <LinearLayout
        android:id="@+id/alarm_checkboxes_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/alarm_date_and_time_layout"
        android:layout_marginTop="15dp">

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="15dp"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:clickable="false" />

        <CheckBox
            android:id="@+id/alarm_wake"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/wake_screen"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:clickable="false"
            android:text="" />

        <CheckBox
            android:id="@+id/alarm_vibrate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/vibrate"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="15dp"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:clickable="false"
            android:text="" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/alarm_layout_pro1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/alarm_checkboxes_layout"
        android:layout_marginTop="5dp">

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="20dp"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:clickable="false"
            android:text="" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/alarm_sound_btn"
            android:background="@drawable/ic_volume_up_grey600_24dp"
            android:layout_gravity="center_vertical"
            android:layout_marginRight="10dp"
            android:clickable="false"
            />

        <TextView
            android:id="@+id/alarm_sound"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:enabled="false"
            android:clickable="false"
            android:background="?android:selectableItemBackground"
            android:textAppearance="?android:attr/textAppearanceMedium"
            />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/alarm_layout_pro2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/alarm_layout_pro1"
        android:layout_marginTop="5dp">

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="20dp"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:clickable="false"
            android:text="" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/alarm_repeat_iv"
            android:layout_gravity="center_vertical"
            android:clickable="true"
            android:onClick="onClick"
            android:background="?android:selectableItemBackgroundBorderless"
            />

        <org.adw.library.widgets.discreteseekbar.DiscreteSeekBar
            android:id="@+id/discrete_bar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginRight="15dp"
            android:layout_gravity="center"
        />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/alarm_bottom_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/alarm_layout_pro2"
        android:layout_marginTop="15dp">

        <Button
            android:id="@+id/alarm_cancel_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="?android:selectableItemBackground"
            android:text="@string/cancel"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <Button
            android:id="@+id/alarm_set_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="?android:selectableItemBackground"
            android:text="@string/set"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>
</RelativeLayout><!-- From: file:/C:/Users/Jon/Dropbox/My%20Documents/android/Notey2_2/app/src/main/res/layout-v21/alarm_activity_dialog.xml -->


text:
function pulse = hard_pulse(t,Trf,~)
%HARD_PULSE Hard (square) RF pulse function.
%   pulse = hard_pulse(t,Trf,~)
%
%   The hard/square pulse is defined to be 1 from when the pulse starts
%   (t=0) until it ends (t=Trf), and is 0 elsewhere.
%
%   Note that the last argument is ignored, due to how GETPULSE calls its
%   functions using function handles (eg., hard_pulse has no additional
%   pulse options.)
%
%   --args--
%   t: Function handle variable, represents the time.
%   Trf: Width of the hard/square RF pulse.
%
%   Reference: Matt A. Bernstein, Kevin F. Kink and Xiaohong Joe Zhou.
%              Handbook of MRI Pulse Sequences, pp. 37, Table 2.1, (2004)
%
%   See also GETPULSE, VIEWPULSE.
%

pulse = single(~(t < 0 | t>Trf));

end


text:
import collections
import math
import multiprocessing
import os
import random
import threading
from copy import deepcopy

import pandas as pd

import numpy as np
import tensorflow as tf
from docluster.core import Model
from docluster.core.document_embedding import TfIdf
from docluster.core.preprocessing import Preprocessor, TokenFilter
from docluster.utils.constants import DistanceMetric, FileType
from docluster.utils.data_fetcher import FileFetcher
from docluster.utils.data_saver import FileSaver
from scipy.special import expit

from .word_embeddings import WordEmbeddings

class Word2Vec(Model):

    def __init__(self, preprocessor=None, n_skips=16, n_negative_samples=100, n_words=10000, embedding_size=100, batch_size=32, window_size=10, learning_rate=0.025, n_epochs=1, n_workers=4, do_plot=False):
        """
            A Skip-Gram model Word2Vec with multi-thread training capability.

            Paramaters:
            -----------
            preprocessor : Preprocessor
                The preprocessor that will tokenize the documents.
                The default one also filters punctuation, tokens with numeric
                characters and one letter words. Furthermore, no stemming or
                lemmatization is applied. All these can be adjusted
                by passing a custom preprocessor.
            n_skip : int
                The number of skips.
            n_negative_samples : int
                The number of negative samples that are going to collected for each
                batch.
            n_words : int
                The number of words that the vocabulary will have. The filtering is
                based on the word frequency. Therefore, less frequent words will not
                be included in the vocabulary.
            embedding_size : int
                The size of the embedding vectors. Usually the more makes the embeddings
                more accurate, but this is not always the case. Increasing the size
                dramatically affects trainning time.
            batch_size : int
                The batch size.
            window_size : int
                The window size where the words to the left and to the right of the words
                will give context to the word.
            learning_rate : int
                The initial learning rate of the gradient decent.
            n_epochs : int
                The number of epoches the model is going to be trained. Increasing the number
                dramatically affects trainning time.
            n_workers : int
                The number of workers that is going to train the model concurrently.
                It is not recommended to use more than the number of core.
            do_plot : bool

            Attributes:
            -----------
            embeddings :
                The embedding vectors that represents each word
        """
        if preprocessor is None:
            additional_filters = [lambda token: len(token) == 1]
            token_filter = TokenFilter(filter_stop_words=False,
                                       additional_filters=additional_filters)
            preprocessor = Preprocessor(do_stem=False, do_lemmatize=False,
                                        parse_html=False, token_filter=token_filter, lower=False)

        self.preprocessor = preprocessor
        self.n_skips = n_skips
        self.n_negative_samples = n_negative_samples
        self.embedding_size = embedding_size
        self.batch_size = batch_size
        self.window_size = window_size
        self.learning_rate = learning_rate
        self.n_epochs = n_epochs
        self.n_words = n_words
        self.n_workers = n_workers

        self._total_loss = 0
        self._dist_metric = DistanceMetric.cosine
        self.embeddings = WordEmbeddings(size=embedding_size, n_words=n_words)
        self.locks = np.ones(n_words)

        self.syn1 = np.zeros((n_words, embedding_size))
        self.syn1neg = np.zeros((n_words, embedding_size))

    def fit(self, documents):
        """
            Train the Word2Vec model with the documents.

            Paramaters:
            -----------
            documents : list(str)
                the documents that the Word2Vec model is going to learn the embeddings from.
        """
        n_words_trained = 0
        tokens, self.vocab, data, self._frequencies, self.diction, self.reverse_diction = self._build_dataset(
            documents)
        n_tokens = len(tokens)
        n_vocab = len(self.vocab)
        words_per_epoch = n_vocab / self.n_epochs
        self._cum_dist = self._build_cum_dist()

    def _build_dataset(self, documents):
        """Preprocesses the documents and creates the dataset for fitting."""

        # Get the term frequencies without idf
        tfidf = TfIdf(do_idf=False, preprocessor=self.preprocessor, n_words=self.n_words)
        tfidf.fit(documents)

        # Flatten the document tokens to create one long list
        tokens = list(np.hstack(np.array(tfidf.document_tokens)))

        # Create the vocab list with 'UNK' for vocab that couldn't make the vocab list
        vocab = tfidf.vocab
        vocab_set = set(vocab)

        diction = {token: index for index, token in enumerate(vocab)}
        reverse_diction = dict(zip(diction.values(), diction.keys()))

        # Turn the long token list into a index references to the diction
        data = list(map(lambda token: diction[token]
                        if token in vocab_set else 0, tokens))

        # Get the frequencies of tokens and add the frequency of 'UNK' at the beginning
        # frequencies = np.insert(tfidf.total_term_freq, 0, data.count(0))[:self.n_words]
        frequencies = tfidf.total_term_freq[:self.n_words]

        return tokens, vocab, data, frequencies, diction, reverse_diction

    def _build_cum_dist(self, distortion=0.75, domain=2**31 - 1):

        freq_total = np.sum(self._frequencies ** distortion)
        cum_dist = np.cumsum(self._frequencies) * domain / freq_total
        return cum_dist

    def _train(self, data, optimizer, loss):
        """Train the model."""

        start_index = 0
        init_op = tf.global_variables_initializer()
        with tf.Session() as sess:

            self._sess = sess
            self._sess.run(init_op)
            for epoch in range(self.n_epochs):
                self._train_one_epoch(data, optimizer, loss)

                print("Epoch:", (epoch + 1))

            self.embeddings = self._embeddings.eval()

        print("\nTraining complete!")

    def _train_one_example(self, example, label, alpha):

        predict_word = model.wv.vocab[word]  # target word (NN output)

        # input word (NN input/projection layer)
        example_index = self._diction[example]
        embedding = self.embeddings.vectors[example_index]
        lock = self.locks[example_index]

        # work on the entire tree at once, to push as much work into numpy's C routines as possible (performance)
        # 2d matrix, codelen x layer1_size
        l2a = deepcopy(self.syn1[predict_word.point])
        prod_term = np.dot(embedding, l2a.T)
        fa = expit(prod_term)  # propagate hidden -> output
        # vector of error gradients multiplied by the learning rate
        ga = (1 - predict_word.code - fa) * alpha
        if learn_hidden:
            model.syn1[predict_word.point] += outer(ga, l1)  # learn hidden -> output

        sgn = (-1.0)**predict_word.code  # `ch` function, 0 -> 1, 1 -> -1
        lprob = -log(expit(-sgn * prod_term))
        self._total_loss += sum(lprob)

        if model.negative:
            # use this word (label = 1) + `negative` other random words not from this sentence (label = 0)
            word_indices = [predict_word.index]
            while len(word_indices) < model.negative + 1:
                w = model.cum_table.searchsorted(
                    model.random.randint(model.cum_table[-1]))
                if w != predict_word.index:
                    word_indices.append(w)
            l2b = model.syn1neg[word_indices]  # 2d matrix, k+1 x layer1_size
            prod_term = dot(l1, l2b.T)
            fb = expit(prod_term)  # propagate hidden -> output
            # vector of error gradients multiplied by the learning rate
            gb = (model.neg_labels - fb) * alpha
            if learn_hidden:
                model.syn1neg[word_indices] += outer(gb, l1)  # learn hidden -> output

            # loss component corresponding to negative sampling
            if compute_loss:
                # for the sampled words
                self._total_loss -= sum(log(expit(-1 * prod_term[1:])))
                # for the output word
                self._total_loss -= log(expit(prod_term[0]))

        if learn_vectors:
            # learn input -> hidden (mutates model.wv.syn0[word2.index], if that is l1)
            embedding += neu1e * lock_factor

    def _train_one_epoch(self, data, optimizer, loss):
        """Train one epoch with workers."""
        # Each worker generates a batch and trains it until posion pill

        def worker_duty():
            """The duty of a single worker."""

            while True:
                batch = queue.get()
                if batch is None:
                    break
                examples, labels, alphas = batch
                for example, label, alpha in batch:
                    self._train_one_example(example, label, alpha)

        def generate_batch():
            """Create a batch for a training step in Word2Vec."""

            # Initialize variables
            example = np.zeros(self.batch_size)
            labels = np.zeros((self.batch_size, 1))
            alphas = np.zeros(self.batch_size)
            n_items = 0
            index = 0

            while index < len(data):
                reduced_window = random.randint(0, self.window_size)
                if data[index] is not None:

                    left = max(0, index - self.window_size + reduced_window)
                    right = min((index + self.window_size + 1 -
                                 reduced_window), len(data) - 1)
                    for pos2 in range(left, right, 1):

                        if n_items == self.batch_size:
                            queue.put((example, labels, index))
                            example = np.zeros(self.batch_size)
                            labels = np.zeros((self.batch_size, 1))
                            n_items = 0

                        if pos2 != index and data[pos2] is not None:
                            example[n_items] = data[pos2]
                            labels[n_items] = data[index]
                            alpha = self.learning_rate - \
                                (self.learning_rate - 0.001) * (index / self.n_words)
                            alphas[n_items] = max(0.001, alpha)
                            n_items += 1
                index += 1

            # Poison pills
            for _ in range(n_workers):
                queue.put(None)

        # Create a threadsafe queue to store the batch indexes
        queue = multiprocessing.Queue(maxsize=2 * self.n_workers)

        # Create and run the threads
        workers = [threading.Thread(target=generate_batch)]
        workers.extend([threading.Thread(target=worker_duty)
                        for _ in range(self.n_workers - 1)])

        for worker in workers:
            worker.start()

        for thread in workers:
            thread.join()

    def most_similar_words(self, word, n_words=5, include_similarity=False):
        """
            Get the most similar words to a word.

            Paramaters:
            -----------
            word : list(str)
                The word that is the point of intrest.
            n_words : int
                The number of words that is going to be returned.
            include_similarity : bool
                If to include the similarity score as part of a tuple next to the words.

            Return:
            -------
            similar_words : list(str) or list(tuple(str, float))
                The words that are most similar to the word according to the trained
                embeddings.
        """

        if word in self.vocab:
            token_id = self.diction[word]
            tiled_embedding = np.tile(self.embeddings[token_id], (self.n_words, 1))
            embedding_similarities = self._dist_metric(tiled_embedding, self.embeddings)
            most_similar_token_ids = (-embedding_similarities).argsort()

            return list(map(lambda token_id: self.reverse_diction[token_id], most_similar_token_ids))
        else:
            print('not in vocab')

    def save_model(self, model_name, file_type=FileType.csv, safe=True, directory_path=None):
        """
            Save the fitted model.

            Paramaters:
            -----------
            model_name : str
                The model name (also the file name) of the model is going to be saved under.
            file_type : FileType
                The file type that the model is going to be saved as.

            Return:
            -------
            saved : bool
                If the model is saved successfully or not.
        """

        if self.embeddings is None:
            return False

        data = pd.DataFrame(self.embeddings.T)
        data.columns = self.vocab

        if directory_path:
            file_saver = FileSaver(directory_path=directory_path)
        else:
            file_saver = FileSaver()

        return file_saver.save(data, model_name, file_type=file_type, safe=safe)

    def load_model(self, model_name, file_type=FileType.csv, directory_path=None):

        if directory_path:
            file_fetcher = FileFetcher(directory_path=directory_path)
        else:
            file_fetcher = FileFetcher()

        self.n_words += 1
        data = file_fetcher.load(model_name, file_type)

        self.embeddings = data.as_matrix().T
        self.vocab = data.columns.tolist()
        self.diction = {token: index for index, token in enumerate(self.vocab)}
        self.reverse_diction = dict(zip(self.diction.values(), self.diction.keys()))