<commit_before>OUTPUT=0
INPUT=1
LOOP=2
ENDLOOP=3
MOVE=4
ADD=5
SET=6
MULCOPY=7
SCAN=8
LOADOUT=9
LOADOUTSET=10

def parse(code):
    code = ''.join(i for i in code if i in '.,[]+-<>')
    tokens = []
    for i in code:
        if i == '+':
            tokens.append((ADD, (0, 1)))
        elif i == '-':
            tokens.append((ADD, (0, -1)))
        elif i == '>':
            tokens.append((MOVE, 1))
        elif i == '<':
            tokens.append((MOVE, -1))
        elif i == '[':
            tokens.append((LOOP, None))
        elif i == ']':
            tokens.append((ENDLOOP, None))
        elif i == ',':
            tokens.append((INPUT, 1))
        if i == '.':
            tokens.append((LOADOUT, (0, 0)))
            tokens.append((OUTPUT, None))
    return tokens

def optimize(tokens):
    add = 0
    move = 0
    newtokens = []
    for token, value in tokens:
        if add and token != ADD:
            newtokens.append((ADD, (0, add)))
            add = 0
        elif move and token != MOVE:
            newtokens.append((MOVE, move))
            move = 0

        if token == ADD and value[0] == 0:
            add += value[1]
        elif token == MOVE:
            move += value
        else:
            newtokens.append((token, value))
    if add:
        newtokens.append((ADD, (0, add)))
    elif move:
        newtokens.append((MOVE, move))

    newtokens2 = []

    i = 0
    while i < len(newtokens):
        optimized = False

        # Optimize scan loop
        if (i < len(newtokens)-2 and
             newtokens[i][0] == LOOP and
             newtokens[i+1][0] == MOVE and
             newtokens[i+2][0] == ENDLOOP):

            offset = newtokens[i+1][1]
            newtokens2.append((SCAN, offset))
            optimized = True
            i += 2

        # Optimize out clear loop / multiply move loop
        if not optimized and newtokens[i][0] == LOOP:
            j = i + 1
            adds = {}
            while j < len(newtokens) and newtokens[j][0] != ENDLOOP:
                if newtokens[j][0] != ADD:
                    break
                offset, add = newtokens[j][1]
                adds[offset] = adds.get(offset, 0) + add
                j += 1
            else:
                if 0 not in adds:
                    pass
                    # print("Warning: Infinite loop detected.")
                elif len(adds) == 1:
                    newtokens2.append((SET, (0, 0)))
                    i = j - 1
                    optimized = True
                elif adds[0] == -1:
                    for k, v in adds.items():
                        if k != 0:
                            newtokens2.append((MULCOPY, (0, k, v)))
                    newtokens2.append((SET, (0, 0)))
                    i = j - 1
                    optimized = True

        # SET + ADD = SET
        if (not optimized and
             i < len(newtokens)-1 and
             newtokens[i][0] == SET and
             newtokens[i+1][0] == ADD and
             newtokens[i][1][0] == newtokens[i+1][1][0]):

            offset = newtokens[i][1][0]
            value = newtokens[i][1][1] + newtokens[i+1][1][1]
            newtokens2.append((SET, (offset, value)))
            i += 1
            optimized = True

        # Optimize MOVE + (SET/ADD) + MOVE -> (SET/ADD) + MOVE
        if (not optimized and
             i < len(newtokens)-2 and
             newtokens[i][0] == MOVE and
             newtokens[i+1][0] in (SET, ADD)):

            vals = {}
            ops = {}
            j = i + 1
            while j < len(newtokens) and newtokens[j][0] != MOVE:
                if newtokens[j][0] not in (SET, ADD):
                    break
                offset, val = newtokens[j][1]
                # ADD then SET does nothing; remove it
                if ops.get(offset) == ADD and newtokens[j][0] == SET:
                    ops.pop(offset)
                    vals.pop(offset)
                if offset not in ops:
                    ops[offset] = newtokens[j][0] # SET or ADD
                vals[offset] = vals.get(offset, 0) + val
                j += 1
            else:
                offset = newtokens[i][1]
                move = offset + newtokens[j][1]
                for k, v in vals.items():
                    opp = ops[k]
                    newtokens2.append((opp, (offset+k, v)))
                if move:
                    newtokens2.append((MOVE, move))
                i = j - 1
                optimized = True

        if (not optimized and
             i < len(newtokens)-2 and
             newtokens[i][0] in (LOADOUT, LOADOUTSET) and
             newtokens[i+1][0] == OUTPUT and
             newtokens[i+2][0] in (LOADOUT, LOADOUTSET)):

            newtokens2.append(newtokens[i])
            newtokens2.append(newtokens[i+2])
            i += 2
            optimized = True

        # Optimize ADD/MOVE + OUTPUT + ADD/MOVE
        if (not optimized and
             i < len(newtokens)-2 and
             newtokens[i][0] in (ADD, MOVE, SET) and
             newtokens[i][0] in (LOADOUT, LOADOUTSET)):
            j = i
            outputs = []
            adds = {}
            sets = {}
            shift = 0
            shifted = False
            while j < len(newtokens):
                if newtokens[j][0] == ADD:
                    offset, val = newtokens[j][1]
                    offset += shift
                    adds[offset] = adds.get(offset, 0) + val
                elif newtokens[j][0] == SET:
                    offset, val = newtokens[j][1]
                    offset += shift
                    adds[offset] = 0
                    sets[offset] = val
                elif newtokens[j][0] == LOADOUT:
                    offset, add = newtokens[j][1]
                    offset += shift
                    if offset in sets:
                        val = sets[offset] + adds.get(offset, 0) + add
                        outputs.append((None, None, val))
                    else:
                        outputs.append((offset, adds.get(offset, 0) + add, None))
                elif newtokens[j][0] == LOADOUTSET:
                    value = newtokens[j][1]
                    outputs.append((None, None, value))
                elif newtokens[j][0] == MOVE:
                    shift += newtokens[j][1]
                    shifted = True
                elif newtokens[j][0] == OUTPUT:
                    pass
                else:
                    j -= 1
                    break
                j += 1
            if (adds or shifted or sets) and outputs:
                for offset, add, _set in outputs:
                    if _set is not None:
                        newtokens2.append((LOADOUTSET, _set))
                    else:
                        newtokens2.append((LOADOUT, (offset, add)))
                newtokens2.append((OUTPUT, None))
                for offset, val in sets.items():
                    val = val + adds.get(offset, 0)
                    newtokens2.append((SET, (offset, val)))
                for offset, add in adds.items():
                    if add and (offset not in sets):
                        newtokens2.append((ADD, (offset, add)))
                if shift:
                    newtokens2.append((MOVE, shift))
                i = j
                optimized = True

        if not optimized:
            newtokens2.append(newtokens[i])

        i += 1

    # Optimize recursively
    print(1)
    if newtokens2 != tokens:
        return optimize(newtokens2)

    return newtokens2
<commit_msg>Remove incorrect and (now) unneeded(?) test<commit_after>OUTPUT=0
INPUT=1
LOOP=2
ENDLOOP=3
MOVE=4
ADD=5
SET=6
MULCOPY=7
SCAN=8
LOADOUT=9
LOADOUTSET=10

def parse(code):
    code = ''.join(i for i in code if i in '.,[]+-<>')
    tokens = []
    for i in code:
        if i == '+':
            tokens.append((ADD, (0, 1)))
        elif i == '-':
            tokens.append((ADD, (0, -1)))
        elif i == '>':
            tokens.append((MOVE, 1))
        elif i == '<':
            tokens.append((MOVE, -1))
        elif i == '[':
            tokens.append((LOOP, None))
        elif i == ']':
            tokens.append((ENDLOOP, None))
        elif i == ',':
            tokens.append((INPUT, 1))
        if i == '.':
            tokens.append((LOADOUT, (0, 0)))
            tokens.append((OUTPUT, None))
    return tokens

def optimize(tokens):
    add = 0
    move = 0
    newtokens = []
    for token, value in tokens:
        if add and token != ADD:
            newtokens.append((ADD, (0, add)))
            add = 0
        elif move and token != MOVE:
            newtokens.append((MOVE, move))
            move = 0

        if token == ADD and value[0] == 0:
            add += value[1]
        elif token == MOVE:
            move += value
        else:
            newtokens.append((token, value))
    if add:
        newtokens.append((ADD, (0, add)))
    elif move:
        newtokens.append((MOVE, move))

    newtokens2 = []

    i = 0
    while i < len(newtokens):
        optimized = False

        # Optimize scan loop
        if (i < len(newtokens)-2 and
             newtokens[i][0] == LOOP and
             newtokens[i+1][0] == MOVE and
             newtokens[i+2][0] == ENDLOOP):

            offset = newtokens[i+1][1]
            newtokens2.append((SCAN, offset))
            optimized = True
            i += 2

        # Optimize out clear loop / multiply move loop
        if not optimized and newtokens[i][0] == LOOP:
            j = i + 1
            adds = {}
            while j < len(newtokens) and newtokens[j][0] != ENDLOOP:
                if newtokens[j][0] != ADD:
                    break
                offset, add = newtokens[j][1]
                adds[offset] = adds.get(offset, 0) + add
                j += 1
            else:
                if 0 not in adds:
                    pass
                    # print("Warning: Infinite loop detected.")
                elif len(adds) == 1:
                    newtokens2.append((SET, (0, 0)))
                    i = j - 1
                    optimized = True
                elif adds[0] == -1:
                    for k, v in adds.items():
                        if k != 0:
                            newtokens2.append((MULCOPY, (0, k, v)))
                    newtokens2.append((SET, (0, 0)))
                    i = j - 1
                    optimized = True

        # SET + ADD = SET
        if (not optimized and
             i < len(newtokens)-1 and
             newtokens[i][0] == SET and
             newtokens[i+1][0] == ADD and
             newtokens[i][1][0] == newtokens[i+1][1][0]):

            offset = newtokens[i][1][0]
            value = newtokens[i][1][1] + newtokens[i+1][1][1]
            newtokens2.append((SET, (offset, value)))
            i += 1
            optimized = True

        # Optimize MOVE + (SET/ADD) + MOVE -> (SET/ADD) + MOVE
        if (not optimized and
             i < len(newtokens)-2 and
             newtokens[i][0] == MOVE and
             newtokens[i+1][0] in (SET, ADD)):

            vals = {}
            ops = {}
            j = i + 1
            while j < len(newtokens) and newtokens[j][0] != MOVE:
                if newtokens[j][0] not in (SET, ADD):
                    break
                offset, val = newtokens[j][1]
                # ADD then SET does nothing; remove it
                if ops.get(offset) == ADD and newtokens[j][0] == SET:
                    ops.pop(offset)
                    vals.pop(offset)
                if offset not in ops:
                    ops[offset] = newtokens[j][0] # SET or ADD
                vals[offset] = vals.get(offset, 0) + val
                j += 1
            else:
                offset = newtokens[i][1]
                move = offset + newtokens[j][1]
                for k, v in vals.items():
                    opp = ops[k]
                    newtokens2.append((opp, (offset+k, v)))
                if move:
                    newtokens2.append((MOVE, move))
                i = j - 1
                optimized = True

        if (not optimized and
             i < len(newtokens)-2 and
             newtokens[i][0] in (LOADOUT, LOADOUTSET) and
             newtokens[i+1][0] == OUTPUT and
             newtokens[i+2][0] in (LOADOUT, LOADOUTSET)):

            newtokens2.append(newtokens[i])
            newtokens2.append(newtokens[i+2])
            i += 2
            optimized = True

        # Optimize ADD/MOVE + OUTPUT + ADD/MOVE
        if (not optimized and
             i < len(newtokens)-2 and
             newtokens[i][0] in (ADD, MOVE, SET)):
            j = i
            outputs = []
            adds = {}
            sets = {}
            shift = 0
            shifted = False
            while j < len(newtokens):
                if newtokens[j][0] == ADD:
                    offset, val = newtokens[j][1]
                    offset += shift
                    adds[offset] = adds.get(offset, 0) + val
                elif newtokens[j][0] == SET:
                    offset, val = newtokens[j][1]
                    offset += shift
                    adds[offset] = 0
                    sets[offset] = val
                elif newtokens[j][0] == LOADOUT:
                    offset, add = newtokens[j][1]
                    offset += shift
                    if offset in sets:
                        val = sets[offset] + adds.get(offset, 0) + add
                        outputs.append((None, None, val))
                    else:
                        outputs.append((offset, adds.get(offset, 0) + add, None))
                elif newtokens[j][0] == LOADOUTSET:
                    value = newtokens[j][1]
                    outputs.append((None, None, value))
                elif newtokens[j][0] == MOVE:
                    shift += newtokens[j][1]
                    shifted = True
                elif newtokens[j][0] == OUTPUT:
                    pass
                else:
                    j -= 1
                    break
                j += 1
            if (adds or shifted or sets) and outputs:
                for offset, add, _set in outputs:
                    if _set is not None:
                        newtokens2.append((LOADOUTSET, _set))
                    else:
                        newtokens2.append((LOADOUT, (offset, add)))
                newtokens2.append((OUTPUT, None))
                for offset, val in sets.items():
                    val = val + adds.get(offset, 0)
                    newtokens2.append((SET, (offset, val)))
                for offset, add in adds.items():
                    if add and (offset not in sets):
                        newtokens2.append((ADD, (offset, add)))
                if shift:
                    newtokens2.append((MOVE, shift))
                i = j
                optimized = True

        if not optimized:
            newtokens2.append(newtokens[i])

        i += 1

    # Optimize recursively
    print(1)
    if newtokens2 != tokens:
        return optimize(newtokens2)

    return newtokens2
<|endoftext|>


<commit_before># Copyright (c) 2020 Ian C. Good
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

from setuptools import setup, find_packages

with open('README.md') as f:
    readme = f.read()

with open('LICENSE.md') as f:
    license = f.read()

setup(name='pymap',
      version='0.24.7',
      author='Ian Good',
      author_email='ian@icgood.net',
      description='Lightweight, asynchronous IMAP serving in Python.',
      long_description=readme + license,
      long_description_content_type='text/markdown',
      license='MIT',
      url='https://github.com/icgood/pymap/',
      classifiers=[
          'Development Status :: 3 - Alpha',
          'Topic :: Communications :: Email :: Post-Office',
          'Topic :: Communications :: Email :: Post-Office :: IMAP',
          'Intended Audience :: Developers',
          'Intended Audience :: Information Technology',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python',
          'Programming Language :: Python :: 3.9'],
      python_requires='~=3.9',
      include_package_data=True,
      packages=find_packages(),
      install_requires=[
          'pysasl ~= 0.8.0',
          'proxy-protocol ~= 0.7.0'],
      extras_require={
          'admin': ['pymap-admin ~= 0.7.0', 'googleapis-common-protos'],
          'macaroon': ['pymacaroons'],
          'redis': ['aioredis ~= 1.3.1', 'msgpack ~= 1.0'],
          'sieve': ['sievelib'],
          'swim': ['swim-protocol ~= 0.3.8'],
          'systemd': ['systemd-python'],
          'optional': ['hiredis', 'passlib', 'pid']},
      entry_points={
          'console_scripts': [
              'pymap = pymap.main:main'],
          'pymap.backend': [
              'dict = pymap.backend.dict:DictBackend',
              'maildir = pymap.backend.maildir:MaildirBackend',
              'redis = pymap.backend.redis:RedisBackend [redis]'],
          'pymap.service': [
              'imap = pymap.imap:IMAPService',
              'admin = pymap.admin:AdminService [admin]',
              'managesieve = pymap.sieve.manage:ManageSieveService [sieve]',
              'swim = pymap.cluster.swim:SwimService [swim]'],
          'pymap.filter': [
              'sieve = pymap.sieve:SieveCompiler [sieve]'],
          'pymap.token': [
              'macaroon = pymap.token.macaroon:MacaroonTokens [macaroon]'],
          'pymap.admin.handlers': [
              'server = pymap.admin.handlers.system:SystemHandlers',
              'mailbox = pymap.admin.handlers.mailbox:MailboxHandlers',
              'user = pymap.admin.handlers.user:UserHandlers']})
<commit_msg>Set version 0.25.0<commit_after># Copyright (c) 2020 Ian C. Good
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

from setuptools import setup, find_packages

with open('README.md') as f:
    readme = f.read()

with open('LICENSE.md') as f:
    license = f.read()

setup(name='pymap',
      version='0.25.0',
      author='Ian Good',
      author_email='ian@icgood.net',
      description='Lightweight, asynchronous IMAP serving in Python.',
      long_description=readme + license,
      long_description_content_type='text/markdown',
      license='MIT',
      url='https://github.com/icgood/pymap/',
      classifiers=[
          'Development Status :: 3 - Alpha',
          'Topic :: Communications :: Email :: Post-Office',
          'Topic :: Communications :: Email :: Post-Office :: IMAP',
          'Intended Audience :: Developers',
          'Intended Audience :: Information Technology',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python',
          'Programming Language :: Python :: 3.9'],
      python_requires='~=3.9',
      include_package_data=True,
      packages=find_packages(),
      install_requires=[
          'pysasl ~= 0.8.0',
          'proxy-protocol ~= 0.7.0'],
      extras_require={
          'admin': ['pymap-admin ~= 0.7.0', 'googleapis-common-protos'],
          'macaroon': ['pymacaroons'],
          'redis': ['aioredis ~= 1.3.1', 'msgpack ~= 1.0'],
          'sieve': ['sievelib'],
          'swim': ['swim-protocol ~= 0.3.8'],
          'systemd': ['systemd-python'],
          'optional': ['hiredis', 'passlib', 'pid']},
      entry_points={
          'console_scripts': [
              'pymap = pymap.main:main'],
          'pymap.backend': [
              'dict = pymap.backend.dict:DictBackend',
              'maildir = pymap.backend.maildir:MaildirBackend',
              'redis = pymap.backend.redis:RedisBackend [redis]'],
          'pymap.service': [
              'imap = pymap.imap:IMAPService',
              'admin = pymap.admin:AdminService [admin]',
              'managesieve = pymap.sieve.manage:ManageSieveService [sieve]',
              'swim = pymap.cluster.swim:SwimService [swim]'],
          'pymap.filter': [
              'sieve = pymap.sieve:SieveCompiler [sieve]'],
          'pymap.token': [
              'macaroon = pymap.token.macaroon:MacaroonTokens [macaroon]'],
          'pymap.admin.handlers': [
              'server = pymap.admin.handlers.system:SystemHandlers',
              'mailbox = pymap.admin.handlers.mailbox:MailboxHandlers',
              'user = pymap.admin.handlers.user:UserHandlers']})
<|endoftext|>


<commit_before>#! /usr/bin/env python

from __future__ import print_function

import re
import sys
import warnings

class Instruction:
	"""Class that represents a twttr instruction."""

	def __init__(self, instruction):
		match = re.match(r"([a-zA-Z]+): (.+)", instruction)

		if match == None:
			raise ValueError('Instruction is not valid format of "author: status"')

		self.author = match.group(1)
		self.status = match.group(2)

		if len(self.status) > 140:
			raise ValueError('Tweet must be less than or equal to 140 characters')

		self.hashtags = self.extract_hashtags();

	def extract_hashtags(self):
		"""Extracts the hashtags (#tag) from the status."""
		return re.findall(r"#([A-Za-z]+)", self.status)

	def remove_hashtags(self):
		"""Return the status of any hashtags."""
		return re.sub(r"#[A-Za-z]+", "", self.status).strip()

	def value(self):
		"""Read the value of the status based on the number of words in the first two sentences."""
		fragments = re.findall(r"([A-Za-z '-]+)[\.,!;\?:-] ?", self.status)

		if len(fragments) == 1:
			return self.__count_words(fragments[0])

		return self.__count_words(fragments[0]) - self.__count_words(fragments[1])

	def is_input(self):
		"""Detects whether the instruction is asking for input."""
		return self.remove_hashtags()[-1] == '?'

	def is_output(self):
		"""Detects whether the instruction is a print."""
		return self.remove_hashtags()[-1] == '!'

	def __count_words(self, string):
		"""Count the number of words in a string."""
		return len(re.findall(r"([A-Za-z\.\"-']+) ?", string))

class Parser:
	"""Class that parses a twttr program."""

	def __init__(self, file):
		self.instructions = []
		self.variables = {}

		with open(file, 'r') as f:
			for line in f:
				self.instructions.append(Instruction(line))

		self.hashtags = {}

		for i in reversed(range(len(self.instructions))):
			instruction = self.instructions[i]

			for hashtag in instruction.extract_hashtags():
				if hashtag in self.hashtags:
					self.hashtags[hashtag].append(i)
				else:
					self.hashtags[hashtag] = [i]

	def run(self, debug=True):
		looping = False

		pc = len(self.instructions) - 1
		while pc >= 0:
			instruction = self.instructions[pc]

			if instruction.author not in self.variables:
				self.variables[instruction.author] = 0

			self.variables[instruction.author] += instruction.value()

			if instruction.is_input():
				input = raw_input(instruction.status + " ")

				if len(input) > 0:
					self.variables[instruction.author] += ord(input[0])
			elif instruction.is_output():
				if debug:
					print("%s" % chr(self.variables[instruction.author]))
				else:
					print("%s" % chr(self.variables[instruction.author]), end='')

			if debug:
				print("PC = %d %s", pc, self.variables)

			hashtags = instruction.extract_hashtags()

			if len(hashtags) > 0:
				for hashtag in hashtags:
					if len(self.hashtags[hashtag]) > 0:
						# Found a hashtag that has more than one instance
						indices = self.hashtags[hashtag]

						current_index = indices.index(pc)

						if current_index == len(indices) - 1:
							# Currently at the last instance of this hashtag
							if self.variables[instruction.author] != 0:
								pc = indices[0]
								looping = True
							else:
								looping = False
						else:
							# Not at the last instance of this hashtag
							if looping:
								pc = indices[current_index + 1]

						break

			if not looping:
				pc -= 1

		print()

def main():
	parser = Parser(sys.argv[1])

	parser.run(True)

if __name__ =='__main__':
	main()<commit_msg>Make debugging false on run() by default.<commit_after>#! /usr/bin/env python

from __future__ import print_function

import re
import sys
import warnings

class Instruction:
	"""Class that represents a twttr instruction."""

	def __init__(self, instruction):
		match = re.match(r"([a-zA-Z]+): (.+)", instruction)

		if match == None:
			raise ValueError('Instruction is not valid format of "author: status"')

		self.author = match.group(1)
		self.status = match.group(2)

		if len(self.status) > 140:
			raise ValueError('Tweet must be less than or equal to 140 characters')

		self.hashtags = self.extract_hashtags();

	def extract_hashtags(self):
		"""Extracts the hashtags (#tag) from the status."""
		return re.findall(r"#([A-Za-z]+)", self.status)

	def remove_hashtags(self):
		"""Return the status of any hashtags."""
		return re.sub(r"#[A-Za-z]+", "", self.status).strip()

	def value(self):
		"""Read the value of the status based on the number of words in the first two sentences."""
		fragments = re.findall(r"([A-Za-z '-]+)[\.,!;\?:-] ?", self.status)

		if len(fragments) == 1:
			return self.__count_words(fragments[0])

		return self.__count_words(fragments[0]) - self.__count_words(fragments[1])

	def is_input(self):
		"""Detects whether the instruction is asking for input."""
		return self.remove_hashtags()[-1] == '?'

	def is_output(self):
		"""Detects whether the instruction is a print."""
		return self.remove_hashtags()[-1] == '!'

	def __count_words(self, string):
		"""Count the number of words in a string."""
		return len(re.findall(r"([A-Za-z\.\"-']+) ?", string))

class Parser:
	"""Class that parses a twttr program."""

	def __init__(self, file):
		self.instructions = []
		self.variables = {}

		with open(file, 'r') as f:
			for line in f:
				self.instructions.append(Instruction(line))

		self.hashtags = {}

		for i in reversed(range(len(self.instructions))):
			instruction = self.instructions[i]

			for hashtag in instruction.extract_hashtags():
				if hashtag in self.hashtags:
					self.hashtags[hashtag].append(i)
				else:
					self.hashtags[hashtag] = [i]

	def run(self, debug=False):
		looping = False

		pc = len(self.instructions) - 1
		while pc >= 0:
			instruction = self.instructions[pc]

			if instruction.author not in self.variables:
				self.variables[instruction.author] = 0

			self.variables[instruction.author] += instruction.value()

			if instruction.is_input():
				input = raw_input(instruction.status + " ")

				if len(input) > 0:
					self.variables[instruction.author] += ord(input[0])
			elif instruction.is_output():
				if debug:
					print("%s" % chr(self.variables[instruction.author]))
				else:
					print("%s" % chr(self.variables[instruction.author]), end='')

			if debug:
				print("PC = %d %s", pc, self.variables)

			hashtags = instruction.extract_hashtags()

			if len(hashtags) > 0:
				for hashtag in hashtags:
					if len(self.hashtags[hashtag]) > 0:
						# Found a hashtag that has more than one instance
						indices = self.hashtags[hashtag]

						current_index = indices.index(pc)

						if current_index == len(indices) - 1:
							# Currently at the last instance of this hashtag
							if self.variables[instruction.author] != 0:
								pc = indices[0]
								looping = True
							else:
								looping = False
						else:
							# Not at the last instance of this hashtag
							if looping:
								pc = indices[current_index + 1]

						break

			if not looping:
				pc -= 1

		print()

def main():
	parser = Parser(sys.argv[1])

	parser.run()

if __name__ =='__main__':
	main()<|endoftext|>


<commit_before>import os
from setuptools import find_packages, setup

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-keybase-verification',
    version='1.0.6',
    packages=find_packages(),
    include_package_data=True,
    license='MIT License',
    description='A simple Django app to make Keybase.io verification easy.',
    long_description=README,
    url='https://www.bsquidwrd.com/',
    author='bsquidwrd',
    author_email='pypi@bsquidwrd.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.10',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)
<commit_msg>Changed the website to be the github page instead of a broken link to my website<commit_after>import os
from setuptools import find_packages, setup

with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='django-keybase-verification',
    version='1.0.6',
    packages=find_packages(),
    include_package_data=True,
    license='MIT License',
    description='A simple Django app to make Keybase.io verification easy.',
    long_description=README,
    url='https://github.com/bsquidwrd/django-keybase-verification',
    author='bsquidwrd',
    author_email='pypi@bsquidwrd.com',
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.10',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)
<|endoftext|>


<commit_before>from setuptools import find_packages, setup
import os
import re

PACKAGE = 'APITaxi'

DEPENDENCIES = [
    'werkzeug<=0.16.1'
    'APITaxi_utils',
    'APITaxi_models',
    'Cython',
    'nose',
    'Flask-Testing',
    'Flask-Redis',
    'Flask-Celery-Helper',
    'Flask-Cors',
    'psycopg2',
    'geopy',
    'Flask-Uploads',
    'Flask-Script',
    'Flask-Migrate',
    'Shapely',
    'pyshp',
    'bcrypt',
    'Geohash2',
    'redis',
]

def get_pkgvar(name):
    """Get the value of :param name: from __init__.py.

    The package cannot be imported since dependencies might not be installed
    yet."""
    here = os.path.abspath(os.path.dirname(__file__))
    init_path = os.path.join(here, PACKAGE, '__init__.py')

    # Cache file content into get_pkgvar.init_content to avoid reading the
    # __init__.py file several times.
    if not hasattr(get_pkgvar, 'init_content'):
        with open(init_path) as handle:
            get_pkgvar.init_content = handle.read().splitlines()

    for line in get_pkgvar.init_content:
        res = re.search(r'^%s\s*=\s*["\'](.*)["\']' % name, line)
        if res:
            return res.groups()[0]

    raise ValueError('%s not found in %s' % (name, init_path))

setup(
    name=PACKAGE,
    version=get_pkgvar('__version__'),
    description=get_pkgvar('__doc__'),
    url=get_pkgvar('__homepage__'),
    author=get_pkgvar('__author__'),
    author_email=get_pkgvar('__contact__'),
    license='MIT',
    classifiers=[
        'Development Status :: 4 Beta',
        'Intended Audience :: Developpers',
        'Programming Language :: Python :: 3'
    ],
    keywords='taxi transportation',
    packages=find_packages(),
    install_requires=DEPENDENCIES
)
<commit_msg>Add missing dependency on email-validator<commit_after>from setuptools import find_packages, setup
import os
import re

PACKAGE = 'APITaxi'

DEPENDENCIES = [
    'werkzeug<=0.16.1'
    'APITaxi_utils',
    'APITaxi_models',
    'Cython',
    'nose',
    'Flask-Testing',
    'Flask-Redis',
    'Flask-Celery-Helper',
    'Flask-Cors',
    'psycopg2',
    'geopy',
    'Flask-Uploads',
    'Flask-Script',
    'Flask-Migrate',
    'Shapely',
    'pyshp',
    'bcrypt',
    'Geohash2',
    'redis',
    'email-validator',
]

def get_pkgvar(name):
    """Get the value of :param name: from __init__.py.

    The package cannot be imported since dependencies might not be installed
    yet."""
    here = os.path.abspath(os.path.dirname(__file__))
    init_path = os.path.join(here, PACKAGE, '__init__.py')

    # Cache file content into get_pkgvar.init_content to avoid reading the
    # __init__.py file several times.
    if not hasattr(get_pkgvar, 'init_content'):
        with open(init_path) as handle:
            get_pkgvar.init_content = handle.read().splitlines()

    for line in get_pkgvar.init_content:
        res = re.search(r'^%s\s*=\s*["\'](.*)["\']' % name, line)
        if res:
            return res.groups()[0]

    raise ValueError('%s not found in %s' % (name, init_path))

setup(
    name=PACKAGE,
    version=get_pkgvar('__version__'),
    description=get_pkgvar('__doc__'),
    url=get_pkgvar('__homepage__'),
    author=get_pkgvar('__author__'),
    author_email=get_pkgvar('__contact__'),
    license='MIT',
    classifiers=[
        'Development Status :: 4 Beta',
        'Intended Audience :: Developpers',
        'Programming Language :: Python :: 3'
    ],
    keywords='taxi transportation',
    packages=find_packages(),
    install_requires=DEPENDENCIES
)
<|endoftext|>


<commit_before>#! /user/bin/env python3
#
# Copycenter [2015-08-06], ISC, [Ampling]

import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("entry", help="Sends the protected entry to Xclip",
            type=str)
    args = parser.parse_args()

    entry_list = list(str(args.entry))
    entry_count = (len(entry_list))

    print(entry_list[entry_count - 1])

if __name__ == '__main__':
    main()
<commit_msg>new funtions: loop, clip<commit_after>#! /user/bin/env python3
#
# Copycenter [2015-08-06], ISC, [Ampling]

import argparse
from glob import glob
import subprocess
import os
import sys

# CONFIG
PASSWORD_STORE_DIR = '.password-store/'

# global veriables
home = os.path.expanduser("~")
store = home + "/" + PASSWORD_STORE_DIR

#loop
def loop(): #{
    global entry_list
    for file in entry_list:
        global path
        names = glob(store+"/"+file+"*")
        global name
        name = names[0]
        clip()
#}

# shell magic
def clip(): #{
    global store
    global name
    afile = name.replace(store, '', 1)
    os.environ['afile'] = afile
    print(afile)
    #subprocess.call('pass $afile | xclip -l 1 -quiet -selection clipboard',shell=True)
#}

# Define Options
def main(): #{
    parser = argparse.ArgumentParser(description='Select some files')
    parser.add_argument("entry", help="Sends the entry to Xclip",
            type=str)
    #parser.add_argument("path", "path",help="path/to/file",
    #        type=str)
    args = parser.parse_args()

    global entry_list
    entry_list = list(str(args.entry))

    #entry_count = (len(entry_list))
    #print(entry_list[entry_count - 1])
#}

if __name__ == '__main__':
    main()
    loop()
<|endoftext|>


<commit_before>from setuptools import setup

setup(
    name='urlwait',
    version='1.0',
    description='A CLI utility for blocking until a service is listening',
    long_description=open('README.rst').read(),
    author='Paul McLanahan',
    author_email='paul@mclanahan.net',
    license='MIT',
    py_modules=['urlwait'],
    entry_points={
        'console_scripts': ['urlwait = urlwait:main'],
    },
    url='https://github.com/pmac/urlwait',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Topic :: System :: Systems Administration'
    ],
    keywords=['database_url', 'tcp', 'port', 'docker', 'service',
              'deploy', 'deployment'],
)
<commit_msg>Upgrade the Development Status classifier to stable<commit_after>from setuptools import setup

setup(
    name='urlwait',
    version='1.0',
    description='A CLI utility for blocking until a service is listening',
    long_description=open('README.rst').read(),
    author='Paul McLanahan',
    author_email='paul@mclanahan.net',
    license='MIT',
    py_modules=['urlwait'],
    entry_points={
        'console_scripts': ['urlwait = urlwait:main'],
    },
    url='https://github.com/pmac/urlwait',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Topic :: System :: Systems Administration'
    ],
    keywords=['database_url', 'tcp', 'port', 'docker', 'service',
              'deploy', 'deployment'],
)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# This file is part of Tumulus.
#
# Copyright (C) 2013 OKso (http://okso.me)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from setuptools import setup

setup(name='Tumulus',
      version='0.1',
      description='Python HTML Generator; Goodbye Templates',
      author='OKso.me',
      author_email='@okso.me',
      url='https://github.com/oksome/Tumulus/',
      packages=['tumulus'],
      install_requires=['beautifulsoup4'],
      license='AGPLv3',
      keywords="html generator template templating engine",
      classifiers=['Development Status :: 3 - Alpha',
                   'Environment :: Web Environment',
                   'Programming Language :: Python :: 3',
                   'Operating System :: POSIX',
                   'Operating System :: POSIX :: Linux',
                   'Operating System :: MacOS :: MacOS X',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: GNU Affero General Public License v3',
                   'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
                   'Topic :: Software Development :: Code Generators',
                   'Topic :: Software Development :: Libraries :: Python Modules',
                   'Topic :: Text Processing :: Markup :: HTML '
                   ],
      )
<commit_msg>Updated long_description<commit_after># -*- coding: utf-8 -*-

# This file is part of Tumulus.
#
# Copyright (C) 2013 OKso (http://okso.me)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from setuptools import setup

setup(name='Tumulus',
      version='0.1',
      description='Python HTML Generator for Recyclable Web Elements',
      long_description=open('README.md').read(),
      author='OKso.me',
      author_email='@okso.me',
      url='https://github.com/oksome/Tumulus/',
      packages=['tumulus'],
      install_requires=['beautifulsoup4'],
      license='AGPLv3',
      keywords="html generator template templating engine",
      classifiers=['Development Status :: 3 - Alpha',
                   'Environment :: Web Environment',
                   'Programming Language :: Python :: 3',
                   'Operating System :: POSIX',
                   'Operating System :: POSIX :: Linux',
                   'Operating System :: MacOS :: MacOS X',
                   'Intended Audience :: Developers',
                   'License :: OSI Approved :: GNU Affero General Public License v3',
                   'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
                   'Topic :: Software Development :: Code Generators',
                   'Topic :: Software Development :: Libraries :: Python Modules',
                   'Topic :: Text Processing :: Markup :: HTML '
                   ],
      )
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='flask-appconfig',
    version='0.10.1.dev1',
    description=('Configures Flask applications in a canonical way. Also auto-'
                 'configures Heroku. Aims to standardize configuration.'),
    long_description=read('README.rst'),
    author='Marc Brinkmann',
    author_email='git@marcbrinkmann.de',
    url='http://github.com/mbr/flask-appconfig',
    license='MIT',
    packages=find_packages(exclude=['tests']),
    install_requires=['flask', 'six', 'click'],
    entry_points={
        'console_scripts': [
            'flaskdev = flask_appconfig.cli:main',
        ],
    },
    classifiers=[
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ]
)
<commit_msg>Start developing version 0.10.2.dev1 (after release of 0.10.1)<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

from setuptools import setup, find_packages

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='flask-appconfig',
    version='0.10.2.dev1',
    description=('Configures Flask applications in a canonical way. Also auto-'
                 'configures Heroku. Aims to standardize configuration.'),
    long_description=read('README.rst'),
    author='Marc Brinkmann',
    author_email='git@marcbrinkmann.de',
    url='http://github.com/mbr/flask-appconfig',
    license='MIT',
    packages=find_packages(exclude=['tests']),
    install_requires=['flask', 'six', 'click'],
    entry_points={
        'console_scripts': [
            'flaskdev = flask_appconfig.cli:main',
        ],
    },
    classifiers=[
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ]
)
<|endoftext|>


<commit_before>#!/usr/bin/env python

# Copyright 2012, Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import setuptools
import sys

from rackspace import info

if sys.version_info < (2, 6, 0):
    sys.stderr.write("This requires Python 2.6.0 or greater \n")
    sys.exit('\nUpgrade python because you version of it is VERY deprecated\n')

with open('README', 'rb') as r_file:
    LDINFO = r_file.read()

setuptools.setup(
    name=info.__appname__,
    version=info.__version__,
    author=info.__author__,
    author_email=info.__email__,
    description=info.__description__,
    long_description=LDINFO,
    license='Apache2',
    packages=['rackspace',
              'rackspace.heat_store',
              'rackspace.heat_store.catalog'],
    package_data={'rackspace': ['static/rackspace/img/*',
                                'static/rackspace/css/*',
                                'static/rackspace/scss/*',
                                'static/rackspace/js/*',
                                'templates/*.html',
                                'templates/rackspace/*.html',
                                'templates/rackspace/heat_store/*']},
    url=info.__url__,
    install_requires=['Markdown'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Information Technology',
        'Intended Audience :: System Administrators',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content']
)
<commit_msg>Fix typo<commit_after>#!/usr/bin/env python

# Copyright 2012, Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import setuptools
import sys

from rackspace import info

if sys.version_info < (2, 6, 0):
    sys.stderr.write("This requires Python 2.6.0 or greater \n")
    sys.exit('\nUpgrade python because your version of it is VERY deprecated\n')

with open('README', 'rb') as r_file:
    LDINFO = r_file.read()

setuptools.setup(
    name=info.__appname__,
    version=info.__version__,
    author=info.__author__,
    author_email=info.__email__,
    description=info.__description__,
    long_description=LDINFO,
    license='Apache2',
    packages=['rackspace',
              'rackspace.heat_store',
              'rackspace.heat_store.catalog'],
    package_data={'rackspace': ['static/rackspace/img/*',
                                'static/rackspace/css/*',
                                'static/rackspace/scss/*',
                                'static/rackspace/js/*',
                                'templates/*.html',
                                'templates/rackspace/*.html',
                                'templates/rackspace/heat_store/*']},
    url=info.__url__,
    install_requires=['Markdown'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Information Technology',
        'Intended Audience :: System Administrators',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content']
)
<|endoftext|>


<commit_before>#
# Upload to pypi:
#   python setup.py sdist bdist_wheel
#   twine upload dist/*
#
#   To use these commands install wheel and twine
#   pip install wheel twine
#
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup
import os
import io
import itertools
import re
import ast

_version_re = re.compile(r'__version__\s+=\s+(.*)')
_license_re = re.compile(r'__license__\s+=\s+(.*)')
_author_re = re.compile(r'__author__\s+=\s+(.*)')
line_numbers = 20

with io.open('femagtools/__init__.py', 'r') as f:
    meta_data = list(itertools.islice(f, line_numbers))
meta_data = ''.join(meta_data)

version = str(ast.literal_eval(_version_re.search(meta_data).group(1)))
license = str(ast.literal_eval(_license_re.search(meta_data).group(1)))
author = str(ast.literal_eval(_author_re.search(meta_data).group(1)))

here = os.path.abspath(os.path.dirname(__file__))
# Get the long description from the README file
with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    description='Femag Tools: a Python API for FEMAG',
    long_description=long_description,
    author=author,
    url='https://github.com/SEMAFORInformatik/femagtools',
    author_email='tar@semafor.ch',
    version=version,
    install_requires=['numpy', 'scipy', 'mako'],
    packages=['femagtools', 'femagtools.moo'],
    package_data={'femagtools': ['templates/*.mako']},
    license=license,
    name='femagtools',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Topic :: Scientific/Engineering']
)

<commit_msg>3,5, 3.6 added<commit_after>#
# Upload to pypi:
#   python setup.py sdist bdist_wheel
#   twine upload dist/*
#
#   To use these commands install wheel and twine
#   pip install wheel twine
#
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup
import os
import io
import itertools
import re
import ast

_version_re = re.compile(r'__version__\s+=\s+(.*)')
_license_re = re.compile(r'__license__\s+=\s+(.*)')
_author_re = re.compile(r'__author__\s+=\s+(.*)')
line_numbers = 20

with io.open('femagtools/__init__.py', 'r') as f:
    meta_data = list(itertools.islice(f, line_numbers))
meta_data = ''.join(meta_data)

version = str(ast.literal_eval(_version_re.search(meta_data).group(1)))
license = str(ast.literal_eval(_license_re.search(meta_data).group(1)))
author = str(ast.literal_eval(_author_re.search(meta_data).group(1)))

here = os.path.abspath(os.path.dirname(__file__))
# Get the long description from the README file
with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    description='Femag Tools: a Python API for FEMAG',
    long_description=long_description,
    author=author,
    url='https://github.com/SEMAFORInformatik/femagtools',
    author_email='tar@semafor.ch',
    version=version,
    install_requires=['numpy', 'scipy', 'mako'],
    packages=['femagtools', 'femagtools.moo'],
    package_data={'femagtools': ['templates/*.mako']},
    license=license,
    name='femagtools',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Topic :: Scientific/Engineering']
)

<|endoftext|>


<commit_before>#!/usr/bin/env python

from distutils.core import setup

setup(
    name='hashable',
    version='1.0',
    description='Creates a __hash__ method',
    author='Karataev Pavel',
    author_email='karataev.pavel@gmail.com',
    url='https://github.com/minmax/hashable',
)
<commit_msg>Migrate setup.py to setuptools<commit_after>#!/usr/bin/env python

from setuptools import setup, find_packages

setup(
    name='hashable',
    version='0.1',
    description='Allow objects to be hashable and comparable by attributes',
    author='Karataev Pavel',
    author_email='karataev.pavel@gmail.com',
    url='https://github.com/minmax/hashable',
    license='MIT',
    packages=find_packages(),
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)
<|endoftext|>


<commit_before>#!/usr/bin/env python

import argparse
import logging
import sys

import pebble.PblAnalytics as PblAnalytics

# Catch any missing python dependencies so we can send an event to analytics
try:
    # NOTE: Even though we don't use websocket in this module, keep this
    #  import here for the unit tests so that they can trigger a missing
    #  python dependency event.
    import websocket
    import pebble as libpebble
    from pebble.PblProjectCreator   import (PblProjectCreator,
                                            InvalidProjectException,
                                            OutdatedProjectException)
    from pebble.PblProjectConverter import PblProjectConverter
    from pebble.PblBuildCommand     import (PblBuildCommand,
                                            PblCleanCommand,
                                            PblAnalyzeSizeCommand)
    from pebble.LibPebblesCommand   import *
except Exception as e:
    logging.basicConfig(format='[%(levelname)-8s] %(message)s',
                    level = logging.DEBUG)
    PblAnalytics.missing_python_dependency_evt(str(e))
    raise

class PbSDKShell:
    commands = []

    def __init__(self):
        self.commands.append(PblProjectCreator())
        self.commands.append(PblProjectConverter())
        self.commands.append(PblBuildCommand())
        self.commands.append(PblCleanCommand())
        self.commands.append(PblAnalyzeSizeCommand())
        self.commands.append(PblInstallCommand())
        self.commands.append(PblPingCommand())
        self.commands.append(PblListCommand())
        self.commands.append(PblRemoveCommand())
        self.commands.append(PblCurrentAppCommand())
        self.commands.append(PblListUuidCommand())
        self.commands.append(PblLogsCommand())
        self.commands.append(PblReplCommand())
        self.commands.append(PblScreenshotCommand())

    def _get_version(self):
        try:
            from pebble.VersionGenerated import SDK_VERSION
            return SDK_VERSION
        except:
            return "Development"

    def main(self):
        parser = argparse.ArgumentParser(description = 'Pebble SDK Shell')
        parser.add_argument('--debug', action="store_true",
                            help="Enable debugging output")
        parser.add_argument('--version', action='version',
                            version='PebbleSDK %s' % self._get_version())
        subparsers = parser.add_subparsers(dest="command", title="Command",
                                           description="Action to perform")
        for command in self.commands:
            subparser = subparsers.add_parser(command.name, help = command.help)
            command.configure_subparser(subparser)
        args = parser.parse_args()

        log_level = logging.INFO
        if args.debug:
            log_level = logging.DEBUG

        logging.basicConfig(format='[%(levelname)-8s] %(message)s',
                            level = log_level)
        # Just in case logging was already setup, basicConfig would not
        # do anything, so set the level on the root logger
        logging.getLogger().setLevel(log_level)

        return self.run_action(args.command, args)

    def run_action(self, action, args):
        # Find the extension that was called
        command = [x for x in self.commands if x.name == args.command][0]

        try:
            retval = command.run(args)
            if retval:
                PblAnalytics.cmd_fail_evt(args.command, 'unknown error')
            else:
                cmdName = args.command
                if cmdName == 'install' and args.logs is True:
                    cmdName = 'install --logs'
                PblAnalytics.cmd_success_evt(cmdName)
            return retval

        except libpebble.PebbleError as e:
            PblAnalytics.cmd_fail_evt(args.command, 'pebble error')
            if args.debug:
                raise e
            else:
                logging.error(e)
                return 1

        except ConfigurationException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'configuration error')
            logging.error(e)
            return 1

        except InvalidProjectException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'invalid project')
            logging.error("This command must be run from a Pebble project "
                          "directory")
            return 1

        except OutdatedProjectException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'outdated project')
            logging.error("The Pebble project directory is using an outdated "
                          "version of the SDK!")
            logging.error("Try running `pebble convert-project` to update the "
                          "project")
            return 1

        except NoCompilerException as e:
            PblAnalytics.missing_tools_evt()
            logging.error("The compiler/linker tools could not be found. "
                          "Insure that the arm-cs-tools directory is present "
                          "in the Pebble SDK directory (%s)" %
                          PblCommand().sdk_path(args))
            return 1

        except BuildErrorException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'compilation error')
            logging.error("A compilation error occurred")
            return 1

        except AppTooBigException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'application too big')
            logging.error("The built application is too big")
            return 1

        except Exception as e:
            PblAnalytics.cmd_fail_evt(args.command, 'unhandled exception: %s' %
                                 str(e))
            logging.error(str(e))

            # Print out stack trace if in debug mode to aid in bug reporting
            if args.debug:
                raise
            return 1

if __name__ == '__main__':
    retval = PbSDKShell().main()
    if retval is None:
        retval = 0
    sys.exit(retval)

<commit_msg>fix spelling in error message<commit_after>#!/usr/bin/env python

import argparse
import logging
import sys

import pebble.PblAnalytics as PblAnalytics

# Catch any missing python dependencies so we can send an event to analytics
try:
    # NOTE: Even though we don't use websocket in this module, keep this
    #  import here for the unit tests so that they can trigger a missing
    #  python dependency event.
    import websocket
    import pebble as libpebble
    from pebble.PblProjectCreator   import (PblProjectCreator,
                                            InvalidProjectException,
                                            OutdatedProjectException)
    from pebble.PblProjectConverter import PblProjectConverter
    from pebble.PblBuildCommand     import (PblBuildCommand,
                                            PblCleanCommand,
                                            PblAnalyzeSizeCommand)
    from pebble.LibPebblesCommand   import *
except Exception as e:
    logging.basicConfig(format='[%(levelname)-8s] %(message)s',
                    level = logging.DEBUG)
    PblAnalytics.missing_python_dependency_evt(str(e))
    raise

class PbSDKShell:
    commands = []

    def __init__(self):
        self.commands.append(PblProjectCreator())
        self.commands.append(PblProjectConverter())
        self.commands.append(PblBuildCommand())
        self.commands.append(PblCleanCommand())
        self.commands.append(PblAnalyzeSizeCommand())
        self.commands.append(PblInstallCommand())
        self.commands.append(PblPingCommand())
        self.commands.append(PblListCommand())
        self.commands.append(PblRemoveCommand())
        self.commands.append(PblCurrentAppCommand())
        self.commands.append(PblListUuidCommand())
        self.commands.append(PblLogsCommand())
        self.commands.append(PblReplCommand())
        self.commands.append(PblScreenshotCommand())

    def _get_version(self):
        try:
            from pebble.VersionGenerated import SDK_VERSION
            return SDK_VERSION
        except:
            return "Development"

    def main(self):
        parser = argparse.ArgumentParser(description = 'Pebble SDK Shell')
        parser.add_argument('--debug', action="store_true",
                            help="Enable debugging output")
        parser.add_argument('--version', action='version',
                            version='PebbleSDK %s' % self._get_version())
        subparsers = parser.add_subparsers(dest="command", title="Command",
                                           description="Action to perform")
        for command in self.commands:
            subparser = subparsers.add_parser(command.name, help = command.help)
            command.configure_subparser(subparser)
        args = parser.parse_args()

        log_level = logging.INFO
        if args.debug:
            log_level = logging.DEBUG

        logging.basicConfig(format='[%(levelname)-8s] %(message)s',
                            level = log_level)
        # Just in case logging was already setup, basicConfig would not
        # do anything, so set the level on the root logger
        logging.getLogger().setLevel(log_level)

        return self.run_action(args.command, args)

    def run_action(self, action, args):
        # Find the extension that was called
        command = [x for x in self.commands if x.name == args.command][0]

        try:
            retval = command.run(args)
            if retval:
                PblAnalytics.cmd_fail_evt(args.command, 'unknown error')
            else:
                cmdName = args.command
                if cmdName == 'install' and args.logs is True:
                    cmdName = 'install --logs'
                PblAnalytics.cmd_success_evt(cmdName)
            return retval

        except libpebble.PebbleError as e:
            PblAnalytics.cmd_fail_evt(args.command, 'pebble error')
            if args.debug:
                raise e
            else:
                logging.error(e)
                return 1

        except ConfigurationException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'configuration error')
            logging.error(e)
            return 1

        except InvalidProjectException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'invalid project')
            logging.error("This command must be run from a Pebble project "
                          "directory")
            return 1

        except OutdatedProjectException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'outdated project')
            logging.error("The Pebble project directory is using an outdated "
                          "version of the SDK!")
            logging.error("Try running `pebble convert-project` to update the "
                          "project")
            return 1

        except NoCompilerException as e:
            PblAnalytics.missing_tools_evt()
            logging.error("The compiler/linker tools could not be found. "
                          "Ensure that the arm-cs-tools directory is present "
                          "in the Pebble SDK directory (%s)" %
                          PblCommand().sdk_path(args))
            return 1

        except BuildErrorException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'compilation error')
            logging.error("A compilation error occurred")
            return 1

        except AppTooBigException as e:
            PblAnalytics.cmd_fail_evt(args.command, 'application too big')
            logging.error("The built application is too big")
            return 1

        except Exception as e:
            PblAnalytics.cmd_fail_evt(args.command, 'unhandled exception: %s' %
                                 str(e))
            logging.error(str(e))

            # Print out stack trace if in debug mode to aid in bug reporting
            if args.debug:
                raise
            return 1

if __name__ == '__main__':
    retval = PbSDKShell().main()
    if retval is None:
        retval = 0
    sys.exit(retval)

<|endoftext|>


<commit_before>from setuptools import setup
from os         import path

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name             = 'neovim-remote',
    author           = 'Marco Hinz',
    author_email     = 'mh.codebro@gmail.com',
    url              = 'https://github.com/mhinz/neovim-remote',
    description      = 'Control nvim processes using "nvr" commandline tool',
    long_description = long_description,
    install_requires = ['neovim', 'psutil'],
    entry_points     = {
        'console_scripts': ['nvr = nvr.nvr:main']
    },
    packages         = ['nvr'],
    version          = '1.6.1',
    license          = 'MIT',
    keywords         = 'neovim nvim nvr remote helper',
    classifiers      = [
        'Topic :: Utilities',
        'License :: OSI Approved :: MIT License',
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: End Users/Desktop',
        'Intended Audience :: Developers',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
)

<commit_msg>Release v1.7.0<commit_after>from setuptools import setup
from os         import path

here = path.abspath(path.dirname(__file__))

with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name             = 'neovim-remote',
    author           = 'Marco Hinz',
    author_email     = 'mh.codebro@gmail.com',
    url              = 'https://github.com/mhinz/neovim-remote',
    description      = 'Control nvim processes using "nvr" commandline tool',
    long_description = long_description,
    install_requires = ['neovim', 'psutil'],
    entry_points     = {
        'console_scripts': ['nvr = nvr.nvr:main']
    },
    packages         = ['nvr'],
    version          = '1.7.0',
    license          = 'MIT',
    keywords         = 'neovim nvim nvr remote helper',
    classifiers      = [
        'Topic :: Utilities',
        'License :: OSI Approved :: MIT License',
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: End Users/Desktop',
        'Intended Audience :: Developers',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
)

<|endoftext|>


<commit_before>#!/usr/bin/env python

from setuptools import setup, find_packages

dev_requires = [
    'Sphinx==1.2.2'
]

tests_requires = [
    'factory_boy==2.4.1',
    'mock==1.0.1',
    'mock-django==0.6.6',
    'six>=1.7.3',
    'django-celery==3.1.16',
]

install_requires = [
    'Celery>=3.1.15,<3.2',
    'croniter>=0.3.4,<0.3.6',
    'Django>=1.7.1,<1.8',
    'django-auth-ldap==1.2.0',
    'django-filter==0.7',
    'django-fsm==2.2.0',
    'django-model-utils==2.2',
    'django-permission==0.8.2',
    'django-polymorphic>=0.7',
    'django-uuidfield==0.5.0',
    'djangorestframework>=3.1.0,<3.2.0',
    'djangosaml2==0.13.0',
    'elasticsearch>=1.0.0,<2.0.0',
    'jira>=0.47',
    'jsonfield==1.0.0',
    'Pillow>=2.0.0',
    'python-ceilometerclient==1.0.10',
    'python-cinderclient==1.0.9',
    'python-glanceclient==0.12.0',
    'python-keystoneclient==0.9.0',
    'python-neutronclient==2.3.4',
    'python-novaclient==2.17.0',
    'PyYAML>=3.10',
    'pyzabbix>=0.7.2',
    'redis==2.10.3',
    'requests>=2.6.0',
]

setup(
    name='nodeconductor',
    version='0.57.0',
    author='OpenNode Team',
    author_email='info@opennodecloud.com',
    url='https://github.com/opennode/nodeconductor',
    description='NodeConductor is REST server for infrastructure management.',
    long_description=open('README.rst').read(),
    packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    install_requires=install_requires,
    extras_require={
        'dev': dev_requires,
        'tests': tests_requires,
    },
    entry_points={
        'backup_strategies': ('Instance = nodeconductor.iaas.backup.instance_backup:InstanceBackupStrategy',),
        'template_services': ('IaaS = nodeconductor.iaas.template.strategy:IaasTemplateServiceStrategy',),
        'console_scripts': ('nodeconductor = nodeconductor.server.manage:main',),
    },
    tests_require=tests_requires,
    test_suite='nodeconductor.server.test_runner.run_tests',
    include_package_data=True,
    classifiers=[
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
    ],
)
<commit_msg>Preparing new release: 0.58.0<commit_after>#!/usr/bin/env python

from setuptools import setup, find_packages

dev_requires = [
    'Sphinx==1.2.2'
]

tests_requires = [
    'factory_boy==2.4.1',
    'mock==1.0.1',
    'mock-django==0.6.6',
    'six>=1.7.3',
    'django-celery==3.1.16',
]

install_requires = [
    'Celery>=3.1.15,<3.2',
    'croniter>=0.3.4,<0.3.6',
    'Django>=1.7.1,<1.8',
    'django-auth-ldap==1.2.0',
    'django-filter==0.7',
    'django-fsm==2.2.0',
    'django-model-utils==2.2',
    'django-permission==0.8.2',
    'django-polymorphic>=0.7',
    'django-uuidfield==0.5.0',
    'djangorestframework>=3.1.0,<3.2.0',
    'djangosaml2==0.13.0',
    'elasticsearch>=1.0.0,<2.0.0',
    'jira>=0.47',
    'jsonfield==1.0.0',
    'Pillow>=2.0.0',
    'python-ceilometerclient==1.0.10',
    'python-cinderclient==1.0.9',
    'python-glanceclient==0.12.0',
    'python-keystoneclient==0.9.0',
    'python-neutronclient==2.3.4',
    'python-novaclient==2.17.0',
    'PyYAML>=3.10',
    'pyzabbix>=0.7.2',
    'redis==2.10.3',
    'requests>=2.6.0',
]

setup(
    name='nodeconductor',
    version='0.58.0',
    author='OpenNode Team',
    author_email='info@opennodecloud.com',
    url='https://github.com/opennode/nodeconductor',
    description='NodeConductor is REST server for infrastructure management.',
    long_description=open('README.rst').read(),
    packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    install_requires=install_requires,
    extras_require={
        'dev': dev_requires,
        'tests': tests_requires,
    },
    entry_points={
        'backup_strategies': ('Instance = nodeconductor.iaas.backup.instance_backup:InstanceBackupStrategy',),
        'template_services': ('IaaS = nodeconductor.iaas.template.strategy:IaasTemplateServiceStrategy',),
        'console_scripts': ('nodeconductor = nodeconductor.server.manage:main',),
    },
    tests_require=tests_requires,
    test_suite='nodeconductor.server.test_runner.run_tests',
    include_package_data=True,
    classifiers=[
        'Framework :: Django',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
    ],
)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Nipype : Neuroimaging in Python pipelines and interfaces package.

Nipype intends to create python interfaces to other neuroimaging
packages and create an API for specifying a full analysis pipeline in
python.

Much of the machinery at the beginning of this file has been copied over from
nibabel denoted by ## START - COPIED FROM NIBABEL and a corresponding ## END

"""
# Build helper
import sys
from glob import glob
import os
from os.path import join as pjoin
from io import open

# Commit hash writing, and dependency checking
from setuptools.command.build_py import build_py

PY3 = sys.version_info[0] >= 3

class BuildWithCommitInfoCommand(build_py):
    """ Return extended build command class for recording commit

    The extended command tries to run git to find the current commit, getting
    the empty string if it fails.  It then writes the commit hash into a file
    in the `pkg_dir` path, named ``COMMIT_INFO.txt``.

    In due course this information can be used by the package after it is
    installed, to tell you what commit it was installed from if known.

    To make use of this system, you need a package with a COMMIT_INFO.txt file -
    e.g. ``myproject/COMMIT_INFO.txt`` - that might well look like this::

        # This is an ini file that may contain information about the code state
        [commit hash]
        # The line below may contain a valid hash if it has been substituted during 'git archive'
        archive_subst_hash=$Format:%h$
        # This line may be modified by the install process
        install_hash=

    The COMMIT_INFO file above is also designed to be used with git substitution
    - so you probably also want a ``.gitattributes`` file in the root directory
    of your working tree that contains something like this::

       myproject/COMMIT_INFO.txt export-subst

    That will cause the ``COMMIT_INFO.txt`` file to get filled in by ``git
    archive`` - useful in case someone makes such an archive - for example with
    via the github 'download source' button.

    Although all the above will work as is, you might consider having something
    like a ``get_info()`` function in your package to display the commit
    information at the terminal.  See the ``pkg_info.py`` module in the nipy
    package for an example.
    """
    def run(self):
        from configparser import ConfigParser
        import subprocess

        build_py.run(self)
        proc = subprocess.Popen('git rev-parse --short HEAD',
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
        repo_commit, _ = proc.communicate()
        # Fix for python 3
        if PY3:
            repo_commit = repo_commit.decode()

        # We write the installation commit even if it's empty
        cfg_parser = ConfigParser()
        cfg_parser.read(pjoin('nipype', 'COMMIT_INFO.txt'))
        cfg_parser.set('commit hash', 'install_hash', repo_commit.strip())
        out_pth = pjoin(self.build_lib, 'nipype', 'COMMIT_INFO.txt')
        if PY3:
            cfg_parser.write(open(out_pth, 'wt'))
        else:
            cfg_parser.write(open(out_pth, 'wb'))

def main():
    from setuptools import setup, find_packages

    thispath, _ = os.path.split(__file__)

    testdatafiles = [pjoin('testing', 'data', val)
                     for val in os.listdir(pjoin(thispath, 'nipype', 'testing', 'data'))
                     if not os.path.isdir(pjoin(thispath, 'nipype', 'testing', 'data', val))]

    testdatafiles += [
        pjoin('testing', 'data', 'dicomdir', '*'),
        pjoin('testing', 'data', 'bedpostxout', '*'),
        pjoin('testing', 'data', 'tbss_dir', '*'),
        pjoin('workflows', 'data', '*'),
        pjoin('pipeline', 'engine', 'report_template.html'),
        pjoin('external', 'd3.js'),
        pjoin('interfaces', 'script_templates', '*'),
        pjoin('interfaces', 'tests', 'realign_json.json'),
        pjoin('interfaces', 'tests', 'use_resources'),
    ]

    # Python 3: use a locals dictionary
    # http://stackoverflow.com/a/1463370/6820620
    ldict = locals()
    # Get version and release info, which is all stored in nipype/info.py
    ver_file = os.path.join(thispath, 'nipype', 'info.py')
    with open(ver_file) as infofile:
        exec(infofile.read(), globals(), ldict)

    setup(
        name=ldict['NAME'],
        maintainer=ldict['MAINTAINER'],
        maintainer_email=ldict['MAINTAINER_EMAIL'],
        description=ldict['DESCRIPTION'],
        long_description=ldict['LONG_DESCRIPTION'],
        url=ldict['URL'],
        download_url=ldict['DOWNLOAD_URL'],
        license=ldict['LICENSE'],
        classifiers=ldict['CLASSIFIERS'],
        author=ldict['AUTHOR'],
        author_email=ldict['AUTHOR_EMAIL'],
        platforms=ldict['PLATFORMS'],
        version=ldict['VERSION'],
        install_requires=ldict['REQUIRES'],
        setup_requires=['future', 'configparser'],
        provides=ldict['PROVIDES'],
        packages=find_packages(exclude=['*.tests']),
        package_data={'nipype': testdatafiles},
        scripts=glob('bin/*'),
        cmdclass={'build_py': BuildWithCommitInfoCommand},
        tests_require=ldict['TESTS_REQUIRES'],
        test_suite='nose.collector',
        zip_safe=False,
        extras_require=ldict['EXTRA_REQUIRES']
    )

if __name__ == "__main__":
    main()
<commit_msg>add script installer<commit_after>#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Nipype : Neuroimaging in Python pipelines and interfaces package.

Nipype intends to create python interfaces to other neuroimaging
packages and create an API for specifying a full analysis pipeline in
python.

Much of the machinery at the beginning of this file has been copied over from
nibabel denoted by ## START - COPIED FROM NIBABEL and a corresponding ## END

"""
# Build helper
import sys
from glob import glob
import os
from os.path import join as pjoin
from io import open

# Commit hash writing, and dependency checking
from setuptools.command.build_py import build_py

PY3 = sys.version_info[0] >= 3

class BuildWithCommitInfoCommand(build_py):
    """ Return extended build command class for recording commit

    The extended command tries to run git to find the current commit, getting
    the empty string if it fails.  It then writes the commit hash into a file
    in the `pkg_dir` path, named ``COMMIT_INFO.txt``.

    In due course this information can be used by the package after it is
    installed, to tell you what commit it was installed from if known.

    To make use of this system, you need a package with a COMMIT_INFO.txt file -
    e.g. ``myproject/COMMIT_INFO.txt`` - that might well look like this::

        # This is an ini file that may contain information about the code state
        [commit hash]
        # The line below may contain a valid hash if it has been substituted during 'git archive'
        archive_subst_hash=$Format:%h$
        # This line may be modified by the install process
        install_hash=

    The COMMIT_INFO file above is also designed to be used with git substitution
    - so you probably also want a ``.gitattributes`` file in the root directory
    of your working tree that contains something like this::

       myproject/COMMIT_INFO.txt export-subst

    That will cause the ``COMMIT_INFO.txt`` file to get filled in by ``git
    archive`` - useful in case someone makes such an archive - for example with
    via the github 'download source' button.

    Although all the above will work as is, you might consider having something
    like a ``get_info()`` function in your package to display the commit
    information at the terminal.  See the ``pkg_info.py`` module in the nipy
    package for an example.
    """
    def run(self):
        from configparser import ConfigParser
        import subprocess

        build_py.run(self)
        proc = subprocess.Popen('git rev-parse --short HEAD',
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=True)
        repo_commit, _ = proc.communicate()
        # Fix for python 3
        if PY3:
            repo_commit = repo_commit.decode()

        # We write the installation commit even if it's empty
        cfg_parser = ConfigParser()
        cfg_parser.read(pjoin('nipype', 'COMMIT_INFO.txt'))
        cfg_parser.set('commit hash', 'install_hash', repo_commit.strip())
        out_pth = pjoin(self.build_lib, 'nipype', 'COMMIT_INFO.txt')
        if PY3:
            cfg_parser.write(open(out_pth, 'wt'))
        else:
            cfg_parser.write(open(out_pth, 'wb'))

def main():
    from setuptools import setup, find_packages

    thispath, _ = os.path.split(__file__)

    testdatafiles = [pjoin('testing', 'data', val)
                     for val in os.listdir(pjoin(thispath, 'nipype', 'testing', 'data'))
                     if not os.path.isdir(pjoin(thispath, 'nipype', 'testing', 'data', val))]

    testdatafiles += [
        pjoin('testing', 'data', 'dicomdir', '*'),
        pjoin('testing', 'data', 'bedpostxout', '*'),
        pjoin('testing', 'data', 'tbss_dir', '*'),
        pjoin('workflows', 'data', '*'),
        pjoin('pipeline', 'engine', 'report_template.html'),
        pjoin('external', 'd3.js'),
        pjoin('interfaces', 'script_templates', '*'),
        pjoin('interfaces', 'tests', 'realign_json.json'),
        pjoin('interfaces', 'tests', 'use_resources'),
    ]

    # Python 3: use a locals dictionary
    # http://stackoverflow.com/a/1463370/6820620
    ldict = locals()
    # Get version and release info, which is all stored in nipype/info.py
    ver_file = os.path.join(thispath, 'nipype', 'info.py')
    with open(ver_file) as infofile:
        exec(infofile.read(), globals(), ldict)

    setup(
        name=ldict['NAME'],
        maintainer=ldict['MAINTAINER'],
        maintainer_email=ldict['MAINTAINER_EMAIL'],
        description=ldict['DESCRIPTION'],
        long_description=ldict['LONG_DESCRIPTION'],
        url=ldict['URL'],
        download_url=ldict['DOWNLOAD_URL'],
        license=ldict['LICENSE'],
        classifiers=ldict['CLASSIFIERS'],
        author=ldict['AUTHOR'],
        author_email=ldict['AUTHOR_EMAIL'],
        platforms=ldict['PLATFORMS'],
        version=ldict['VERSION'],
        install_requires=ldict['REQUIRES'],
        setup_requires=['future', 'configparser'],
        provides=ldict['PROVIDES'],
        packages=find_packages(exclude=['*.tests']),
        package_data={'nipype': testdatafiles},
        scripts=glob('bin/*'),
        cmdclass={'build_py': BuildWithCommitInfoCommand},
        tests_require=ldict['TESTS_REQUIRES'],
        test_suite='nose.collector',
        zip_safe=False,
        extras_require=ldict['EXTRA_REQUIRES'],
        entry_points='''
           [console_scripts]
           nipypecli=nipype.scripts.cli:cli
        '''
    )

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>#!/usr/bin/env python

"""Setup script for bdist_nsi."""

classifiers = """Development Status :: 5 - Production/Stable
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Natural Language :: English
Operating System :: OS Independent
Programming Language :: Python
Topic :: System :: Software Distribution
Topic :: Software Development :: Code Generators"""

from distutils.core import setup
import os

long_description = open("README.rst").read()

setup(
    name = 'bdist_nsi',
    packages = ['bdist_nsi'],
    package_data = {'': ['*.ico', '*.bmp']}, # include ico and bmp files
    version = '0.1.3',
    description = 'Create NSIS windows installers for Python modules.',
    # note: author of the original http://bdist-nsi.sourceforge.net/ package
    #       (which formed the original basis of bdist_nsi) is j-cg
    author = 'Amorilia',
    author_email = 'amorilia@users.sourceforge.net',
    url = 'http://bdist-nsi.sourceforge.net/',
    license = 'BSD',
    platforms = ["any"],
    classifiers = [_f for _f in classifiers.split("\n") if _f],
    long_description = long_description
)
<commit_msg>Extension is py3k compatible, so set classifier accordingly.<commit_after>#!/usr/bin/env python

"""Setup script for bdist_nsi."""

classifiers = """Development Status :: 5 - Production/Stable
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Natural Language :: English
Operating System :: OS Independent
Programming Language :: Python
Programming Language :: Python :: 2
Programming Language :: Python :: 3
Topic :: System :: Software Distribution
Topic :: Software Development :: Code Generators"""

from distutils.core import setup
import os

long_description = open("README.rst").read()

setup(
    name = 'bdist_nsi',
    packages = ['bdist_nsi'],
    package_data = {'': ['*.ico', '*.bmp']}, # include ico and bmp files
    version = '0.1.3',
    description = 'Create NSIS windows installers for Python modules.',
    # note: author of the original http://bdist-nsi.sourceforge.net/ package
    #       (which formed the original basis of bdist_nsi) is j-cg
    author = 'Amorilia',
    author_email = 'amorilia@users.sourceforge.net',
    url = 'http://bdist-nsi.sourceforge.net/',
    license = 'BSD',
    platforms = ["any"],
    classifiers = [_f for _f in classifiers.split("\n") if _f],
    long_description = long_description
)
<|endoftext|>