text:
package org.aludratest.eclipse.vde.internal.util;

import java.util.Collection;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;

public final class SignatureUtil {

	private SignatureUtil() {
	}

	public static String getFullyQualifiedType(IField field) throws JavaModelException {
		String typeSignature = field.getTypeSignature();
		String qualifier = Signature.getSignatureQualifier(typeSignature);
		String simpleName = Signature.getSignatureSimpleName(typeSignature);
		simpleName = Signature.getTypeErasure(simpleName);

		if (qualifier == null || "".equals(qualifier)) {
			return getFullyQualifiedType(field.getTypeRoot(), simpleName);

		}
		else {
			return Signature.getSignatureQualifier(typeSignature) + "." + Signature.getSignatureSimpleName(typeSignature);
		}
	}

	public static boolean isCollection(IField field) {
		try {
			String fqcn = getFullyQualifiedType(field);

			// check against our own classloader, as only Collection Framework types should be used
			Class<?> clz = Class.forName(fqcn);
			return Collection.class.isAssignableFrom(clz);
		}
		catch (Exception e) {
			// ignore; dunno class
			return false;
		}
	}

	public static String getFullyQualifiedSignatureType(ITypeRoot typeRoot, String signature) throws JavaModelException {
		String qualifier = Signature.getSignatureQualifier(signature);
		if (qualifier != null && !"".equals(qualifier)) {
			return qualifier + "." + Signature.getSignatureSimpleName(signature);
		}

		return getFullyQualifiedType(typeRoot, Signature.getSignatureSimpleName(signature));
	}

	public static String getFullyQualifiedType(ITypeRoot typeRoot, String simpleOrQualifiedName) throws JavaModelException {
		IJavaProject project = typeRoot.getJavaProject();

		// try if this already marks an existing class (could also be e.g. "Map.Entry")
		if (simpleOrQualifiedName.contains(".")) {
			IType tp = project.findType(simpleOrQualifiedName);
			if (tp != null) {
				return tp.getFullyQualifiedName();
			}
		}

		if (typeRoot instanceof ICompilationUnit) {
			ICompilationUnit cu = (ICompilationUnit) typeRoot;

			for (IImportDeclaration imp : cu.getImports()) {
				String importName = imp.getElementName();
				if (importName.endsWith(".*")) {
					String testName = importName.substring(0, importName.length() - 1) + simpleOrQualifiedName;
					IType testType = project.findType(testName);
					if (testType != null) {
						return testName;
					}
				}
				else if (importName.endsWith("." + simpleOrQualifiedName)) {
					return importName;
				}
			}
		}

		// OK, now check package of type
		IType primaryType = typeRoot.findPrimaryType();
		if (primaryType != null) {
			IPackageFragment pkg = primaryType.getPackageFragment();
			if (pkg != null && !pkg.isDefaultPackage()) {
				String testName = pkg.getElementName() + "." + simpleOrQualifiedName;
				IType testType = project.findType(testName);
				if (testType != null) {
					return testName;
				}
			}
		}

		// now check java.lang
		String testName = "java.lang." + simpleOrQualifiedName;
		IType testType = project.findType(testName);
		if (testType != null) {
			return testName;
		}

		// return simple name. Could be default package
		return simpleOrQualifiedName;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.midgetontoes</groupId>
	<artifactId>todolist</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>To-do List</name>
	<description>A simple to-do list</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.1.9.RELEASE</version>
		<relativePath/>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.hateoas</groupId>
			<artifactId>spring-hateoas</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.plugin</groupId>
			<artifactId>spring-plugin-core</artifactId>
			<version>1.1.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>18.0</version>
		</dependency>
		<dependency>
			<groupId>org.atteo</groupId>
			<artifactId>evo-inflector</artifactId>
			<version>1.2.1</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<start-class>com.midgetontoes.todolist.Application</start-class>
		<java.version>1.8</java.version>
	</properties>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const Support   = require('../support'),
  DataTypes = require('../../../lib/data-types'),
  expectsql = Support.expectsql,
  current   = Support.sequelize,
  sql       = current.dialect.QueryGenerator,
  _         = require('lodash');

describe(Support.getTestDialectTeaser('SQL'), () => {
  describe('createTable', () => {
    const FooUser = current.define('user', {
      mood: DataTypes.ENUM('happy', 'sad')
    }, {
      schema: 'foo',
      timestamps: false
    });

    describe('with enums', () => {
      it('references enum in the right schema #3171', () => {
        expectsql(sql.createTableQuery(FooUser.getTableName(), sql.attributesToSQL(FooUser.rawAttributes), { }), {
          sqlite: 'CREATE TABLE IF NOT EXISTS `foo.users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `mood` TEXT);',
          postgres: 'CREATE TABLE IF NOT EXISTS "foo"."users" ("id"   SERIAL , "mood" "foo"."enum_users_mood", PRIMARY KEY ("id"));',
          mysql: "CREATE TABLE IF NOT EXISTS `foo.users` (`id` INTEGER NOT NULL auto_increment , `mood` ENUM('happy', 'sad'), PRIMARY KEY (`id`)) ENGINE=InnoDB;",
          mssql: "IF OBJECT_ID('[foo].[users]', 'U') IS NULL CREATE TABLE [foo].[users] ([id] INTEGER NOT NULL IDENTITY(1,1) , [mood] VARCHAR(255) CHECK ([mood] IN(N'happy', N'sad')), PRIMARY KEY ([id]));"
        });
      });
    });

    describe('with references', () => {
      const BarUser = current.define('user', {
        timestamps: false
      }).schema('bar');

      const BarProject = current.define('project', {
        user_id: {
          type: DataTypes.INTEGER,
          references: { model: BarUser },
          onUpdate: 'CASCADE',
          onDelete: 'NO ACTION'
        }
      }, {
        timestamps: false
      }).schema('bar');

      BarProject.belongsTo(BarUser, { foreignKey: 'user_id' });

      it('references right schema when adding foreign key #9029', () => {
        expectsql(sql.createTableQuery(BarProject.getTableName(), sql.attributesToSQL(BarProject.rawAttributes), { }), {
          sqlite: 'CREATE TABLE IF NOT EXISTS `bar.projects` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `user_id` INTEGER REFERENCES `bar.users` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE);',
          postgres: 'CREATE TABLE IF NOT EXISTS "bar"."projects" ("id"   SERIAL , "user_id" INTEGER REFERENCES "bar"."users" ("id") ON DELETE NO ACTION ON UPDATE CASCADE, PRIMARY KEY ("id"));',
          mysql: 'CREATE TABLE IF NOT EXISTS `bar.projects` (`id` INTEGER NOT NULL auto_increment , `user_id` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`user_id`) REFERENCES `bar.users` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE) ENGINE=InnoDB;',
          mssql: 'IF OBJECT_ID(\'[bar].[projects]\', \'U\') IS NULL CREATE TABLE [bar].[projects] ([id] INTEGER NOT NULL IDENTITY(1,1) , [user_id] INTEGER NULL, PRIMARY KEY ([id]), FOREIGN KEY ([user_id]) REFERENCES [bar].[users] ([id]) ON DELETE NO ACTION);'
        });
      });
    });

    describe('with references on primary key', () => {
      const File = current.define('file', {}, { timestamps: false });
      const Image = current.define('image', {
        id: {
          primaryKey: true,
          autoIncrement: true,
          type: DataTypes.INTEGER,
          references: {
            model: File,
            key: 'id'
          }
        }
      }, {
        timestamps: false
      });

      it('references on primary key #9461', () => {
        expectsql(sql.createTableQuery(Image.getTableName(), sql.attributesToSQL(Image.rawAttributes), { }), {
          sqlite: 'CREATE TABLE IF NOT EXISTS `images` (`id` INTEGER PRIMARY KEY AUTOINCREMENT REFERENCES `files` (`id`));',
          postgres: 'CREATE TABLE IF NOT EXISTS "images" ("id"  SERIAL  REFERENCES "files" ("id"), PRIMARY KEY ("id"));',
          mysql: 'CREATE TABLE IF NOT EXISTS `images` (`id` INTEGER auto_increment , PRIMARY KEY (`id`), FOREIGN KEY (`id`) REFERENCES `files` (`id`)) ENGINE=InnoDB;',
          mssql: 'IF OBJECT_ID(\'[images]\', \'U\') IS NULL CREATE TABLE [images] ([id] INTEGER IDENTITY(1,1) , PRIMARY KEY ([id]), FOREIGN KEY ([id]) REFERENCES [files] ([id]));'
        });
      });
    });

    if (current.dialect.name === 'postgres') {
      describe('IF NOT EXISTS version check', () => {
        const modifiedSQL = _.clone(sql);
        const createTableQueryModified = sql.createTableQuery.bind(modifiedSQL);
        it('it will not have IF NOT EXISTS for version 9.0 or below', () => {
          modifiedSQL.sequelize.options.databaseVersion = '9.0.0';
          expectsql(createTableQueryModified(FooUser.getTableName(), sql.attributesToSQL(FooUser.rawAttributes), { }), {
            postgres: 'CREATE TABLE "foo"."users" ("id"   SERIAL , "mood" "foo"."enum_users_mood", PRIMARY KEY ("id"));'
          });
        });
        it('it will have IF NOT EXISTS for version 9.1 or above', () => {
          modifiedSQL.sequelize.options.databaseVersion = '9.1.0';
          expectsql(createTableQueryModified(FooUser.getTableName(), sql.attributesToSQL(FooUser.rawAttributes), { }), {
            postgres: 'CREATE TABLE IF NOT EXISTS "foo"."users" ("id"   SERIAL , "mood" "foo"."enum_users_mood", PRIMARY KEY ("id"));'
          });
        });
        it('it will have IF NOT EXISTS for default version', () => {
          modifiedSQL.sequelize.options.databaseVersion = 0;
          expectsql(createTableQueryModified(FooUser.getTableName(), sql.attributesToSQL(FooUser.rawAttributes), { }), {
            postgres: 'CREATE TABLE IF NOT EXISTS "foo"."users" ("id"   SERIAL , "mood" "foo"."enum_users_mood", PRIMARY KEY ("id"));'
          });
        });
      });

      describe('Attempt to use different lodash template settings', () => {
        before(() => {
          // make handlebars
          _.templateSettings.evaluate = /{{([\s\S]+?)}}/g;
          _.templateSettings.interpolate = /{{=([\s\S]+?)}}/g;
          _.templateSettings.escape = /{{-([\s\S]+?)}}/g;
        });

        after(() => {
          // reset
          const __ = require('lodash').runInContext();
          _.templateSettings.evaluate = __.templateSettings.evaluate;
          _.templateSettings.interpolate = __.templateSettings.interpolate;
          _.templateSettings.escape = __.templateSettings.escape;
        });

        it('it should be a okay!', () => {
          expectsql(sql.createTableQuery(FooUser.getTableName(), sql.attributesToSQL(FooUser.rawAttributes), {
            comment: 'This is a test of the lodash template settings.'
          }), {
            postgres: 'CREATE TABLE IF NOT EXISTS "foo"."users" ("id"   SERIAL , "mood" "foo"."enum_users_mood", PRIMARY KEY ("id")); COMMENT ON TABLE "foo"."users" IS \'This is a test of the lodash template settings.\';'
          });
        });
      });
    }
  });
});


text:
#import "NSView.h"

#import "DVTInvalidation-Protocol.h"

@class DVTStackBacktrace, IDEActivityView, IDEWorkspaceWindowController;

@interface IDEActivityPlaceholderView : NSView <DVTInvalidation>
{
    IDEWorkspaceWindowController *_workspaceWindowController;
    IDEActivityView *_activityView;
}

+ (void)initialize;
@property(retain) IDEWorkspaceWindowController *workspaceWindowController; // @synthesize workspaceWindowController=_workspaceWindowController;
- (void).cxx_destruct;
- (void)primitiveInvalidate;
- (id)hitTest:(struct CGPoint)arg1;
- (void)viewDidMoveToWindow;
- (void)viewWillMoveToWindow:(id)arg1;
- (void)sizeAndPositionActivityView;
- (void)sizeToFitToolbarDisplayMode:(unsigned long long)arg1 sizeMode:(unsigned long long)arg2;
- (Class)_activityViewClass;

// Remaining properties
@property(retain) DVTStackBacktrace *creationBacktrace;
@property(readonly) DVTStackBacktrace *invalidationBacktrace;
@property(readonly, nonatomic, getter=isValid) BOOL valid;

@end


text:
struct TBtItem
{
   TBtItem();
};

struct TBtInnerNode
{
   TBtInnerNode();
   int     MaxIndex() const { return 10; }
};

TBtInnerNode::TBtInnerNode()
{
   new TBtItem[MaxIndex()+1];
}


text:
*Creates the access point with forwarded NAT.*
![alt text](https://github.com/krystianbajno/scripts/blob/testing/networking/git.gif "GIF HERE")
## dhcp_create:
*Creates forwarded NAT network with DHCP.*
## connection_restart.sh
*Drops and restarts the connection to defaults.*

# Dependencies:
## ap_create:
>systemd, systemd-networkd, iptables, iproute2, dhcpd, hostapd.
## dhcp_create:
>systemd, dhcpd, iproute2, iptables.
## connection_restart.sh
>systemd, systemd-networkd, iproute2.


text:
using System;
using System.Collections.Generic;
using System.Dynamic;
using Frapid.NPoco;
using Frapid.Account.Entities;
namespace Frapid.Account.DataAccess
{
    public interface IHasActiveResetRequestRepository
    {

        string Email { get; set; }

        /// <summary>
        /// Prepares and executes IHasActiveResetRequestRepository.
        /// </summary>
        bool Execute();
    }
}


text:
CC ?=	gcc
CXX ?=	g++

all: multichoose multipermute

#multichoose_recursive: multichoose_recursive.cpp
#	${CXX} $(LDFLAGS) $(CPPFLAGS) $(CXXFLAGS) multichoose_recursive.cpp -o multichoose_recursive

multichoose: multichoose.cpp multichoose.h
	${CXX} $(LDFLAGS) $(CPPFLAGS) $(CXXFLAGS) multichoose.cpp -o multichoose

multipermute: multipermute.cpp multipermute.h
	${CXX} $(LDFLAGS) $(CPPFLAGS) $(CXXFLAGS) multipermute.cpp -o multipermute

cmultichoose: multichoose.c
	${CC} $(LDFLAGS) $(CPPFLAGS) $(CXXFLAGS) multichoose.c -o cmultichoose

clean:
	rm -f cmultichoose
	rm -f multichoose
	rm -f multipermute


text:
"""
Configuration of the server

The priority (from low to high) for loading configuration values is :
- the default builtin values
- the configuration file values
- the command line values
"""

import configparser
import argparse
import os.path
import os
import stat

import mnemopwd
from ...common.util.X509 import X509
from .funcutils import getIPAddress

class MyParserAction(argparse.Action):
    """Actions for command line parser"""

    def __init__(self, option_strings, dest, **kwargs):
        super(MyParserAction, self).__init__(option_strings, dest, **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        if option_string in ['-m', '--searchmode']:
            Configuration.search_mode = values
        if option_string in ['-s', '--poolsize']:
            Configuration.poolsize = values
        if option_string in ['-d', '--dbpath']:
            Configuration.dbpath = values
        if option_string in ['-c', '--cert']:
            Configuration.certfile = values
        if option_string in ['-k', '--key']:
            Configuration.keyfile = values
        if option_string in ['-i', '--ip']:
            Configuration.host = values
        if option_string in ['-p', '--port']:
            if values in range(Configuration.port_min, Configuration.port_max):
                Configuration.port = int(values)
            else:
                parser.error("argument -p/--port: invalid choice: {} (choose between {} and {})"
                             .format(values, Configuration.port_min, Configuration.port_max))

class Configuration:
    """Configuration of the server"""

    configfile = os.path.expanduser('~') + '/.mnemopwds'  # Configuration file
    dbpath = os.path.expanduser('~') + '/mnemopwddata'  # Default database path
    pidfile = os.path.expanduser('~') + '/mnemopwddata/mnemopwds.pid'  # Default daemon pid file
    logfile = os.path.expanduser('~') + '/mnemopwddata/mnemopwds.log'  # Default log file
    certfile = 'None'  # Default certificate X509 file
    keyfile = 'None'  # Default certificate private key file
    logmaxmb = 1  # Default logfile volume (1 => 1 MBytes)
    logbackups = 20  # Default backup logfile
    loglevel = 'INFO'  # Default logging level
    version = mnemopwd.__version__  # Server version
    host = getIPAddress()  # Default host
    port = 62230  # Default port
    port_min = 49152  # Minimum port value
    port_max = 65535  # Maximum port value
    poolsize = 10  # Default pool executor size
    search_mode = 'all'  # Default search mode
    max_login = 5  # Default maximum login attempts per hour
    action = 'status'  # Default action if not given

    @staticmethod
    def __test_cert_key_files__(parser, certfile, keyfile):
        """Test existence and permissions of private key file"""
        if not os.path.exists(keyfile):
            parser.error("invalid key file {} (it not exists)".format(keyfile))
        elif not os.path.exists(certfile):
            parser.error("invalid certificate file {} (it not exists)".
                         format(certfile))
        else:
            statinfo = os.stat(keyfile)
            if certfile == keyfile:
                parser.error(
                    "the certificate file ({}) and the key file ({}) must be different"
                    .format(certfile, keyfile))
            if stat.filemode(statinfo.st_mode) != '-rw-------':
                parser.error(
                    "invalid key file {} (it must have only read, write and execution permissions for user)"
                    .format(keyfile))
            elif statinfo.st_uid != os.getuid():
                parser.error("invalid key file {} (the owner must be the user)".
                             format(keyfile))
        return True

    @staticmethod
    def __test_dbpath__(parser, path):
        """Test existence and permissions of database directory"""
        if not os.path.exists(path):
            os.mkdir(path, mode=0o700)
        else:
            statinfo = os.stat(path)
            if not os.path.isdir(path) or os.path.islink(path):
                parser.error("invalid database path {} (it must be a directory)".format(path))
            elif stat.filemode(statinfo.st_mode) != 'drwx------':
                parser.error(
                    "invalid database path {} (it must have only read, write and execution permissions for user)"
                    .format(path))
            elif statinfo.st_uid != os.getuid():
                parser.error(
                    "invalid database path {} (the owner must be the user)"
                    .format(path))
        return True

    @staticmethod
    def __test_config_file__(parser, path):
        """Test existence and permissions of configuration file"""
        if not os.path.exists(path):
            return False
        else:
            statinfo = os.stat(path)
            if not os.path.isfile(path) or os.path.islink(path):
                parser.error(
                    "invalid configuration file {} (it must be a regular file)"
                    .format(path))
            elif stat.filemode(statinfo.st_mode) != '-rw-------':
                parser.error(
                    "invalid configuration file {} (it must have only read and write permissions for user)"
                    .format(path))
            elif statinfo.st_uid != os.getuid():
                parser.error(
                    "invalid configuration file {} (the owner must be the user)"
                    .format(path))
        return True

    @staticmethod
    def __load_config_file__(parser, fileparser):
        """Load configuration file"""
        try:
            fileparser.read(Configuration.configfile)
        except configparser.ParsingError:
            parser.error("parsing error of configuration file {}"
                         .format(Configuration.configfile))
        else:
            Configuration.port = int(fileparser['server']['port'])
            Configuration.host = fileparser['server']['host']
            Configuration.dbpath = fileparser['server']['dbpath']
            Configuration.certfile = fileparser['server']['certfile']
            Configuration.keyfile = fileparser['server']['keyfile']
            Configuration.poolsize = int(fileparser['server']['poolsize'])
            Configuration.search_mode = fileparser['server']['search_mode']
            Configuration.loglevel = fileparser['server']['loglevel']
            Configuration.max_login = int(fileparser['server']['max_login'])
            Configuration.pidfile = fileparser['daemon']['pidfile']
            Configuration.logfile = fileparser['daemon']['logfile']
            Configuration.logmaxmb = int(fileparser['daemon']['logmaxmb'])
            Configuration.logbackups = int(fileparser['daemon']['logbackups'])

    @staticmethod
    def __create_config_file__(fileparser):
        """Method to create default configuration file"""
        fileparser['server'] = {
            'port': str(Configuration.port) + " # Values allowed: "
            + str(Configuration.port_min)
            + "..." + str(Configuration.port_max),
            'host': Configuration.host + " # IP server",
            'dbpath': Configuration.dbpath + " # Use an absolute path",
            'certfile': Configuration.certfile + " # Use an absolute path",
            'keyfile': Configuration.keyfile + " # Use an absolute path",
            'poolsize': str(Configuration.poolsize) + " # Number of thread",
            'search_mode': Configuration.search_mode
            + " # Values allowed: all first",
            'loglevel': Configuration.loglevel
            + " # Values allowed: DEBUG INFO WARNING ERROR CRITICAL",
            'max_login': str(Configuration.max_login)
            + " # Maximum login attempt per hour"
        }
        fileparser['daemon'] = {
            'pidfile': Configuration.pidfile + " # Use an absolute path",
            'logfile': Configuration.logfile + " # Use an absolute path",
            'logmaxmb': str(Configuration.logmaxmb)
            + " # Maximum size of log file in MBytes",
            'logbackups': str(Configuration.logbackups)
            + " # Number of backup log files"
        }
        with open(Configuration.configfile, 'w') as configfile:
            fileparser.write(configfile)
        os.chmod(Configuration.configfile,
                 stat.S_IRUSR | stat.S_IWUSR | stat.S_IREAD | stat.S_IWRITE)

    @staticmethod
    def configure():
        """
        Configure the server: load configuration file then parse command line
        """

        # Create and configure a command line parser
        argparser = argparse.ArgumentParser(
            description='MnemoPwd server v' + Configuration.version,
            epilog='More information can be found at https://github.com/thethythy/Mnemopwd',
            formatter_class=argparse.ArgumentDefaultsHelpFormatter)

        # IP server
        argparser.add_argument(
            '-i', '--ip', nargs='?', default=Configuration.host, metavar='ip',
            help='the IP address of the server', action=MyParserAction)

        # Port
        argparser.add_argument(
            '-p', '--port', type=int, nargs='?', default=Configuration.port,
            metavar='port', help='the server connexion port',
            action=MyParserAction)

        # Database directory
        argparser.add_argument(
            '-d', '--dbpath', nargs='?', default=Configuration.dbpath,
            metavar='path', type=str, help="the directory to store secret data; \
            it will be created if it does not exist; if the directory already \
            exists only the user must have read, write and execution permissions",
            action=MyParserAction)

        # Certificat file
        argparser.add_argument(
            '-c', '--cert', nargs='?', default=Configuration.certfile,
            metavar='certificate', type=str, help="the PEM X509 certificate file",
            action=MyParserAction)

        # Certificat private key file
        argparser.add_argument(
            '-k', '--key', nargs='?', default=Configuration.keyfile,
            metavar='private_key', type=str, help="the private key file \
            to authenticate the certificate", action=MyParserAction)

        # Pool executor size
        argparser.add_argument(
            '-s', '--poolsize', type=int, default=Configuration.poolsize,
            metavar='pool_size', help="the size of the pool of execution",
            action=MyParserAction)

        # Search mode
        argparser.add_argument(
            '-m', '--searchmode', type=str, default=Configuration.search_mode,
            metavar='search_mode', help="the search mode; 'first' for \
            searching only on first secret information block and 'all' \
            for searching on all information", action=MyParserAction)

        # Start action
        argparser.add_argument(
            '--start', action='store_const', const='start', dest='action',
            default=Configuration.action, help='start the server')

        # Stop action
        argparser.add_argument(
            '--stop', action='store_const', const='stop', dest='action',
            default=Configuration.action, help='stop the server')

        # Status action
        argparser.add_argument(
            '--status', action='store_const', const='status', dest='action',
            default=Configuration.action, help='get server status')

        # Program version
        argparser.add_argument(
            '-v', '--version', action='version',
            version='version ' + Configuration.version)

        # Create, configure a configuration file parser and parse
        fileparser = configparser.ConfigParser(inline_comment_prefixes='#')
        if Configuration.__test_config_file__(
                argparser, Configuration.configfile):
            # Load values from configuration file
            Configuration.__load_config_file__(argparser, fileparser)
        else:
            # Create default configuration file
            Configuration.__create_config_file__(fileparser)

        # Parse the command line to get options
        options = argparser.parse_args()
        Configuration.action = options.action  # Action to apply to the server

        # Verify dbpath
        Configuration.__test_dbpath__(argparser, Configuration.dbpath)

        # Verify private key and certificate files
        if Configuration.keyfile != 'None' and Configuration.certfile != 'None':
            Configuration.__test_cert_key_files__(
                argparser, Configuration.certfile, Configuration.keyfile)
            try:
                # Control validity period
                X509(Configuration.certfile).check_validity_period()
            except Exception as e:
                print(e)
                exit(1)
        elif (Configuration.keyfile != 'None' and
                Configuration.certfile == 'None') or \
             (Configuration.keyfile == 'None' and
                Configuration.certfile != 'None'):
            argparser.error(
                "give two files (certificate file and key file) or nothing")


text:
public class Calculator {

    public int sum(int numberOne, int numberTwo) {
        System.out.println("Method One");
        return numberOne + numberTwo;
    }

    public float sum(float numberOne, float numberTwo) {
        System.out.println("Method Two");
        return numberOne + numberTwo;
    }

    public float sum(int numberOne, float numberTwo) {
        System.out.println("Method Three");
        return numberOne + numberTwo;
    }
}


text:
import {Mesh, MeshBasicMaterial, OrthographicCamera, PlaneGeometry, Scene, Texture as ThreeTexture, WebGLRenderTarget} from 'three';

import {blobCanvas} from '../../model-viewer-base.js';
import {Image as GLTFImage} from '../../three-components/gltf-instance/gltf-2.0.js';
import {Renderer} from '../../three-components/Renderer.js';

import {Image as ImageInterface} from './api.js';
import {$correlatedObjects, $sourceObject, ThreeDOMElement} from './three-dom-element.js';

const quadMaterial = new MeshBasicMaterial();
const quad = new PlaneGeometry(2, 2);
let adhocNum = 0;

export const $threeTexture = Symbol('threeTexture');
export const $applyTexture = Symbol('applyTexture');

/**
 * Image facade implementation for Three.js textures
 */
export class Image extends ThreeDOMElement implements ImageInterface {
  get[$threeTexture]() {
    console.assert(
        this[$correlatedObjects] != null && this[$correlatedObjects]!.size > 0,
        'Image correlated object is undefined');
    return this[$correlatedObjects]?.values().next().value as ThreeTexture;
  }

  constructor(
      onUpdate: () => void, texture: ThreeTexture|null,
      gltfImage: GLTFImage|null) {
    gltfImage = gltfImage ?? {
      name: (texture && texture.image && texture.image.src) ?
          texture.image.src.split('/').pop() :
          'adhoc_image',
      uri: (texture && texture.image && texture.image.src) ?
          texture.image.src :
          'adhoc_image' + adhocNum++
    };
    super(onUpdate, gltfImage, new Set<ThreeTexture>(texture ? [texture] : []));
  }

  get name(): string {
    return (this[$sourceObject] as GLTFImage).name || '';
  }

  get uri(): string|undefined {
    return (this[$sourceObject] as GLTFImage).uri;
  }

  get bufferView(): number|undefined {
    return (this[$sourceObject] as GLTFImage).bufferView;
  }

  get type(): 'embedded'|'external' {
    return this.uri != null ? 'external' : 'embedded';
  }

  set name(name: string) {
    (this[$sourceObject] as GLTFImage).name = name;
  }

  async createThumbnail(width: number, height: number): Promise<string> {
    const scene = new Scene();
    quadMaterial.map = this[$threeTexture];
    const mesh = new Mesh(quad, quadMaterial);
    scene.add(mesh);
    const camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);

    const {threeRenderer} = Renderer.singleton;
    const renderTarget = new WebGLRenderTarget(width, height);
    threeRenderer.setRenderTarget(renderTarget);
    threeRenderer.render(scene, camera);
    threeRenderer.setRenderTarget(null);

    const buffer = new Uint8Array(width * height * 4);
    threeRenderer.readRenderTargetPixels(
        renderTarget, 0, 0, width, height, buffer);

    blobCanvas.width = width;
    blobCanvas.height = height;
    const blobContext = blobCanvas.getContext('2d')!;
    const imageData = blobContext.createImageData(width, height);
    imageData.data.set(buffer);
    blobContext.putImageData(imageData, 0, 0);

    return new Promise<string>(async (resolve, reject) => {
      blobCanvas.toBlob(blob => {
        if (!blob) {
          return reject('Failed to capture thumbnail.');
        }
        resolve(URL.createObjectURL(blob));
      }, 'image/png');
    });
  }
}


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LeftTurnReport
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

                //var connection = Configuration
                //    .GetConnectionString("SPM");
                //services.AddDbContext<EfCoreContext>(
                //    options => options.UseSqlServer(connection,
                //    b => b.MigrationsAssembly("DataLayer")));

            services.AddControllers();

            // Register the Swagger services
            services.AddSwaggerDocument();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseOpenApi();
            app.UseSwaggerUi3();
        }
    }
}


text:
package org.edx.mobile.core;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class LinearLayoutManagerProvider implements Provider<LinearLayoutManager> {

    @Inject
    Context context;

    @Override
    public LinearLayoutManager get() {
        return new LinearLayoutManager(context);
    }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\PhotoCD;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class ScannerPixelSize extends AbstractTag
{

    protected $Id = 110;

    protected $Name = 'ScannerPixelSize';

    protected $FullName = 'PhotoCD::Main';

    protected $GroupName = 'PhotoCD';

    protected $g0 = 'PhotoCD';

    protected $g1 = 'PhotoCD';

    protected $g2 = 'Image';

    protected $Type = 'undef';

    protected $Writable = false;

    protected $Description = 'Scanner Pixel Size';

    protected $MaxLength = 2;
}


text:
var exampleRoutes = require('./example-route-data')
var expressApp = require('./express-application/app')
var pathfinder = require('../')
var assert = require('chai').assert
var expect = require('chai').expect

describe("Test Routes - SIMULATED ROUTES", function() {
  it("Should get all routes from the list", function() {
    var routes = pathfinder(exampleRoutes)
    assert.equal(routes.length, 6)
  })

  it("should get all GET routes", function() {
    var routes = pathfinder(exampleRoutes, "POST")

    assert.equal(routes.length, 2)
  })

  it("should include the mount path at the start of the url", function() {
    var routes = pathfinder(exampleRoutes, "DELETE") // Delete is only used in a "mounted route"
    var regex = /^\/admin\/[a-zA-Z0-9]*/

    var test = regex.test(routes[0].path)

    assert.isTrue(test)
  })

  it("should throw an Error as supplied HTTP method is not supported", function() {
    expect(() => {
      pathfinder(exampleRoutes, "FOOBAR")
    }).to.throw(Error)
  })

  it("should throw an TypeError as supplied method parameter is not of the correct type", function() {
    expect(() => {
      pathfinder(exampleRoutes, 123456)
    }).to.throw(TypeError)
  })
})

describe("Test Routes - EXPRESS APPLICATION", function() {
  it("Should get all routes from the list", function() {
    var routes = pathfinder(expressApp._router.stack)
    assert.equal(routes.length, 6)
  })

  it("should get all GET routes", function() {
    var routes = pathfinder(expressApp._router.stack, "POST")

    assert.equal(routes.length, 2)
  })

  it("should include the mount path at the start of the url", function() {
    var routes = pathfinder(expressApp._router.stack, "DELETE") // Delete is only used in a "mounted route"
    var regex = /^\/admin\/[a-zA-Z0-9]*/

    var test = regex.test(routes[0].path)

    assert.isTrue(test)
  })

  it("should throw an Error as supplied HTTP method is not supported", function() {
    expect(() => {
      pathfinder(expressApp._router.stack, "FOOBAR")
    }).to.throw(Error)
  })

  it("should throw a TypeError as supplied method parameter is not of the correct type", function() {
    expect(() => {
      pathfinder(expressApp._router.stack, 123456)
    }).to.throw(TypeError)
  })
})


text:
create class xoo ( id int not null, name string );

select * from db_attribute where class_name = 'xoo' order by 1;

drop xoo;


text:
using Dot42;

namespace System.Runtime.CompilerServices
{
    /// <summary>
    /// Specifies whether to wrap exceptions that do not derive from the Exception class with a RuntimeWrappedException object. This class cannot be inherited.
    /// </summary>
    [SerializableAttribute]
    [AttributeUsageAttribute(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
    [Ignore]
    public sealed class RuntimeCompatibilityAttribute : Attribute
	{
        /// <summary>
        /// Gets or sets a value that indicates whether to wrap exceptions that do not derive from the Exception class with a RuntimeWrappedException object.
        /// </summary>
        public bool WrapNonExceptionThrows { get; set; }
	}
}


text:
"use strict";
/*global alert: true, console: true, ODSA */

(function ($) {
  var settings = ODSA.SETTINGS,
      odsaUtils = ODSA.UTILS;

  // Set the book ID (SHA1 hash of the book URL)
  settings.BOOK_ID = odsaUtils.getBookID();
  //function that displays config page

  var b_json = (function () {
    var b_json = null;
    $.ajax({
        'async': false,
        'global': false,
        'url': '_static/' + settings.BOOK_NAME + '.json',
        'dataType': "json",
        'success': function (data) {
          b_json = data;
        }
      });
    return b_json;
  })();

  //prepare data to send to the backend
  var jsonBook = {};

  jsonBook.key = odsaUtils.getSessionKey();
  jsonBook.book =  settings.BOOK_ID;
  // Calculate the URL of the book, relative to the current module page
  jsonBook.url = location.href.substring(0, location.href.lastIndexOf('/') + 1);
  jsonBook.b_json = JSON.stringify(b_json);

  function sendConfig() {
    //Add book build date
    jsonBook.build_date = settings.BUILD_DATE;
    $('#bookjson').html("Sending data ...");
    // Send the data to the server
    jQuery.ajax({
      url:   settings.SCORE_SERVER + "/api/v1/module/loadbook/",
      type:  "POST",
      data: jsonBook,
      contentType: "application/json; charset=utf-8",
      datatype: "json",
      xhrFields: {withCredentials: true},
      success: function (data) {
        alert("SUCCESS:\nAll chapters and exercises of book instance " + settings.BOOK_NAME + " have been saved on the data server.");
        $('#bookjson').html("SUCCESS");
        console.log("success: " + data);
      },
      error: function (data) {
        alert("ERROR:\nSomething went wrong when storing chapters and exercises of book instance " + settings.BOOK_NAME + ".\nYou might not have the right to complete this action. Refresh the page, the try again. If the problem persists, contact the administrator.");
        $('#bookjson').html("FAILED");
        console.log("error: " + data);
      }
    });
  }

  //*****************************************************************************
  //***********            Runs When Page Finishes Loading            ***********
  //*****************************************************************************
  $(document).ready(function () {
    $('#bookname').val(settings.BOOK_NAME);
    $('#bookid').val(settings.BOOK_ID);
    //$('#bookjson').html(JSON.stringify(b_json));
    $('#registerbook').click(function () {
      sendConfig();
    });
  });

}(jQuery));


text:
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-- | Provides means to communicate over the Peer Wire Protocol.
-- You can encode and decode messages using the 'Binary' instances.
module Network.BitTorrent.PWP (
  PWP(..)
, BHandshake(..)
) where

import Control.Monad
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Foldable

protocolString :: ByteString
protocolString = "BitTorrent protocol"

-- | Encodes all the messages in PWP.
data PWP = KeepAlive
         | Choke
         | Unchoke
         | Interested
         | Uninterested
         | Have Word32 -- ^ PieceId
         | Bitfield ByteString
         | Request Word32 Word32 Word32 -- ^ PieceId Offset Length
         | Piece Word32 Word32 ByteString -- ^ PieceId Offset Data
         | Cancel Word32 Word32 Word32 -- ^ PieceId Offset Length
         deriving(Show, Eq)

putPieceDescription :: Word32 -> Word32 -> Word32 -> Put
putPieceDescription p o l = traverse_ put [p, o, l]
{-# INLINABLE putPieceDescription #-}

instance Binary PWP where
  put KeepAlive =
    put (0 :: Word32)
  put Choke = do
    put (1 :: Word32)
    put (0 :: Word8)
  put Unchoke = do
    put (1 :: Word32)
    put (1 :: Word8)
  put Interested = do
    put (1 :: Word32)
    put (2 :: Word8)
  put Uninterested = do
    put (1 :: Word32)
    put (3 :: Word8)
  put (Have pieceId) = do
    put (5 :: Word32)
    put (4 :: Word8)
    put (pieceId :: Word32)
  put (Bitfield field) = do
    putWord32be $ fromIntegral $ 1 + B.length field
    put (5 :: Word8)
    putByteString field
  put (Request piece offset len) = do
    put (13 :: Word32)
    put (6 :: Word8)
    putPieceDescription piece offset len
  put (Piece piece offset d) = do
    put (fromIntegral $ 9 + B.length d :: Word32)
    put (7 :: Word8)
    put piece
    put offset
    putByteString d
  put (Cancel piece offset len) = do
    put (13 :: Word32)
    put (8 :: Word8)
    putPieceDescription piece offset len
  {-# INLINABLE put #-}

  get = do
    len <- get :: Get Word32
    case len of
      0 -> return KeepAlive
      _ -> do
        messageId <- getWord8
        case messageId of
          0 -> return Choke
          1 -> return Unchoke
          2 -> return Interested
          3 -> return Uninterested
          4 -> Have <$> get
          5 -> do
            let payloadLength = len - 1
            bytestring <- getByteString (fromIntegral payloadLength)
            return $ Bitfield bytestring
          6 -> Request <$> get <*> get <*> get
          7 -> Piece <$> get <*> get
                     <*> getByteString (fromIntegral len - 9)
          8 -> Cancel <$> get <*> get <*> get
          _ -> fail "incorrect!"
  {-# INLINABLE get #-}

-- | Encodes the BHandshake message.
data BHandshake = BHandshake
  { handshakeInfoHash :: ByteString -- ^ Info hash of the torrent
  , handshakePeerId   :: ByteString -- ^ Peer's ID
  } deriving(Show, Eq)

instance Binary BHandshake where
  put (BHandshake infoHash peerId) = do
    putWord8 (fromIntegral $ B.length protocolString)
    putByteString protocolString
    replicateM_ 8 (putWord8 0)
    putByteString infoHash
    putByteString peerId

  get = do
    protoSize <- get :: Get Word8
    replicateM_ (fromIntegral protoSize) getWord8
    skip 8
    infoHash <- getByteString 20
    peerId   <- getByteString 20
    return $ BHandshake infoHash peerId


text:
package io.github.andhikayuana.core;

import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import io.github.andhikayuana.core.login.Contact;
import io.github.andhikayuana.core.login.ContactsAdapter;
import io.github.andhikayuana.core.login.ContactsSectionedAdapter;
import io.github.andhikayuana.lib.base.BaseActivity;
import io.github.andhikayuana.lib.util.SharedPrefUtil;

public class MainActivity extends BaseActivity {

    private RecyclerView rvContact;
    private ContactsAdapter mAdapter;

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

        SharedPrefUtil.putString("tag", "Hai");

        initView();

        initData();
    }

    private void initView() {
        rvContact = (RecyclerView) findViewById(R.id.rvContact);
        rvContact.setLayoutManager(new LinearLayoutManager(this));
        rvContact.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    }

    private void initData() {
        mAdapter = new ContactsAdapter(this);
        mAdapter.addAll(Contact.generateData());

        // TODO: 7/10/17 sectioned
        //This is the code to provide a sectioned list
        List<ContactsSectionedAdapter.Section> sections =
                new ArrayList<ContactsSectionedAdapter.Section>();

        //Sections
        sections.add(new ContactsSectionedAdapter.Section(0, "Section 1"));
        sections.add(new ContactsSectionedAdapter.Section(3, "Section 2"));

        //Add your adapter to the sectionAdapter
        ContactsSectionedAdapter.Section[] dummy = new ContactsSectionedAdapter.Section[sections.size()];
        ContactsSectionedAdapter mSectionedAdapter = new
                ContactsSectionedAdapter(this, R.layout.item_section, R.id.tvSection, mAdapter);
        mSectionedAdapter.setSections(sections.toArray(dummy));

        rvContact.setAdapter(mSectionedAdapter);
    }
}


text:
"""
Created on Thu Jun 26 14:43:19 2014

@author: Kyle Ellefsen
"""
from __future__ import (absolute_import, division,print_function, unicode_literals)
from future.builtins import (bytes, dict, int, list, object, range, str, ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import pyqtgraph as pg
import pyqtgraph.exporters
import time
import os.path
import numpy as np
from skimage.io import imread, imsave
from window import Window
import global_vars as g
import codecs
import shutil, subprocess
import tifffile
import json
import re

__all__ = ['open_file_gui','open_file','save_file_gui', 'close', 'simulate_distances', 'exportMSD', 'export_distances', 'import_coords', 'export_track_lengths','set_background_image']

def open_file_gui(func, filetypes, prompt='Open File'):
    filename=g.m.filename
    if filename is not None and os.path.isfile(filename):
        filename= QFileDialog.getOpenFileName(g.m, prompt, filename, filetypes)
    else:
        filename= QFileDialog.getOpenFileName(g.m, prompt, '', filetypes)
    filename=str(filename)
    if filename != '':
        g.m.filename = filename
        func(filename)
    else:
        g.m.statusBar().showMessage('No File Selected')

def save_file_gui(func, filetypes, prompt = 'Save File'):
    filename=g.m.filename
    try:
        directory=os.path.dirname(filename)
    except:
        directory = ''
    if filename is not None and directory != '':
        filename= QFileDialog.getSaveFileName(g.m, prompt, directory, filetypes)
    else:
        filename= QFileDialog.getSaveFileName(g.m, prompt, filetypes)
    filename=str(filename)
    if filename != '':
        func(filename)
        g.m.filename = filename
    else:
        g.m.statusBar().showMessage('Save Cancelled')

def open_file(filename):
    g.m.statusBar().showMessage('Loading {}'.format(os.path.basename(filename)))
    t=time.time()
    Tiff=tifffile.TiffFile(filename)
    try:
        metadata=Tiff[0].image_description
        metadata = txt2dict(metadata)
    except AttributeError:
        metadata=dict()
    tif=Tiff.asarray()
    Tiff.close()
    if len(tif.shape)>3: # WARNING THIS TURNS COLOR movies TO BLACK AND WHITE BY AVERAGING ACROSS THE THREE CHANNELS
        if 'channels' in metadata.keys() and 'ImageJ' in metadata.keys():
            tif=np.transpose(tif,(0,3,2,1))
        tif=np.mean(tif,3)
    tif=np.squeeze(tif) #this gets rid of the meaningless 4th dimention in .stk files
    if len(tif.shape)==3: #this could either be a movie or a colored still frame
        if tif.shape[2]==3: #this is probably a colored still frame
            tif=np.mean(tif,2)
            tif=np.transpose(tif,(1,0)) # This keeps the x and y the same as in FIJI.
        else:
            tif=np.transpose(tif,(0,2,1)) # This keeps the x and y the same as in FIJI.
    elif len(tif.shape)==2: # I haven't tested whether this preserved the x y and keeps it the same as in FIJI.  TEST THIS!!
        tif=np.transpose(tif,(1,0))
    g.m.statusBar().showMessage('{} successfully loaded ({} s)'.format(os.path.basename(filename), time.time()-t))
    g.m.filename=filename
    return tif

def set_background_image(filename):
    tif = open_file(filename)
    if np.ndim(tif) == 3:
        tif = np.average(tif, 0)
    g.m.trackView.imageview.setImage(tif)

def txt2dict(metadata):
    meta=dict()
    try:
        metadata=json.loads(metadata.decode('utf-8'))
        return metadata
    except ValueError: #if the metadata isn't in JSON
        pass
    for line in metadata.splitlines():
        line=re.split('[:=]',line.decode())
        if len(line)==1:
            meta[line[0]]=''
        else:
            meta[line[0].lstrip().rstrip()]=line[1].lstrip().rstrip()
    return meta

def close(windows=None):
    '''Will close a window or a set of windows.  Takes several types as its argument:
        | 'all' (str) -- closes all windows
        | windows (list) - closes each window in the list
        | (Window) - closes individual window
        | (None) - closes current window
    '''
    if isinstance(windows,basestring):
        if windows=='all':
            windows=[window for window in g.m.windows]
            for window in windows:
                window.close()
    elif isinstance(windows,list):
        for window in windows:
            if isinstance(window,Window):
                window.close()
    elif isinstance(windows,Window):
        windows.close()
    elif windows is None:
        if g.m.currentWindow is not None:
            g.m.currentWindow.close()

def simulate_distances(filename):
    #export all distances from randomly generated XY coordinates to random Track means
    if not hasattr(g.m.trackView, 'imported'):
        print('No coordinates imported')
    g.m.statusBar().showMessage('Saving tracks to {}'.format(os.path.basename(filename)))
    coord_count = len(g.m.trackView.imported.getData()[1])
    means = g.m.trackPlot.means.getData()
    minP = (min(means[0]), min(means[1]))
    maxP = (max(means[0]), max(means[1]))
    coords = np.random.random(len(means[1]), 2) * maxP + minP
    rand_means = np.random.random(coord_count, 2) * maxP + minP
    export_distances(filenamecoords, rand_means)

def import_coords(filename):
    data = np.loadtxt(filename, skiprows=1, delimiter='\t')
    try:
        x, y = np.transpose(data)
    except:
        print('%s has more than 2 columns of values. Must import X,Y coordinates only' % filename)
    g.m.trackView.imported.setData(x=x, y=y)

def export_distances(filename, ptsA, ptsB):
    t = time.time()
    with open(filename, 'w') as outf:
        outf.write('Distances\n')
        for i, pt in enumerate(ptsA):
            for j in range(len(ptsB)):
                outf.write('%.3f\n' % np.linalg.norm(np.subtract(pt, ptsB[j])))
    g.m.statusBar().showMessage('Successfully saved simulated distances in {}'.format(time.time() - t))

def export_track_lengths(filename):
    t = time.time()
    g.m.statusBar().showMessage('Exporting Track Lengths to {}'.format(os.path.basename(filename)))
    data = np.array([tr['fr_length'] for tr in g.m.trackPlot.filtered_tracks])
    np.savetxt(filename, data, header='Frame Length', comments='', delimiter='\t')
    g.m.statusBar().showMessage('Track Lengths successfully exported ({} s)'.format(os.path.basename(filename), time.time()-t))

def exportMSD(filename):
    t = time.time()
    g.m.statusBar().showMessage('Exporting MSD to {}'.format(os.path.basename(filename)))
    d = g.m.MSDWidget.plot_data
    data = np.transpose([d['x'], d['y'], d['er']])
    np.savetxt(filename, data, header='X\tY\tError', comments='', delimiter='\t')
    g.m.statusBar().showMessage('MSD successfully exported ({} s)'.format(os.path.basename(filename), time.time()-t))