from django.contrib import admin

from .models import Page, PageRead, Tag

class PageAdmin(admin.ModelAdmin):
    search_fields = ["title"]
    list_display = ["title", "parent", "updated"]
    prepopulated_fields = {"slug": ("title",)}
    readonly_fields = ["updated"]
    ordering = ["parent", "title"]
    filter_horizontal = ("tags",)
    save_on_top = True
    fieldsets = (
        (
            None,
            {
                "fields": (
                    ("content",),
                    ("title", "parent"),
                    ("slug", "updated"),
                    ("tags",),
                )
            },
        ),
    )

admin.site.register(Page, PageAdmin)
admin.site.register(PageRead)
admin.site.register(Tag)

from django.contrib import admin

from .models import Page, PageRead, Tag

class PageAdmin(admin.ModelAdmin):
    search_fields = ["title"]
    list_display = ["title", "parent", "updated"]
    prepopulated_fields = {"slug": ("title",)}
    readonly_fields = ["updated"]
    ordering = ["parent", "title"]
    filter_horizontal = ("tags",)
    save_on_top = True
    fieldsets = (
        (
            None,
            {
                "fields": (
                    ("content",),
                    ("title", "parent"),
                    ("slug", "updated"),
                    ("tags",),
                )
            },
        ),
    )

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "parent":
            kwargs["queryset"] = Page.objects.order_by("title")
        return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

admin.site.register(Page, PageAdmin)
admin.site.register(PageRead)
admin.site.register(Tag)

Order parents in Admin select field

Order parents in Admin select field


import json
import datetime
from django.utils.encoding import force_unicode
from django.utils.functional import Promise

class LazyEncoder(json.JSONEncoder):
    """Taken from https://github.com/tomchristie/django-rest-framework/issues/87
    This makes sure that ugettext_lazy refrences in a dict are properly evaluated
    """
    def default(self, obj):
        if isinstance(obj, Promise):
            return force_unicode(obj)
        return super(LazyEncoder, self).default(obj)

import json
import datetime
from decimal import Decimal
from django.utils.encoding import force_unicode
from django.utils.functional import Promise

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        return super(DecimalEncoder, self).default(obj)

class LazyEncoder(DecimalEncoder):
    """Taken from https://github.com/tomchristie/django-rest-framework/issues/87
    This makes sure that ugettext_lazy refrences in a dict are properly evaluated
    """
    def default(self, obj):
        if isinstance(obj, Promise):
            return force_unicode(obj)
        return super(LazyEncoder, self).default(obj)

Fix for json encoding Decimal values

Fix for json encoding Decimal values


#!/usr/bin/env python

import unittest

import git_mnemonic as gm

class GitMnemonicTests(unittest.TestCase):
    def test_encode(self):
        self.assertTrue(gm.encode("master"))

    def test_decode(self):
        self.assertTrue(gm.decode("bis alo ama aha"))

    def test_invertible(self):
        once = gm.encode("master")
        self.assertEquals(gm.encode(gm.decode(once)), once)

if __name__ == '__main__':
    unittest.main(verbosity=2)

#!/usr/bin/env python

import unittest

import git_mnemonic as gm

class GitMnemonicTests(unittest.TestCase):
    def test_encode(self):
        self.assertTrue(gm.encode("master"))

    def test_decode(self):
        self.assertTrue(gm.decode("bis alo ama aha"))

    def test_invertible(self):
        once = gm.encode("master")
        self.assertEquals(gm.encode(gm.decode(once)), once)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(GitMnemonicTests)
    results = unittest.TextTestRunner(verbosity=2).run(suite)
    if not results.wasSuccessful():
        import sys
        sys.exit(1)

Make unittest test runner work in older pythons


# -*- coding: utf-8 -*-

"""
test_replay
-----------
"""

import pytest

from cookiecutter import replay, main, exceptions

def test_get_replay_file_name():
    """Make sure that replay.get_file_name generates a valid json file path."""
    assert replay.get_file_name('foo', 'bar') == 'foo/bar.json'

@pytest.fixture(params=[
    {'no_input': True},
    {'extra_context': {}},
    {'no_input': True, 'extra_context': {}},
])
def invalid_kwargs(request):
    return request.param

def test_raise_on_invalid_mode(invalid_kwargs):
    with pytest.raises(exceptions.InvalidModeException):
        main.cookiecutter('foo', replay=True, **invalid_kwargs)

def test_main_does_not_invoke_dump_but_load(mocker):
    mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
    mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
    mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
    mock_replay_dump = mocker.patch('cookiecutter.main.dump')
    mock_replay_load = mocker.patch('cookiecutter.main.load')

    main.cookiecutter('foobar', replay=True)

    assert not mock_prompt.called
    assert not mock_gen_context.called
    assert not mock_replay_dump.called
    assert mock_replay_load.called
    assert mock_gen_files.called

def test_main_does_not_invoke_load_but_dump(mocker):
    mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
    mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
    mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
    mock_replay_dump = mocker.patch('cookiecutter.main.dump')
    mock_replay_load = mocker.patch('cookiecutter.main.load')

    main.cookiecutter('foobar', replay=False)

    assert mock_prompt.called
    assert mock_gen_context.called
    assert mock_replay_dump.called
    assert not mock_replay_load.called
    assert mock_gen_files.called

Add tests for a correct behaviour in cookiecutter.main for replay


import xmlrpclib
import cPickle
import subprocess
from time import sleep

p = None
s = None

def start_plot_server():
    global p
    if p is None:
        p = subprocess.Popen(["python", "plot_server.py"])

def stop_plot_server():
    if p is not None:
        p.terminate()
        sleep(0.01)
        p.kill()

def plot_server_alive():
    global s
    try:
        s.alive()
    except Exception, e:
        if str(e).endswith("Connection refused"):
            return False
        else:
            raise
    return True

def establish_connection():
    global s
    s = xmlrpclib.ServerProxy("http://localhost:8000/", allow_none=True)
    if not plot_server_alive():
        start_plot_server()
        print "waiting for the plot server to start up..."
        while not plot_server_alive():
            sleep(0.05)
        print "  done."

def plot(vert, triangles):
    print "plotting using mayavi..."
    v = cPickle.dumps(vert)
    t = cPickle.dumps(triangles)
    s.plot(v, t)
    print "   done."

establish_connection()

import xmlrpclib
import cPickle
import subprocess
from time import sleep

p = None
s = None

def start_plot_server():
    global p
    if p is None:
        p = subprocess.Popen(["python", "plot_server.py"])

def stop_plot_server():
    if p is not None:
        p.terminate()
        sleep(0.01)
        p.kill()

def plot_server_alive():
    global s
    try:
        s.alive()
    except Exception, e:
        if str(e).endswith("Connection refused"):
            return False
        else:
            raise
    return True

def establish_connection():
    global s
    if s is not None:
        return
    s = xmlrpclib.ServerProxy("http://localhost:8000/", allow_none=True)
    if not plot_server_alive():
        start_plot_server()
        print "waiting for the plot server to start up..."
        while not plot_server_alive():
            sleep(0.05)
        print "  done."

def plot(vert, triangles):
    establish_connection()
    print "plotting using mayavi..."
    v = cPickle.dumps(vert)
    t = cPickle.dumps(triangles)
    s.plot(v, t)
    print "   done."

Establish connection only when needed

Establish connection only when needed


#!/usr/bin/python

import sys
import os
import glob
#sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py"))
sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/"))
sys.path.append(os.path.dirname(__file__) )

from thrift.transport import TSocket
from thrift.server import TServer
#import thrift_solr

import ExtractorService

import sys

import readability

import readability

def extract_with_python_readability( raw_content ):
    doc = readability.Document( raw_content )

    return [ u'' + doc.short_title(),
             u'' + doc.summary() ]

class ExtractorHandler:
    def extract_html( self, raw_html ):

        #print raw_html

        #raw_html = raw_html.encode( 'utf-8' )

        ret =  extract_with_python_readability( raw_html )
        #print ret[1]
        return ret

handler = ExtractorHandler()
processor = ExtractorService.Processor(handler)
listening_socket = TSocket.TServerSocket(port=9090)
server = TServer.TThreadPoolServer(processor, listening_socket)

print ("[Server] Started")
server.serve()

#!/usr/bin/python

import sys
import os
import glob
#sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py"))
sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/"))
sys.path.append(os.path.dirname(__file__) )

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated

#import thrift_solr

import ExtractorService

import sys

import readability

import readability

def extract_with_python_readability( raw_content ):
    doc = readability.Document( raw_content )

    return [ u'' + doc.short_title(),
             u'' + doc.summary() ]

class ExtractorHandler:
    def extract_html( self, raw_html ):

        #print raw_html

        #raw_html = raw_html.encode( 'utf-8' )

        ret =  extract_with_python_readability( raw_html )
        #print ret[1]
        return ret

handler = ExtractorHandler()
processor = ExtractorService.Processor(handler)
listening_socket = TSocket.TServerSocket(port=9090)
tfactory = TTransport.TBufferedTransportFactory()
#pfactory = TBinaryProtocol.TBinaryProtocolFactory()
pfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory()

server = TServer.TThreadPoolServer(processor, listening_socket, tfactory, pfactory)

print ("[Server] Started")
server.serve()

Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.


from imhotep.tools import Tool
from collections import defaultdict
import json
import os
import logging

log = logging.getLogger(__name__)

class FoodCritic(Tool):

    def invoke(self,
               dirname,
               filenames=set(),
               config_file=None,
               file_list=None):
        retval = defaultdict(lambda: defaultdict(list))
        if file_list is None:
            cmd = "find %s/cookbooks -type d -maxdepth 1 ! -path %s/cookbooks | xargs foodcritic" % (dirname, dirname)
        else:
            cmd = "foodcritic %s" % (" ".join(file_list))
        log.debug("Command: %s", cmd)
        try:
            output = self.executor(cmd)
            for line in output.split('\n'):
                rule, message, file_name, line_number = line.split(':')
                file_name = file_name.lstrip()
                file_name = file_name.replace(dirname, "")[1:]
                message = "[%s](http://acrmp.github.io/foodcritic/#%s): %s" % (rule, rule, message)
                retval[file_name][line_number].append(message)
        except:
            pass
        return retval

from imhotep.tools import Tool
from collections import defaultdict
import json
import os
import logging

log = logging.getLogger(__name__)

class FoodCritic(Tool):

    def invoke(self,
               dirname,
               filenames=set(),
               config_file=None):
        retval = defaultdict(lambda: defaultdict(list))
        if len(filenames) == 0:
            cmd = "find %s/cookbooks -type d -maxdepth 1 ! -path %s/cookbooks | xargs foodcritic" % (dirname, dirname)
        else:
            filenames = ["%s/%s" % (dirname, "/".join(filename.split('/')[:2])) for filename in filenames]
            cmd = "foodcritic %s" % (" ".join(filenames))
        log.debug("Command: %s", cmd)
        try:
            output = self.executor(cmd)
            for line in output.split('\n'):
                rule, message, file_name, line_number = line.split(':')
                file_name = file_name.lstrip()
                file_name = file_name.replace(dirname, "")[1:]
                message = "[%s](http://acrmp.github.io/foodcritic/#%s): %s" % (rule, rule, message)
                retval[file_name][line_number].append(message)
        except:
            pass
        return retval

Update support for passing in filenames.

This shit is gross


"""
Asphalt framework mixin for Kyokai.
"""
import logging

import asyncio
from functools import partial
from typing import Union

from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types

from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
from kyokai.context import HTTPRequestContext

logger = logging.getLogger("Kyokai")

class KyoukaiComponent(Component):
    def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444, **cfg):
        assert check_argument_types()
        if not isinstance(app, Kyokai):
            self.app = resolve_reference(app)
        else:
            self.app = app
        self.ip = ip
        self.port = port
        self._extra_cfg = cfg

        # Set HTTPRequestContext's `cfg` val to the extra config.
        HTTPRequestContext.cfg = self._extra_cfg

        self.server = None

        self.app.reconfigure(cfg)

    def get_protocol(self, ctx: Context):
        return KyokaiProtocol(self.app, ctx)

    async def start(self, ctx: Context):
        """
        Starts a Kyokai server.
        """
        protocol = self.get_protocol(ctx)
        self.server = await asyncio.get_event_loop().create_server(protocol, self.ip, self.port)
        logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))

"""
Asphalt framework mixin for Kyokai.
"""
import logging

import asyncio
from functools import partial
from typing import Union

from asphalt.core import Component, resolve_reference, Context
from typeguard import check_argument_types

from kyokai.app import Kyokai
from kyokai.protocol import KyokaiProtocol
from kyokai.context import HTTPRequestContext

logger = logging.getLogger("Kyokai")

class KyoukaiComponent(Component):
    def __init__(self, app: Union[str, Kyokai], ip: str = '0.0.0.0', port: int = 4444, **cfg):
        assert check_argument_types()
        if not isinstance(app, Kyokai):
            self.app = resolve_reference(app)
        else:
            self.app = app
        self.ip = ip
        self.port = port
        self._extra_cfg = cfg

        # Set HTTPRequestContext's `cfg` val to the extra config.
        HTTPRequestContext.cfg = self._extra_cfg

        self.server = None

        self.app.reconfigure(cfg)

    def get_protocol(self, ctx: Context):
        return KyokaiProtocol(self.app, ctx)

    async def start(self, ctx: Context):
        """
        Starts a Kyokai server.
        """
        protocol = partial(self.get_protocol, ctx)
        self.server = await asyncio.get_event_loop().create_server(protocol, self.ip, self.port)
        logger.info("Kyokai serving on {}:{}.".format(self.ip, self.port))

Make this into a partial to get the protocol correctly.


import pytest_twisted

from hendrix.ux import main
from hendrix.options import HendrixOptionParser

def test_no_arguments_gives_help_text(mocker):

    class MockFile(object):
        @classmethod
        def write(cls, whatever):
            cls.things_written = whatever

    class MockStdOut(object):

        @classmethod
        def write(cls, whatever):
            HendrixOptionParser.print_help(MockFile)
            assert MockFile.things_written == whatever

    mocker.patch('sys.stdout', new=MockStdOut)
    main([])

from hendrix.options import HendrixOptionParser
from hendrix.ux import main

def test_no_arguments_gives_help_text(mocker):
    class MockFile(object):
        @classmethod
        def write(cls, whatever):
            cls.things_written = whatever

    class MockStdOut(object):

        @classmethod
        def write(cls, whatever):
            HendrixOptionParser.print_help(MockFile)
            assert MockFile.things_written == whatever

    mocker.patch('sys.stdout', new=MockStdOut)
    main([])

Test for the hx launcher.

Test for the hx launcher.


#!/usr/bin/env python

"""
MPI utilities.
"""

from mpi4py import MPI
import twiggy

class MPIOutput(twiggy.outputs.Output):
    """
    Output messages to a file via MPI I/O.
    """

    def __init__(self, name, format, comm,
                 mode=MPI.MODE_CREATE | MPI.MODE_WRONLY,
                 close_atexit=True):
        self.filename = name
        self._format = format if format is not None else self._noop_format
        self.comm = comm
        self.mode = mode
        super(MPIOutput, self).__init__(format, close_atexit)

    def _open(self):
        self.file = MPI.File.Open(self.comm, self.filename,
                                  self.mode)

    def _close(self):
        self.file.Close()

    def _write(self, x):
        self.file.Iwrite_shared(x)

        # This seems to be necessary to prevent some log lines from being lost:
        self.file.Sync()

Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost.


from django.db import models
from django.contrib.auth.models import User

class Project(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    version = models.CharField(max_length=15, null=True)
    release_date = models.DateField(null=True)

class Issue(models.Model):
    project = models.ForeignKey(Project)
    status_choices = (
        ("0", "OPEN"),
        ("1", "IN PROGRESS"),
        ("2", "FINISHED"),
        ("3", "CLOSED"),
        ("4", "CANCELED"),
    )
    status = models.CharField(max_length=10, choices=status_choices)
    level_choices = (
        ("0", "LOW"),
        ("1", "MEDIUM"),
        ("2", "HIGH"),
        ("3", "CRITICAL"),
        ("4", "BLOCKER"),
    )
    level = models.CharField(max_length=10, choices=level_choices)
    title = models.CharField(max_length=50, null=True)
    description = models.CharField(max_length=50, null=True)
    date_created = models.DateField(auto_now_add=True)
    date_completed = models.DateField(null=True)
    # TODO implement these
    # time_estimate
    # percentage_completed

class Comments(models.Model):
    issue = models.ForeignKey(Issue)
    comment = models.CharField(max_length=500)
    user = models.ForeignKey(User,null=True, blank=True)

from django.db import models
from django.contrib.auth.models import User

class Project(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    version = models.CharField(max_length=15, null=True)
    release_date = models.DateField(null=True)

class Issue(models.Model):
    project = models.ForeignKey(Project)
    status_choices = (
        ("0", "OPEN"),
        ("1", "IN PROGRESS"),
        ("2", "FINISHED"),
        ("3", "CLOSED"),
        ("4", "CANCELED"),
    )
    status = models.CharField(max_length=10, choices=status_choices)
    level_choices = (
        ("0", "LOW"),
        ("1", "MEDIUM"),
        ("2", "HIGH"),
        ("3", "CRITICAL"),
        ("4", "BLOCKER"),
    )
    level = models.CharField(max_length=10, choices=level_choices)
    title = models.CharField(max_length=50, null=True)
    description = models.CharField(max_length=50, null=True)
    date_created = models.DateField(auto_now_add=True)
    date_completed = models.DateField(null=True)
    # TODO implement these
    # time_estimate
    # percentage_completed

class Comments(models.Model):
    issue = models.ForeignKey(Issue)
    comment = models.TextField(max_length=500)
    date_created = models.DateTimeField(null=False, auto_now_add=True)
    user = models.ForeignKey(User,null=True, blank=True)

Change comment from a charfield to a textfield, and add a date_created field; which is not working correctly.


"""Displays currently active gpu by optimus-manager
Requires the following packages:

    * optimus-manager

"""

import subprocess

import core.module
import core.widget

class Module(core.module.Module):
    def __init__(self, config, theme):
        super().__init__(config, theme, core.widget.Widget(self.output))
        self.__gpumode = ""

    def output(self, _):
        return "GPU: {}".format(self.__gpumode)

    def update(self):
        cmd = ["optimus-manager", "--print-mode"]
        output = (
            subprocess.Popen(cmd, stdout=subprocess.PIPE)
            .communicate()[0]
            .decode("utf-8")
            .lower()
        )

        if "intel" in output:
            self.__gpumode = "Intel"
        elif "nvidia" in output:
            self.__gpumode = "Nvidia"
        elif "amd" in output:
            self.__gpumode = "AMD"

"""Displays currently active gpu by optimus-manager
Requires the following packages:

    * optimus-manager

"""

import core.module
import core.widget

import util.cli

class Module(core.module.Module):
    def __init__(self, config, theme):
        super().__init__(config, theme, core.widget.Widget(self.output))
        self.__gpumode = ""

    def output(self, _):
        return "GPU: {}".format(self.__gpumode)

    def update(self):
        cmd = "optimus-manager --print-mode"
        output = util.cli.execute(cmd).strip()

        if "intel" in output:
            self.__gpumode = "Intel"
        elif "nvidia" in output:
            self.__gpumode = "Nvidia"
        elif "amd" in output:
            self.__gpumode = "AMD"

Use the existing util.cli module

Use the existing util.cli module


from core import BotAI
from core import Connector

from decorators import message_must_begin_with
from decorators import message_must_begin_with_attr
from decorators import message_must_begin_with_nickname

Allow modules that use dudebot to just import dudebot...


from .initial_data import request_user, chatid

request = {
    "endpoint": "/api/chats/{}/participants".format(chatid),
    "method": "post",
    "user": request_user,
    "body": {
        "users": [666666]
    }
}

from .initial_data import request_user, chatid

request = {
    "endpoint": "/api/chats/{}/participants".format(chatid),
    "method": "post",
    "user": request_user,
    "body": {
        "users": [666666, 22]
    }
}

Fix testcase for better coverage

Fix testcase for better coverage


from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Role(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Category(models.Model):
    name = models.CharField(max_length=100)
    weight = models.PositiveSmallIntegerField(default=1)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "categories"
        ordering = ['weight']

class Employee(AbstractUser):
    role = models.ForeignKey(Role, null=True, blank=True)
    skype_id = models.CharField(max_length=200, null=True, blank=True)
    last_month_score = models.PositiveIntegerField(default=0)
    current_month_score = models.PositiveIntegerField(default=0)
    level = models.PositiveIntegerField(default=0)
    total_score = models.PositiveIntegerField(default=0)
    avatar = models.ImageField(upload_to='avatar', null=True, blank=True)
    categories = models.ManyToManyField(Category)

from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Role(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Category(models.Model):
    name = models.CharField(max_length=100)
    weight = models.PositiveSmallIntegerField(default=1)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "categories"
        ordering = ['weight']

class Employee(AbstractUser):
    role = models.ForeignKey(Role, null=True, blank=True)
    skype_id = models.CharField(max_length=200, null=True, blank=True)
    last_month_score = models.PositiveIntegerField(default=0)
    current_month_score = models.PositiveIntegerField(default=0)
    level = models.PositiveIntegerField(default=0)
    total_score = models.PositiveIntegerField(default=0)
    avatar = models.ImageField(upload_to='avatar', null=True, blank=True)
    categories = models.ManyToManyField(Category, blank=True)

Change categories field to non required.


from django import template
from django.conf import settings
from django.core import urlresolvers
from django.template import Context, Template
from django.utils.translation import get_language, ugettext_lazy as _
from satchmo.configuration import config_value
from satchmo.product.models import Category
from satchmo.shop.templatetags import get_filter_args

register = template.Library()

def is_producttype(product, ptype):
    """Returns True if product is ptype"""
    if ptype in product.get_subtypes():
        return "true"
    else:
        return ""

register.filter('is_producttype', is_producttype)

def product_images(product, args=""):
    args, kwargs = get_filter_args(args,
        keywords=('include_main', 'maximum'),
        boolargs=('include_main'),
        intargs=('maximum'),
        stripquotes=True)

    q = product.productimage_set
    if kwargs.get('include_main', True):
        q = q.all()
    else:
        main = product.main_image
        q = q.exclude(id = main.id)

    maximum = kwargs.get('maximum', -1)
    if maximum>-1:
        q = list(q)[:maximum]

    return q

register.filter('product_images', product_images)

def smart_attr(product, key):
    """Run the smart_attr function on the spec'd product
    """
    return product.smart_attr(key)

register.filter('smart_attr', smart_attr)

from django import template
from django.conf import settings
from django.core import urlresolvers
from django.template import Context, Template
from django.utils.translation import get_language, ugettext_lazy as _
from satchmo.configuration import config_value
from satchmo.product.models import Category
from satchmo.shop.templatetags import get_filter_args

register = template.Library()

def is_producttype(product, ptype):
    """Returns True if product is ptype"""
    if ptype in product.get_subtypes():
        return True
    else:
        return False

register.filter('is_producttype', is_producttype)

def product_images(product, args=""):
    args, kwargs = get_filter_args(args,
        keywords=('include_main', 'maximum'),
        boolargs=('include_main'),
        intargs=('maximum'),
        stripquotes=True)

    q = product.productimage_set
    if kwargs.get('include_main', True):
        q = q.all()
    else:
        main = product.main_image
        q = q.exclude(id = main.id)

    maximum = kwargs.get('maximum', -1)
    if maximum>-1:
        q = list(q)[:maximum]

    return q

register.filter('product_images', product_images)

def smart_attr(product, key):
    """Run the smart_attr function on the spec'd product
    """
    return product.smart_attr(key)

register.filter('smart_attr', smart_attr)

Change the is_producttype template tag to return a boolean rather than a string.

--HG--
extra : convert_revision : svn%3Aa38d40e9-c014-0410-b785-c606c0c8e7de/satchmo/trunk%401200


# -*- coding: utf-8 -*-

"""Jinja2 extensions."""

import json

from jinja2.ext import Extension

class JsonifyExtension(Extension):
    """Jinja2 extension to convert a python object to json."""

    def __init__(self, environment):
        """Initilize extension with given environment."""
        super(JsonifyExtension, self).__init__(environment)

        def jsonify(obj):
            return json.dumps(obj, sort_keys=True, indent=4)

        environment.filters['jsonify'] = jsonify

# -*- coding: utf-8 -*-

"""Jinja2 extensions."""

import json

from jinja2.ext import Extension

class JsonifyExtension(Extension):
    """Jinja2 extension to convert a Python object to JSON."""

    def __init__(self, environment):
        """Initialize the extension with the given environment."""
        super(JsonifyExtension, self).__init__(environment)

        def jsonify(obj):
            return json.dumps(obj, sort_keys=True, indent=4)

        environment.filters['jsonify'] = jsonify

Fix typo and improve grammar in doc string


""" To test if the new code produces the same precision values on the published results."""

from __future__ import division, print_function
import pytest
import numpy as np

import eniric.Qcalculator as Q
import eniric.IOmodule as IO
from bin.prec_1 import calc_prec1

# For python2.X compatibility
file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError)

path = "data/Published_Results/resampled/"

@pytest.mark.xfail(raises=file_error_to_catch)   # Data file may not exist
def test_presicion_1():
    """ New precision 1 test that works."""
    published_results = {1: 3.8, 5: 9.1, 10: 20.7}
    path = "data/resampled/"
    for vsini in [1, 5, 10]:
        # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini)
        __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path)

        assert np.round(p1, 1).value == published_results[vsini]

""" To test if the new code produces the same precision values on the published results."""

from __future__ import division, print_function
import pytest
import numpy as np

import eniric.Qcalculator as Q
import eniric.IOmodule as IO
from bin.prec_1 import calc_prec1

# For python2.X compatibility
file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError)

path = "data/Published_Results/resampled/"

@pytest.mark.xfail(raises=file_error_to_catch)   # Data file may not exist
def test_presicion_1():
    """ New precision 1 test that works."""
    published_results = {1: 3.8, 5: 9.1, 10: 20.7}
    path = "data/resampled/"
    for vsini in [1, 5, 10]:
        # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini)
        __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path)

        # assert np.round(p1, 1).value == published_results[vsini]
        assert np.round(100 * p1, 1).value == published_results[vsini]  # With incorect normalization

Add known offset for known bad calibration.

Former-commit-id: afa3d6a66e32bbcc2b20f00f7e63fba5cb45882e [formerly 0470ca22b8a24205d2eb1c66caee912c990da0b3] [formerly c23210f4056c27e61708da2f2440bce3eda151a8 [formerly 5c0a6b9c0fefd2b88b9382d4a6ed98d9eac626df]]
Former-commit-id: 8bfdaa1f7940b26aee05f20e801616f4a8d1d55d [formerly 1c85db5b2b87b73dfb28a1db171ff79a69e3a24a]
Former-commit-id: d02a26b263c5c59776a35fc130e5c96b7ac30f5d


from getpass import getpass
from bessie import BaseClient

import config

class MicroBlogApi(BaseClient):

	endpoints = config.available_endpoints
	separator = '/'
	base_url='https://micro.blog'

	def __init__(self, path='', token=''):
		self.token = token
		super(self.__class__, self).__init__(path, token=token)

	# override method from BaseClient to inject Authorization header
	def _prepare_request(self):
		super(self.__class__, self)._prepare_request()
		self.request.headers['Authorization'] = 'Token {}'.format(self.token)

if __name__ == '__main__':
	token = getpass('Token... ')
	mba = MicroBlogApi(token=token)

	# GET - https://micro.blog/posts/all
	posts = mba.posts.all.get()

	print(posts.status_code, posts.reason)
	print(posts.json())

from getpass import getpass
from bessie import BaseClient

import config

class MicroBlogApi(BaseClient):

	endpoints = config.available_endpoints
	separator = '/'
	base_url='https://micro.blog'

	def __init__(self, path='', path_params=None, token=''):
		self.token = token
		super(self.__class__, self).__init__(path, path_params, token=token)

	# override method from BaseClient to inject Authorization header
	def _prepare_request(self):
		super(self.__class__, self)._prepare_request()
		self.request.headers['Authorization'] = 'Token {}'.format(self.token)

if __name__ == '__main__':
	token = getpass('Token... ')
	mba = MicroBlogApi(token=token)

	# GET - https://micro.blog/posts/all
	posts = mba.posts.all.get()

	print(posts.status_code, posts.reason)
	print(posts.json())

Include path_params in override constructor


""" Tests for the garbage collection of Scene objects.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.

import unittest
import weakref
import gc

from traits.etsconfig.api import ETSConfig

from tvtk.pyface.scene import Scene
from tvtk.tests.common import restore_gc_state

class TestScene(unittest.TestCase):

    @unittest.skipIf(
        ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
    def test_scene_garbage_collected(self):

        # given
        scene_collected = []
        scene_weakref = None

        def scene_collected_callback(weakref):
            scene_collected.append(True)

        def do():
            scene = Scene()
            reference = weakref.ref(scene, scene_collected_callback)
            scene.close()
            return reference

        # when
        with restore_gc_state():
            gc.disable()
            scene_weakref = do()

        # The Scene should have been collected.
        self.assertTrue(scene_collected[0])

if __name__ == "__main__":
    unittest.main()

""" Tests for the garbage collection of Scene objects.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.

import unittest
import weakref
import gc

from traits.etsconfig.api import ETSConfig

from tvtk.pyface.scene import Scene
from tvtk.tests.common import restore_gc_state

class TestScene(unittest.TestCase):

    @unittest.skipIf(
        ETSConfig.toolkit=='wx', 'Test segfaults using WX (issue #216)')
    def test_scene_garbage_collected(self):

        # given
        scene_collected = []
        scene_weakref = None

        def scene_collected_callback(weakref):
            scene_collected.append(True)

        def do():
            scene = Scene()
            reference = weakref.ref(scene, scene_collected_callback)
            scene.close()
            return reference

        # when
        with restore_gc_state():
            gc.disable()
            scene_weakref = do()

        # The Scene should have been collected.
        self.assertTrue(scene_collected[0])
        self.assertIsNone(scene_weakref())

if __name__ == "__main__":
    unittest.main()

Add weakref assertion in test case

Add weakref assertion in test case


from django.conf import settings
from django.conf.urls import patterns, url

from . import app_settings
from .views import (map_screenshot, convert, history_delete,
                    serve_secure_media, JSSettings)

_MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')[1:]

urlpatterns = patterns(
    '',
    url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media),
    url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'),
    url(r'^convert/$', convert, name='convert'),
    url(r'^history/delete/$', history_delete, name='history_delete'),
    # See default value in app_settings.JS_SETTINGS.
    # Will be overriden, most probably.
    url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'),
)

from django.conf import settings
from django.conf.urls import patterns, url

from . import app_settings
from .views import (map_screenshot, convert, history_delete,
                    serve_secure_media, JSSettings)

_MEDIA_URL = settings.MEDIA_URL.replace(app_settings['ROOT_URL'], '')
if _MEDIA_URL.startswith('/'):
    _MEDIA_URL = _MEDIA_URL[1:]
if _MEDIA_URL.endswith('/'):
    _MEDIA_URL = _MEDIA_URL[:-1]

urlpatterns = patterns(
    '',
    url(r'^%s(?P<path>.*?)$' % _MEDIA_URL, serve_secure_media),
    url(r'^map_screenshot/$', map_screenshot, name='map_screenshot'),
    url(r'^convert/$', convert, name='convert'),
    url(r'^history/delete/$', history_delete, name='history_delete'),
    # See default value in app_settings.JS_SETTINGS.
    # Will be overriden, most probably.
    url(r'^api/settings.json$', JSSettings.as_view(), name='js_settings'),
)

Remove leading and trailing slash of MEDIA_URL

Conflicts:

	mapentity/static/mapentity/Leaflet.label


#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

""" Run the Skia render_pdfs executable. """

from android_build_step import AndroidBuildStep
from build_step import BuildStep
from render_pdfs import RenderPdfs
from utils import android_utils
import sys

BINARY_NAME = 'render_pdfs'

class AndroidRenderPdfs(RenderPdfs, AndroidBuildStep):
  def DoRenderPdfs(self):
    args = self._PdfArgs(self._device_dirs.SKPDir())
    android_utils.RunShell(self._serial, [BINARY_NAME] + args)

if '__main__' == __name__:
  sys.exit(BuildStep.RunBuildStep(AndroidRenderPdfs))

#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

""" Run the Skia render_pdfs executable. """

from android_build_step import AndroidBuildStep
from build_step import BuildStep
from render_pdfs import RenderPdfs
from utils import android_utils
import sys

BINARY_NAME = 'render_pdfs'

class AndroidRenderPdfs(RenderPdfs, AndroidBuildStep):
  def DoRenderPdfs(self):
    args = self._PdfArgs(self._device_dirs.SKPDir())
    android_utils.RunSkia(self._serial, [BINARY_NAME] + args,
                          use_intent=(not self._has_root),
                          stop_shell=self._has_root)

if '__main__' == __name__:
  sys.exit(BuildStep.RunBuildStep(AndroidRenderPdfs))

Fix RenderPDFs on Android
Review URL: https://codereview.appspot.com/7306057

git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@7623 2bbb7eff-a529-9590-31e7-b0007b416f81


import os
from asyncaws import SQS
from tornado.testing import AsyncTestCase, gen_test

aws_key_id = os.environ['AWS_ACCESS_KEY_ID']
aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']
aws_region = os.environ['AWS_REGION']

class TestSQS(AsyncTestCase):
    sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=False)

    @gen_test(timeout=60)
    def test_create_queue(self):
        queue_url = self.sqs.create_queue(
            "test-queue", {"MessageRetentionPeriod": 60})
        self.assertIsInstance(queue_url, str)
        self.assertTrue(queue_url.startswith('http'))
        get_attr_result = self.sqs.get_queue_attributes(
            queue_url, ['MessageRetentionPeriod'])
        self.assertIsInstance(get_attr_result, dict)
        self.assertEqual(get_attr_result['MessageRetentionPeriod'], '60')
        add_perm_result = self.sqs.add_permission(
            queue_url, ['637085312181'], ["SendMessage"], "test-permission-id")
        self.assertIsInstance(add_perm_result, str)
        delete_result = self.sqs.delete_queue(queue_url)
        self.assertIsInstance(delete_result, str)

import os
from asyncaws import SQS
from tornado.testing import AsyncTestCase, gen_test
from random import randint

aws_key_id = os.environ['AWS_ACCESS_KEY_ID']
aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']
aws_region = os.environ['AWS_REGION']
aws_test_account_id = "637085312181"

class TestSQS(AsyncTestCase):

    @classmethod
    def setUpClass(cls):
        cls.sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=False)
        cls.queue_name = "test-queue-%s" % randint(1000, 9999)
        cls.queue_url = cls.sqs.create_queue(
            cls.queue_name, {"MessageRetentionPeriod": 60})

    @classmethod
    def tearDownClass(cls):
        cls.sqs.delete_queue(cls.queue_url)

    @gen_test
    def test_queue_actions(self):
        self.assertTrue(self.queue_url.startswith('http'))
        get_attr_result = self.sqs.get_queue_attributes(
            self.queue_url, ['MessageRetentionPeriod'])
        self.assertIsInstance(get_attr_result, dict)
        self.assertEqual(get_attr_result['MessageRetentionPeriod'], '60')
        add_perm_result = self.sqs.add_permission(
            self.queue_url, [aws_test_account_id], ["SendMessage"], "test-permission-id")
        self.assertIsInstance(add_perm_result, str)

Add correct setUp/tearDown methods for integration sqs test


import re
import sys

from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# Admin section
from django.contrib import admin
admin.autodiscover()

urlpatterns = staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# If we're running test, then we need to serve static files even though DEBUG
# is false to prevent lots of 404s. So do what staticfiles_urlpatterns would do.
if 'test' in sys.argv:
    static_url = re.escape(settings.STATIC_URL.lstrip('/'))
    urlpatterns += patterns('',
        url(r'^%s(?P<path>.*)$' % static_url, 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT,
        }),
        url('^(?P<path>favicon\.ico)$', 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT,
        }),
    )

urlpatterns += patterns('',

    url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
    url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),

    url(r'^', include('speeches.urls', app_name='speeches', namespace='speeches')),
)

import re
import sys

from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# Admin section
from django.contrib import admin
admin.autodiscover()

urlpatterns = staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# If we're running test, then we need to serve static files even though DEBUG
# is false to prevent lots of 404s. So do what staticfiles_urlpatterns would do.
if 'test' in sys.argv:
    static_url = re.escape(settings.STATIC_URL.lstrip('/'))
    urlpatterns += patterns('',
        url(r'^%s(?P<path>.*)$' % static_url, 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT,
        }),
        url('^(?P<path>favicon\.ico)$', 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT,
        }),
    )

urlpatterns += patterns('',
    (r'^admin/doc/', include('django.contrib.admindocs.urls')),
    (r'^admin/', include(admin.site.urls)),

    url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
    url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),

    url(r'^', include('speeches.urls', app_name='speeches', namespace='speeches')),
)

Include admin in example project.

Include admin in example project.


from django.db import models
from south.db import DEFAULT_DB_ALIAS

class MigrationHistory(models.Model):
    app_name = models.CharField(max_length=255)
    migration = models.CharField(max_length=255)
    applied = models.DateTimeField(blank=True)

    @classmethod
    def for_migration(cls, migration, database):
        try:
            # Switch on multi-db-ness
            if database != DEFAULT_DB_ALIAS:
                # Django 1.2
                objects = cls.objects.using(database)
            else:
                # Django <= 1.1
                objects = cls.objects
            return objects.get(
                app_name=migration.app_label(),
                migration=migration.name(),
            )
        except cls.DoesNotExist:
            return cls(
                app_name=migration.app_label(),
                migration=migration.name(),
            )

    def get_migrations(self):
        from south.migration.base import Migrations
        return Migrations(self.app_name)

    def get_migration(self):
        return self.get_migrations().migration(self.migration)

    def __str__(self):
        return "<%s: %s>" % (self.app_name, self.migration)

from django.db import models
from south.db import DEFAULT_DB_ALIAS

# If we detect Django 1.7 or higher, then exit
# Placed here so it's guaranteed to be imported on Django start
import django
if django.VERSION[0] > 1 or (django.VERSION[0] == 1 and django.VERSION[1] > 6):
    raise RuntimeError("South does not support Django 1.7 or higher. Please use native Django migrations.")

class MigrationHistory(models.Model):
    app_name = models.CharField(max_length=255)
    migration = models.CharField(max_length=255)
    applied = models.DateTimeField(blank=True)

    @classmethod
    def for_migration(cls, migration, database):
        try:
            # Switch on multi-db-ness
            if database != DEFAULT_DB_ALIAS:
                # Django 1.2
                objects = cls.objects.using(database)
            else:
                # Django <= 1.1
                objects = cls.objects
            return objects.get(
                app_name=migration.app_label(),
                migration=migration.name(),
            )
        except cls.DoesNotExist:
            return cls(
                app_name=migration.app_label(),
                migration=migration.name(),
            )

    def get_migrations(self):
        from south.migration.base import Migrations
        return Migrations(self.app_name)

    def get_migration(self):
        return self.get_migrations().migration(self.migration)

    def __str__(self):
        return "<%s: %s>" % (self.app_name, self.migration)

Add explicit version check for Django 1.7 or above


import os
import tempfile
from subprocess import call

class SlidePresenter(object):

    def __init__(self):
        pass

    def present(self, slides):
        for sno, slide in enumerate(slides):
            with open(os.path.join(tempfile.gettempdir(), str(sno)+".md"), 'w') as f:
                f.write(slide)

class VimPresenter(SlidePresenter):

    def __init__(self, vim_rc_generator, vim_args=[]):
        super(VimPresenter, self).__init__()
        self.vim_args = vim_args
        self.vim_rc_generator = vim_rc_generator

    def withRC(self):
        temp_rc = self.vim_rc_generator.generateFile()
        self.vim_args += ['-u', temp_rc]
        return self

    def _get_command(self, num_slides):
        self.withRC()
        return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+".md") for num in xrange(num_slides)]

    def present(self, slides):
        super(VimPresenter, self).present(slides)
        call(self._get_command(len(slides)))

class VimRCGenerator(object):
    def __init__(self):
        self.rc_string = "set nonu"

    def generateFile(self):
        temp_vimrc = os.path.join(tempfile.gettempdir(), 'rand.vimrc')
        with open(temp_vimrc, 'w') as f:
            f.write(self.rc_string)
        return temp_vimrc

import os
import tempfile
from subprocess import call

class SlidePresenter(object):

    def __init__(self):
        pass

    def present(self, slides):
        for sno, slide in enumerate(slides):
            with open(os.path.join(tempfile.gettempdir(), str(sno)+".md"), 'w') as f:
                f.write(slide)

class VimPresenter(SlidePresenter):

    def __init__(self, vim_rc_generator, vim_args=[]):
        super(VimPresenter, self).__init__()
        self.vim_args = vim_args
        self.vim_rc_generator = vim_rc_generator

    def withRC(self):
        temp_rc = self.vim_rc_generator.generateFile()
        self.vim_args += ['-u', temp_rc]
        return self

    def _get_command(self, num_slides):
        self.withRC()
        return ['vim'] + self.vim_args + [os.path.join(tempfile.gettempdir(), str(num)+".md") for num in range(num_slides)]

    def present(self, slides):
        super(VimPresenter, self).present(slides)
        call(self._get_command(len(slides)))

class VimRCGenerator(object):
    def __init__(self):
        self.rc_string = "set nonu"

    def generateFile(self):
        temp_vimrc = os.path.join(tempfile.gettempdir(), 'rand.vimrc')
        with open(temp_vimrc, 'w') as f:
            f.write(self.rc_string)
        return temp_vimrc

Use range instead of xrange

Use range instead of xrange


class MonsterAI(object):
    def __init__(self, level):
        self.owner = None
        self.level = level

    def take_turn(self):
        self.owner.log.log_begin_turn(self.owner.oid)
        self._take_turn()

    def _take_turn(self):
        raise NotImplementedError('Subclass this before usage please.')

class TestMonster(MonsterAI):
    def _take_turn(self):
        enemies = self.level.get_objects_outside_faction(self.owner.faction)
        if len(enemies) > 0:
            distances = {self.owner.distance_to(e): e for e in enemies}
            closest_distance = min(distances)
            closest_enemy = distances[closest_distance]
            if closest_distance <= 1.5:
                self.owner.fighter.attack(closest_enemy)
            else:
                self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)

from src.constants import *

class MonsterAI(object):
    def __init__(self, level):
        self.owner = None
        self.level = level

    def take_turn(self):
        self.owner.log.log_begin_turn(self.owner.oid)
        self._take_turn()

    def _take_turn(self):
        raise NotImplementedError('Subclass this before usage please.')

class TestMonster(MonsterAI):
    def _take_turn(self):

        enemies = self.level.get_objects_outside_faction(self.owner.faction)

        if len(enemies) > 0:
            # Identify the closest enemy
            distances = {self.owner.distance_to(e): e for e in enemies}
            closest_distance = min(distances)
            closest_enemy = distances[closest_distance]

            # Inspect inventory for usable items
            if self.owner.inventory is not None:
                usable = self.owner.inventory.get_usable_items()
                throwing_items = [i for i in usable if i.item.can_use(self.owner, closest_enemy, self.level)]
            else:
                throwing_items = []

            # Attack if adjacent
            if closest_distance <= 1.5:
                self.owner.fighter.attack(closest_enemy)
            # Throw if you have a throwing item
            if len(throwing_items) > 0:
                throwing_items[0].item.use(self.owner, closest_enemy, self.level)
            else:
                self.owner.move_towards(closest_enemy.x, closest_enemy.y, self.level)

Add throwing item usage to test AI

Add throwing item usage to test AI

Unforutnately the item isn't evicted from the inventory on usage,
so the guy with the throwing item can kill everybody, but it's
working - he does throw it!


# -*- coding: utf-8 -*-
from flask import Flask
import os
import psycopg2
from contextlib import closing

DB_SCHEMA = """
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
    id serial PRIMARY KEY,
    title VARCHAR (127) NOT NULL,
    text TEXT NOT NULL,
    created TIMESTAMP NOT NULL
)
"""

app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
    'DATABASE_URL', 'dbname=learning_journal user=miked, lfritts'
)

def connect_db():
    """Return a connection to the configured database"""
    return psycopg2.connect(app.config['DATABASE'])

def init_db():
    """Initialize the database using DB_SCHEMA

    WARNING: executing this function will drop existing tables.
    """
    with closing(connect_db()) as db:
        db.cursor().execute(DB_SCHEMA)
        db.commit()

@app.route('/')
def hello():
    return u'Hello world!'

if __name__ == '__main__':
    app.run(debug=True)

# -*- coding: utf-8 -*-
from flask import Flask
import os
import psycopg2
from contextlib import closing

DB_SCHEMA = """
DROP TABLE IF EXISTS entries;
CREATE TABLE entries (
    id serial PRIMARY KEY,
    title VARCHAR (127) NOT NULL,
    text TEXT NOT NULL,
    created TIMESTAMP NOT NULL
)
"""

app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
    'DATABASE_URL', 'dbname=learning_journal'
)

def connect_db():
    """Return a connection to the configured database"""
    return psycopg2.connect(app.config['DATABASE'])

def init_db():
    """Initialize the database using DB_SCHEMA

    WARNING: executing this function will drop existing tables.
    """
    with closing(connect_db()) as db:
        db.cursor().execute(DB_SCHEMA)
        db.commit()

@app.route('/')
def hello():
    return u'Hello world!'

if __name__ == '__main__':
    app.run(debug=True)

Remove user from db connection string

Remove user from db connection string


STARTER = -1
SEPARATOR = 0
TERMINATOR = 1

def readlines(fp, sep, mode=TERMINATOR, retain=True, size=512):
    if mode < 0:
        return _readlines_start(fp, sep, retain, size)
    elif mode == 0:
        return _readlines_sep(fp, sep, size)
    else:
        return _readlines_term(fp, sep, retain, size)

def _readlines_start(fp, sep, retain=True, size=512):
    # Omits empty leading entry
    entries = _readlines_sep(fp, sep, size=size)
    e = next(entries)
    if e:
        yield e
    for e in entries:
        if retain:
            e = sep + e
        yield e

def _readlines_sep(fp, sep, size=512):
    buff = ''
    for chunk in iter(lambda: fp.read(size), ''):
        buff += chunk
        lines = buff.split(sep)
        buff = lines.pop()
        for l in lines:
            yield l
    yield buff

def _readlines_term(fp, sep, retain=True, size=512):
    # Omits empty trailing entry
    buff = ''
    for chunk in iter(lambda: fp.read(size), ''):
        buff += chunk
        lines = buff.split(sep)
        buff = lines.pop()
        for l in lines:
            if retain:
                l += sep
            yield l
    if buff:
        yield buff

def read_begun(fp, sep, retain=True, size=512):
    # Omits empty leading entry
    entries = read_separated(fp, sep, size=size)
    e = next(entries)
    if e:
        yield e
    for e in entries:
        if retain:
            e = sep + e
        yield e

def read_separated(fp, sep, size=512):
    buff = ''
    for chunk in iter(lambda: fp.read(size), ''):
        buff += chunk
        lines = buff.split(sep)
        buff = lines.pop()
        for l in lines:
            yield l
    yield buff

def read_terminated(fp, sep, retain=True, size=512):
    # Omits empty trailing entry
    buff = ''
    for chunk in iter(lambda: fp.read(size), ''):
        buff += chunk
        lines = buff.split(sep)
        buff = lines.pop()
        for l in lines:
            if retain:
                l += sep
            yield l
    if buff:
        yield buff

Use three public functions instead of one


# For now I am assuming the investment date will be returned from the db
# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time

#!/usr/bin/env python3

from datetime import datetime, timedelta
import pytz

def get_start_times(date):
    """
    date: an epoch integer representing the date that the investment was purchased
    returns the integers (year, month, day)
    """
    datetime_object = datetime.utcfromtimestamp(date)
    return datetime_object.year, datetime_object.month, datetime_object.day

def get_end_times():
    """
    returns the end dates to query pytrends for as integers (year, month, day)
    """
    datetime = get_current_date() - timedelta(days = 1) #get yesterday's date
    return datetime.year, datetime.month, datetime.day

def get_current_date():
    """
    returns the current date in UTC as a datetime object
    """
    utc = pytz.utc
    date = datetime.now(tz=utc)
    return date

def date_to_epoch(date):
    """
    converts date object back into epoch
    """
    return date.timestamp()

# For now I am assuming the investment date will be returned from the db
# as a string yyyy-mm-dd, representing the day the trend was purchased in UTC time

#!/usr/bin/env python3

from datetime import datetime, timedelta
import pytz

def get_start_times(date):
    """
    date: an epoch integer representing the date that the investment was purchased
    returns the integers (year, month, day)
    """
    datetime_object = datetime.utcfromtimestamp(date)
    return datetime_object.year, datetime_object.month, datetime_object.day

def get_end_times():
    """
    returns the end dates to query pytrends for as integers (year, month, day)
    """
    datetime = get_current_date() - timedelta(days = 1) #get yesterday's date
    return datetime.year, datetime.month, datetime.day

def get_current_date():
    """
    returns the current date in UTC as a datetime object
    """
    utc = pytz.utc
    date = datetime.now(tz=utc)
    return date

def date_to_epoch(date):
    """
    converts date object back into epoch
    """
    return int(date.timestamp())

Make sure epoch return type is int

Make sure epoch return type is int


from .interfaces import IRoot, IApp
from .publish import publish
from .request import Request
from .traject import Traject
from comparch import ClassRegistry, Lookup, ChainClassLookup

known_apps = {}

class App(IApp, ClassRegistry):
    def __init__(self, name='', parent=None):
        super(App, self).__init__()
        self.name = name
        self.root_model = None
        self.root_obj = None
        self.child_apps = {}
        self.parent = parent
        self.traject = Traject()
        if self.parent is not None:
            parent.add_child(self)

    def add_child(self, app):
        self.child_apps[app.name] = app
        self.traject.register(app.name, lambda: app, conflicting=True)

    def class_lookup(self):
        if self.parent is None:
            return ChainClassLookup(self, global_app)
        return ChainClassLookup(self, self.parent.class_lookup())

    def __call__(self, environ, start_response):
        # XXX do caching lookup where?
        lookup = Lookup(self.class_lookup())
        request = Request(environ)
        request.lookup = lookup
        response = publish(request, self, lookup)
        return response(environ, start_response)

global_app = App()

# XXX this shouldn't be here but be the root of the global app
class Root(IRoot):
    pass
root = Root()

Remove root that wasn't used.

Remove root that wasn't used.


from __future__ import unicode_literals

from moto.compat import OrderedDict
from .responses import S3ResponseInstance

url_bases = [
    "https?://s3(.*).amazonaws.com",
    "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com"
]

url_paths = OrderedDict([
    # subdomain bucket
    ('{0}/$', S3ResponseInstance.bucket_response),

    # subdomain key of path-based bucket
    ('{0}/(?P<key_or_bucket_name>.+)', S3ResponseInstance.ambiguous_response),

    # path-based bucket + key
    ('{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)', S3ResponseInstance.key_response),
])

from __future__ import unicode_literals

from .responses import S3ResponseInstance

url_bases = [
    "https?://s3(.*).amazonaws.com",
    "https?://(?P<bucket_name>[a-zA-Z0-9\-_.]*)\.?s3(.*).amazonaws.com"
]

url_paths = {
    # subdomain bucket
    '{0}/$': S3ResponseInstance.bucket_response,

    # subdomain key of path-based bucket
    '{0}/(?P<key_or_bucket_name>[^/]+)/?$': S3ResponseInstance.ambiguous_response,

    # path-based bucket + key
    '{0}/(?P<bucket_name_path>[a-zA-Z0-9\-_./]+)/(?P<key_name>.+)': S3ResponseInstance.key_response,
}

Fix s3 url regex to ensure path-based bucket and key does not catch.


shopping_list = []

def show_help():
  print("What should we pick up at the store?")
  print("Enter DONE to stop. Enter HELP for this help. Enter SHOW to see your current list.")

def add_to_list(item):
  shopping_list.append(item)
  print("Added! List has {} items.".format(len(shopping_list)))

Add an item to the shopping list.

Add an item to the shopping list.


#!/bin/python3

import math
import os
import random
import re
import sys
from collections import Counter

def countTriplets(arr, r):
    potential_triplets_with_middle = Counter()
    potential_triplets_with_end = Counter()
    total_triplets = 0
    for num in arr:
        # num completed potential_triplets_with_end[num] triplets
        if potential_triplets_with_end[num]:
            total_triplets += potential_triplets_with_end[num]

        # num can be the middle number in potential_triplets_with_middle[num] triplets
        if potential_triplets_with_middle[num]:
            potential_triplets_with_end[num * r] += potential_triplets_with_middle[num]

        # num can be the begining of a triplet
        potential_triplets_with_middle[num * r] += 1
        print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets)
    return total_triplets

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nr = input().rstrip().split()

    n = int(nr[0])

    r = int(nr[1])

    arr = list(map(int, input().rstrip().split()))

    ans = countTriplets(arr, r)

    fptr.write(str(ans) + '\n')

    fptr.close()

#!/bin/python3

import math
import os
import random
import re
import sys
from collections import Counter

def countTriplets(arr, r):
    potential_triplets_with_middle = Counter()
    potential_triplets_with_end = Counter()
    total_triplets = 0
    for num in arr:
        # num completed potential_triplets_with_end[num] triplets
        if potential_triplets_with_end[num]:
            total_triplets += potential_triplets_with_end[num]

        # num can be the middle number in
        # potential_triplets_with_middle[num] triplets
        if potential_triplets_with_middle[num]:
            potential_triplets_with_end[num * r] += \
            potential_triplets_with_middle[num]

        # num can be the begining of a triplet
        potential_triplets_with_middle[num * r] += 1
    return total_triplets

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nr = input().rstrip().split()

    n = int(nr[0])

    r = int(nr[1])

    arr = list(map(int, input().rstrip().split()))

    ans = countTriplets(arr, r)

    fptr.write(str(ans) + '\n')

    fptr.close()

Remove debug output and pycodestyle

Remove debug output and pycodestyle


#!/usr/bin/env python

import json
import socket
import sys

if len(sys.argv) < 4:
    print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
    sys.exit(128)

check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000

# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl

# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
print (json.dumps(result))
socket.sendall(json.dumps(result))

#!/usr/bin/env python

import json
import socket
import sys

if len(sys.argv) < 4:
    print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>")
    sys.exit(128)

check_client = sys.argv[1]
check_name = sys.argv[2]
check_output = sys.argv[3]
check_status = int(sys.argv[4])
check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000

# Our result dict
result = dict()
result['source'] = check_client
result['name'] = check_name
result['output'] = check_output
result['status'] = check_status
result['ttl'] = check_ttl

# TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 3030)
sock.connect(server_address)
sock.sendall(json.dumps(result))
print (json.dumps(result))

Fix mistake with socket constructor

Fix mistake with socket constructor


import json

try:
    # Only works in Python 3.5
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen
from yank import version

if not version.release:
    print("This is not a release.")
    exit(0)

URL = 'http://www.getyank.org'
try:
    data = urlopen(URL + '/versions.json').read().decode()
    versions = json.loads(data)
except:
    # Initial population
    versions = [
        {'version': "0.14.1",
         'display': "0.14.1",
         'url': "{base}/{version}".format(base=URL, version="0.14.1"),
         'latest': False
        }
    ]

# Debug lines
# import pdb
# sd = urlopen('http://mdtraj.org' + '/versions.json').read().decode()
# sv = json.loads(sd)

# Sort the list so the versions are in the right order online
versions = sorted(versions, key=lambda k: k['version'])

# new release so all the others are now old
for i in range(len(versions)):
    versions[i]['latest'] = False

versions.append({
    'version': version.version,
    'display': version.short_version,
    'url': "{base}/{version}".format(base=URL, version=version.version),
    'latest': True,
})

with open("docs/_deploy/versions.json", 'w') as versionf:
    json.dump(versions, versionf, indent=2)

import json

try:
    # Only works in Python 3.5
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen
from yank import version

#if not version.release:
#   print("This is not a release.")
#    exit(0)

URL = 'http://www.getyank.org'
try:
    data = urlopen(URL + '/versions.json').read().decode()
    versions = json.loads(data)
except:
    # Initial population
    versions = [
        {'version': "0.14.1",
         'display': "0.14.1",
         'url': "{base}/{version}".format(base=URL, version="0.14.1"),
         'latest': False
        }
    ]

# Debug lines
# import pdb
# sd = urlopen('http://mdtraj.org' + '/versions.json').read().decode()
# sv = json.loads(sd)

# Sort the list so the versions are in the right order online
versions = sorted(versions, key=lambda k: k['version'])

# new release so all the others are now old
for i in range(len(versions)):
    versions[i]['latest'] = False

versions.append({
    'version': version.version,
    'display': version.short_version,
    'url': "{base}/{version}".format(base=URL, version=version.version),
    'latest': True,
})

with open("docs/_deploy/versions.json", 'w') as versionf:
    json.dump(versions, versionf, indent=2)

Disable the check for the initial versions push


#!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2008-2014 California Institute of Technology.
# License: 3-clause BSD.  The full license text is available at:
#  - http://trac.mystic.cacr.caltech.edu/project/pathos/browser/dill/LICENSE

import sys
import dill
import test_mixins as module

module.a = 1234

pik_mod = dill.dumps(module)

module.a = 0

# remove module
del sys.modules[module.__name__]
del module

module = dill.loads(pik_mod)
assert module.a == 1234
assert module.double_add(1, 2, 3) == 2 * module.fx

#!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2008-2014 California Institute of Technology.
# License: 3-clause BSD.  The full license text is available at:
#  - http://trac.mystic.cacr.caltech.edu/project/pathos/browser/dill/LICENSE

import sys
import dill
import test_mixins as module

cached = (module.__cached__ if hasattr(module, "__cached__")
          else module.__file__ + "c")

module.a = 1234

pik_mod = dill.dumps(module)

module.a = 0

# remove module
del sys.modules[module.__name__]
del module

module = dill.loads(pik_mod)
assert hasattr(module, "a") and module.a == 1234
assert module.double_add(1, 2, 3) == 2 * module.fx

# clean up
import os
os.remove(cached)
if os.path.exists("__pycache__") and not os.listdir("__pycache__"):
    os.removedirs("__pycache__")

Add code to clean up

Add code to clean up


"""
Machine Learning module for NeuroImaging in python
==================================================

See http://nisl.github.com for complete documentation.
"""

#from . import check_build
#from .base import clone

try:
    from numpy.testing import nosetester

    class NoseTester(nosetester.NoseTester):
        """ Subclass numpy's NoseTester to add doctests by default
        """

        def test(self, label='fast', verbose=1, extra_argv=['--exe'],
                        doctests=True, coverage=False):
            """Run the full test suite

            Examples
            --------
            This will run the test suite and stop at the first failing
            example
            >>> from nisl import test
            >>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP
            """
            return super(NoseTester, self).test(label=label, verbose=verbose,
                                    extra_argv=extra_argv,
                                    doctests=doctests, coverage=coverage)

    test = NoseTester().test
    del nosetester
except:
    pass

__all__ = ['datasets']

__version__ = '2010'

"""
Machine Learning module for NeuroImaging in python
==================================================

See http://nisl.github.com for complete documentation.
"""

try:
    import numpy
except ImportError:
    print 'Numpy could not be found, please install it properly to use nisl.'

try:
    import scipy
except ImportError:
    print 'Scipy could not be found, please install it properly to use nisl.'

try:
    import sklearn
except ImportError:
    print 'Sklearn could not be found, please install it properly to use nisl.'

try:
    from numpy.testing import nosetester

    class NoseTester(nosetester.NoseTester):
        """ Subclass numpy's NoseTester to add doctests by default
        """

        def test(self, label='fast', verbose=1, extra_argv=['--exe'],
                        doctests=True, coverage=False):
            """Run the full test suite

            Examples
            --------
            This will run the test suite and stop at the first failing
            example
            >>> from nisl import test
            >>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP
            """
            return super(NoseTester, self).test(label=label, verbose=verbose,
                                    extra_argv=extra_argv,
                                    doctests=doctests, coverage=coverage)

    test = NoseTester().test
    del nosetester
except:
    pass

__all__ = ['datasets']

__version__ = '2010'

Add an error message when trying to load nisl without having Numpy, Scipy and Sklearn installed.


import chainerx
from chainerx import _pybind_cuda

try:
    import cupy
    _cupy_available = True
except Exception:
    _cupy_available = False

_chainerx_allocator = None

def cupy_share_allocator(owner=chainerx._global_context):
    # Replace CuPy's allocator with ChainerX's if ChainerX is available with
    # the CUDA backend. This is needed in order to share the GPU memory
    # without having both modules using separate memory pools.

    # TODO(imanishi): Make sure this allocator works when the global
    # default context is changed by the user. It currently will not
    # since the allocator is only configured here once.
    try:
        owner.get_backend('cuda')
    except chainerx.BackendError:
        raise RuntimeError(
            'Cannot share allocator with CuPy without the CUDA backend.')

    if not _cupy_available:
        raise RuntimeError(
            'Cannot share allocator with CuPy since CuPy is not available.')

    param = _pybind_cuda.get_backend_ptr()
    malloc_func, free_func = _pybind_cuda.get_backend_malloc_free_ptrs()

    global _chainerx_allocator
    _chainerx_allocator = cupy.cuda.memory.CFunctionAllocator(
        param, malloc_func, free_func, owner)

    cupy.cuda.set_allocator(_chainerx_allocator.malloc)

import chainerx

try:
    import cupy
    _cupy_available = True
except Exception:
    _cupy_available = False

_chainerx_allocator = None

def cupy_share_allocator(owner=chainerx._global_context):
    # Replace CuPy's allocator with ChainerX's if ChainerX is available with
    # the CUDA backend. This is needed in order to share the GPU memory
    # without having both modules using separate memory pools.

    # TODO(imanishi): Make sure this allocator works when the global
    # default context is changed by the user. It currently will not
    # since the allocator is only configured here once.
    try:
        owner.get_backend('cuda')
    except chainerx.BackendError:
        raise RuntimeError(
            'Cannot share allocator with CuPy without the CUDA backend.')

    if not _cupy_available:
        raise RuntimeError(
            'Cannot share allocator with CuPy since CuPy is not available.')

    param = chainerx._pybind_cuda.get_backend_ptr()
    malloc_func, free_func = (
        chainerx._pybind_cuda.get_backend_malloc_free_ptrs())

    global _chainerx_allocator
    _chainerx_allocator = cupy.cuda.memory.CFunctionAllocator(
        param, malloc_func, free_func, owner)

    cupy.cuda.set_allocator(_chainerx_allocator.malloc)

Fix import error when CUDA is not available


# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.

from . import Operation

from UM.Scene.Selection import Selection
from UM.Application import Application

##  An operation that removes a SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
    ##  Initialises the RemoveSceneNodeOperation.
    #
    #   \param node The node to remove.
    def __init__(self, node):
        super().__init__()
        self._node = node
        self._parent = node.getParent()

    ##  Undoes the operation, putting the node back in the scene.
    def undo(self):
        self._node.setParent(self._parent)  # Hanging it back under its original parent puts it back in the scene.

    ##  Redo the operation, removing the node again.
    def redo(self):
        self._node.setParent(None)

        # Hack to ensure that the _onchanged is triggered correctly.
        # We can't do it the right way as most remove changes don't need to trigger
        # a reslice (eg; removing hull nodes don't need to trigger reslice).
        try:
            Application.getInstance().getBackend().forceSlice()
        except:
            pass
        if Selection.isSelected(self._node):  # Also remove the selection.
            Selection.remove(self._node)

# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.

from . import Operation

from UM.Scene.Selection import Selection
from UM.Application import Application

##  An operation that removes a SceneNode from the scene.
class RemoveSceneNodeOperation(Operation.Operation):
    ##  Initialises the RemoveSceneNodeOperation.
    #
    #   \param node The node to remove.
    def __init__(self, node):
        super().__init__()
        self._node = node
        self._parent = node.getParent()

    ##  Undoes the operation, putting the node back in the scene.
    def undo(self):
        self._node.setParent(self._parent)  # Hanging it back under its original parent puts it back in the scene.

    ##  Redo the operation, removing the node again.
    def redo(self):
        old_parent = self._parent
        self._node.setParent(None)

        if old_parent and old_parent.callDecoration("isGroup"):
            old_parent.callDecoration("recomputeConvexHull")

        # Hack to ensure that the _onchanged is triggered correctly.
        # We can't do it the right way as most remove changes don't need to trigger
        # a reslice (eg; removing hull nodes don't need to trigger reslice).
        try:
            Application.getInstance().getBackend().forceSlice()
        except:
            pass
        if Selection.isSelected(self._node):  # Also remove the selection.
            Selection.remove(self._node)

Update convex hull of the group when removing a node from the group

CURA-2573


from __future__ import print_function
import sys
import os
import fcntl
import termios
import argparse

class RootRequired(Exception):

    """Our standard exception."""

    pass

def send(data, tty):
    """Send each char of data to tty."""
    if(os.getuid() != 0):
        raise RootRequired('Only root can send input to other TTYs.')
    for c in data:
        fcntl.ioctl(tty, termios.TIOCSTI, c)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('tty', type=argparse.FileType('w'),
                        help='display a square of a given number')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-n', action='store_true',
                       help='Do not print the trailing newline character.')
    group.add_argument('--stdin', action='store_true',
                       help='Read input from stdin.')
    args, data = parser.parse_known_args()

    # Prepare data
    if args.stdin:
        data = sys.stdin.read()
    else:
        data = ' '.join(data)

    # Send data
    try:
        send(data, args.tty)
    except RootRequired, e:
        sys.exit(print('ERROR:', e, file=sys.stderr))

    # Handle trailing newline
    if data[-1][-1] != '\n' and not args.n:
        send('\n', args.tty)

#!/usr/bin/env python
from __future__ import print_function
import sys
import os
import fcntl
import termios
import argparse

class RootRequired(Exception):

    """Our standard exception."""

    pass

def send(data, tty):
    if len(data):
        # Handle trailing newline
        if data[-1][-1] != '\n':
            data += '\n'
        send_raw(data, tty)

def send_raw(data, tty):
    """Send each char of data to tty."""
    if(os.getuid() != 0):
        raise RootRequired('Only root can send input to other TTYs.')
    for c in data:
        fcntl.ioctl(tty, termios.TIOCSTI, c)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('tty', type=argparse.FileType('w'),
                        help='display a square of a given number')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-n', action='store_true',
                       help='Do not force a trailing newline character.')
    group.add_argument('--stdin', action='store_true',
                       help='Read input from stdin.')
    args, data = parser.parse_known_args()

    # Prepare data
    if args.stdin:
        data = sys.stdin.read()
    else:
        data = ' '.join(data)

    # Send data
    try:
        if args.n:
            send_raw(data, args.tty)
        else:
            send(data, args.tty)
    except RootRequired, e:
        sys.exit(print('ERROR:', e, file=sys.stderr))

Move newline handling to a function.

Move newline handling to a function.

Allows library users to choose to force trailing newlines.


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

import matplotlib.pyplot as plt
from numpy import array, log
import sys

x = []

y = []

infile = open(sys.argv[1])

for line in infile:
    data = line.replace('\n','').split()
    print(data)
    try :
        x.append(float(data[0]))
        y.append(float(data[1]))
    except ValueError:
        pass

#x = array(x)
#y = array(y)

figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
#plt.plot(log(x),log(y))
plt.plot(x,y,"o")

plt.ylabel('$\log T$')
plt.xlabel('$\log \Sigma$')
plt.grid()
plt.show()

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

import matplotlib.pyplot as plt
from numpy import array, log
import sys
import os

import matplotlib.animation as animation

fig = plt.figure()

inpath = sys.argv[1]

if os.path.isfile(inpath):
    print('Visiting {}'.format(inpath))
    filenames = [inpath]
else:
    _filenames = os.listdir(inpath)
    _filenames.sort()
    filesnames = [inpath + '/' + fname for fname in _filesnames if '_tot.dat' in fname]

    print('Visiting all files of {}'.format(inpath))

axline, = plt.plot(0, 0, 'o')

def draw_once(filename):
    x = []
    y = []
    if not 'tot.dat' in filename:
        return ([0], [0])
    else:
        print('Visiting {}'.format(filename))
        outfile = filename.replace('.dat', '.png')

    for line in open(filename):
        data = line.replace('\n', '').split()
        try :
            print (data)
            xData = float(data[0])
            yData = float(data[1])
            x.append(xData)
            y.append(yData)
        except ValueError:
            pass

    axline.set_xdata(x)
    axline.set_ydata(y)

    return axline,

def init():
    print('Initialisation')
    plt.ylabel('$\log T$')
    plt.xlabel('$\log \Sigma$')
    plt.xlim(1.8, 4)
    plt.ylim(6, 8)
    plt.grid()

if len(filenames) > 1:
    ani = animation.FuncAnimation(fig, draw_once, filenames, init_func=init, interval=10)
else:
    init()
    draw_once(filenames[0])
    plt.show()
# x, y = draw_once(filenames[2])
# plt.plot(x, y, 'o')

Use animation if dirname is provided

Use animation if dirname is provided


#!/usr/bin/env python3

from setuptools import setup, find_packages

setup(
    name='ppp_datamodel',
    version='0.5.3',
    description='Data model for the Projet Pensées Profondes.',
    url='https://github.com/ProjetPP/PPP-datamodel-Python',
    author='Valentin Lorentz',
    author_email='valentin.lorentz+ppp@ens-lyon.org',
    license='MIT',
    classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Libraries',
    ],
    install_requires=[
    ],
    packages=[
        'ppp_datamodel',
    ],
)

#!/usr/bin/env python3

from setuptools import setup, find_packages

setup(
    name='ppp_datamodel',
    version='0.5.4',
    description='Data model for the Projet Pensées Profondes.',
    url='https://github.com/ProjetPP/PPP-datamodel-Python',
    author='Valentin Lorentz',
    author_email='valentin.lorentz+ppp@ens-lyon.org',
    license='MIT',
    classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Topic :: Software Development :: Libraries',
    ],
    install_requires=[
    ],
    packages=[
        'ppp_datamodel',
    ],
)

Bump version number to 0.5.4.

Bump version number to 0.5.4.


from setuptools import setup, find_packages

setup(
    name='snippets',
    version='0.0.dev',
    license='ISC',
    description='Code snippets repository generator',
    url='https://github.com/trilan/snippets',
    author='Mike Yumatov',
    author_email='mike@yumatov.org',
    packages=find_packages(),
    classifiers=[
        'Development Status :: 1 - Planning',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: ISC License (ISCL)',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
    ],
)

from setuptools import setup, find_packages

setup(
    name='snippets',
    version='0.0.dev',
    license='ISC',
    description='Code snippets repository generator',
    url='https://github.com/trilan/snippets',
    author='Mike Yumatov',
    author_email='mike@yumatov.org',
    packages=find_packages(),
    install_requires=[
        'Pygments',
    ],
    classifiers=[
        'Development Status :: 1 - Planning',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: ISC License (ISCL)',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
    ],
)

Add Pygments as installation requirement


from distutils.core import setup
setup(name='pv_atmos',
      version='1.1',
      description='Utilities for scientific visualization with ParaView',
      long_description='This package is described in a peer-reviewed open access article, which can be found at http://dx.doi.org/10.5334/jors.al'.
      author='Martin Jucker',
      url='https://github.com/mjucker/pv_atmos',
      package_dir={'pv_atmos': ''},
      packages=['pv_atmos'],
      )

from distutils.core import setup
setup(name='pv_atmos',
      version='1.1.1',
      description='Utilities for scientific visualization with ParaView',
      long_description='This package is described in a peer-reviewed open access article, which can be found at http://dx.doi.org/10.5334/jors.al'.
      author='Martin Jucker',
      url='https://github.com/mjucker/pv_atmos',
      package_dir={'pv_atmos': ''},
      packages=['pv_atmos'],
      )

Update to appropriate version number

Update to appropriate version number


"""Setup script to generate an stand-alone executable.

Author-email: "Dietmar Winkler" <dietmar.winkler@dwe.no>

License: See UNLICENSE file

Usage: Run the build process by running the command 'python setup.py build'
       If everything works well you should find a subdirectory in the build
       subdirectory that contains the files needed to run the script
       without Python

"""

from setuptools import setup, find_packages

CLASSIFIERS = """
Environment :: Console
Intended Audience :: Developers
Operating System :: OS Independent
Programming Language :: Python :: 2
""".strip().splitlines()

META = {
    'name': 'ttws',
    'url': 'https://github.com/dietmarw/trimtrailingwhitespaces',
    'version': '0.3',
    'description': 'WSGI middleware to handle HTTP responses using exceptions',
    'description': 'Script to remove trailing whitespaces from textfiles.',
    'classifiers': CLASSIFIERS,
    'license': 'UNLICENSE',
    'author': 'Dietmar Winkler',
    'author_email': 'http://claimid/dietmarw',
    'packages': find_packages(exclude=['test']),
    'entry_points': {
        'console_scripts': 'ttws = ttws.cli:main'
    },
    'platforms': 'Posix; MacOS X; Windows',
    'include_package_data': False,
    'zip_safe': False,
    'install_requires': ['pyparsing'],
    'extras_require': {
        'testing': ['pytest']
    }
}

if __name__ == '__main__':
    setup(**META)

"""Setup script to generate an stand-alone executable.

Author-email: "Dietmar Winkler" <dietmar.winkler@dwe.no>

License: See UNLICENSE file

Usage: Run the build process by running the command 'python setup.py build'
       If everything works well you should find a subdirectory in the build
       subdirectory that contains the files needed to run the script
       without Python

"""

from setuptools import setup, find_packages

CLASSIFIERS = """
Environment :: Console
Intended Audience :: Developers
Operating System :: OS Independent
Programming Language :: Python :: 2
""".strip().splitlines()

META = {
    'name': 'ttws',
    'url': 'https://github.com/dietmarw/trimtrailingwhitespaces',
    'version': '0.3',
    'description': 'Script to remove trailing whitespaces from textfiles.',
    'classifiers': CLASSIFIERS,
    'license': 'UNLICENSE',
    'author': 'Dietmar Winkler',
    'author_email': 'http://claimid/dietmarw',
    'packages': find_packages(exclude=['test']),
    'entry_points': {
        'console_scripts': 'ttws = ttws.cli:main'
    },
    'platforms': 'Posix; MacOS X; Windows',
    'include_package_data': False,
    'zip_safe': False,
    'install_requires': ['pyparsing'],
    'extras_require': {
        'testing': ['pytest']
    }
}

if __name__ == '__main__':
    setup(**META)

Remove string from a copy and paste fail.


#!/usr/bin/env python
from setuptools import setup

setup(
    name='py-vkontakte',
    version='2016.8',
    packages=['vk'],
    url='https://github.com/sgaynetdinov/py-vkontakte',
    license='MIT License',
    author='Sergey Gaynetdinov',
    author_email='s.gaynetdinov@gmail.com',
    description='Python API wrapper around vk.com API',
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7'
    ],
    install_requires=[
        'requests',
    ],
)

#!/usr/bin/env python
from setuptools import setup

setup(
    name='py-vkontakte',
    version='2016.10',
    packages=['vk'],
    url='https://github.com/sgaynetdinov/py-vkontakte',
    license='MIT License',
    author='Sergey Gaynetdinov',
    author_email='s.gaynetdinov@gmail.com',
    description='Python API wrapper around vk.com API',
    classifiers=[
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7'
    ],
    install_requires=[
        'requests',
    ],
)

Change version `2016.8` => `2016.10`

Change version `2016.8` => `2016.10`


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

import xml4h

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

setup(
    name=xml4h.__title__,
    version=xml4h.__version__,
    description='XML for Humans in Python',
    long_description=open('README.rst').read(),
    author='James Murty',
    author_email='james@murty.co',
    url='https://github.com/jmurty/xml4h',
    packages=[
        'xml4h',
        'xml4h.impls',
    ],
    package_dir={'xml4h': 'xml4h'},
    package_data={'': ['README.rst', 'LICENSE']},
    include_package_data=True,
    install_requires=[
        'six',
    ],
    license=open('LICENSE').read(),
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Topic :: Text Processing :: Markup :: XML',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        # 'Programming Language :: Python :: 3.0',
        # 'Programming Language :: Python :: 3.1',
        # 'Programming Language :: Python :: 3.2',
    ],
    test_suite='tests',
)

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

import xml4h

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

setup(
    name=xml4h.__title__,
    version=xml4h.__version__,
    description='XML for Humans in Python',
    long_description=open('README.rst').read(),
    author='James Murty',
    author_email='james@murty.co',
    url='https://github.com/jmurty/xml4h',
    packages=[
        'xml4h',
        'xml4h.impls',
    ],
    package_dir={'xml4h': 'xml4h'},
    package_data={'': ['README.rst', 'LICENSE']},
    include_package_data=True,
    install_requires=[
        'six',
    ],
    license=open('LICENSE').read(),
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Topic :: Text Processing :: Markup :: XML',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ],
    test_suite='tests',
)

Update Python version classifiers to supported versions


from distutils.core import setup

desc = (
    'An interface to the Pluggable Authentication Modules (PAM) library'
    'on linux, written in pure python (using ctypes)'
)

setup(name='python3-simplepam', version='0.1.4',
      description=desc,
      py_modules=['simplepam'],
      author='Leon Weber <leon@leonweber.de>, Chris AtLee <chris@atlee.ca>',
      author_email='leon@leonweber.de',
      url='https://github.com/leonnnn/python3-simplepam',
      license='MIT'
      )

from distutils.core import setup

desc = (
    'An interface to the Pluggable Authentication Modules (PAM) library '
    'on linux, written in pure python (using ctypes)'
)

setup(name='python3-simplepam', version='0.1.4',
      description=desc,
      py_modules=['simplepam'],
      author='Leon Weber <leon@leonweber.de>, Chris AtLee <chris@atlee.ca>',
      author_email='leon@leonweber.de',
      url='https://github.com/leonnnn/python3-simplepam',
      license='MIT'
      )

Add missing space in description

Add missing space in description


from setuptools import setup, find_packages

setup(
    name="echidna",
    version="0.0.1-dev",
    url='http://github.com/praekelt/echidna',
    license='BSD',
    description='A scalable pub-sub WebSocket service.',
    long_description=open('README.rst', 'r').read(),
    author='Praekelt Foundation',
    author_email='dev@praekeltfoundation.org',
    packages=find_packages(),
    install_requires=[
        'Twisted',
        'cyclone',
        'txzookeeper',
        'redis',
        'zope.dottedname',
    ],
    tests_require=[
        'ws4py',
        'requests',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Cyclone',
        'Framework :: Twisted',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: POSIX',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Communications',
        'Topic :: Internet',
        'Topic :: System :: Networking',
    ]
)

from setuptools import setup, find_packages

setup(
    name="echidna",
    version="0.0.1-dev",
    url='http://github.com/praekelt/echidna',
    license='BSD',
    description='A scalable pub-sub WebSocket service.',
    long_description=open('README.rst', 'r').read(),
    author='Praekelt Foundation',
    author_email='dev@praekeltfoundation.org',
    packages=find_packages(),
    install_requires=[
        'Twisted',
        'cyclone',
        'txzookeeper',
        'redis',
        'zope.dottedname',
        'ws4py',
    ],
    tests_require=[
        'ws4py',
        'requests',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Framework :: Cyclone',
        'Framework :: Twisted',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: POSIX',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Communications',
        'Topic :: Internet',
        'Topic :: System :: Networking',
    ]
)

Add ws4py to normal requirements in an attempt to get Travis to install it


from django_website.settings.www import *

PREPEND_WWW = False
APPEND_SLASH = True
INSTALLED_APPS = ['django_website.docs']
TEMPLATE_CONTEXT_PROCESSORS += ["django.core.context_processors.request"]
ROOT_URLCONF = 'django_website.urls.docs'
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'

# Where to store the build Sphinx docs.
if PRODUCTION:
    DOCS_BUILD_ROOT = BASE.parent.child('docbuilds')
else:
    DOCS_BUILD_ROOT = '/tmp/djangodocs'

from django_website.settings.www import *

PREPEND_WWW = False
APPEND_SLASH = True
INSTALLED_APPS = ['django_website.docs']
TEMPLATE_CONTEXT_PROCESSORS += ["django.core.context_processors.request"]
ROOT_URLCONF = 'django_website.urls.docs'
CACHE_MIDDLEWARE_KEY_PREFIX = 'djangodocs'

# Where to store the build Sphinx docs.
if PRODUCTION:
    DOCS_BUILD_ROOT = BASE.ancestor(2).child('docbuilds')
else:
    DOCS_BUILD_ROOT = '/tmp/djangodocs'

Fix the docbuilds path location.

Fix the docbuilds path location.


from setuptools import setup, find_packages

import codecs
import os
import re

root_dir = os.path.abspath(os.path.dirname(__file__))
PACKAGE = 'hackernews_scraper'

def get_version(package_name):
    version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
    package_components = package_name.split('.')
    init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))
    with codecs.open(init_path, 'r', 'utf-8') as f:
        for line in f:
            match = version_re.match(line[:-1])
            if match:
                return match.groups()[0]
    return '0.1.0'

setup(name=PACKAGE
      description='Python library for retrieving comments and stories from HackerNews',
      packages=find_packages(),
      version=get_version(PACKAGE),
      install_requires=['requests'],
      url='https://github.com/NiGhTTraX/hackernews-scraper',
      license='MIT',
      platforms='any',
      tests_require=['nose', 'factory_boy', 'httpretty'],
      )

from setuptools import setup, find_packages

import codecs
import os
import re

root_dir = os.path.abspath(os.path.dirname(__file__))
PACKAGE = 'hackernews_scraper'

def get_version(package_name):
    version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
    package_components = package_name.split('.')
    init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))
    with codecs.open(init_path, 'r', 'utf-8') as f:
        for line in f:
            match = version_re.match(line[:-1])
            if match:
                return match.groups()[0]
    raise Exception("No package version found!")

setup(name=PACKAGE
      description='Python library for retrieving comments and stories from HackerNews',
      packages=find_packages(),
      version=get_version(PACKAGE),
      install_requires=['requests'],
      url='https://github.com/NiGhTTraX/hackernews-scraper',
      license='MIT',
      platforms='any',
      tests_require=['nose', 'factory_boy', 'httpretty'],
      )

Raise exception if version does not exist