import sys
import argparse

from . import parse
from . import compile
from . import runtime
from .interactive import Interactive

class Interactive (Interactive):

    def __init__(self, args):

        super().__init__()

        self.args = args

    def traceback(self, trace):

        # When running in non-interactive mode, strip the first 4 lines.
        # These correspond to stuff in this module.
        return super().traceback(trace)[4 * (not sys.stdin.isatty()):]

    def compile(self, code):

        q = parse.r.compile_command(code)
        q = q if q is None else compile.r(q, name='<module>', single=True)
        return q

    def run(self, ns):

        q = parse.r(sys.stdin.read(), sys.stdin.name)
        q = compile.r(q, name='<module>')
        return self.eval(q, ns)

parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()

sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin

Interactive(args).shell(__name__)

Remove the -p command-line option.

Response:
import sys
import argparse

from . import parse
from . import compile
from . import runtime
from .interactive import Interactive

class Interactive (Interactive):

    def __init__(self, args):

        super().__init__()

        self.args = args

    def traceback(self, trace):

        # When running in non-interactive mode, strip the first 4 lines.
        # These correspond to stuff in this module.
        return super().traceback(trace)[4 * (not sys.stdin.isatty()):]

    def compile(self, code):

        q = parse.r.compile_command(code)
        q = q if q is None else compile.r(q, name='<module>', single=True)
        return q

    def run(self, ns):

        q = parse.r(sys.stdin.read(), sys.stdin.name)
        q = compile.r(q, name='<module>')
        return self.eval(q, ns)

parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()

sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin

Interactive(args).shell(__name__)

Prompt:
Remove the -p command-line option.

It's pretty useless anyway. Use  instead.

import sys
import argparse

from . import parse
from . import compile
from . import runtime
from .interactive import Interactive

class Interactive (Interactive):

    def __init__(self, args):

        super().__init__()

        self.args   = args
        self.single = sys.stdin.isatty() or args.print

    def displayhook(self, value):

        self.args.print and print(value)
        return super().displayhook(value)

    def traceback(self, trace):

        # When running in non-interactive mode, strip the first 4 lines.
        # These correspond to stuff in this module.
        return super().traceback(trace)[4 * (not sys.stdin.isatty()):]

    def compile(self, code):

        q = parse.r.compile_command(code)
        q = q if q is None else compile.r(q, name='<module>', single=self.single)
        return q

    def run(self, ns):

        q = parse.r(sys.stdin.read(), sys.stdin.name)
        q = compile.r(q, name='<module>', single=self.single)
        return self.eval(q, ns)

parser = argparse.ArgumentParser()
parser.add_argument('-p', '--print', action='store_true', help='when compiling, make the top-level code print its evaluation result in addition to returning it (does not affect REPL)')
parser.add_argument('file', nargs='?', help='files to parse/compile', type=argparse.FileType())
parser.add_argument('arguments', nargs='*', help='additional arguments')
args = parser.parse_args()

sys.argv = [args.file.name if args.file else '-'] + args.arguments
sys.stdin = args.file or sys.stdin

Interactive(args).shell(__name__)


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

from paasta_tools.monitoring.check_mesos_quorum import check_mesos_quorum

def test_check_mesos_quorum_ok(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=3,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "OK" in out
        assert error.value.code == 0

def test_check_mesos_quorum_critical(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=1,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "CRITICAL" in out
        assert error.value.code == 2

Add last metastatus check test

Add last metastatus check test

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

from paasta_tools.monitoring.check_mesos_quorum import check_mesos_quorum

def test_check_mesos_quorum_ok(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=3,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "OK" in out
        assert error.value.code == 0

def test_check_mesos_quorum_critical(capfd):
    with mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_num_masters', autospec=True,
        return_value=1,
    ), mock.patch(
        'paasta_tools.metrics.metastatus_lib.get_mesos_quorum', autospec=True,
        return_value=2,
    ):
        with pytest.raises(SystemExit) as error:
            check_mesos_quorum()
        out, err = capfd.readouterr()
        assert "CRITICAL" in out
        assert error.value.code == 2

Prompt: Add last metastatus check test


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

__author__ = 'Armando Guereca'

class ScriptFields:
    _internal_name = "script_fields"
    """
    This object create the script_fields definition
    """
    def __init__(self, field_name, script, params = None):
        self.fields={}
        self.add_field(field_name, script, params or {})

    def add_field(self, field_name, script, params = None):
        """
        Add a field to script_fields
        """
        data = {}
        if script:
            data['script'] = script
        else:
            raise ScriptFieldsError("Script is required for script_fields definition")
        if params:
            if isinstance(params, dict):
                if len(params):
                    data['params'] = params
            else:
                raise ScriptFieldsError("Parameters should be a valid dictionary")

        self.fields[field_name] = data

    def add_parameter(self, field_name, param_name, param_value):
        """
        Add a parameter to a field into script_fields

        The ScriptFields object will be returned, so calls to this can be chained.
        """
        try:
            self.fields[field_name]['params'][param_name] = param_value
        except Exception as ex:
            raise ScriptFieldsError("Error adding parameter %s with value %s :%s" % (param_name,param_value,ex))

        return self

    def serialize(self):
        return self.fields

Add ScriptFields object used as parameter script_fields of Search object

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

__author__ = 'Armando Guereca'

class ScriptFields:
    _internal_name = "script_fields"
    """
    This object create the script_fields definition
    """
    def __init__(self, field_name, script, params = None):
        self.fields={}
        self.add_field(field_name, script, params or {})

    def add_field(self, field_name, script, params = None):
        """
        Add a field to script_fields
        """
        data = {}
        if script:
            data['script'] = script
        else:
            raise ScriptFieldsError("Script is required for script_fields definition")
        if params:
            if isinstance(params, dict):
                if len(params):
                    data['params'] = params
            else:
                raise ScriptFieldsError("Parameters should be a valid dictionary")

        self.fields[field_name] = data

    def add_parameter(self, field_name, param_name, param_value):
        """
        Add a parameter to a field into script_fields

        The ScriptFields object will be returned, so calls to this can be chained.
        """
        try:
            self.fields[field_name]['params'][param_name] = param_value
        except Exception as ex:
            raise ScriptFieldsError("Error adding parameter %s with value %s :%s" % (param_name,param_value,ex))

        return self

    def serialize(self):
        return self.fields

Prompt: Add ScriptFields object used as parameter script_fields of Search object


import sys
from CITests import CITests

# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}

# Instance of CITests
ci = CITests("/OpenIPSL")

# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")

if not passLib:
    # Error in OpenIPSL
    sys.exit(1)
else:
    # Run Check on App Examples
    passAppEx = 1
    for package in appExamples.keys():
        passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])

    # The tests are failing if the number of failed check > 0
    if passAppEx:
        # Everything is fine
        sys.exit(0)
    else:
        # Exit with error
        sys.exit(1)

Fix the location path of OpenIPSL

Fix the location path of OpenIPSL

Response:
import sys
from CITests import CITests

# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}

# Instance of CITests
ci = CITests("/OpenIPSL")

# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")

if not passLib:
    # Error in OpenIPSL
    sys.exit(1)
else:
    # Run Check on App Examples
    passAppEx = 1
    for package in appExamples.keys():
        passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])

    # The tests are failing if the number of failed check > 0
    if passAppEx:
        # Everything is fine
        sys.exit(0)
    else:
        # Exit with error
        sys.exit(1)

Prompt:
Fix the location path of OpenIPSL

import sys
from CITests import CITests

# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}

# Instance of CITests
ci = CITests("/OpenIPSL")

# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")

if not passLib:
    # Error in OpenIPSL
    sys.exit(1)
else:
    # Run Check on App Examples
    passAppEx = 1
    for package in appExamples.keys():
        passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])

    # The tests are failing if the number of failed check > 0
    if passAppEx:
        # Everything is fine
        sys.exit(0)
    else:
        # Exit with error
        sys.exit(1)


from __future__ import unicode_literals, print_function
import sqlite3, os, random

_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'

def generate_name():
    conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
    cursor = conn.cursor()

    adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
    anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
    rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
    uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
    uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()

    conn.close()

    r = random.random()
    if r < 0.001 or r >= 0.999:
        return rare
    elif r < 0.3 and uncommon_anim is not None:
        return ' '.join((adj, uncommon_anim[0]))
    elif r >= 0.7 and uncommon_adj is not None:
        return ' '.join((uncommon_adj[0], anim))

    return ' '.join((adj, anim))

if __name__ == '__main__':
    for _ in range(20):
        print(generate_name())

Response:
from __future__ import unicode_literals, print_function
import sqlite3, os, random

_select_random = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_select_uncommon = 'select value from uncommons where key=?;'

def generate_name():
    conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
    cursor = conn.cursor()

    adj = cursor.execute(_select_random.format('adjective', 'adjectives')).fetchone()[0]
    anim = cursor.execute(_select_random.format('animal', 'animals')).fetchone()[0]
    rare = cursor.execute(_select_random.format('name', 'rares')).fetchone()[0]
    uncommon_anim = cursor.execute(_select_uncommon, [adj]).fetchone()
    uncommon_adj = cursor.execute(_select_uncommon, [anim]).fetchone()

    conn.close()

    r = random.random()
    if r < 0.001 or r >= 0.999:
        return rare
    elif r < 0.3 and uncommon_anim is not None:
        return ' '.join((adj, uncommon_anim[0]))
    elif r >= 0.7 and uncommon_adj is not None:
        return ' '.join((uncommon_adj[0], anim))

    return ' '.join((adj, anim))

if __name__ == '__main__':
    for _ in range(20):
        print(generate_name())

Prompt:
Rename the SQL module vars for consistency.

from __future__ import unicode_literals, print_function
import sqlite3, os, random

_select = 'select {0} from {1} limit 1 offset abs(random()) % (select count({0}) from {1});'
_uncommon_select = 'select value from uncommons where key=?;'

def generate_name():
    conn = sqlite3.connect(os.path.join(os.path.dirname(__file__), 'names.db'))
    cursor = conn.cursor()

    adj = cursor.execute(_select.format('adjective', 'adjectives')).fetchone()[0]
    anim = cursor.execute(_select.format('animal', 'animals')).fetchone()[0]
    rare = cursor.execute(_select.format('name', 'rares')).fetchone()[0]
    uncommon_anim = cursor.execute(_uncommon_select, [adj]).fetchone()
    uncommon_adj = cursor.execute(_uncommon_select, [anim]).fetchone()

    conn.close()

    r = random.random()
    if r < 0.001 or r >= 0.999:
        return rare
    elif r < 0.3 and uncommon_anim is not None:
        return ' '.join((adj, uncommon_anim[0]))
    elif r >= 0.7 and uncommon_adj is not None:
        return ' '.join((uncommon_adj[0], anim))

    return ' '.join((adj, anim))

if __name__ == '__main__':
    print(generate_name())


#!/usr/bin/env python

"""Simple Genetic Algorithm for solving TSP.

Usage:
  main.py FILE --pop-size=POP_SIZE --max-gen=MAX_GENERATIONS --xover-rate=CROSSOVER_RATE --mute-rate=MUTATION_RATE --num-elites=NUM_ELITES --tournament-k=K
  main.py (-h | --help)
  main.py (-v | --version)

Options:
  -h --help     Show this screen.
  -v --version  Show version.

"""
from docopt import docopt

class Genotype(object):
    """The population of chromosomes."""

    def __init__(self, population, elite):
        self.population = population
        # TODO: new_pop?
        self.elite = elite

if __name__ == '__main__':
    arguments = docopt(__doc__, version='0.1')
    print(arguments)
    # TODO
    # read file
    # initialize pop
    # run ga (break down)

# Default crossover is PMX. Can also use CX.

Build interface w/ docopt and add POD

Build interface w/ docopt and add POD

Response:
#!/usr/bin/env python

"""Simple Genetic Algorithm for solving TSP.

Usage:
  main.py FILE --pop-size=POP_SIZE --max-gen=MAX_GENERATIONS --xover-rate=CROSSOVER_RATE --mute-rate=MUTATION_RATE --num-elites=NUM_ELITES --tournament-k=K
  main.py (-h | --help)
  main.py (-v | --version)

Options:
  -h --help     Show this screen.
  -v --version  Show version.

"""
from docopt import docopt

class Genotype(object):
    """The population of chromosomes."""

    def __init__(self, population, elite):
        self.population = population
        # TODO: new_pop?
        self.elite = elite

if __name__ == '__main__':
    arguments = docopt(__doc__, version='0.1')
    print(arguments)
    # TODO
    # read file
    # initialize pop
    # run ga (break down)

# Default crossover is PMX. Can also use CX.

Prompt:
Build interface w/ docopt and add POD

#!/usr/bin/env python

if __name__ == "__main__":
    run()


# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm

class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
    form = AnalyzeRepositoryForm
    service_class = AnalyzeRepositoryService
    search_fields = ("database_name", "engine_name",
                     "environment_name", "instance_name", "databaseinfra_name")
    list_filter = ("analyzed_at", "memory_alarm", "cpu_alarm", "volume_alarm", "engine_name",
                   "environment_name", "databaseinfra_name")
    list_display = ("analyzed_at", "databaseinfra_name", "database_name", "engine_name",
                    "environment_name", "instance_name", "cpu_alarm",
                    "memory_alarm", "volume_alarm")

Add more options on filters

Add more options on filters

Response:
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm

class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
    form = AnalyzeRepositoryForm
    service_class = AnalyzeRepositoryService
    search_fields = ("database_name", "engine_name",
                     "environment_name", "instance_name", "databaseinfra_name")
    list_filter = ("analyzed_at", "memory_alarm", "cpu_alarm", "volume_alarm", "engine_name",
                   "environment_name", "databaseinfra_name")
    list_display = ("analyzed_at", "databaseinfra_name", "database_name", "engine_name",
                    "environment_name", "instance_name", "cpu_alarm",
                    "memory_alarm", "volume_alarm")

Prompt:
Add more options on filters

# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm

class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
    form = AnalyzeRepositoryForm
    service_class = AnalyzeRepositoryService
    search_fields = ("database_name", "engine_name",
                     "environment_name", "instance_name", "databaseinfra_name")
    list_filter = ("analyzed_at", "memory_alarm", "cpu_alarm", "volume_alarm")
    list_display = ("analyzed_at", "databaseinfra_name", "database_name", "engine_name",
                    "environment_name", "instance_name", "cpu_alarm",
                    "memory_alarm", "volume_alarm")


"""Queries the CSDMS model repository for all models written in C,
C++, Fortran 77, or Fortran 90."""
from ask_api_examples import make_query

query = '[[Programming language::C||C++||Fortran77||Fortran90]]|limit=10000'

def main():
    r = make_query(query, __file__)
    return r

if __name__ == '__main__':
    print main()

Add example to list all models written in Fortran or C/C++

Response:
"""Queries the CSDMS model repository for all models written in C,
C++, Fortran 77, or Fortran 90."""
from ask_api_examples import make_query

query = '[[Programming language::C||C++||Fortran77||Fortran90]]|limit=10000'

def main():
    r = make_query(query, __file__)
    return r

if __name__ == '__main__':
    print main()

Prompt: Add example to list all models written in Fortran or C/C++


# List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']

class UserRouter(object):
    """
    A router to control all database operations on models in the
    login application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read login models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the login app is involved.
        """
        if obj1._meta.app_label in USERS_DATABASE_APPS or \
           obj2._meta.app_label in USERS_DATABASE_APPS:
           return True
        print model._meta.app_label
        print "BRISA1"
        return None

    def allow_syncdb(self, db, model):
        """
        Make sure the login app only appears in the 'users'
        database.
        """
        if db == 'users':
            return model._meta.app_label in USERS_DATABASE_APPS
        elif model._meta.app_label in USERS_DATABASE_APPS:
            return False
        print model._meta.app_label
        print "BRISA"
        return None

Response:
# List of apps that will use the users database
USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites']

class UserRouter(object):
    """
    A router to control all database operations on models in the
    login application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read login models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the login app is involved.
        """
        if obj1._meta.app_label in USERS_DATABASE_APPS or \
           obj2._meta.app_label in USERS_DATABASE_APPS:
           return True
        print model._meta.app_label
        print "BRISA1"
        return None

    def allow_syncdb(self, db, model):
        """
        Make sure the login app only appears in the 'users'
        database.
        """
        if db == 'users':
            return model._meta.app_label in USERS_DATABASE_APPS
        elif model._meta.app_label in USERS_DATABASE_APPS:
            return False
        print model._meta.app_label
        print "BRISA"
        return None

Prompt:
[login] Add apps on list that will be used on the test databases

Added apps sites and contenttypes to the list.
These apps were causing troubles on the test databases.

Signed off by: Heitor Reis <marcheing@gmail.com>
Signed off by: Filipe Vaz <vazfilipe92@gmail.com>

# List of apps that will use the users database
USERS_DATABASE_APPS = ['auth','login','sessions']

class UserRouter(object):
    """
    A router to control all database operations on models in the
    login application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read login models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        print model._meta.app_label
        print "BRISA"
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to users.
        """
        if model._meta.app_label in USERS_DATABASE_APPS:
            return 'users'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the login app is involved.
        """
        if obj1._meta.app_label in USERS_DATABASE_APPS or \
           obj2._meta.app_label in USERS_DATABASE_APPS:
           return True
        return None

    def allow_syncdb(self, db, model):
        """
        Make sure the login app only appears in the 'users'
        database.
        """
        if db == 'users':
            return model._meta.app_label in USERS_DATABASE_APPS
        elif model._meta.app_label in USERS_DATABASE_APPS:
            return False
        return None


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

import argparse
import json
import logging
import sys

from devil.android import device_blacklist
from devil.android import device_errors
from devil.android import device_utils
from devil.utils import run_tests_helper

def main():
  parser = argparse.ArgumentParser(
      'Run an adb shell command on selected devices')
  parser.add_argument('cmd', help='Adb shell command to run.', nargs="+")
  parser.add_argument('-d', '--device', action='append', dest='devices',
                      help='Device to run cmd on. Runs on all devices if not '
                           'specified. Set multiple times for multiple devices')
  parser.add_argument('-v', '--verbose', default=0, action='count',
                      help='Verbose level (multiple times for more)')
  parser.add_argument('--blacklist-file', help='Device blacklist file.')
  parser.add_argument('--as-root', action='store_true', help='Run as root.')
  parser.add_argument('--json-output',
                      help='File to dump json output to.')
  args = parser.parse_args()
  run_tests_helper.SetLogLevel(args.verbose)

  args.blacklist_file = device_blacklist.Blacklist(
      args.blacklist_file) if args.blacklist_file else None
  attached_devices = device_utils.DeviceUtils.HealthyDevices(
      blacklist=args.blacklist_file)

  if args.devices:
    selected_devices = []
    attached_devices = {str(d): d for d in attached_devices}
    for serial in args.devices:
      if serial in attached_devices:
        selected_devices.append(attached_devices[serial])
      else:
        logging.warning('Specified device %s not found.', serial)
  else:
    selected_devices = attached_devices

  if not selected_devices:
    raise device_errors.NoDevicesError

  p_out = (device_utils.DeviceUtils.parallel(selected_devices).RunShellCommand(
      args.cmd, large_output=True, as_root=args.as_root, check_return=True)
      .pGet(None))

  data = {}
  for device, output in zip(selected_devices, p_out):
    for line in output:
      print '%s: %s' %(device, line)
    data[str(device)] = output

  if args.json_output:
    with open(args.json_output, 'w') as f:
      json.dump(data, f)

  return 0

if __name__ == '__main__':
  sys.exit(main())

[Android] Add util for running adb shell commands on device.

BUG=543257

Review URL: https://codereview.chromium.org/1498113002

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#365301}

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

import argparse
import json
import logging
import sys

from devil.android import device_blacklist
from devil.android import device_errors
from devil.android import device_utils
from devil.utils import run_tests_helper

def main():
  parser = argparse.ArgumentParser(
      'Run an adb shell command on selected devices')
  parser.add_argument('cmd', help='Adb shell command to run.', nargs="+")
  parser.add_argument('-d', '--device', action='append', dest='devices',
                      help='Device to run cmd on. Runs on all devices if not '
                           'specified. Set multiple times for multiple devices')
  parser.add_argument('-v', '--verbose', default=0, action='count',
                      help='Verbose level (multiple times for more)')
  parser.add_argument('--blacklist-file', help='Device blacklist file.')
  parser.add_argument('--as-root', action='store_true', help='Run as root.')
  parser.add_argument('--json-output',
                      help='File to dump json output to.')
  args = parser.parse_args()
  run_tests_helper.SetLogLevel(args.verbose)

  args.blacklist_file = device_blacklist.Blacklist(
      args.blacklist_file) if args.blacklist_file else None
  attached_devices = device_utils.DeviceUtils.HealthyDevices(
      blacklist=args.blacklist_file)

  if args.devices:
    selected_devices = []
    attached_devices = {str(d): d for d in attached_devices}
    for serial in args.devices:
      if serial in attached_devices:
        selected_devices.append(attached_devices[serial])
      else:
        logging.warning('Specified device %s not found.', serial)
  else:
    selected_devices = attached_devices

  if not selected_devices:
    raise device_errors.NoDevicesError

  p_out = (device_utils.DeviceUtils.parallel(selected_devices).RunShellCommand(
      args.cmd, large_output=True, as_root=args.as_root, check_return=True)
      .pGet(None))

  data = {}
  for device, output in zip(selected_devices, p_out):
    for line in output:
      print '%s: %s' %(device, line)
    data[str(device)] = output

  if args.json_output:
    with open(args.json_output, 'w') as f:
      json.dump(data, f)

  return 0

if __name__ == '__main__':
  sys.exit(main())

Prompt:
[Android] Add util for running adb shell commands on device.

BUG=543257

Review URL: https://codereview.chromium.org/1498113002

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#365301}


from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages

version_classifiers = ['Programming Language :: Python :: %s' % version
                       for version in ['2', '2.5', '2.6', '2.7']]
other_classifiers = [
    'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: BSD License',
    'Intended Audience :: Developers',
    'Environment :: Console',
    'Operating System :: OS Independent',
    'Topic :: Software Development :: Testing',
    ]

with open('README', 'rt') as file_obj:
    detailed_description = file_obj.read()
with open('CHANGELOG', 'rt') as file_obj:
    detailed_description += file_obj.read()

setup(
    name="nosy",
    version="1.1.1",
    description="""\
Run the nose test discovery and execution tool whenever a source file
is changed.
    """,
    long_description=detailed_description,
    author="Doug Latornell",
    author_email="djl@douglatornell.ca",
    url="http://douglatornell.ca/software/python/Nosy/",
    license="New BSD License",
    classifiers=version_classifiers + other_classifiers,
    packages=find_packages(),
    entry_points={'console_scripts':['nosy = nosy.nosy:main']}
)

Response:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages

version_classifiers = ['Programming Language :: Python :: %s' % version
                       for version in ['2', '2.5', '2.6', '2.7']]
other_classifiers = [
    'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: BSD License',
    'Intended Audience :: Developers',
    'Environment :: Console',
    'Operating System :: OS Independent',
    'Topic :: Software Development :: Testing',
    ]

with open('README', 'rt') as file_obj:
    detailed_description = file_obj.read()
with open('CHANGELOG', 'rt') as file_obj:
    detailed_description += file_obj.read()

setup(
    name="nosy",
    version="1.1.1",
    description="""\
Run the nose test discovery and execution tool whenever a source file
is changed.
    """,
    long_description=detailed_description,
    author="Doug Latornell",
    author_email="djl@douglatornell.ca",
    url="http://douglatornell.ca/software/python/Nosy/",
    license="New BSD License",
    classifiers=version_classifiers + other_classifiers,
    packages=find_packages(),
    entry_points={'console_scripts':['nosy = nosy.nosy:main']}
)

Prompt:
Use context managers to build detailed_description.

from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages

version_classifiers = ['Programming Language :: Python :: %s' % version
                       for version in ['2', '2.5', '2.6', '2.7']]
other_classifiers = [
    'Development Status :: 5 - Production/Stable',
    'License :: OSI Approved :: BSD License',
    'Intended Audience :: Developers',
    'Environment :: Console',
    'Operating System :: OS Independent',
    'Topic :: Software Development :: Testing',
    ]

readme_file = open('README', 'rt')
try:
    detailed_description = readme_file.read()
finally:
    readme_file.close()

setup(
    name="nosy",
    version="1.1.1",
    description="""\
Run the nose test discovery and execution tool whenever a source file
is changed.
    """,
    long_description=detailed_description,
    author="Doug Latornell",
    author_email="djl@douglatornell.ca",
    url="http://douglatornell.ca/software/python/Nosy/",
    license="New BSD License",
    classifiers=version_classifiers + other_classifiers,
    packages=find_packages(),
    entry_points={'console_scripts':['nosy = nosy.nosy:main']}
)


from django.db import models
from django.utils.timezone import now

from towel import deletion
from towel.managers import SearchManager
from towel.modelview import ModelViewURLs

class PersonManager(SearchManager):
    search_fields = ('family_name', 'given_name')

class Person(models.Model):
    created = models.DateTimeField(default=now)
    family_name = models.CharField(max_length=100)
    given_name = models.CharField(max_length=100)

    objects = PersonManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return u'%s %s' % (self.given_name, self.family_name)

    def get_absolute_url(self):
        return self.urls['detail']

class EmailManager(SearchManager):
    search_fields = ('person__family_name', 'person__given_name', 'email')

class EmailAddress(deletion.Model):
    person = models.ForeignKey(Person)
    email = models.EmailField()

    objects = EmailManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return self.email

    def get_absolute_url(self):
        return self.urls['detail']

Use the item access variant instead

Use the item access variant instead

Response:
from django.db import models
from django.utils.timezone import now

from towel import deletion
from towel.managers import SearchManager
from towel.modelview import ModelViewURLs

class PersonManager(SearchManager):
    search_fields = ('family_name', 'given_name')

class Person(models.Model):
    created = models.DateTimeField(default=now)
    family_name = models.CharField(max_length=100)
    given_name = models.CharField(max_length=100)

    objects = PersonManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return u'%s %s' % (self.given_name, self.family_name)

    def get_absolute_url(self):
        return self.urls['detail']

class EmailManager(SearchManager):
    search_fields = ('person__family_name', 'person__given_name', 'email')

class EmailAddress(deletion.Model):
    person = models.ForeignKey(Person)
    email = models.EmailField()

    objects = EmailManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return self.email

    def get_absolute_url(self):
        return self.urls['detail']

Prompt:
Use the item access variant instead

from django.db import models
from django.utils.timezone import now

from towel import deletion
from towel.managers import SearchManager
from towel.modelview import ModelViewURLs

class PersonManager(SearchManager):
    search_fields = ('family_name', 'given_name')

class Person(models.Model):
    created = models.DateTimeField(default=now)
    family_name = models.CharField(max_length=100)
    given_name = models.CharField(max_length=100)

    objects = PersonManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return u'%s %s' % (self.given_name, self.family_name)

    def get_absolute_url(self):
        return self.urls.url('detail')

class EmailManager(SearchManager):
    search_fields = ('person__family_name', 'person__given_name', 'email')

class EmailAddress(deletion.Model):
    person = models.ForeignKey(Person)
    email = models.EmailField()

    objects = EmailManager()
    urls = ModelViewURLs(lambda obj: {'pk': obj.pk})

    def __unicode__(self):
        return self.email

    def get_absolute_url(self):
        return self.urls.url('detail')


import os

import blivet
from blivet.size import Size
from blivet.util import set_up_logging, create_sparse_tempfile

set_up_logging()
b = blivet.Blivet()   # create an instance of Blivet (don't add system devices)

# create a disk image file on which to create new devices
disk1_file = create_sparse_tempfile("disk1", Size("100GiB"))
b.disk_images["disk1"] = disk1_file
disk2_file = create_sparse_tempfile("disk2", Size("100GiB"))
b.disk_images["disk2"] = disk2_file

b.reset()

try:
    disk1 = b.devicetree.get_device_by_name("disk1")
    disk2 = b.devicetree.get_device_by_name("disk2")

    b.initialize_disk(disk1)
    b.initialize_disk(disk2)

    pv = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk1])
    b.create_device(pv)
    pv2 = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk2])
    b.create_device(pv2)

    # allocate the partitions (decide where and on which disks they'll reside)
    blivet.partitioning.do_partitioning(b)

    vg = b.new_vg(parents=[pv, pv2])
    b.create_device(vg)

    # new lv with base size 5GiB and growth up to 15GiB and an ext4 filesystem
    lv = b.new_lv(fmt_type="ext4", size=Size("5GiB"), parents=[vg], name="cached")
    b.create_device(lv)

    # new cache pool
    cpool = b.new_lv(size=Size("1 GiB"), parents=[vg], pvs=[pv2], cache_pool=True, name="fastlv")
    b.create_device(cpool)

    # write the new partitions to disk and format them as specified
    b.do_it()
    print(b.devicetree)

    # attach the newly created cache pool to the "slow" LV
    lv.attach_cache(cpool)

    b.reset()
    print(b.devicetree)

    input("Check the state and hit ENTER to trigger cleanup")
finally:
    b.devicetree.teardown_disk_images()
    os.unlink(disk1_file)
    os.unlink(disk2_file)

Add LVM cache pool example

examples: Add LVM cache pool example

Response:
import os

import blivet
from blivet.size import Size
from blivet.util import set_up_logging, create_sparse_tempfile

set_up_logging()
b = blivet.Blivet()   # create an instance of Blivet (don't add system devices)

# create a disk image file on which to create new devices
disk1_file = create_sparse_tempfile("disk1", Size("100GiB"))
b.disk_images["disk1"] = disk1_file
disk2_file = create_sparse_tempfile("disk2", Size("100GiB"))
b.disk_images["disk2"] = disk2_file

b.reset()

try:
    disk1 = b.devicetree.get_device_by_name("disk1")
    disk2 = b.devicetree.get_device_by_name("disk2")

    b.initialize_disk(disk1)
    b.initialize_disk(disk2)

    pv = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk1])
    b.create_device(pv)
    pv2 = b.new_partition(size=Size("50GiB"), fmt_type="lvmpv", parents=[disk2])
    b.create_device(pv2)

    # allocate the partitions (decide where and on which disks they'll reside)
    blivet.partitioning.do_partitioning(b)

    vg = b.new_vg(parents=[pv, pv2])
    b.create_device(vg)

    # new lv with base size 5GiB and growth up to 15GiB and an ext4 filesystem
    lv = b.new_lv(fmt_type="ext4", size=Size("5GiB"), parents=[vg], name="cached")
    b.create_device(lv)

    # new cache pool
    cpool = b.new_lv(size=Size("1 GiB"), parents=[vg], pvs=[pv2], cache_pool=True, name="fastlv")
    b.create_device(cpool)

    # write the new partitions to disk and format them as specified
    b.do_it()
    print(b.devicetree)

    # attach the newly created cache pool to the "slow" LV
    lv.attach_cache(cpool)

    b.reset()
    print(b.devicetree)

    input("Check the state and hit ENTER to trigger cleanup")
finally:
    b.devicetree.teardown_disk_images()
    os.unlink(disk1_file)
    os.unlink(disk2_file)

Prompt: examples: Add LVM cache pool example


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

from __future__ import absolute_import, unicode_literals

from flask import Flask
from werkzeug.utils import import_string

from me_api.middleware.me import me
from me_api.cache import cache

middlewares = {
    'douban': 'me_api.middleware.douban:douban_api',
    'github': 'me_api.middleware.github:github_api',
    'instagram': 'me_api.middleware.instagram:instagram_api',
    'keybase': 'me_api.middleware.keybase:keybase_api',
    'medium': 'me_api.middleware.medium:medium_api',
    'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
}

def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    cache.init_app(app)

    modules = config.modules['modules']
    app.register_blueprint(me)
    for module in modules.keys():
        blueprint = import_string(middlewares[module])
        app.register_blueprint(blueprint)

    return app

Improve the way that import middlewares

Improve the way that import middlewares

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

from __future__ import absolute_import, unicode_literals

from flask import Flask
from werkzeug.utils import import_string

from me_api.middleware.me import me
from me_api.cache import cache

middlewares = {
    'douban': 'me_api.middleware.douban:douban_api',
    'github': 'me_api.middleware.github:github_api',
    'instagram': 'me_api.middleware.instagram:instagram_api',
    'keybase': 'me_api.middleware.keybase:keybase_api',
    'medium': 'me_api.middleware.medium:medium_api',
    'stackoverflow': 'me_api.middleware.stackoverflow:stackoverflow_api',
}

def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    cache.init_app(app)

    modules = config.modules['modules']
    app.register_blueprint(me)
    for module in modules.keys():
        blueprint = import_string(middlewares[module])
        app.register_blueprint(blueprint)

    return app

Prompt:
Improve the way that import middlewares

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

from __future__ import absolute_import, unicode_literals

from flask import Flask

from .middleware.me import me
from .cache import cache

def _register_module(app, module):
    if module == 'douban':
        from .middleware import douban
        app.register_blueprint(douban.douban_api)
    elif module == 'github':
        from .middleware import github
        app.register_blueprint(github.github_api)
    elif module == 'instagram':
        from .middleware import instagram
        app.register_blueprint(instagram.instagram_api)
    elif module == 'keybase':
        from .middleware import keybase
        app.register_blueprint(keybase.keybase_api)
    elif module == 'medium':
        from .middleware import medium
        app.register_blueprint(medium.medium_api)
    elif module == 'stackoverflow':
        from .middleware import stackoverflow
        app.register_blueprint(stackoverflow.stackoverflow_api)

def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    cache.init_app(app)

    modules = config.modules['modules']
    app.register_blueprint(me)
    for module in modules.keys():
        _register_module(app, module)

    return app


import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    if 'agb' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.agb).value
    else:
        data.type = ecwa.MotionTypes(entry.data.zzaEg).value

    if 'agc' in entry.data:
        data.confidence = entry.data.agc
    else:
        data.confidence = entry.data.zzaEh

    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry

Response:
import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    if 'agb' in entry.data:
        data.type = ecwa.MotionTypes(entry.data.agb).value
    else:
        data.type = ecwa.MotionTypes(entry.data.zzaEg).value

    if 'agc' in entry.data:
        data.confidence = entry.data.agc
    else:
        data.confidence = entry.data.zzaEh

    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry

Prompt:
Handle the weird field names from the new version of the API

As part of the switch to cordova, we moved to a newer version of the google
play API. Unfortunately, this meant that the weird field names for the
confidence and type changed to a different set of weird field names. We should
really use a standard wrapper class for this on android as well to avoid such
silent breakages in the future.

https://github.com/e-mission/e-mission-data-collection/issues/80

import logging

import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad

def format(entry):
    formatted_entry = ad.AttrDict()
    formatted_entry["_id"] = entry["_id"]
    formatted_entry.user_id = entry.user_id

    metadata = entry.metadata
    if "time_zone" not in metadata:
        metadata.time_zone = "America/Los_Angeles"
    fc.expand_metadata_times(metadata)
    formatted_entry.metadata = metadata

    data = ad.AttrDict()
    data.type = ecwa.MotionTypes(entry.data.agb).value
    data.confidence = entry.data.agc
    data.ts = formatted_entry.metadata.write_ts
    data.local_dt = formatted_entry.metadata.write_local_dt
    data.fmt_time = formatted_entry.metadata.write_fmt_time
    formatted_entry.data = data

    return formatted_entry


#!/usr/bin/env python3

'''
    Process two different streams in parallel,
    retrieving them from the module's scope
'''

import rx
import asyncio
from concurrent.futures import ThreadPoolExecutor
from functools import partial

import APIReaderTwitter as Twitter

try:
    import json
except ImportError:
    import simplejson as json

def is_not_delete(element):
    return not "delete" in element

def is_delete(element):
    return "delete" in element

def pretty_print(element):
    print(json.dumps(element, indent=4))

twitter_stream = rx.Observable.from_(Twitter.get_iterable())

deleted_stream = twitter_stream.filter(is_not_delete)
tweet_stream = twitter_stream.filter(is_delete)

def process_deleted():
    deleted_stream.subscribe(pretty_print)

def process_tweets():
    tweet_stream.subscribe(pretty_print)

if __name__ == "__main__":
    executor = ThreadPoolExecutor(2)
    loop = asyncio.get_event_loop()

    deleted = asyncio.async(loop.run_in_executor(executor, process_deleted))
    tweets  = asyncio.async(loop.run_in_executor(executor, process_tweets))

    loop.run_forever()

Add example of processing two different streams in separate threads retrieving the streams from the module's global scope.

Response:
#!/usr/bin/env python3

'''
    Process two different streams in parallel,
    retrieving them from the module's scope
'''

import rx
import asyncio
from concurrent.futures import ThreadPoolExecutor
from functools import partial

import APIReaderTwitter as Twitter

try:
    import json
except ImportError:
    import simplejson as json

def is_not_delete(element):
    return not "delete" in element

def is_delete(element):
    return "delete" in element

def pretty_print(element):
    print(json.dumps(element, indent=4))

twitter_stream = rx.Observable.from_(Twitter.get_iterable())

deleted_stream = twitter_stream.filter(is_not_delete)
tweet_stream = twitter_stream.filter(is_delete)

def process_deleted():
    deleted_stream.subscribe(pretty_print)

def process_tweets():
    tweet_stream.subscribe(pretty_print)

if __name__ == "__main__":
    executor = ThreadPoolExecutor(2)
    loop = asyncio.get_event_loop()

    deleted = asyncio.async(loop.run_in_executor(executor, process_deleted))
    tweets  = asyncio.async(loop.run_in_executor(executor, process_tweets))

    loop.run_forever()

Prompt:
Add example of processing two different streams in separate threads
retrieving the streams from the module's global scope.


from setuptools import setup, find_packages

with open('README.rst') as readme:
    long_description = ''.join(readme).strip()

setup(
    name='rsocks',
    version='0.3.3',
    author='Jiangge Zhang',
    author_email='tonyseek@gmail.com',
    description='A SOCKS reverse proxy server.',
    long_description=long_description,
    url='https://github.com/tonyseek/rsocks',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
    packages=find_packages(),
    platforms=['Any'],
    install_requires=[
        'PySocks>=1.7.1,<1.8',
        'eventlet>=0.31,<0.34',
        'click>=3.3,<3.4',
        'toml.py>=0.1,<0.2',
        'six',
    ],
    entry_points={
        'console_scripts': [
            'rsocks=rsocks.cli:main',
        ],
    },
)

Response:
from setuptools import setup, find_packages

with open('README.rst') as readme:
    long_description = ''.join(readme).strip()

setup(
    name='rsocks',
    version='0.3.3',
    author='Jiangge Zhang',
    author_email='tonyseek@gmail.com',
    description='A SOCKS reverse proxy server.',
    long_description=long_description,
    url='https://github.com/tonyseek/rsocks',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.10',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
    packages=find_packages(),
    platforms=['Any'],
    install_requires=[
        'PySocks>=1.7.1,<1.8',
        'eventlet>=0.31,<0.34',
        'click>=3.3,<3.4',
        'toml.py>=0.1,<0.2',
        'six',
    ],
    entry_points={
        'console_scripts': [
            'rsocks=rsocks.cli:main',
        ],
    },
)

Prompt:
Upgrade PySocks to fix Python 3.10 compatbility

from setuptools import setup, find_packages

with open('README.rst') as readme:
    long_description = ''.join(readme).strip()

setup(
    name='rsocks',
    version='0.3.3',
    author='Jiangge Zhang',
    author_email='tonyseek@gmail.com',
    description='A SOCKS reverse proxy server.',
    long_description=long_description,
    url='https://github.com/tonyseek/rsocks',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
    packages=find_packages(),
    platforms=['Any'],
    install_requires=[
        'PySocks>=1.5,<1.6',
        'eventlet>=0.31,<0.34',
        'click>=3.3,<3.4',
        'toml.py>=0.1,<0.2',
        'six',
    ],
    entry_points={
        'console_scripts': [
            'rsocks=rsocks.cli:main',
        ],
    },
)


#!/usr/bin/python
#Author: Scott T. Salesky
#Created: 12.6.2014
#Purpose: Collection of functions, routines to use
#Python for scientific work
#----------------------------------------------

Add function to read 3d direct access Fortran binary files into NumPy arrays.

Response:
#!/usr/bin/python
#Author: Scott T. Salesky
#Created: 12.6.2014
#Purpose: Collection of functions, routines to use
#Python for scientific work
#----------------------------------------------

Prompt: Add function to read 3d direct access Fortran binary files into NumPy arrays.


from models import Protein, Mutation
from database import get_or_create

class SearchResult:

    def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
        self.protein = protein
        self.mutation = mutation
        self.is_mutation_novel = is_mutation_novel
        self.type = type
        self.meta_user = None
        self.__dict__.update(kwargs)

    def __getstate__(self):
        state = self.__dict__.copy()

        state['protein_refseq'] = self.protein.refseq
        del state['protein']

        state['mutation_kwargs'] = {
            'position': self.mutation.position,
            'alt': self.mutation.alt
        }
        del state['mutation']

        state['meta_user'].mutation = None

        return state

    def __setstate__(self, state):

        state['protein'] = Protein.query.filter_by(
            refseq=state['protein_refseq']
        ).one()
        del state['protein_refseq']

        state['mutation'], created = get_or_create(
            Mutation,
            protein=state['protein'],
            **state['mutation_kwargs']
        )
        del state['mutation_kwargs']

        state['meta_user'].mutation = state['mutation']
        state['mutation'].meta_user = state['meta_user']

        self.__dict__.update(state)

Fix result loading for novel mutations

Fix result loading for novel mutations

Response:
from models import Protein, Mutation
from database import get_or_create

class SearchResult:

    def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
        self.protein = protein
        self.mutation = mutation
        self.is_mutation_novel = is_mutation_novel
        self.type = type
        self.meta_user = None
        self.__dict__.update(kwargs)

    def __getstate__(self):
        state = self.__dict__.copy()

        state['protein_refseq'] = self.protein.refseq
        del state['protein']

        state['mutation_kwargs'] = {
            'position': self.mutation.position,
            'alt': self.mutation.alt
        }
        del state['mutation']

        state['meta_user'].mutation = None

        return state

    def __setstate__(self, state):

        state['protein'] = Protein.query.filter_by(
            refseq=state['protein_refseq']
        ).one()
        del state['protein_refseq']

        state['mutation'], created = get_or_create(
            Mutation,
            protein=state['protein'],
            **state['mutation_kwargs']
        )
        del state['mutation_kwargs']

        state['meta_user'].mutation = state['mutation']
        state['mutation'].meta_user = state['meta_user']

        self.__dict__.update(state)

Prompt:
Fix result loading for novel mutations

from models import Protein, Mutation

class SearchResult:

    def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
        self.protein = protein
        self.mutation = mutation
        self.is_mutation_novel = is_mutation_novel
        self.type = type
        self.meta_user = None
        self.__dict__.update(kwargs)

    def __getstate__(self):
        state = self.__dict__.copy()

        state['protein_refseq'] = self.protein.refseq
        del state['protein']

        state['mutation_kwargs'] = {
            'position': self.mutation.position,
            'alt': self.mutation.alt
        }
        del state['mutation']

        state['meta_user'].mutation = None

        return state

    def __setstate__(self, state):

        state['protein'] = Protein.query.filter_by(
            refseq=state['protein_refseq']
        ).one()
        del state['protein_refseq']

        state['mutation'] = Mutation.query.filter_by(
            protein=state['protein'],
            **state['mutation_kwargs']
        ).one()
        del state['mutation_kwargs']

        state['meta_user'].mutation = state['mutation']
        state['mutation'].meta_user = state['meta_user']

        self.__dict__.update(state)


from traits.testing.unittest_tools import unittest

from traits.api import Float, HasTraits, Int, List

class Foo(HasTraits):
    x = Float

    y_changes = List

    def _y_changed(self, new):
        self.y_changes.append(new)

class TestDynamicTraitDefinition(unittest.TestCase):
    """ Test demonstrating special change events using the 'event' metadata.
    """

    def test_add_trait(self):
        foo = Foo(x=3)
        foo.add_trait('y', Int)

        self.assertTrue(hasattr(foo, 'y'))
        self.assertEqual(type(foo.y), int)

        foo.y = 4
        self.assertEqual(foo.y_changes, [4])

    def test_remove_trait(self):
        foo = Foo(x=3)

        # We can't remove a "statically" added trait (i.e., a trait defined
        # in the Foo class).
        result = foo.remove_trait('x')
        self.assertFalse(result)

        # We can remove dynamically added traits.
        foo.add_trait('y', Int)
        foo.y = 70

        result = foo.remove_trait('y')
        self.assertTrue(result)

        self.assertFalse(hasattr(foo, 'y'))
        foo.y = 10
        self.assertEqual(foo.y_changes, [70])

Response:
from traits.testing.unittest_tools import unittest

from traits.api import Float, HasTraits, Int, List

class Foo(HasTraits):
    x = Float

    y_changes = List

    def _y_changed(self, new):
        self.y_changes.append(new)

class TestDynamicTraitDefinition(unittest.TestCase):
    """ Test demonstrating special change events using the 'event' metadata.
    """

    def test_add_trait(self):
        foo = Foo(x=3)
        foo.add_trait('y', Int)

        self.assertTrue(hasattr(foo, 'y'))
        self.assertEqual(type(foo.y), int)

        foo.y = 4
        self.assertEqual(foo.y_changes, [4])

    def test_remove_trait(self):
        foo = Foo(x=3)

        # We can't remove a "statically" added trait (i.e., a trait defined
        # in the Foo class).
        result = foo.remove_trait('x')
        self.assertFalse(result)

        # We can remove dynamically added traits.
        foo.add_trait('y', Int)
        foo.y = 70

        result = foo.remove_trait('y')
        self.assertTrue(result)

        self.assertFalse(hasattr(foo, 'y'))
        foo.y = 10
        self.assertEqual(foo.y_changes, [70])

Prompt:
Remove unused trait definitions in test.

from traits.testing.unittest_tools import unittest

from traits.api import Float, HasTraits, Int, List

class Foo(HasTraits):
    x = Float

    x_changes = List
    y_changes = List

    def _x_changed(self, new):
        self.x_changes.append(new)

    def _y_changed(self, new):
        self.y_changes.append(new)

class TestDynamicTraitDefinition(unittest.TestCase):
    """ Test demonstrating special change events using the 'event' metadata.
    """

    def test_add_trait(self):
        foo = Foo(x=3)
        foo.add_trait('y', Int)

        self.assertTrue(hasattr(foo, 'y'))
        self.assertEqual(type(foo.y), int)

        foo.y = 4
        self.assertEqual(foo.y_changes, [4])

    def test_remove_trait(self):
        foo = Foo(x=3)

        # We can't remove a "statically" added trait (i.e., a trait defined
        # in the Foo class).
        result = foo.remove_trait('x')
        self.assertFalse(result)

        # We can remove dynamically added traits.
        foo.add_trait('y', Int)
        foo.y = 70

        result = foo.remove_trait('y')
        self.assertTrue(result)

        self.assertFalse(hasattr(foo, 'y'))
        foo.y = 10
        self.assertEqual(foo.y_changes, [70])


"""
===========================================
Robust linear model estimation using RANSAC
===========================================

In this example we see how to robustly fit a linear model to faulty data using
the RANSAC algorithm.

"""
import numpy as np
from matplotlib import pyplot as plt

from sklearn import linear_model
from sklearn.utils import ransac

# Set random seed for both equal data noise and equal random sample selection
np.random.seed(seed=1)

# Generate coordinates of line
X = np.arange(-200, 200)
y = 0.2 * X + 20
data = np.column_stack([X, y])

# Add faulty data
faulty = np.array(30 * [(180, -100)], dtype=np.double)
faulty += 5 * np.random.normal(size=faulty.shape)
data[:faulty.shape[0]] = faulty

# Add gaussian noise to coordinates
noise = np.random.normal(size=data.shape)
data += 0.5 * noise
data[::2] += 5 * noise[::2]
data[::4] += 20 * noise[::4]

X = data[:, 0][:, np.newaxis]
y = data[:, 1]

# Fit line using all data
model = linear_model.LinearRegression()
model.fit(X, y)

# Robustly fit linear model with RANSAC algorithm
model_robust = linear_model.LinearRegression()
inlier_mask = ransac(X, y, model_robust, min_n_samples=2, residual_threshold=2)
outlier_mask = ~inlier_mask

# Generate coordinates of estimated models
line_X = np.arange(-250, 250)
line_y = model.predict(line_X[:, np.newaxis])
line_y_robust = model_robust.predict(line_X[:, np.newaxis])

plt.plot(data[inlier_mask, 0], data[inlier_mask, 1], '.g',
         label='Inlier data')
plt.plot(data[outlier_mask, 0], data[outlier_mask, 1], '.r',
         label='Outlier data')
plt.plot(line_X, line_y, '-k', label='Linear model from all data')
plt.plot(line_X, line_y_robust, '-b', label='Robustly fitted linear model')
plt.legend(loc='lower left')
plt.show()

Add example plot script for RANSAC

Add example plot script for RANSAC

Response:
"""
===========================================
Robust linear model estimation using RANSAC
===========================================

In this example we see how to robustly fit a linear model to faulty data using
the RANSAC algorithm.

"""
import numpy as np
from matplotlib import pyplot as plt

from sklearn import linear_model
from sklearn.utils import ransac

# Set random seed for both equal data noise and equal random sample selection
np.random.seed(seed=1)

# Generate coordinates of line
X = np.arange(-200, 200)
y = 0.2 * X + 20
data = np.column_stack([X, y])

# Add faulty data
faulty = np.array(30 * [(180, -100)], dtype=np.double)
faulty += 5 * np.random.normal(size=faulty.shape)
data[:faulty.shape[0]] = faulty

# Add gaussian noise to coordinates
noise = np.random.normal(size=data.shape)
data += 0.5 * noise
data[::2] += 5 * noise[::2]
data[::4] += 20 * noise[::4]

X = data[:, 0][:, np.newaxis]
y = data[:, 1]

# Fit line using all data
model = linear_model.LinearRegression()
model.fit(X, y)

# Robustly fit linear model with RANSAC algorithm
model_robust = linear_model.LinearRegression()
inlier_mask = ransac(X, y, model_robust, min_n_samples=2, residual_threshold=2)
outlier_mask = ~inlier_mask

# Generate coordinates of estimated models
line_X = np.arange(-250, 250)
line_y = model.predict(line_X[:, np.newaxis])
line_y_robust = model_robust.predict(line_X[:, np.newaxis])

plt.plot(data[inlier_mask, 0], data[inlier_mask, 1], '.g',
         label='Inlier data')
plt.plot(data[outlier_mask, 0], data[outlier_mask, 1], '.r',
         label='Outlier data')
plt.plot(line_X, line_y, '-k', label='Linear model from all data')
plt.plot(line_X, line_y_robust, '-b', label='Robustly fitted linear model')
plt.legend(loc='lower left')
plt.show()

Prompt: Add example plot script for RANSAC


import unittest
import github

class TestGithub(unittest.TestCase):

    def setUp(self):

        pass

    def test_user(self):

        u = github.user()
        u1 = github.user()

        self.assertTrue(u)
        # make sure hash works
        self.assertTrue(u is u1)

    def test_has_issues(self):

        self.assertTrue(github.has_issues(("jonmorehouse/vim-github")))
        self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))

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

Response:
import unittest
import github

class TestGithub(unittest.TestCase):

    def setUp(self):

        pass

    def test_user(self):

        u = github.user()
        u1 = github.user()

        self.assertTrue(u)
        # make sure hash works
        self.assertTrue(u is u1)

    def test_has_issues(self):

        self.assertTrue(github.has_issues(("jonmorehouse/vim-github")))
        self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))

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

Prompt:
Remove old repo_from_path tests. This is a very hard functionality to
test

import unittest
import github

class TestGithub(unittest.TestCase):

    def setUp(self):

        pass

    def test_user(self):

        u = github.user()
        u1 = github.user()

        self.assertTrue(u)
        # make sure hash works
        self.assertTrue(u is u1)

    def test_has_issues(self):

        self.assertTrue(github.has_issues(("jonmorehouse/vim-github")))
        self.assertFalse(github.has_issues(("jonmorehouse/github-issues.vim")))

    def test_repo_from_path(self):

        up = "/Users/MorehouseJ09/Desktop/github-issues.vim"
        self.assertTrue(github.repo_from_path(up))

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


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

"""The Base level for Savu

use with :

import savu

.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>

"""

from . import core
from . import data
from . import plugins

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

"""The Base level for Savu

use with :

import savu

.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>

"""

from . import core
from . import data
from . import plugins

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

"""The Base level for Savu

use with :

import savu

.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>

"""


import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')

from unittest import TestCase
from individual import Individual
from bitarray import bitarray

class TestIndividual(TestCase):
    """
    Testing class for Individual.
    """

    def test_get(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

    def test_set(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

    def test_flip(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)

Remove BitVector import - Build fails

Remove BitVector import - Build fails

Response:
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')

from unittest import TestCase
from individual import Individual
from bitarray import bitarray

class TestIndividual(TestCase):
    """
    Testing class for Individual.
    """

    def test_get(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

    def test_set(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

    def test_flip(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)

Prompt:
Remove BitVector import - Build fails
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')

from unittest import TestCase
from individual import Individual
from BitVector import BitVector
from bitarray import bitarray

class TestIndividual(TestCase):
    """
    Testing class for Individual.
    """

    def test_get(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        self.assertEqual(ind.get(5), 1)
        self.assertEqual(ind.get(1), 0)
        self.assertEqual(ind.get(10), None)

    def test_set(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.set(2, 1)
        self.assertEqual(ind.get(2), 1)
        ind.set(7, 0)
        self.assertEqual(ind.get(7), 0)
        ind.set(6, 1)
        self.assertEqual(ind.get(6), 1)

    def test_flip(self):
        ind = Individual(9)
        ind.data = bitarray("011010100")
        ind.flip(1)
        self.assertEqual(ind.get(1), 1)
        ind.flip(8)
        self.assertEqual(ind.get(8), 1)
        ind.flip(4)
        self.assertEqual(ind.get(4), 1)


from django.urls import path
from invite import views

app_name = 'invite'
urlpatterns = [
    path('', views.index, name='index'),
    path('invite/', views.invite, name='invite'),
    path('resend/<slug:code>/', views.resend, name='resend'),
    path('revoke/<slug:code>/', views.revoke, name='revoke'),
    path('login/', views.log_in_user, name='login'),
    path('logout/', views.log_out_user, name='edit_logout'),
    path('amnesia/', views.amnesia, name='amnesia'),
    path('reset/', views.reset, name='reset'),
    path('signup/', views.signup, name='account_signup'),
    path('about/', views.about, name='about'),
    path('check/', views.check, name='check'),
]

Response:
from django.urls import path
from invite import views

app_name = 'invite'
urlpatterns = [
    path('', views.index, name='index'),
    path('invite/', views.invite, name='invite'),
    path('resend/<slug:code>/', views.resend, name='resend'),
    path('revoke/<slug:code>/', views.revoke, name='revoke'),
    path('login/', views.log_in_user, name='login'),
    path('logout/', views.log_out_user, name='edit_logout'),
    path('amnesia/', views.amnesia, name='amnesia'),
    path('reset/', views.reset, name='reset'),
    path('signup/', views.signup, name='account_signup'),
    path('about/', views.about, name='about'),
    path('check/', views.check, name='check'),
]

Prompt:
Fix issue with URL patterns adding parentheses around codes.

from django.urls import path
from invite import views

app_name = 'invite'
urlpatterns = [
    path('', views.index, name='index'),
    path('invite/', views.invite, name='invite'),
    path('resend/(<slug:code>)/', views.resend, name='resend'),
    path('revoke/(<slug:code>)/', views.revoke, name='revoke'),
    path('login/', views.log_in_user, name='login'),
    path('logout/', views.log_out_user, name='edit_logout'),
    path('amnesia/', views.amnesia, name='amnesia'),
    path('reset/', views.reset, name='reset'),
    path('signup/', views.signup, name='account_signup'),
    path('about/', views.about, name='about'),
    path('check/', views.check, name='check'),
]


#!/usr/bin/env python
# My solution to the following challenge: https://redd.it/39ws1x

import os
from datetime import date
from collections import defaultdict

home = os.path.expanduser('~')

class Todo:
    def __init__(self):
        self.items = defaultdict(list)

    def __load_items(self):
        try:
            with open(home + '/.config/todo/list', 'r') as todo:
                for item in todo.readline():
                    # TODO: Need to figure out a way to store tags and items.
                    pass
        except IOError:
            print 'You do not have any items to load.'

    def __save_items(self):
        try:
            with open(home + '/.config/todo/list', 'w') as todo:
                # TODO: Implement saving items.
                pass

    def add_item(self, item, tag):
        self.items[tag].append(item)

    def remove_item(self, item, tag):
        if tag in self.items:
            if item in self.items[tag]:
                self.items[tag].remove(item)
            else:
                print "Item %s could not be found." % item
        else:
            print 'There is not tag named %s' % tag

    def print_all_items(self):
        for (tag, items) in self.items.items():
            print str(tag) + ':'
            for item in items:
                print ' ' + item
            print ''

if __name__ == '__main__':
    todo = Todo()
    # I actually need to do this, for real.
    todo.add_item('Get an oil change.', 'Car')
    todo.add_item('Plastidip my wheels.', 'Car')
    todo.add_item('Clean my room.', 'Housework')
    todo.print_all_items()
    todo.remove_item('Get an oil change.', 'Car')
    todo.remove_item('x', 'x')
    todo.remove_item('x', 'Housework')
    todo.print_all_items()

Response:
#!/usr/bin/env python
# My solution to the following challenge: https://redd.it/39ws1x

import os
from datetime import date
from collections import defaultdict

home = os.path.expanduser('~')

class Todo:
    def __init__(self):
        self.items = defaultdict(list)

    def __load_items(self):
        try:
            with open(home + '/.config/todo/list', 'r') as todo:
                for item in todo.readline():
                    # TODO: Need to figure out a way to store tags and items.
                    pass
        except IOError:
            print 'You do not have any items to load.'

    def __save_items(self):
        try:
            with open(home + '/.config/todo/list', 'w') as todo:
                # TODO: Implement saving items.
                pass

    def add_item(self, item, tag):
        self.items[tag].append(item)

    def remove_item(self, item, tag):
        if tag in self.items:
            if item in self.items[tag]:
                self.items[tag].remove(item)
            else:
                print "Item %s could not be found." % item
        else:
            print 'There is not tag named %s' % tag

    def print_all_items(self):
        for (tag, items) in self.items.items():
            print str(tag) + ':'
            for item in items:
                print ' ' + item
            print ''

if __name__ == '__main__':
    todo = Todo()
    # I actually need to do this, for real.
    todo.add_item('Get an oil change.', 'Car')
    todo.add_item('Plastidip my wheels.', 'Car')
    todo.add_item('Clean my room.', 'Housework')
    todo.print_all_items()
    todo.remove_item('Get an oil change.', 'Car')
    todo.remove_item('x', 'x')
    todo.remove_item('x', 'Housework')
    todo.print_all_items()

Prompt:
Add and remove now work with minimal error checking.

#!/usr/bin/env python
# My solution to the following challenge: https://redd.it/39ws1x

from datetime import date
from collections import defaultdict

class Todo:
    def __init__(self):
        self.items = defaultdict(list)

    def add_item(self, item, tag):
        self.items[tag].append(item)

    def remove_item(self, item, tag):
        self.items[tag].remove(item)

    def print_all_items(self):
        for (tag, items) in self.items.items():
            print str(tag) + ':'
            for item in items:
                print ' ' + item
            print ''

if __name__ == '__main__':
    todo = Todo()
    # I actually need to do this, for real.
    todo.add_item('Get an oil change.', 'Car')
    todo.add_item('Plastidip my wheels.', 'Car')
    todo.add_item('Clean my room.', 'Housework')
    todo.print_all_items()
    todo.remove_item('Get an oil change.', 'Car')
    todo.print_all_items()


"""
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from dataclasses import dataclass
from typing import NewType
from uuid import UUID

TourneyCategoryID = NewType('TourneyCategoryID', UUID)

TourneyID = NewType('TourneyID', UUID)

MatchID = NewType('MatchID', UUID)

MatchCommentID = NewType('MatchCommentID', UUID)

ParticipantID = NewType('ParticipantID', UUID)

@dataclass(frozen=True)
class Match:
    id: MatchID

Response:
"""
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from dataclasses import dataclass
from typing import NewType
from uuid import UUID

TourneyCategoryID = NewType('TourneyCategoryID', UUID)

TourneyID = NewType('TourneyID', UUID)

MatchID = NewType('MatchID', UUID)

MatchCommentID = NewType('MatchCommentID', UUID)

ParticipantID = NewType('ParticipantID', UUID)

@dataclass(frozen=True)
class Match:
    id: MatchID

Prompt:
Change tourney match transfer model from `attrs` to `dataclass`

"""
byceps.services.tourney.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

from typing import NewType
from uuid import UUID

from attr import attrs

TourneyCategoryID = NewType('TourneyCategoryID', UUID)

TourneyID = NewType('TourneyID', UUID)

MatchID = NewType('MatchID', UUID)

MatchCommentID = NewType('MatchCommentID', UUID)

ParticipantID = NewType('ParticipantID', UUID)

@attrs(auto_attribs=True, frozen=True, slots=True)
class Match:
    id: MatchID


from django.template.base import Library
from django.core.urlresolvers import reverse

from projects.models import ProjectBuild

register = Library()

@register.simple_tag()
def build_url(build_key):
    """
    Fetches the ProjectBuild for a given build_id, if any.
    """
    try:
        build = ProjectBuild.objects.get(build_key=build_key)
        return reverse(
            "project_projectbuild_detail",
            kwargs={"project_pk": build.project.pk, "build_pk": build.pk})
    except ProjectBuild.DoesNotExist:
        return ""

Response:
from django.template.base import Library
from django.core.urlresolvers import reverse

from projects.models import ProjectBuild

register = Library()

@register.simple_tag()
def build_url(build_key):
    """
    Fetches the ProjectBuild for a given build_id, if any.
    """
    try:
        build = ProjectBuild.objects.get(build_key=build_key)
        return reverse(
            "project_projectbuild_detail",
            kwargs={"project_pk": build.project.pk, "build_pk": build.pk})
    except ProjectBuild.DoesNotExist:
        return ""

Prompt:
Change the project_tags parameter to use build_key which makes it clearer.

from django.template.base import Library
from django.core.urlresolvers import reverse

from projects.models import ProjectBuild

register = Library()

@register.simple_tag()
def build_url(build_id):
    """
    Fetches the ProjectBuild for a given build_id, if any.
    """
    try:
        build = ProjectBuild.objects.get(build_key=build_id)
        return reverse(
            "project_projectbuild_detail",
            kwargs={"project_pk": build.project.pk, "build_pk": build.pk})
    except ProjectBuild.DoesNotExist:
        return ""


from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

import db.schema as schema
import db.query as query
from handlers.rest import app

admin = Admin(app, url="/admin")

class RoundModelView(ModelView):
  column_list = ('id', 'perspective', 'start_time')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(RoundModelView, self).__init__(
      schema.Round,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class PerspectiveModelView(ModelView):
  form_columns = \
    ('gender',
     'text')

  column_list = ('id', 'gender', 'text', 'created_at')

  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(PerspectiveModelView, self).__init__(
      schema.Perspective,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class SubmissionModelView(ModelView):
  column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(SubmissionModelView, self).__init__(
      schema.Submission,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())

Fix list columns for all models

Fix list columns for all models

Response:
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

import db.schema as schema
import db.query as query
from handlers.rest import app

admin = Admin(app, url="/admin")

class RoundModelView(ModelView):
  column_list = ('id', 'perspective', 'start_time')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(RoundModelView, self).__init__(
      schema.Round,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class PerspectiveModelView(ModelView):
  form_columns = \
    ('gender',
     'text')

  column_list = ('id', 'gender', 'text', 'created_at')

  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(PerspectiveModelView, self).__init__(
      schema.Perspective,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class SubmissionModelView(ModelView):
  column_list = ('id', 'perspective_id', 'text', 'likes', 'created_at')
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(SubmissionModelView, self).__init__(
      schema.Submission,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(SubmissionModelView())

Prompt:
Fix list columns for all models

from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

import db.schema as schema
import db.query as query
from handlers.rest import app

admin = Admin(app, url="/admin")

class RoundModelView(ModelView):
  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(RoundModelView, self).__init__(
      schema.Round,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

class PerspectiveModelView(ModelView):
  form_columns = \
    ('gender',
     'text')

  def __init__(self, name=None, category=None, endpoint=None, url=None, **kwargs):
    for k, v in kwargs.iteritems():
      setattr(self, k, v)

    super(PerspectiveModelView, self).__init__(
      schema.Perspective,
      query.session,
      name=name,
      category=category,
      endpoint=endpoint,
      url=url
    )

admin.add_view(RoundModelView())
admin.add_view(PerspectiveModelView())
admin.add_view(ModelView(schema.Submission, query.session))


"""Make the functionalities of this package auto-discoverable by mara-app"""

def MARA_CONFIG_MODULES():
    from . import config
    return [config]

def MARA_FLASK_BLUEPRINTS():
    from . import views
    return [views.blueprint]

def MARA_AUTOMIGRATE_SQLALCHEMY_MODELS():
    return []

def MARA_ACL_RESOURCES():
    from . import views
    return {'DB Schema': views.acl_resource}

def MARA_CLICK_COMMANDS():
    from . import cli
    return [cli.migrate]

def MARA_NAVIGATION_ENTRIES():
    from . import views
    return {'DB Schema': views.navigation_entry()}

Response:
"""Make the functionalities of this package auto-discoverable by mara-app"""

def MARA_CONFIG_MODULES():
    from . import config
    return [config]

def MARA_FLASK_BLUEPRINTS():
    from . import views
    return [views.blueprint]

def MARA_AUTOMIGRATE_SQLALCHEMY_MODELS():
    return []

def MARA_ACL_RESOURCES():
    from . import views
    return {'DB Schema': views.acl_resource}

def MARA_CLICK_COMMANDS():
    from . import cli
    return [cli.migrate]

def MARA_NAVIGATION_ENTRIES():
    from . import views
    return {'DB Schema': views.navigation_entry()}

Prompt:
Change MARA_XXX variables to functions to delay importing of imports (requires updating mara-app to 2.0.0)

from mara_db import config, views, cli

MARA_CONFIG_MODULES = [config]

MARA_NAVIGATION_ENTRY_FNS = [views.navigation_entry]

MARA_ACL_RESOURCES = [views.acl_resource]

MARA_FLASK_BLUEPRINTS = [views.blueprint]

MARA_CLICK_COMMANDS = [cli.migrate]


from django.test import TestCase
from billjobs.admin import UserAdmin

class EmailExportTestCase(TestCase):
    """ Tests for email account export """

    def test_action_is_avaible(self):
        """ Test admin can select the action in dropdown list """
        self.assertTrue(hasattr(UserAdmin, 'export_email'))

Add test for email account export

Add test for email account export

Response:
from django.test import TestCase
from billjobs.admin import UserAdmin

class EmailExportTestCase(TestCase):
    """ Tests for email account export """

    def test_action_is_avaible(self):
        """ Test admin can select the action in dropdown list """
        self.assertTrue(hasattr(UserAdmin, 'export_email'))

Prompt: Add test for email account export


import sys
import itertools

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

def transpose(xs):
    return zip(*xs)

def read_sides(line):
    return map(int, line.split())

def valid_triangle((a, b, c)):
    return a + b > c and b + c > a and a + c > b

if __name__ == '__main__':
    print len(filter(valid_triangle,
                     grouper(
                         itertools.chain.from_iterable(
                             transpose(map(read_sides, sys.stdin))), 3)))

Response:
import sys
import itertools

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

def transpose(xs):
    return zip(*xs)

def read_sides(line):
    return map(int, line.split())

def valid_triangle((a, b, c)):
    return a + b > c and b + c > a and a + c > b

if __name__ == '__main__':
    print len(filter(valid_triangle,
                     grouper(
                         itertools.chain.from_iterable(
                             transpose(map(read_sides, sys.stdin))), 3)))

Prompt:
Implement part 2 of day 3 Python solution.

import sys

def read_sides(line):
    return map(int, line.split())

def valid_triangle((a, b, c)):
    return a + b > c and b + c > a and a + c > b

if __name__ == '__main__':
    print len(filter(valid_triangle, map(read_sides, sys.stdin)))


#!/usr/bin/env python
#
# resize_ranges
# Resizes ranges in a  BED file around a center point
#

import sys
import argparse
import csv

def resize_row(row, width):
    start, end = int(row[1]), int(row[2])
    original_range = end-start
    margin = (original_range - width) / 2
    start = start + margin
    end = end - margin
    row[1] = start
    row[2] = end
    return row

def resize_ranges(input, output, width):
    """
    Resizes regions in a bed file to the given width
    :param input: An input stream or open file
    :param output: An output stream
    :param width: the desired width
    :return:
    """
    reader = csv.reader(input, delimiter='\t')
    writer = csv.writer(output, delimiter='\t')
    for row in reader:
        writer.writerow(resize_row(row, width))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Resize ranges in a BED file')
    parser.add_argument('inputfile', type=argparse.FileType('rb'))
    parser.add_argument('width', type=int)
    parser.add_argument_group()
    args = parser.parse_args()
    resize_ranges(args.inputfile, sys.stdout, args.width)

Add python script to resize regions

Add python script to resize regions

Response:
#!/usr/bin/env python
#
# resize_ranges
# Resizes ranges in a  BED file around a center point
#

import sys
import argparse
import csv

def resize_row(row, width):
    start, end = int(row[1]), int(row[2])
    original_range = end-start
    margin = (original_range - width) / 2
    start = start + margin
    end = end - margin
    row[1] = start
    row[2] = end
    return row

def resize_ranges(input, output, width):
    """
    Resizes regions in a bed file to the given width
    :param input: An input stream or open file
    :param output: An output stream
    :param width: the desired width
    :return:
    """
    reader = csv.reader(input, delimiter='\t')
    writer = csv.writer(output, delimiter='\t')
    for row in reader:
        writer.writerow(resize_row(row, width))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Resize ranges in a BED file')
    parser.add_argument('inputfile', type=argparse.FileType('rb'))
    parser.add_argument('width', type=int)
    parser.add_argument_group()
    args = parser.parse_args()
    resize_ranges(args.inputfile, sys.stdout, args.width)

Prompt: Add python script to resize regions


"""An example of writing an API to scrapper hacker news once, and then enabling usage everywhere"""
import hug
import requests

@hug.local()
@hug.cli()
@hug.get()
def top_post(section:hug.types.one_of(('news', 'newest', 'show'))='news'):
    """Returns the top post from the provided section"""
    content = requests.get('https://news.ycombinator.com/{0}'.format(section)).content
    text = content.decode('utf-8')
    return text.split('<tr class=\'athing\'>')[1].split("<a href")[1].split(">")[1].split("<")[0]

Add example of a write once API

Add example of a write once API

Response:
"""An example of writing an API to scrapper hacker news once, and then enabling usage everywhere"""
import hug
import requests

@hug.local()
@hug.cli()
@hug.get()
def top_post(section:hug.types.one_of(('news', 'newest', 'show'))='news'):
    """Returns the top post from the provided section"""
    content = requests.get('https://news.ycombinator.com/{0}'.format(section)).content
    text = content.decode('utf-8')
    return text.split('<tr class=\'athing\'>')[1].split("<a href")[1].split(">")[1].split("<")[0]

Prompt: Add example of a write once API


# Color Prefs for idle

class ColorPrefs:
    CNormal     = "black", "white"      # "purple", "white"
    CKeyword    = "#ff7700", None
    CComment    = "#dd0000", None
    CString     = "#00aa00", None
    CDefinition = "#0000ff", None
    CHilite     = "#000068", "#006868"
    CSync       = None, None            # None, "#ffff00"
    CTodo       = None, None            # None, "#cccccc"
    CBreak      = "#ff7777", None
    CHit        = "#ffffff", "#000000"
    CStdIn      = None, None            # None, "yellow"
    CStdOut     = "blue", None
    CStdErr     = "red", None
    CConsole    = "#770000", None
    CError      = None, "#ff7777"
    CCursor     = None, "black"

Response:
# Color Prefs for idle

class ColorPrefs:
    CNormal     = "black", "white"      # "purple", "white"
    CKeyword    = "#ff7700", None
    CComment    = "#dd0000", None
    CString     = "#00aa00", None
    CDefinition = "#0000ff", None
    CHilite     = "#000068", "#006868"
    CSync       = None, None            # None, "#ffff00"
    CTodo       = None, None            # None, "#cccccc"
    CBreak      = "#ff7777", None
    CHit        = "#ffffff", "#000000"
    CStdIn      = None, None            # None, "yellow"
    CStdOut     = "blue", None
    CStdErr     = "red", None
    CConsole    = "#770000", None
    CError      = None, "#ff7777"
    CCursor     = None, "black"

Prompt:
Make the color for stderr red (i.e. the standard warning/danger/stop
color) rather than green.  Suggested by Sam Schulenburg.

# Color Prefs for idle

class ColorPrefs:
    CNormal     = "black", "white"      # "purple", "white"
    CKeyword    = "#ff7700", None
    CComment    = "#dd0000", None
    CString     = "#00aa00", None
    CDefinition = "#0000ff", None
    CHilite     = "#000068", "#006868"
    CSync       = None, None            # None, "#ffff00"
    CTodo       = None, None            # None, "#cccccc"
    CBreak      = "#ff7777", None
    CHit        = "#ffffff", "#000000"
    CStdIn      = None, None            # None, "yellow"
    CStdOut     = "blue", None
    CStdErr     = "#007700", None
    CConsole    = "#770000", None
    CError      = None, "#ff7777"
    CCursor     = None, "black"


#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

Add module for Terminal tests

Add module for Terminal tests

Response:
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy

"""

Prompt: Add module for Terminal tests