from __future__ import unicode_literals

from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings

from taggit.managers import TaggableManager

import requests

class Bookmark(models.Model):
    title = models.CharField(max_length=200, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    date_added = models.DateTimeField(default=timezone.now, blank=True)
    tags = TaggableManager(blank=True)
    private = models.BooleanField(default=False)
    url = models.URLField(max_length=500)

    def __unicode__(self):
        return "{}: {} [{}]".format(
            self.pk,
            self.title[:40],
            self.date_added
        )

@receiver(models.signals.post_save, sender=Bookmark)
def bookmark_pre_save_handler(sender, instance, created, *args, **kwargs):
    # Only run for new items, not updates
    if created:
        if not hasattr(settings, 'SLACK_WEBHOOK_URL'):
            return

        payload = {
            'channel': "#bookmarks-dev",
            'username': "Bookmarks",
            'text': "<{}|{}>\n{}".format(
                instance.url,
                instance.title,
                instance.description,
            ),
            'icon_emoji': ":blue_book:",
            'unfurl_links': True
        }

        requests.post(settings.SLACK_WEBHOOK_URL, json=payload)

Response:
<REPLACE_OLD> "{}".format(
                "Bookmark added:",
 <REPLACE_NEW> "<{}|{}>\n{}".format(
                instance.url,
                instance.title,
                instance.description,
 <REPLACE_END> <REPLACE_OLD> 'attachments': [
                {
                    "fallback": instance.title,
                    "color": "good",
                    "title": instance.title,
                    "title_link": instance.url,
                    "text": instance.description,
                }
            ]
 <REPLACE_NEW> 'unfurl_links': True
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals

from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings

from taggit.managers import TaggableManager

import requests

class Bookmark(models.Model):
    title = models.CharField(max_length=200, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    date_added = models.DateTimeField(default=timezone.now, blank=True)
    tags = TaggableManager(blank=True)
    private = models.BooleanField(default=False)
    url = models.URLField(max_length=500)

    def __unicode__(self):
        return "{}: {} [{}]".format(
            self.pk,
            self.title[:40],
            self.date_added
        )

@receiver(models.signals.post_save, sender=Bookmark)
def bookmark_pre_save_handler(sender, instance, created, *args, **kwargs):
    # Only run for new items, not updates
    if created:
        if not hasattr(settings, 'SLACK_WEBHOOK_URL'):
            return

        payload = {
            'channel': "#bookmarks-dev",
            'username': "Bookmarks",
            'text': "<{}|{}>\n{}".format(
                instance.url,
                instance.title,
                instance.description,
            ),
            'icon_emoji': ":blue_book:",
            'unfurl_links': True
        }

        requests.post(settings.SLACK_WEBHOOK_URL, json=payload)

Prompt:
Remove attachment and use slack link unfurling

from __future__ import unicode_literals

from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.conf import settings

from taggit.managers import TaggableManager

import requests

class Bookmark(models.Model):
    title = models.CharField(max_length=200, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    date_added = models.DateTimeField(default=timezone.now, blank=True)
    tags = TaggableManager(blank=True)
    private = models.BooleanField(default=False)
    url = models.URLField(max_length=500)

    def __unicode__(self):
        return "{}: {} [{}]".format(
            self.pk,
            self.title[:40],
            self.date_added
        )

@receiver(models.signals.post_save, sender=Bookmark)
def bookmark_pre_save_handler(sender, instance, created, *args, **kwargs):
    # Only run for new items, not updates
    if created:
        if not hasattr(settings, 'SLACK_WEBHOOK_URL'):
            return

        payload = {
            'channel': "#bookmarks-dev",
            'username': "Bookmarks",
            'text': "{}".format(
                "Bookmark added:",
            ),
            'icon_emoji': ":blue_book:",
            'attachments': [
                {
                    "fallback": instance.title,
                    "color": "good",
                    "title": instance.title,
                    "title_link": instance.url,
                    "text": instance.description,
                }
            ]
        }

        requests.post(settings.SLACK_WEBHOOK_URL, json=payload)


import os
import sys

(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
    print(file)

print()
print()
print()
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updir)
for file in filenames:
    print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(updir)
upupdir = os.path.abspath('..')
print(upupdir)
filenames = os.listdir(upupdir)
for file in filenames:
    print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(upupdir)
upupupdir = os.path.abspath('..')
print(upupupdir)
filenames = os.listdir(upupupdir)
for file in filenames:
    print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(upupupdir)
upupupupdir = os.path.abspath('..')
print(upupupupdir)
filenames = os.listdir(upupupupdir)
for file in filenames:
    print(file)

Add a level of uper directory

Add a level of uper directory

Response:
<REPLACE_OLD> print(file)

print('*****************************************************')
updir <REPLACE_NEW> print(file)

print()
print()
print()
print('*****************************************************')
updir <REPLACE_END> <REPLACE_OLD> print(file)

print('*****************************************************')
os.chdir(updir)
upupdir <REPLACE_NEW> print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(updir)
upupdir <REPLACE_END> <REPLACE_OLD> print(file)

print('*****************************************************')
os.chdir(upupdir)
upupupdir <REPLACE_NEW> print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(upupdir)
upupupdir <REPLACE_END> <INSERT> print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(upupupdir)
upupupupdir = os.path.abspath('..')
print(upupupupdir)
filenames = os.listdir(upupupupdir)
for file in filenames:
    <INSERT_END> <|endoftext|> import os
import sys

(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
    print(file)

print()
print()
print()
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updir)
for file in filenames:
    print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(updir)
upupdir = os.path.abspath('..')
print(upupdir)
filenames = os.listdir(upupdir)
for file in filenames:
    print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(upupdir)
upupupdir = os.path.abspath('..')
print(upupupdir)
filenames = os.listdir(upupupdir)
for file in filenames:
    print(file)

print()
print()
print()
print('*****************************************************')
os.chdir(upupupdir)
upupupupdir = os.path.abspath('..')
print(upupupupdir)
filenames = os.listdir(upupupupdir)
for file in filenames:
    print(file)

Prompt:
Add a level of uper directory

import os
import sys

(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
    print(file)

print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updir)
for file in filenames:
    print(file)

print('*****************************************************')
os.chdir(updir)
upupdir = os.path.abspath('..')
print(upupdir)
filenames = os.listdir(upupdir)
for file in filenames:
    print(file)

print('*****************************************************')
os.chdir(upupdir)
upupupdir = os.path.abspath('..')
print(upupupdir)
filenames = os.listdir(upupupdir)
for file in filenames:
    print(file)


from flask import current_app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)
from datetime import datetime

from api import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(30))
    last_name = db.Column(db.String(30))
    email = db.Column(db.String(64), unique=True)
    username = db.Column(db.String(80), unique=True)
    password_hash = db.Column(db.String(128))
    bucket_lists = db.relationship('BucketList', backref='user', lazy='dynamic')

    def __init__(self, first_name, last_name, email, username):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email
        self.username = username

    def __repr__(self):
        return '<User %r>' % self.username

    def full_name(self):
        return '%s %s' % (self.first_name, self.last_name)

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)

    def generate_auth_token(self, expiration=7200):
        s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = User.query.get(data['id'])
        return user

Add User object to model

Add User object to model

Response:
<REPLACE_OLD>  <REPLACE_NEW> from flask import current_app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)
from datetime import datetime

from api import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(30))
    last_name = db.Column(db.String(30))
    email = db.Column(db.String(64), unique=True)
    username = db.Column(db.String(80), unique=True)
    password_hash = db.Column(db.String(128))
    bucket_lists = db.relationship('BucketList', backref='user', lazy='dynamic')

    def __init__(self, first_name, last_name, email, username):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email
        self.username = username

    def __repr__(self):
        return '<User %r>' % self.username

    def full_name(self):
        return '%s %s' % (self.first_name, self.last_name)

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)

    def generate_auth_token(self, expiration=7200):
        s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = User.query.get(data['id'])
        return user
 <REPLACE_END> <|endoftext|> from flask import current_app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)
from datetime import datetime

from api import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(30))
    last_name = db.Column(db.String(30))
    email = db.Column(db.String(64), unique=True)
    username = db.Column(db.String(80), unique=True)
    password_hash = db.Column(db.String(128))
    bucket_lists = db.relationship('BucketList', backref='user', lazy='dynamic')

    def __init__(self, first_name, last_name, email, username):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email
        self.username = username

    def __repr__(self):
        return '<User %r>' % self.username

    def full_name(self):
        return '%s %s' % (self.first_name, self.last_name)

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)

    def generate_auth_token(self, expiration=7200):
        s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
        return s.dumps({'id': self.id})

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return None  # valid token, but expired
        except BadSignature:
            return None  # invalid token
        user = User.query.get(data['id'])
        return user

Prompt: Add User object to model


import unittest
import mongomock
import ulstats
from dlstats.fetchers._skeleton import (Skeleton, Category, Series, BulkSeries,
                                      Dataset, Provider)
import datetime
from bson import ObjectId

#class CategoriesTestCase(unittest.TestCase):

#if __name__ == '__main__':
#    unittest.main()

Comment test for the moment

Comment test for the moment

Response:
<INSERT> import unittest
import mongomock
import ulstats
from dlstats.fetchers._skeleton import (Skeleton, Category, Series, BulkSeries,
 <INSERT_END> <INSERT>                                     Dataset, Provider)
import datetime
from bson import ObjectId

#class CategoriesTestCase(unittest.TestCase):

#if __name__ == '__main__':
#    unittest.main()
 <INSERT_END> <|endoftext|> import unittest
import mongomock
import ulstats
from dlstats.fetchers._skeleton import (Skeleton, Category, Series, BulkSeries,
                                      Dataset, Provider)
import datetime
from bson import ObjectId

#class CategoriesTestCase(unittest.TestCase):

#if __name__ == '__main__':
#    unittest.main()

Prompt: Comment test for the moment


from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

class LegacyPaginator(PageNumberPagination):
    """
    A legacy paginator that mocks the one from Eve Python
    """
    page_size = 25
    page_size_query_param = "max_results"
    max_page_size = 100

    def get_paginated_response(self, data):
        links = OrderedDict()
        if self.page.has_next():
            links['next'] = OrderedDict([
                ('href', self.get_next_link()),
                ('title', _('page suivante')),
            ])
        if self.page.has_previous():
            links['prev'] = OrderedDict([
                ('href', self.get_previous_link()),
                ('title', _('page précédente')),
            ])

        meta = OrderedDict([
            ('max_results', self.page.paginator.per_page),
            ('total', self.page.paginator.count),
            ('page', self.page.number),
        ])

        return Response(OrderedDict([
            ('_items', data),
            ('_links', links),
            ('_meta', meta),
        ]))

Response:
<REPLACE_OLD> "max_results"

 <REPLACE_NEW> "max_results"
    max_page_size = 100

 <REPLACE_END> <|endoftext|> from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

class LegacyPaginator(PageNumberPagination):
    """
    A legacy paginator that mocks the one from Eve Python
    """
    page_size = 25
    page_size_query_param = "max_results"
    max_page_size = 100

    def get_paginated_response(self, data):
        links = OrderedDict()
        if self.page.has_next():
            links['next'] = OrderedDict([
                ('href', self.get_next_link()),
                ('title', _('page suivante')),
            ])
        if self.page.has_previous():
            links['prev'] = OrderedDict([
                ('href', self.get_previous_link()),
                ('title', _('page précédente')),
            ])

        meta = OrderedDict([
            ('max_results', self.page.paginator.per_page),
            ('total', self.page.paginator.count),
            ('page', self.page.number),
        ])

        return Response(OrderedDict([
            ('_items', data),
            ('_links', links),
            ('_meta', meta),
        ]))

Prompt:
Set a maximum to the number of elements that may be requested

from collections import OrderedDict
from django.utils.translation import ugettext_lazy as _
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

class LegacyPaginator(PageNumberPagination):
    """
    A legacy paginator that mocks the one from Eve Python
    """
    page_size = 25
    page_size_query_param = "max_results"

    def get_paginated_response(self, data):
        links = OrderedDict()
        if self.page.has_next():
            links['next'] = OrderedDict([
                ('href', self.get_next_link()),
                ('title', _('page suivante')),
            ])
        if self.page.has_previous():
            links['prev'] = OrderedDict([
                ('href', self.get_previous_link()),
                ('title', _('page précédente')),
            ])

        meta = OrderedDict([
            ('max_results', self.page.paginator.per_page),
            ('total', self.page.paginator.count),
            ('page', self.page.number),
        ])

        return Response(OrderedDict([
            ('_items', data),
            ('_links', links),
            ('_meta', meta),
        ]))


"""createTodoFile.py: Creates an todo file with title name as current date"""

import os.path
import time

def createfile():
    # My-File--2009-12-31--23-59-59.txt
    date = time.strftime("%d-%m-%Y")
    filename = "GOALS--" + date + ".todo"
    if not os.path.exists(filename):
        with open(filename, "a") as myfile:
            myfile.write("[RESULTS - {}]".format(date))
        print("INFO: " + filename + " created!")
        addfileToSublime(filename)
    else:
        print("ERROR: " + filename + " already exist! Exiting..")

def addfileToSublime(file):
    os.system("subl --add " + file)

def main():
    createfile()

if __name__ == '__main__':
    main()

Add created file to sublime

feat: Add created file to sublime

Response:
<REPLACE_OLD> time
import os.path

def <REPLACE_NEW> os.path
import time

def <REPLACE_END> <INSERT>     addfileToSublime(filename)
    <INSERT_END> <REPLACE_OLD> Exiting..")

# TODO: To move files into archive if more than a week
def archiveFiles():
 <REPLACE_NEW> Exiting..")

def addfileToSublime(file):
 <REPLACE_END> <REPLACE_OLD> pass

def <REPLACE_NEW> os.system("subl --add " + file)

def <REPLACE_END> <|endoftext|> """createTodoFile.py: Creates an todo file with title name as current date"""

import os.path
import time

def createfile():
    # My-File--2009-12-31--23-59-59.txt
    date = time.strftime("%d-%m-%Y")
    filename = "GOALS--" + date + ".todo"
    if not os.path.exists(filename):
        with open(filename, "a") as myfile:
            myfile.write("[RESULTS - {}]".format(date))
        print("INFO: " + filename + " created!")
        addfileToSublime(filename)
    else:
        print("ERROR: " + filename + " already exist! Exiting..")

def addfileToSublime(file):
    os.system("subl --add " + file)

def main():
    createfile()

if __name__ == '__main__':
    main()

Prompt:
feat: Add created file to sublime

"""createTodoFile.py: Creates an todo file with title name as current date"""

import time
import os.path

def createfile():
    # My-File--2009-12-31--23-59-59.txt
    date = time.strftime("%d-%m-%Y")
    filename = "GOALS--" + date + ".todo"
    if not os.path.exists(filename):
        with open(filename, "a") as myfile:
            myfile.write("[RESULTS - {}]".format(date))
        print("INFO: " + filename + " created!")
    else:
        print("ERROR: " + filename + " already exist! Exiting..")

# TODO: To move files into archive if more than a week
def archiveFiles():
    pass

def main():
    createfile()

if __name__ == '__main__':
    main()


#!/usr/bin/env python

import cleanup_marathon_orphaned_images

# These should be left running
mesos_deployed_old = {
    'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
    'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
    'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
    'Names': ['/mesos-undeployed-old', ],
}
running_images = [
    mesos_deployed_old,
    nonmesos_undeployed_old,
    mesos_undeployed_young,
    mesos_undeployed_old,
]

def test_get_mesos_images():
    assert nonmesos_undeployed_old in running_images
    actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
    assert nonmesos_undeployed_old not in actual

def test_get_old_images():
    pass

Clarify intent and fail fast

Clarify intent and fail fast

Response:
<INSERT> assert nonmesos_undeployed_old in running_images
    <INSERT_END> <|endoftext|> #!/usr/bin/env python

import cleanup_marathon_orphaned_images

# These should be left running
mesos_deployed_old = {
    'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
    'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
    'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
    'Names': ['/mesos-undeployed-old', ],
}
running_images = [
    mesos_deployed_old,
    nonmesos_undeployed_old,
    mesos_undeployed_young,
    mesos_undeployed_old,
]

def test_get_mesos_images():
    assert nonmesos_undeployed_old in running_images
    actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
    assert nonmesos_undeployed_old not in actual

def test_get_old_images():
    pass

Prompt:
Clarify intent and fail fast

#!/usr/bin/env python

import cleanup_marathon_orphaned_images

# These should be left running
mesos_deployed_old = {
    'Names': ['/mesos-deployed-old', ],
}
mesos_undeployed_young = {
    'Names': ['/mesos-undeployed-young', ],
}
nonmesos_undeployed_old = {
    'Names': ['/nonmesos-undeployed-old', ],
}
# These should be cleaned up
mesos_undeployed_old = {
    'Names': ['/mesos-undeployed-old', ],
}
running_images = [
    mesos_deployed_old,
    nonmesos_undeployed_old,
    mesos_undeployed_young,
    mesos_undeployed_old,
]

def test_get_mesos_images():
    actual = cleanup_marathon_orphaned_images.get_mesos_images(running_images)
    assert nonmesos_undeployed_old not in actual

def test_get_old_images():
    pass


import pytest

from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession

from virtool.models import Base

@pytest.fixture(scope="function")
async def engine():
    engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
    async with engine.connect() as conn:
        try:
            await conn.execute(text("CREATE DATABASE test"))
        except ProgrammingError:
            pass
    return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test")

@pytest.fixture(scope="function")
async def dbsession(engine, loop):
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

    session = AsyncSession(bind=engine)
    yield session
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await session.close()

Add fixtures for connecting to Postgres test database

Response:
<INSERT> import pytest

from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession

from virtool.models import Base

@pytest.fixture(scope="function")
async def engine():
 <INSERT_END> <INSERT>   engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
    async with engine.connect() as conn:
        try:
            await conn.execute(text("CREATE DATABASE test"))
        except ProgrammingError:
            pass
    return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test")

@pytest.fixture(scope="function")
async def dbsession(engine, loop):
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

    session = AsyncSession(bind=engine)
    yield session
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await session.close() <INSERT_END> <|endoftext|> import pytest

from sqlalchemy import text
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.ext.asyncio import AsyncSession

from virtool.models import Base

@pytest.fixture(scope="function")
async def engine():
    engine = create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/virtool", isolation_level="AUTOCOMMIT")
    async with engine.connect() as conn:
        try:
            await conn.execute(text("CREATE DATABASE test"))
        except ProgrammingError:
            pass
    return create_async_engine("postgresql+asyncpg://virtool:virtool@localhost/test")

@pytest.fixture(scope="function")
async def dbsession(engine, loop):
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

    session = AsyncSession(bind=engine)
    yield session
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
    await session.close()

Prompt: Add fixtures for connecting to Postgres test database


from jinja2 import Markup

def null_formatter(value):
    """
        Return `NULL` as the string for `None` value

        :param value:
            Value to check
    """
    return Markup('NULL')

def empty_formatter(value):
    """
        Return empty string for `None` value

        :param value:
            Value to check
    """
    return ''

def bool_formatter(value):
    """
        Return check icon if value is `True` or empty string otherwise.

        :param value:
            Value to check
    """
    return Markup('' if value else '')

def list_formatter(values):
    """
        Return string with comma separated values

        :param values:
            Value to check
    """
    return u', '.join(values)

DEFAULT_FORMATTERS = {
    type(None): empty_formatter,
    bool: bool_formatter,
    list: list_formatter,
}

Response:
<REPLACE_OLD> '')

DEFAULT_FORMATTERS <REPLACE_NEW> '')

def list_formatter(values):
    """
        Return string with comma separated values

        :param values:
            Value to check
    """
    return u', '.join(values)

DEFAULT_FORMATTERS <REPLACE_END> <REPLACE_OLD> bool_formatter
}
 <REPLACE_NEW> bool_formatter,
    list: list_formatter,
}
 <REPLACE_END> <|endoftext|> from jinja2 import Markup

def null_formatter(value):
    """
        Return `NULL` as the string for `None` value

        :param value:
            Value to check
    """
    return Markup('<i>NULL</i>')

def empty_formatter(value):
    """
        Return empty string for `None` value

        :param value:
            Value to check
    """
    return ''

def bool_formatter(value):
    """
        Return check icon if value is `True` or empty string otherwise.

        :param value:
            Value to check
    """
    return Markup('<i class="icon-ok"></i>' if value else '')

def list_formatter(values):
    """
        Return string with comma separated values

        :param values:
            Value to check
    """
    return u', '.join(values)

DEFAULT_FORMATTERS = {
    type(None): empty_formatter,
    bool: bool_formatter,
    list: list_formatter,
}

Prompt:
Add extra type formatter for `list` type

from jinja2 import Markup

def null_formatter(value):
    """
        Return `NULL` as the string for `None` value

        :param value:
            Value to check
    """
    return Markup('NULL')

def empty_formatter(value):
    """
        Return empty string for `None` value

        :param value:
            Value to check
    """
    return ''

def bool_formatter(value):
    """
        Return check icon if value is `True` or empty string otherwise.

        :param value:
            Value to check
    """
    return Markup('' if value else '')

DEFAULT_FORMATTERS = {
    type(None): empty_formatter,
    bool: bool_formatter
}


from django.contrib.auth import get_user_model

from .oauth2_backends import get_oauthlib_core

UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()

class OAuth2Backend(object):
    """
    Authenticate against an OAuth2 access token
    """

    def authenticate(self, **credentials):
        request = credentials.get('request')
        if request is not None:
            valid, r = OAuthLibCore.verify_request(request, scopes=[])
            if valid:
                return r.user
        return None

    def get_user(self, user_id):
        try:
            return UserModel.objects.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None

Response:
<DELETE> oauthlib_core = get_oauthlib_core()
            <DELETE_END> <REPLACE_OLD> oauthlib_core.verify_request(request, <REPLACE_NEW> OAuthLibCore.verify_request(request, <REPLACE_END> <|endoftext|> from django.contrib.auth import get_user_model

from .oauth2_backends import get_oauthlib_core

UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()

class OAuth2Backend(object):
    """
    Authenticate against an OAuth2 access token
    """

    def authenticate(self, **credentials):
        request = credentials.get('request')
        if request is not None:
            valid, r = OAuthLibCore.verify_request(request, scopes=[])
            if valid:
                return r.user
        return None

    def get_user(self, user_id):
        try:
            return UserModel.objects.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None

Prompt:
Use the OAuthLibCore object defined at the module level.

from django.contrib.auth import get_user_model

from .oauth2_backends import get_oauthlib_core

UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()

class OAuth2Backend(object):
    """
    Authenticate against an OAuth2 access token
    """

    def authenticate(self, **credentials):
        request = credentials.get('request')
        if request is not None:
            oauthlib_core = get_oauthlib_core()
            valid, r = oauthlib_core.verify_request(request, scopes=[])
            if valid:
                return r.user
        return None

    def get_user(self, user_id):
        try:
            return UserModel.objects.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None


import os
import sys

from nose.tools import *

try:
	from importlib import reload
except ImportError:
	pass

def setup_yamlmod():
	import yamlmod
	reload(yamlmod)

def teardown_yamlmod():
	import yamlmod

	for hook in sys.meta_path:
		if isinstance(hook, yamlmod.YamlImportHook):
			sys.meta_path.remove(hook)
			break

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_installs_hook():
	import yamlmod

	hooks = []

	for hook in sys.meta_path:
		if isinstance(hook, yamlmod.YamlImportHook):
			hooks.append(hook)

	eq_(len(hooks), 1, 'did not find exactly one hook')

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_fixture():
	import fixture

	eq_(fixture.debug, True)
	eq_(fixture.domain, 'example.com')
	eq_(fixture.users, ['alice', 'bob', 'cathy'])

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_hidden_attributes():
	import fixture

	eq_(fixture.__name__, 'fixture')
	eq_(fixture.__file__, os.path.join(os.path.dirname(__file__), 'fixture.yml'))

Fix tests on python 3

Fix tests on python 3

Response:
<REPLACE_OLD> *

def <REPLACE_NEW> *

try:
	from importlib import reload
except ImportError:
	pass

def <REPLACE_END> <|endoftext|> import os
import sys

from nose.tools import *

try:
	from importlib import reload
except ImportError:
	pass

def setup_yamlmod():
	import yamlmod
	reload(yamlmod)

def teardown_yamlmod():
	import yamlmod

	for hook in sys.meta_path:
		if isinstance(hook, yamlmod.YamlImportHook):
			sys.meta_path.remove(hook)
			break

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_installs_hook():
	import yamlmod

	hooks = []

	for hook in sys.meta_path:
		if isinstance(hook, yamlmod.YamlImportHook):
			hooks.append(hook)

	eq_(len(hooks), 1, 'did not find exactly one hook')

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_fixture():
	import fixture

	eq_(fixture.debug, True)
	eq_(fixture.domain, 'example.com')
	eq_(fixture.users, ['alice', 'bob', 'cathy'])

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_hidden_attributes():
	import fixture

	eq_(fixture.__name__, 'fixture')
	eq_(fixture.__file__, os.path.join(os.path.dirname(__file__), 'fixture.yml'))

Prompt:
Fix tests on python 3

import os
import sys

from nose.tools import *

def setup_yamlmod():
	import yamlmod
	reload(yamlmod)

def teardown_yamlmod():
	import yamlmod

	for hook in sys.meta_path:
		if isinstance(hook, yamlmod.YamlImportHook):
			sys.meta_path.remove(hook)
			break

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_installs_hook():
	import yamlmod

	hooks = []

	for hook in sys.meta_path:
		if isinstance(hook, yamlmod.YamlImportHook):
			hooks.append(hook)

	eq_(len(hooks), 1, 'did not find exactly one hook')

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_fixture():
	import fixture

	eq_(fixture.debug, True)
	eq_(fixture.domain, 'example.com')
	eq_(fixture.users, ['alice', 'bob', 'cathy'])

@with_setup(setup_yamlmod, teardown_yamlmod)
def test_hidden_attributes():
	import fixture

	eq_(fixture.__name__, 'fixture')
	eq_(fixture.__file__, os.path.join(os.path.dirname(__file__), 'fixture.yml'))


import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal

def is_zip(tmp):
    """
    Returns True if the NamedTemporaryFile given as the argument appears to be
    a well-formed Zip file.
    """

    try:
        zip_file = zipfile.ZipFile(tmp.name, 'r')
        test_result = zip_file.testzip()
        return test_result is None

    except:
        pass

    return False

def tar_gz_has_gdal(member_name):
    """
    Returns a function which, when called with a NamedTemporaryFile, returns
    True if that file is a GZip-encoded TAR file containing a `member_name`
    member which can be opened with GDAL.
    """

    def func(tmp):
        try:
            tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2)
            with tempfile.NamedTemporaryFile() as tmp_member:
                shutil.copyfileobj(tar.extractfile(member_name), tmp_member)
                tmp_member.seek(0)
                return is_gdal(tmp_member)

        except (tarfile.TarError, IOError, OSError) as e:
            return False

    return func

def is_gdal(tmp):
    """
    Returns true if the NamedTemporaryFile given as the argument appears to be
    a well-formed GDAL raster file.
    """

    try:
        ds = gdal.Open(tmp.name)
        band = ds.GetRasterBand(1)
        band.ComputeBandStats()
        return True

    except:
        pass

    return False

Response:
<INSERT> tmp_member.seek(0)
                <INSERT_END> <REPLACE_OLD> False

def <REPLACE_NEW> False

    return func

def <REPLACE_END> <|endoftext|> import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal

def is_zip(tmp):
    """
    Returns True if the NamedTemporaryFile given as the argument appears to be
    a well-formed Zip file.
    """

    try:
        zip_file = zipfile.ZipFile(tmp.name, 'r')
        test_result = zip_file.testzip()
        return test_result is None

    except:
        pass

    return False

def tar_gz_has_gdal(member_name):
    """
    Returns a function which, when called with a NamedTemporaryFile, returns
    True if that file is a GZip-encoded TAR file containing a `member_name`
    member which can be opened with GDAL.
    """

    def func(tmp):
        try:
            tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2)
            with tempfile.NamedTemporaryFile() as tmp_member:
                shutil.copyfileobj(tar.extractfile(member_name), tmp_member)
                tmp_member.seek(0)
                return is_gdal(tmp_member)

        except (tarfile.TarError, IOError, OSError) as e:
            return False

    return func

def is_gdal(tmp):
    """
    Returns true if the NamedTemporaryFile given as the argument appears to be
    a well-formed GDAL raster file.
    """

    try:
        ds = gdal.Open(tmp.name)
        band = ds.GetRasterBand(1)
        band.ComputeBandStats()
        return True

    except:
        pass

    return False

Prompt:
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.

import zipfile
import tarfile
import shutil
import tempfile
from osgeo import gdal

def is_zip(tmp):
    """
    Returns True if the NamedTemporaryFile given as the argument appears to be
    a well-formed Zip file.
    """

    try:
        zip_file = zipfile.ZipFile(tmp.name, 'r')
        test_result = zip_file.testzip()
        return test_result is None

    except:
        pass

    return False

def tar_gz_has_gdal(member_name):
    """
    Returns a function which, when called with a NamedTemporaryFile, returns
    True if that file is a GZip-encoded TAR file containing a `member_name`
    member which can be opened with GDAL.
    """

    def func(tmp):
        try:
            tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2)
            with tempfile.NamedTemporaryFile() as tmp_member:
                shutil.copyfileobj(tar.extractfile(member_name), tmp_member)
                return is_gdal(tmp_member)

        except (tarfile.TarError, IOError, OSError) as e:
            return False

def is_gdal(tmp):
    """
    Returns true if the NamedTemporaryFile given as the argument appears to be
    a well-formed GDAL raster file.
    """

    try:
        ds = gdal.Open(tmp.name)
        band = ds.GetRasterBand(1)
        band.ComputeBandStats()
        return True

    except:
        pass

    return False


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...

"""

import grp

class User(object):
    """Something, something, something darkside...."""

    def __init__(self, settingsInstance, commandInstance, cmdName, *args):
        super(User, self).__init__()
        self.settingsInstance = settingsInstance
        self.commandInstance = commandInstance
        if cmdName is not None:
            if args[0] is not None:
                getattr(self, cmdName)(*args)
            else:
                getattr(self, cmdName)()

    def testuser(self):
        self.commandInstance.replyWithMessage(
            self.commandInstance.user
        )

    def testchannel(self):
        self.commandInstance.replyWithMessage(
            self.commandInstance.channel
        )

    def users(self):
        """Get a list of users in the users group."""
        self.commandInstance.replyWithMessage(self._users())

    def _users(self, output='string'):
        for group in grp.getgrall():
            if group.gr_name == 'users':
                members = group.gr_mem
        if output == 'list':
            return members
        else:
            return ', '.join(members)

Test if you can return the channel.

Test if you can return the channel.

Response:
<REPLACE_OLD> test(self):
 <REPLACE_NEW> testuser(self):
 <REPLACE_END> <INSERT>        )

    def testchannel(self):
        self.commandInstance.replyWithMessage(
            self.commandInstance.channel
 <INSERT_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...

"""

import grp

class User(object):
    """Something, something, something darkside...."""

    def __init__(self, settingsInstance, commandInstance, cmdName, *args):
        super(User, self).__init__()
        self.settingsInstance = settingsInstance
        self.commandInstance = commandInstance
        if cmdName is not None:
            if args[0] is not None:
                getattr(self, cmdName)(*args)
            else:
                getattr(self, cmdName)()

    def testuser(self):
        self.commandInstance.replyWithMessage(
            self.commandInstance.user
        )

    def testchannel(self):
        self.commandInstance.replyWithMessage(
            self.commandInstance.channel
        )

    def users(self):
        """Get a list of users in the users group."""
        self.commandInstance.replyWithMessage(self._users())

    def _users(self, output='string'):
        for group in grp.getgrall():
            if group.gr_name == 'users':
                members = group.gr_mem
        if output == 'list':
            return members
        else:
            return ', '.join(members)

Prompt:
Test if you can return the channel.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...

"""

import grp

class User(object):
    """Something, something, something darkside...."""

    def __init__(self, settingsInstance, commandInstance, cmdName, *args):
        super(User, self).__init__()
        self.settingsInstance = settingsInstance
        self.commandInstance = commandInstance
        if cmdName is not None:
            if args[0] is not None:
                getattr(self, cmdName)(*args)
            else:
                getattr(self, cmdName)()

    def test(self):
        self.commandInstance.replyWithMessage(
            self.commandInstance.user
        )

    def users(self):
        """Get a list of users in the users group."""
        self.commandInstance.replyWithMessage(self._users())

    def _users(self, output='string'):
        for group in grp.getgrall():
            if group.gr_name == 'users':
                members = group.gr_mem
        if output == 'list':
            return members
        else:
            return ', '.join(members)


#pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904

import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest

class TestCleanupJobs(osgunittest.OSGTestCase):
    """Clean any configuration we touched for running jobs"""

    def test_01_restore_job_env(self):
        core.skip_ok_unless_one_installed(['htcondor-ce', 'globus-gatekeeper', 'condor'])

        files.restore(core.config['osg.job-environment'], owner='pbs')
        files.restore(core.config['osg.local-job-environment'], owner='pbs')

Response:
<DELETE> core.skip_ok_unless_installed('osg-configure')
        <DELETE_END> <|endoftext|> #pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904

import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest

class TestCleanupJobs(osgunittest.OSGTestCase):
    """Clean any configuration we touched for running jobs"""

    def test_01_restore_job_env(self):
        core.skip_ok_unless_one_installed(['htcondor-ce', 'globus-gatekeeper', 'condor'])

        files.restore(core.config['osg.job-environment'], owner='pbs')
        files.restore(core.config['osg.local-job-environment'], owner='pbs')

Prompt:
Drop job env backup cleanup dependence on osg-configure

We already dropped the creation of the job env files in 840ea8

#pylint: disable=C0301
#pylint: disable=C0111
#pylint: disable=R0201
#pylint: disable=R0904

import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest

class TestCleanupJobs(osgunittest.OSGTestCase):
    """Clean any configuration we touched for running jobs"""

    def test_01_restore_job_env(self):
        core.skip_ok_unless_installed('osg-configure')
        core.skip_ok_unless_one_installed(['htcondor-ce', 'globus-gatekeeper', 'condor'])

        files.restore(core.config['osg.job-environment'], owner='pbs')
        files.restore(core.config['osg.local-job-environment'], owner='pbs')


import os
import sys
import setuptools

from keystoneclient.openstack.common import setup

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

requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-requires'])

setuptools.setup(
    name="python-keystoneclient",
    version=setup.get_post_version('keystoneclient'),
    description="Client library for OpenStack Keystone API",
    long_description=read('README.rst'),
    url='https://github.com/openstack/python-keystoneclient',
    license='Apache',
    author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
    author_email='gabriel.hurley@nebula.com',
    packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: OpenStack',
        'Intended Audience :: Developers',
        'Intended Audience :: Information Technology',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
    install_requires=requires,
    dependency_links=depend_links,
    cmdclass=setup.get_cmdclass(),

    tests_require=tests_require,
    test_suite="nose.collector",

    entry_points={
        'console_scripts': ['keystone = keystoneclient.shell:main']
    }
)

Add OpenStack trove classifier for PyPI

Response:
<INSERT> 'Environment :: OpenStack',
        <INSERT_END> <|endoftext|> import os
import sys
import setuptools

from keystoneclient.openstack.common import setup

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

requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-requires'])

setuptools.setup(
    name="python-keystoneclient",
    version=setup.get_post_version('keystoneclient'),
    description="Client library for OpenStack Keystone API",
    long_description=read('README.rst'),
    url='https://github.com/openstack/python-keystoneclient',
    license='Apache',
    author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
    author_email='gabriel.hurley@nebula.com',
    packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Environment :: OpenStack',
        'Intended Audience :: Developers',
        'Intended Audience :: Information Technology',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
    install_requires=requires,
    dependency_links=depend_links,
    cmdclass=setup.get_cmdclass(),

    tests_require=tests_require,
    test_suite="nose.collector",

    entry_points={
        'console_scripts': ['keystone = keystoneclient.shell:main']
    }
)

Prompt:
Add OpenStack trove classifier for PyPI

Add trove classifier to have the client listed among the
other OpenStack-related projets on PyPI.

Change-Id: I1ddae8d1272a2b1c5e4c666c9aa4e4a274431415
Signed-off-by: Doug Hellmann <8c845c26a3868dadec615703cd974244eb2ac6d1@dreamhost.com>

import os
import sys
import setuptools

from keystoneclient.openstack.common import setup

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

requires = setup.parse_requirements()
depend_links = setup.parse_dependency_links()
tests_require = setup.parse_requirements(['tools/test-requires'])

setuptools.setup(
    name="python-keystoneclient",
    version=setup.get_post_version('keystoneclient'),
    description="Client library for OpenStack Keystone API",
    long_description=read('README.rst'),
    url='https://github.com/openstack/python-keystoneclient',
    license='Apache',
    author='Nebula Inc, based on work by Rackspace and Jacob Kaplan-Moss',
    author_email='gabriel.hurley@nebula.com',
    packages=setuptools.find_packages(exclude=['tests', 'tests.*']),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: Information Technology',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
    install_requires=requires,
    dependency_links=depend_links,
    cmdclass=setup.get_cmdclass(),

    tests_require=tests_require,
    test_suite="nose.collector",

    entry_points={
        'console_scripts': ['keystone = keystoneclient.shell:main']
    }
)


import time

class BlinkyPlayer(object):
    FOREVER = -1

    def __init__(self, blinkytape):
        self._blinkytape = blinkytape

    def play(self, animation, num_cycles = FOREVER):
        finished = self._finished_predicate(animation, num_cycles)
        animation.begin()
        while not finished():
            pixels = animation.next_frame()
            self._blinkytape.update(pixels)
            time.sleep(animation.frame_period_sec)
        animation.end()

    def _finished_predicate(self, animation, num_cycles):
        if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError
        if num_cycles == self.FOREVER:
            predicate = self._forever_predicate()
        else:
            self._num_frames = animation.frame_count * num_cycles
            predicate = self._frame_count_predicate()
        return predicate

    def _forever_predicate(self):
        return lambda: False

    def _frame_count_predicate(self):
        def predicate():
            finished = self._num_frames <= 0
            self._num_frames = self._num_frames - 1
            return finished
        return predicate

Clean up BlinkyPlayer a little

Clean up BlinkyPlayer a little

Response:
<REPLACE_OLD> self._make_finished_predicate(animation, <REPLACE_NEW> self._finished_predicate(animation, <REPLACE_END> <REPLACE_OLD> _make_finished_predicate(self, <REPLACE_NEW> _finished_predicate(self, <REPLACE_END> <REPLACE_OLD> lambda: False
 <REPLACE_NEW> self._forever_predicate()
 <REPLACE_END> <INSERT> predicate = self._frame_count_predicate()
        return predicate

    def _forever_predicate(self):
        return lambda: False

    def _frame_count_predicate(self):
        <INSERT_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <|endoftext|> import time

class BlinkyPlayer(object):
    FOREVER = -1

    def __init__(self, blinkytape):
        self._blinkytape = blinkytape

    def play(self, animation, num_cycles = FOREVER):
        finished = self._finished_predicate(animation, num_cycles)
        animation.begin()
        while not finished():
            pixels = animation.next_frame()
            self._blinkytape.update(pixels)
            time.sleep(animation.frame_period_sec)
        animation.end()

    def _finished_predicate(self, animation, num_cycles):
        if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError
        if num_cycles == self.FOREVER:
            predicate = self._forever_predicate()
        else:
            self._num_frames = animation.frame_count * num_cycles
            predicate = self._frame_count_predicate()
        return predicate

    def _forever_predicate(self):
        return lambda: False

    def _frame_count_predicate(self):
        def predicate():
            finished = self._num_frames <= 0
            self._num_frames = self._num_frames - 1
            return finished
        return predicate

Prompt:
Clean up BlinkyPlayer a little

import time

class BlinkyPlayer(object):
    FOREVER = -1

    def __init__(self, blinkytape):
        self._blinkytape = blinkytape

    def play(self, animation, num_cycles = FOREVER):
        finished = self._make_finished_predicate(animation, num_cycles)
        animation.begin()
        while not finished():
            pixels = animation.next_frame()
            self._blinkytape.update(pixels)
            time.sleep(animation.frame_period_sec)
        animation.end()

    def _make_finished_predicate(self, animation, num_cycles):
        if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError
        if num_cycles == self.FOREVER:
            predicate = lambda: False
        else:
            self._num_frames = animation.frame_count * num_cycles
            def predicate():
                finished = self._num_frames <= 0
                self._num_frames = self._num_frames - 1
                return finished
        return predicate


def print_header():
    import sys
    from dxtbx.format.Registry import Registry

    # this will do the lookup for every frame - this is strictly not needed
    # if all frames are from the same instrument

    for arg in sys.argv[1:]:
        format = Registry.find(arg)
        print 'Using header reader: %s' % format.__name__
        i = format(arg)
        print 'Beam:'
        print i.get_beam()
        print 'Goniometer:'
        print i.get_goniometer()
        print 'Detector:'
        print i.get_detector()
        print 'Scan:'
        print i.get_scan()
        print 'Total Counts:'
        print sum(i.get_raw_data())

if __name__ == '__main__':
    print_header()

Print the Format class used

Print the Format class used

Response:
<INSERT>        print 'Using header reader: %s' % format.__name__
 <INSERT_END> <|endoftext|> def print_header():
    import sys
    from dxtbx.format.Registry import Registry

    # this will do the lookup for every frame - this is strictly not needed
    # if all frames are from the same instrument

    for arg in sys.argv[1:]:
        format = Registry.find(arg)
        print 'Using header reader: %s' % format.__name__
        i = format(arg)
        print 'Beam:'
        print i.get_beam()
        print 'Goniometer:'
        print i.get_goniometer()
        print 'Detector:'
        print i.get_detector()
        print 'Scan:'
        print i.get_scan()
        print 'Total Counts:'
        print sum(i.get_raw_data())

if __name__ == '__main__':
    print_header()

Prompt:
Print the Format class used
def print_header():
    import sys
    from dxtbx.format.Registry import Registry

    # this will do the lookup for every frame - this is strictly not needed
    # if all frames are from the same instrument

    for arg in sys.argv[1:]:
        format = Registry.find(arg)
        i = format(arg)
        print 'Beam:'
        print i.get_beam()
        print 'Goniometer:'
        print i.get_goniometer()
        print 'Detector:'
        print i.get_detector()
        print 'Scan:'
        print i.get_scan()
        print 'Total Counts:'
        print sum(i.get_raw_data())

if __name__ == '__main__':
    print_header()


"""Test that the clang modules cache directory can be controlled."""

from __future__ import print_function

import unittest2
import os
import time
import platform
import shutil

import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil

class ObjCModulesTestCase(TestBase):
    NO_DEBUG_INFO_TESTCASE = True
    mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        TestBase.setUp(self)

    @skipUnlessDarwin
    def test_expr(self):
        self.build()
        self.main_source_file = lldb.SBFileSpec("main.m")
        self.runCmd("settings set target.auto-import-clang-modules true")
        mod_cache = self.getBuildArtifact("my-clang-modules-cache")
        if os.path.isdir(mod_cache):
          shutil.rmtree(mod_cache)
        self.assertFalse(os.path.isdir(mod_cache),
                         "module cache should not exist")
        self.runCmd('settings set clang.modules-cache-path "%s"' % mod_cache)
        self.runCmd('settings set target.clang-module-search-paths "%s"'
                    % self.getSourceDir())
        (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(
            self, "Set breakpoint here", self.main_source_file)
        self.runCmd("expr @import Foo")
        self.assertTrue(os.path.isdir(mod_cache), "module cache exists")

Response:
<INSERT> @skipUnlessDarwin
    <INSERT_END> <REPLACE_OLD> Darwin")
 <REPLACE_NEW> Foo")
 <REPLACE_END> <|endoftext|> """Test that the clang modules cache directory can be controlled."""

from __future__ import print_function

import unittest2
import os
import time
import platform
import shutil

import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil

class ObjCModulesTestCase(TestBase):
    NO_DEBUG_INFO_TESTCASE = True
    mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        TestBase.setUp(self)

    @skipUnlessDarwin
    def test_expr(self):
        self.build()
        self.main_source_file = lldb.SBFileSpec("main.m")
        self.runCmd("settings set target.auto-import-clang-modules true")
        mod_cache = self.getBuildArtifact("my-clang-modules-cache")
        if os.path.isdir(mod_cache):
          shutil.rmtree(mod_cache)
        self.assertFalse(os.path.isdir(mod_cache),
                         "module cache should not exist")
        self.runCmd('settings set clang.modules-cache-path "%s"' % mod_cache)
        self.runCmd('settings set target.clang-module-search-paths "%s"'
                    % self.getSourceDir())
        (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(
            self, "Set breakpoint here", self.main_source_file)
        self.runCmd("expr @import Foo")
        self.assertTrue(os.path.isdir(mod_cache), "module cache exists")

Prompt:
Mark ObjC testcase as skipUnlessDarwin and fix a typo in test function.

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@326640 91177308-0d34-0410-b5e6-96231b3b80d8

"""Test that the clang modules cache directory can be controlled."""

from __future__ import print_function

import unittest2
import os
import time
import platform
import shutil

import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil

class ObjCModulesTestCase(TestBase):
    NO_DEBUG_INFO_TESTCASE = True
    mydir = TestBase.compute_mydir(__file__)

    def setUp(self):
        TestBase.setUp(self)

    def test_expr(self):
        self.build()
        self.main_source_file = lldb.SBFileSpec("main.m")
        self.runCmd("settings set target.auto-import-clang-modules true")
        mod_cache = self.getBuildArtifact("my-clang-modules-cache")
        if os.path.isdir(mod_cache):
          shutil.rmtree(mod_cache)
        self.assertFalse(os.path.isdir(mod_cache),
                         "module cache should not exist")
        self.runCmd('settings set clang.modules-cache-path "%s"' % mod_cache)
        self.runCmd('settings set target.clang-module-search-paths "%s"'
                    % self.getSourceDir())
        (target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(
            self, "Set breakpoint here", self.main_source_file)
        self.runCmd("expr @import Darwin")
        self.assertTrue(os.path.isdir(mod_cache), "module cache exists")


import sys
import os
import argparse
import shutil

from efselab import build

parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
parser.add_argument('--update', action="store_true")
args = parser.parse_args()

if not any(vars(args).values()):
    parser.print_help()
elif args.run:
    os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
    os.system("git push heroku master")
elif args.update:
    if not os.path.exists("../efselab/"):
        sys.exit("Couldn't find a local efselab checkout...")

    shutil.copy("../efselab/fasthash.c", "./efselab")
    shutil.copy("../efselab/lemmatize.c", "./efselab")
    shutil.copy("../efselab/pysuc.c", "./efselab/suc.c")

    if not os.path.exists("../efselab/swe-pipeline"):
        sys.exit("Couldn't find a local swe-pipeline directory for models...")

    shutil.copy("../efselab/swe-pipeline/suc.bin", "./efselab")
    shutil.copy("../efselab/swe-pipeline/suc-saldo.lemmas", "./efselab")

    print("Building new files...")
    os.chdir("efselab")
    build.main()

Response:
<INSERT> sys
import <INSERT_END> <REPLACE_OLD> argparse
parser <REPLACE_NEW> argparse
import shutil

from efselab import build

parser <REPLACE_END> <INSERT> action="store_true")
parser.add_argument('--update', <INSERT_END> <REPLACE_OLD> master")
 <REPLACE_NEW> master")
elif args.update:
    if not os.path.exists("../efselab/"):
        sys.exit("Couldn't find a local efselab checkout...")

    shutil.copy("../efselab/fasthash.c", "./efselab")
    shutil.copy("../efselab/lemmatize.c", "./efselab")
    shutil.copy("../efselab/pysuc.c", "./efselab/suc.c")

    if not os.path.exists("../efselab/swe-pipeline"):
        sys.exit("Couldn't find a local swe-pipeline directory for models...")

    shutil.copy("../efselab/swe-pipeline/suc.bin", "./efselab")
    shutil.copy("../efselab/swe-pipeline/suc-saldo.lemmas", "./efselab")

    print("Building new files...")
    os.chdir("efselab")
    build.main()
 <REPLACE_END> <|endoftext|> import sys
import os
import argparse
import shutil

from efselab import build

parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
parser.add_argument('--update', action="store_true")
args = parser.parse_args()

if not any(vars(args).values()):
    parser.print_help()
elif args.run:
    os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
    os.system("git push heroku master")
elif args.update:
    if not os.path.exists("../efselab/"):
        sys.exit("Couldn't find a local efselab checkout...")

    shutil.copy("../efselab/fasthash.c", "./efselab")
    shutil.copy("../efselab/lemmatize.c", "./efselab")
    shutil.copy("../efselab/pysuc.c", "./efselab/suc.c")

    if not os.path.exists("../efselab/swe-pipeline"):
        sys.exit("Couldn't find a local swe-pipeline directory for models...")

    shutil.copy("../efselab/swe-pipeline/suc.bin", "./efselab")
    shutil.copy("../efselab/swe-pipeline/suc-saldo.lemmas", "./efselab")

    print("Building new files...")
    os.chdir("efselab")
    build.main()

Prompt:
Add new update command that updates efselab dependencies.

Former-commit-id: 6cfed1b9af9c0bbf34b7e58e3aa8ac3bada85aa7
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--run', action="store_true")
parser.add_argument('--deploy', action="store_true")
args = parser.parse_args()

if not any(vars(args).values()):
    parser.print_help()
elif args.run:
    os.system("ENVIRONMENT=development python server.py")
elif args.deploy:
    os.system("git push heroku master")


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

from __future__ import unicode_literals

from flask import session

from indico.core import signals
from indico.core.logger import Logger
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.menu import SideMenuItem

logger = Logger.get('events.roles')

@signals.menu.items.connect_via('event-management-sidemenu')
def _sidemenu_items(sender, event, **kwargs):
    if event.can_manage(session.user):
        roles_section = 'organization' if event.type == 'conference' else 'advanced'
        return SideMenuItem('roles', _('Roles'), url_for('event_roles.manage', event), section=roles_section)

Move roles menu item into a submenu

Response:
<INSERT> roles_section = 'organization' if event.type == 'conference' else 'advanced'
        <INSERT_END> <REPLACE_OLD> 65, icon='medal')
 <REPLACE_NEW> section=roles_section)
 <REPLACE_END> <|endoftext|> # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

from flask import session

from indico.core import signals
from indico.core.logger import Logger
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.menu import SideMenuItem

logger = Logger.get('events.roles')

@signals.menu.items.connect_via('event-management-sidemenu')
def _sidemenu_items(sender, event, **kwargs):
    if event.can_manage(session.user):
        roles_section = 'organization' if event.type == 'conference' else 'advanced'
        return SideMenuItem('roles', _('Roles'), url_for('event_roles.manage', event), section=roles_section)

Prompt:
Move roles menu item into a submenu

- 'organization' for conferences
- 'advanced' for other event types

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

from __future__ import unicode_literals

from flask import session

from indico.core import signals
from indico.core.logger import Logger
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.menu import SideMenuItem

logger = Logger.get('events.roles')

@signals.menu.items.connect_via('event-management-sidemenu')
def _sidemenu_items(sender, event, **kwargs):
    if event.can_manage(session.user):
        return SideMenuItem('roles', _('Roles'), url_for('event_roles.manage', event), 65, icon='medal')


from yapsy.IPlugin import IPlugin
from lib.methods import BaseMethod

class IMethodPlugin(BaseMethod, IPlugin):

  def __init__(self):
    pass

  def setNameAndFactory(self, name, factory):
    self.methodName = name
    self.factory = factory

  @staticmethod
  def supports(methodName):
    raise NotImplementedError

Response:
<REPLACE_OLD> factory
 <REPLACE_NEW> factory

  @staticmethod
  def supports(methodName):
    raise NotImplementedError
 <REPLACE_END> <|endoftext|> from yapsy.IPlugin import IPlugin
from lib.methods import BaseMethod

class IMethodPlugin(BaseMethod, IPlugin):

  def __init__(self):
    pass

  def setNameAndFactory(self, name, factory):
    self.methodName = name
    self.factory = factory

  @staticmethod
  def supports(methodName):
    raise NotImplementedError

Prompt:
Make supports method throw NotImplementedError so that methods failing to implement it does not fail silently

from yapsy.IPlugin import IPlugin
from lib.methods import BaseMethod

class IMethodPlugin(BaseMethod, IPlugin):

  def __init__(self):
    pass

  def setNameAndFactory(self, name, factory):
    self.methodName = name
    self.factory = factory


#!/usr/bin/env python

# note: must be invoked from the top-level sts directory

import time
import argparse
import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from sts.replay_event import *
from sts.dataplane_traces.trace import Trace
from sts.input_traces.log_parser import parse
from tools.pretty_print_input_trace import default_fields, field_formatters

class EventGrouping(object):
  def __init__(self, name):
    self.name = name
    self.events = []

  def append(self, event):
    self.events.append(event)

  def printToConsole(self):
    # TODO(cs): bad feng-shui to have side-effects rather than returning a
    # string. Should refactor field_formatters to not have side-effects
    # either.
    title_str = "====================== %s ======================" % self.name
    print title_str
    for event in self.events:
      for field in default_fields:
        field_formatters[field](event)
    print "=" * len(title_str)

def main(args):
  # N.B. it would be nice to include link discovery or host location discovery
  # events here, but that's specific to the Controller's log output.
  network_failure_events = EventGrouping("Topology Change Events")
  controlplane_failure_events = EventGrouping("Control Plane Blockages")
  controller_failure_events = EventGrouping("Controller Change Events")
  host_events = EventGrouping("Host Migrations")

  event2grouping = {
    SwitchFailure : network_failure_events,
    SwitchRecovery : network_failure_events,
    LinkFailure : network_failure_events,
    LinkRecovery : network_failure_events,
    ControlChannelBlock : controlplane_failure_events,
    ControlChannelUnblock : controlplane_failure_events,
    ControllerFailure : controller_failure_events,
    ControllerRecovery : controller_failure_events,
    BlockControllerPair : controller_failure_events,
    UnblockControllerPair : controller_failure_events,
    HostMigration : host_events,
    # TODO(cs): support TrafficInjection, DataplaneDrop? Might get too noisy.
  }

  with open(args.input) as input_file:
    trace = parse(input_file)
    for event in trace:
      if type(event) in event2grouping:
        event2grouping[type(event)].append(event)

  for grouping in [network_failure_events, controlplane_failure_events,
                   controller_failure_events, host_events]:
    grouping.printToConsole()
    print

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('input', metavar="INPUT",
                      help='The input json file to be printed')
  args = parser.parse_args()

  main(args)

Add simple tool for tabulating classes of event types for readability

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python

# note: must be invoked from the top-level sts directory

import time
import argparse
import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from sts.replay_event import *
from sts.dataplane_traces.trace import Trace
from sts.input_traces.log_parser import parse
from tools.pretty_print_input_trace import default_fields, field_formatters

class EventGrouping(object):
  def __init__(self, name):
    self.name = name
    self.events = []

  def append(self, event):
    self.events.append(event)

  def printToConsole(self):
    # TODO(cs): bad feng-shui to have side-effects rather than returning a
    # string. Should refactor field_formatters to not have side-effects
    # either.
    title_str = "====================== %s ======================" % self.name
    print title_str
    for event in self.events:
      for field in default_fields:
        field_formatters[field](event)
    print "=" * len(title_str)

def main(args):
  # N.B. it would be nice to include link discovery or host location discovery
  # events here, but that's specific to the Controller's log output.
  network_failure_events = EventGrouping("Topology Change Events")
  controlplane_failure_events = EventGrouping("Control Plane Blockages")
  controller_failure_events = EventGrouping("Controller Change Events")
  host_events = EventGrouping("Host Migrations")

  event2grouping = {
    SwitchFailure : network_failure_events,
    SwitchRecovery : network_failure_events,
    LinkFailure : network_failure_events,
    LinkRecovery : network_failure_events,
    ControlChannelBlock : controlplane_failure_events,
    ControlChannelUnblock : controlplane_failure_events,
    ControllerFailure : controller_failure_events,
    ControllerRecovery : controller_failure_events,
    BlockControllerPair : controller_failure_events,
    UnblockControllerPair : controller_failure_events,
    HostMigration : host_events,
    # TODO(cs): support TrafficInjection, DataplaneDrop? Might get too noisy.
  }

  with open(args.input) as input_file:
    trace = parse(input_file)
    for event in trace:
      if type(event) in event2grouping:
        event2grouping[type(event)].append(event)

  for grouping in [network_failure_events, controlplane_failure_events,
                   controller_failure_events, host_events]:
    grouping.printToConsole()
    print

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('input', metavar="INPUT",
                      help='The input json file to be printed')
  args = parser.parse_args()

  main(args)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

# note: must be invoked from the top-level sts directory

import time
import argparse
import os
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), ".."))

from sts.replay_event import *
from sts.dataplane_traces.trace import Trace
from sts.input_traces.log_parser import parse
from tools.pretty_print_input_trace import default_fields, field_formatters

class EventGrouping(object):
  def __init__(self, name):
    self.name = name
    self.events = []

  def append(self, event):
    self.events.append(event)

  def printToConsole(self):
    # TODO(cs): bad feng-shui to have side-effects rather than returning a
    # string. Should refactor field_formatters to not have side-effects
    # either.
    title_str = "====================== %s ======================" % self.name
    print title_str
    for event in self.events:
      for field in default_fields:
        field_formatters[field](event)
    print "=" * len(title_str)

def main(args):
  # N.B. it would be nice to include link discovery or host location discovery
  # events here, but that's specific to the Controller's log output.
  network_failure_events = EventGrouping("Topology Change Events")
  controlplane_failure_events = EventGrouping("Control Plane Blockages")
  controller_failure_events = EventGrouping("Controller Change Events")
  host_events = EventGrouping("Host Migrations")

  event2grouping = {
    SwitchFailure : network_failure_events,
    SwitchRecovery : network_failure_events,
    LinkFailure : network_failure_events,
    LinkRecovery : network_failure_events,
    ControlChannelBlock : controlplane_failure_events,
    ControlChannelUnblock : controlplane_failure_events,
    ControllerFailure : controller_failure_events,
    ControllerRecovery : controller_failure_events,
    BlockControllerPair : controller_failure_events,
    UnblockControllerPair : controller_failure_events,
    HostMigration : host_events,
    # TODO(cs): support TrafficInjection, DataplaneDrop? Might get too noisy.
  }

  with open(args.input) as input_file:
    trace = parse(input_file)
    for event in trace:
      if type(event) in event2grouping:
        event2grouping[type(event)].append(event)

  for grouping in [network_failure_events, controlplane_failure_events,
                   controller_failure_events, host_events]:
    grouping.printToConsole()
    print

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('input', metavar="INPUT",
                      help='The input json file to be printed')
  args = parser.parse_args()

  main(args)

Prompt: Add simple tool for tabulating classes of event types for readability


"""
Cortical networks correlation matrix
====================================

"""
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")

df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()

f, ax = plt.subplots(figsize=(12, 9))
sns.heatmap(corrmat, vmax=.8, linewidths=0, square=True)

networks = corrmat.columns.get_level_values("network").astype(int).values

start, end = ax.get_ylim()
rect_kws = dict(facecolor="none", edgecolor=".2",
                linewidth=1.5, capstyle="projecting")

for n in range(1, 18):
    n_nodes = (networks == n).sum()
    rect = plt.Rectangle((start, end), n_nodes, -n_nodes, **rect_kws)
    start += n_nodes
    end -= n_nodes
    ax.add_artist(rect)

f.tight_layout()

Add correlation matrix heatmap example

Add correlation matrix heatmap example

Response:
<INSERT> """
Cortical networks correlation matrix
====================================

"""
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")

df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()

f, ax = plt.subplots(figsize=(12, 9))
sns.heatmap(corrmat, vmax=.8, linewidths=0, square=True)

networks = corrmat.columns.get_level_values("network").astype(int).values

start, end = ax.get_ylim()
rect_kws = dict(facecolor="none", edgecolor=".2",
 <INSERT_END> <INSERT>               linewidth=1.5, capstyle="projecting")

for n in range(1, 18):
    n_nodes = (networks == n).sum()
    rect = plt.Rectangle((start, end), n_nodes, -n_nodes, **rect_kws)
    start += n_nodes
    end -= n_nodes
    ax.add_artist(rect)

f.tight_layout()
 <INSERT_END> <|endoftext|> """
Cortical networks correlation matrix
====================================

"""
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")

df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()

f, ax = plt.subplots(figsize=(12, 9))
sns.heatmap(corrmat, vmax=.8, linewidths=0, square=True)

networks = corrmat.columns.get_level_values("network").astype(int).values

start, end = ax.get_ylim()
rect_kws = dict(facecolor="none", edgecolor=".2",
                linewidth=1.5, capstyle="projecting")

for n in range(1, 18):
    n_nodes = (networks == n).sum()
    rect = plt.Rectangle((start, end), n_nodes, -n_nodes, **rect_kws)
    start += n_nodes
    end -= n_nodes
    ax.add_artist(rect)

f.tight_layout()

Prompt: Add correlation matrix heatmap example


from distutils.core import setup
from os import path

from turbasen import VERSION

name = 'turbasen'

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

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    long_description=long_description,
    author='Ali Kaafarani',
    author_email='ali.kaafarani@turistforeningen.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests'],
)

Add long description from README

Add long description from README

Response:
<REPLACE_OLD> setup

from <REPLACE_NEW> setup
from os import path

from <REPLACE_END> <REPLACE_OLD> 'turbasen'

setup(
 <REPLACE_NEW> 'turbasen'

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

setup(
 <REPLACE_END> <INSERT>    long_description=long_description,
 <INSERT_END> <|endoftext|> from distutils.core import setup
from os import path

from turbasen import VERSION

name = 'turbasen'

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

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    long_description=long_description,
    author='Ali Kaafarani',
    author_email='ali.kaafarani@turistforeningen.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests'],
)

Prompt:
Add long description from README

from distutils.core import setup

from turbasen import VERSION

name = 'turbasen'

setup(
    name=name,
    packages=[name],
    version=VERSION,
    description='Client for Nasjonal Turbase REST API',
    author='Ali Kaafarani',
    author_email='ali.kaafarani@turistforeningen.no',
    url='https://github.com/Turbasen/turbasen.py',
    download_url='https://github.com/Turbasen/turbasen.py/tarball/v%s' % (VERSION),
    keywords=['turbasen', 'nasjonalturbase', 'turistforening', 'rest-api'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: Norwegian',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
    install_requires=['requests'],
)


class Solution:
    """
    @param a, b: Two integer
    return: An integer
    """
    def bitSwapRequired(self, a, b):
        # write your code here
        return bin((a^b) & 0xffffffff).count('1')

Add solution to lintcode problem 181

Add solution to lintcode problem 181

Response:
<INSERT> class Solution:
 <INSERT_END> <INSERT>   """
    @param a, b: Two integer
    return: An integer
    """
    def bitSwapRequired(self, a, b):
        # write your code here
        return bin((a^b) & 0xffffffff).count('1')
 <INSERT_END> <|endoftext|> class Solution:
    """
    @param a, b: Two integer
    return: An integer
    """
    def bitSwapRequired(self, a, b):
        # write your code here
        return bin((a^b) & 0xffffffff).count('1')

Prompt: Add solution to lintcode problem 181


import functools

class Tokenizer:
    pass

@functools.total_ordering
class Token:
    def __init__(self, text, offset, data=None):
        self.offset = offset
        self.text = text
        self.end = offset + len(text)
        self.data = data if data else {}

    def set(self, prop, info):
        self.data[prop] = info

    def get(self, prop, default=None):
        return self.data.get(prop, default)

    def __eq__(self, other):
        if not isinstance(other, Token):
            return NotImplemented
        return self.text == other.text

    def __lt__(self, other):
        if not isinstance(other, Token):
            return NotImplemented
        return self.text < other.text

Response:
<REPLACE_OLD> class <REPLACE_NEW> import functools

class <REPLACE_END> <REPLACE_OLD> pass

class <REPLACE_NEW> pass

@functools.total_ordering
class <REPLACE_END> <REPLACE_OLD> default)
 <REPLACE_NEW> default)

    def __eq__(self, other):
        if not isinstance(other, Token):
            return NotImplemented
        return self.text == other.text

    def __lt__(self, other):
        if not isinstance(other, Token):
            return NotImplemented
        return self.text < other.text
 <REPLACE_END> <|endoftext|> import functools

class Tokenizer:
    pass

@functools.total_ordering
class Token:
    def __init__(self, text, offset, data=None):
        self.offset = offset
        self.text = text
        self.end = offset + len(text)
        self.data = data if data else {}

    def set(self, prop, info):
        self.data[prop] = info

    def get(self, prop, default=None):
        return self.data.get(prop, default)

    def __eq__(self, other):
        if not isinstance(other, Token):
            return NotImplemented
        return self.text == other.text

    def __lt__(self, other):
        if not isinstance(other, Token):
            return NotImplemented
        return self.text < other.text

Prompt:
Fix to make sanitize_examples() be able to sort tokens

class Tokenizer:
    pass

class Token:
    def __init__(self, text, offset, data=None):
        self.offset = offset
        self.text = text
        self.end = offset + len(text)
        self.data = data if data else {}

    def set(self, prop, info):
        self.data[prop] = info

    def get(self, prop, default=None):
        return self.data.get(prop, default)


class MyQueue:

    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, element):
        # write your code here
        self.stack1.append(element)

    def top(self):
        # write your code here
        # return the top element
        return self.stack1[0]

    def pop(self):
        # write your code here
        # pop and return the top element
        res = None
        while (self.stack1):
            ele = self.stack1.pop(-1)
            if (self.stack1):
                self.stack2.append(ele)
            else:
                res = ele
        while (self.stack2):
            ele = self.stack2.pop(-1)
            self.stack1.append(ele)
        return res

Add solution to lintcode question 40

Add solution to lintcode question 40

Response:
<REPLACE_OLD>  <REPLACE_NEW> class MyQueue:

    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, element):
        # write your code here
        self.stack1.append(element)

    def top(self):
        # write your code here
        # return the top element
        return self.stack1[0]

    def pop(self):
        # write your code here
        # pop and return the top element
        res = None
        while (self.stack1):
            ele = self.stack1.pop(-1)
            if (self.stack1):
                self.stack2.append(ele)
            else:
                res = ele
        while (self.stack2):
            ele = self.stack2.pop(-1)
            self.stack1.append(ele)
        return res
 <REPLACE_END> <|endoftext|> class MyQueue:

    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, element):
        # write your code here
        self.stack1.append(element)

    def top(self):
        # write your code here
        # return the top element
        return self.stack1[0]

    def pop(self):
        # write your code here
        # pop and return the top element
        res = None
        while (self.stack1):
            ele = self.stack1.pop(-1)
            if (self.stack1):
                self.stack2.append(ele)
            else:
                res = ele
        while (self.stack2):
            ele = self.stack2.pop(-1)
            self.stack1.append(ele)
        return res

Prompt: Add solution to lintcode question 40


#!/usr/bin/python

#
# strlen_hist.py   Histogram of system-wide strlen return values
#
# A basic example of using uprobes along with a histogram to show
# distributions.
#
# Runs until ctrl-c is pressed.
#
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Example output:
# $ sudo ./strlen_hist.py
# 22:12:52
#      strlen return:      : count     distribution
#          0 -> 1          : 2106     |****************                        |
#          2 -> 3          : 1172     |*********                               |
#          4 -> 7          : 3892     |******************************          |
#          8 -> 15         : 5096     |****************************************|
#         16 -> 31         : 2201     |*****************                       |
#         32 -> 63         : 547      |****                                    |
#         64 -> 127        : 106      |                                        |
#        128 -> 255        : 13       |                                        |
#        256 -> 511        : 27       |                                        |
#        512 -> 1023       : 6        |                                        |
#       1024 -> 2047       : 10       |                                        |
# ^C$
#

from __future__ import print_function
import bcc
import time

text = """
#include <uapi/linux/ptrace.h>
BPF_HISTOGRAM(dist);
int count(struct pt_regs *ctx) {
    dist.increment(bpf_log2l(ctx->ax));
    return 0;
}
"""

b = bcc.BPF(text=text)
sym="strlen"
b.attach_uretprobe(name="c", sym=sym, fn_name="count")

dist = b["dist"]

try:
    while True:
        time.sleep(1)
        print("%-8s\n" % time.strftime("%H:%M:%S"), end="")
        dist.print_log2_hist(sym + " return:")
        dist.clear()

except KeyboardInterrupt:
    pass

Add uprobe strlen histogram example

Add uprobe strlen histogram example

This example traces all calls to libc's strlen(). The program is attached as a
retprobe, therefore giving access to the resulting string length. The value is
kept in a log2 histogram that is printed to console once per second.

Example:
```
$ sudo ./strlen_hist.py
22:12:51
     strlen return:      : count     distribution
         0 -> 1          : 2041     |****************                        |
         2 -> 3          : 1120     |********                                |
         4 -> 7          : 3300     |**************************              |
         8 -> 15         : 4995     |****************************************|
        16 -> 31         : 2130     |*****************                       |
        32 -> 63         : 562      |****                                    |
^C
```

Signed-off-by: Brenden Blanco <8e41c261aa8ddb01230a40c21c26a049c1f6d041@plumgrid.com>

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/python

#
# strlen_hist.py   Histogram of system-wide strlen return values
#
# A basic example of using uprobes along with a histogram to show
# distributions.
#
# Runs until ctrl-c is pressed.
#
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Example output:
# $ sudo ./strlen_hist.py
# 22:12:52
#      strlen return:      : count     distribution
#          0 -> 1          : 2106     |****************                        |
#          2 -> 3          : 1172     |*********                               |
#          4 -> 7          : 3892     |******************************          |
#          8 -> 15         : 5096     |****************************************|
#         16 -> 31         : 2201     |*****************                       |
#         32 -> 63         : 547      |****                                    |
#         64 -> 127        : 106      |                                        |
#        128 -> 255        : 13       |                                        |
#        256 -> 511        : 27       |                                        |
#        512 -> 1023       : 6        |                                        |
#       1024 -> 2047       : 10       |                                        |
# ^C$
#

from __future__ import print_function
import bcc
import time

text = """
#include <uapi/linux/ptrace.h>
BPF_HISTOGRAM(dist);
int count(struct pt_regs *ctx) {
    dist.increment(bpf_log2l(ctx->ax));
    return 0;
}
"""

b = bcc.BPF(text=text)
sym="strlen"
b.attach_uretprobe(name="c", sym=sym, fn_name="count")

dist = b["dist"]

try:
    while True:
        time.sleep(1)
        print("%-8s\n" % time.strftime("%H:%M:%S"), end="")
        dist.print_log2_hist(sym + " return:")
        dist.clear()

except KeyboardInterrupt:
    pass
 <REPLACE_END> <|endoftext|> #!/usr/bin/python

#
# strlen_hist.py   Histogram of system-wide strlen return values
#
# A basic example of using uprobes along with a histogram to show
# distributions.
#
# Runs until ctrl-c is pressed.
#
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Example output:
# $ sudo ./strlen_hist.py
# 22:12:52
#      strlen return:      : count     distribution
#          0 -> 1          : 2106     |****************                        |
#          2 -> 3          : 1172     |*********                               |
#          4 -> 7          : 3892     |******************************          |
#          8 -> 15         : 5096     |****************************************|
#         16 -> 31         : 2201     |*****************                       |
#         32 -> 63         : 547      |****                                    |
#         64 -> 127        : 106      |                                        |
#        128 -> 255        : 13       |                                        |
#        256 -> 511        : 27       |                                        |
#        512 -> 1023       : 6        |                                        |
#       1024 -> 2047       : 10       |                                        |
# ^C$
#

from __future__ import print_function
import bcc
import time

text = """
#include <uapi/linux/ptrace.h>
BPF_HISTOGRAM(dist);
int count(struct pt_regs *ctx) {
    dist.increment(bpf_log2l(ctx->ax));
    return 0;
}
"""

b = bcc.BPF(text=text)
sym="strlen"
b.attach_uretprobe(name="c", sym=sym, fn_name="count")

dist = b["dist"]

try:
    while True:
        time.sleep(1)
        print("%-8s\n" % time.strftime("%H:%M:%S"), end="")
        dist.print_log2_hist(sym + " return:")
        dist.clear()

except KeyboardInterrupt:
    pass

Prompt:
Add uprobe strlen histogram example

This example traces all calls to libc's strlen(). The program is attached as a
retprobe, therefore giving access to the resulting string length. The value is
kept in a log2 histogram that is printed to console once per second.

Example:
```
$ sudo ./strlen_hist.py
22:12:51
     strlen return:      : count     distribution
         0 -> 1          : 2041     |****************                        |
         2 -> 3          : 1120     |********                                |
         4 -> 7          : 3300     |**************************              |
         8 -> 15         : 4995     |****************************************|
        16 -> 31         : 2130     |*****************                       |
        32 -> 63         : 562      |****                                    |
^C
```

Signed-off-by: Brenden Blanco <8e41c261aa8ddb01230a40c21c26a049c1f6d041@plumgrid.com>