Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Set deprecated password hashing schemes
# -*- coding: utf-8 -*- # Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from passlib.apps import ldap_context import passlib.utils ldap_context = ldap_context....
# -*- coding: utf-8 -*- # Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from passlib.apps import ldap_context import passlib.utils crypt_context = ldap_context...
Use a separate lock path
from subprocess import getoutput from random import randrange from filelock import FileLock DICT_PATH = './dict.txt' OOPS_SEEK_TOO_FAR = 48 DICT_LENGTH = 61973 # don't run on OS X def randomize(): out = getoutput('sort -R ' + DICT_PATH) with FileLock(DICT_PATH): with open(DICT_PATH, 'w') as f: ...
from subprocess import getoutput from random import randrange from filelock import FileLock LOCK_PATH = '/tmp/ifixit_dict.lock' DICT_PATH = './dict.txt' OOPS_SEEK_TOO_FAR = 48 DICT_LENGTH = 61973 # don't run on OS X def randomize(): out = getoutput('sort -R ' + DICT_PATH) with FileLock(LOCK_PATH): ...
Add ~/.python to PYTHONPATH and import rc
import vx import math from sys import argv _tick_functions = [] def _register_tick_function(f, front=False): if front: _tick_functions.insert(0, f) else: _tick_functions.append(f) def _tick(): for f in _tick_functions: f() vx.my_vx = _tick vx.register_tick_function = _register_tic...
import vx import math import os import sys _tick_functions = [] def _register_tick_function(f, front=False): if front: _tick_functions.insert(0, f) else: _tick_functions.append(f) def _tick(): for f in _tick_functions: f() vx.my_vx = _tick vx.register_tick_function = _register_tic...
Use from .. import (...) parens
"""Distributed Task Queue""" from celery.distmeta import __version__, __author__, __contact__ from celery.distmeta import __homepage__, __docformat__ from celery.distmeta import VERSION, is_stable_release, version_with_meta
"""Distributed Task Queue""" from celery.distmeta import (__version__, __author__, __contact__, __homepage__, __docformat__, VERSION, is_stable_release, version_with_meta)
Add concat filter to fix issue with jquery-pjax
from flask_assets import Bundle, Environment js = Bundle( 'node_modules/jquery/dist/jquery.js', 'node_modules/jquery-pjax/jquery.pjax.js', 'node_modules/bootbox/bootbox.js', 'node_modules/bootstrap/dist/js/bootstrap.min.js', 'js/application.js', filters='jsmin', output='gen/packed.js' ) css...
from flask_assets import Bundle, Environment, Filter # fixes missing semicolon in last statement of jquery.pjax.js class ConcatFilter(Filter): def concat(self, out, hunks, **kw): out.write(';'.join([h.data() for h, info in hunks])) js = Bundle( 'node_modules/jquery/dist/jquery.js', 'node_modules/j...
Update function to get player stats using base_url
import json import csv import requests import secret base_url = https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/ def main(): division_standings() playoff_standings() playoff_standings() player_stats() points_for() tiebreaker() player_score() # Get Division Standings f...
import json import csv import requests from requests.auth import HTTPBasicAuth import secret base_url = 'https://www.mysportsfeeds.com/api/feed/pull/nfl/2016-2017-regular/' def main(): division_standings() playoff_standings() playoff_standings() player_stats() points_for() tiebreaker() pl...
Switch pytest fixture to function scope
# coding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import pytest import rethinkdb from mockthink import MockThink from mockthink.test.common import as_db_and_table, load_stock_data def pytest_addoption(parser): group = parser.getgroup("mockthink", "Mockthink Test...
# coding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals import pytest import rethinkdb from mockthink import MockThink from mockthink.test.common import as_db_and_table, load_stock_data def pytest_addoption(parser): group = parser.getgroup("mockthink", "Mockthink Test...
Test updated to work with Python 2.6
import unittest from porunga import get_manager from porunga.commands.test import PorungaTestCommand class TestManager(unittest.TestCase): def test_manager_has_proper_commands(self): manager = get_manager() commands = manager.get_commands() self.assertIn('test', commands) test_co...
import unittest from porunga import get_manager from porunga.commands.test import PorungaTestCommand class TestManager(unittest.TestCase): def test_manager_has_proper_commands(self): manager = get_manager() commands = manager.get_commands() self.assertTrue('test' in commands) tes...
Call sys.exit when pkg-config fails
#!/usr/bin/env python from setuptools import setup, Extension import string import sys import os sys.path.append('./test') with open("README.md") as f: long_description = f.read() def cmd(line): return os.popen(line).readlines()[0][:-1].split() setup(name = 'sentencepiece', author = 'Taku Kudo', ...
#!/usr/bin/env python from setuptools import setup, Extension import string import subprocess import sys sys.path.append('./test') with open("README.md") as f: long_description = f.read() def cmd(line): try: output = subprocess.check_output(line, shell=True) except subprocess.CalledProcessError:...
Correct set policy on bag.
store_contents = {} store_structure = {} store_contents['_default_errors'] = [ 'src/_errors/index.recipe', ] store_structure['recipes'] = {} store_structure['bags'] = {} store_structure['recipes']['_errors'] = { 'desc': 'Pretty Errors Error Tiddlers', 'recipe': [ ('_defau...
""" Establish the data structures representing the bags and recipes needed by this plugin. """ store_contents = {} store_structure = {} store_contents['_default_errors'] = [ 'src/_errors/index.recipe', ] store_structure['recipes'] = {} store_structure['bags'] = {} store_structure['recipes']['_errors...
Test extension's parameter access for a given period
from __future__ import unicode_literals, print_function, division, absolute_import from nose.tools import raises from openfisca_core.parameters import ParameterNode from openfisca_country_template import CountryTaxBenefitSystem tbs = CountryTaxBenefitSystem() def test_extension_not_already_loaded(): assert tbs...
from __future__ import unicode_literals, print_function, division, absolute_import from nose.tools import raises from openfisca_core.parameters import ParameterNode from openfisca_country_template import CountryTaxBenefitSystem tbs = CountryTaxBenefitSystem() def test_extension_not_already_loaded(): assert tbs...
Make version format PEP 440 compatible
import re import sys from collections import namedtuple from .connection import connect, Connection, TIMEOUT as DEFAULT_TIMEOUT from .cursor import Cursor from .pool import create_pool, Pool __all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool', 'version', 'version_info', 'DEFAULT_TIMEOUT') ...
import re import sys from collections import namedtuple from .connection import connect, Connection, TIMEOUT as DEFAULT_TIMEOUT from .cursor import Cursor from .pool import create_pool, Pool __all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool', 'version', 'version_info', 'DEFAULT_TIMEOUT') ...
Order feedback items by their timestamp.
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.File...
from django.conf import settings from django.db import models class FeedbackItem(models.Model): timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) resolved = models.BooleanField(default=False) content = models.TextField() screenshot = models.File...
Use the new get_adapter api
""" """ from django.contrib.auth import models import pyamf.adapters models.User.__amf__ = { 'exclude': ('message_set', 'password'), 'readonly': ('username',) } # ensure that the adapter that we depend on is loaded .. pyamf.adapters.get_adapter('django.db.models.base') pyamf.register_package(models, model...
""" """ from django.contrib.auth import models import pyamf.adapters models.User.__amf__ = { 'exclude': ('message_set', 'password'), 'readonly': ('username',) } # ensure that the adapter that we depend on is loaded .. pyamf.get_adapter('django.db.models.base') pyamf.register_package(models, models.__name_...
Reduce sample size for faster processing
# importing modules/ libraries import pandas as pd import random import numpy as np # create a sample of prior orders orders_df = pd.read_csv("Data/orders.csv") s = round(3214874 * 0.1) i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s)) orders_df.loc[i,:].to_csv("Data/orders_prior_samp...
# importing modules/ libraries import pandas as pd import random import numpy as np # create a sample of prior orders orders_df = pd.read_csv("Data/orders.csv") s = round(3214874 * 0.01) i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s)) orders_df.loc[i,:].to_csv("Data/orders_prior_sam...
Fix bug with account additions using old Entity API
#!/usr/bin/python from awsom.entity import Entity, Factory from awsom.config import AccountEntity, config class ModelRootFactory(Factory): def __init__(self, entity): super(ModelRootFactory, self).__init__(entity) def populate(self): # Attach all configuration-defined accounts as children of th...
#!/usr/bin/python from awsom.entity import Entity, Factory from awsom.config import AccountEntity, config class ModelRootFactory(Factory): def __init__(self, entity): super(ModelRootFactory, self).__init__(entity) def populate(self): # Attach all configuration-defined accounts as children of th...
Allow importing major classes directly from productmd
# -*- coding: utf-8 -*- # Copyright (C) 2015 Red Hat, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. ...
Add path parameter to notebook_init()
# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(): """ Assuming a project is built ...
# Author: Álvaro Parafita (parafita.alvaro@gmail.com) """ Utilities for Jupyter Notebooks """ # Add parent folder to path and change dir to it # so that we can access easily to all code and data in that folder import sys import os import os.path def notebook_init(path=os.path.pardir): """ Assuming ...
Change the console log level back to WARN
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 s...
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 s...
Use aero info instead for caching info
# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Err...
# -*- coding: utf-8 -*- __author__ = 'nickl-' from aero.__version__ import __version__ from .base import BaseAdapter class Brew(BaseAdapter): """ Homebrew adapter. """ def search(self, query): response = self.command(['search', query])[0] if 'No formula found' not in response and 'Err...
Add method to create a normal user
from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, p...
from mailu import manager, db from mailu.admin import models from passlib import hash @manager.command def flushdb(): """ Flush the database """ db.drop_all() @manager.command def initdb(): """ Initialize the database """ db.create_all() @manager.command def admin(localpart, domain_name, p...
Refactor the task for getting token to store it in DB
from celery.task import Task from celery.utils.log import get_task_logger import requests logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = "gopherairtime.recharges.tasks.hotsocket_login" def run(s...
import requests from django.conf import settings from celery.task import Task from celery.utils.log import get_task_logger from .models import Account logger = get_task_logger(__name__) class Hotsocket_Login(Task): """ Task to get the username and password varified then produce a token """ name = ...
Check to ensure that we're dealing with "green" threads
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) asse...
from guv.green import threading, time def f1(): """A simple function """ print('Hello, world!') def f2(): """A simple function that sleeps for a short period of time """ time.sleep(0.1) class TestThread: def test_thread_create(self): t = threading.Thread(target=f1) asse...
Add unit test for mongofy_courses of udacity module
import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_te...
import unittest from mooc_aggregator_restful_api import udacity class UdacityTestCase(unittest.TestCase): ''' Unit Tests for module udacity ''' def setUp(self): self.udacity_test_object = udacity.UdacityAPI() def test_udacity_api_response(self): self.assertEqual(self.udacity_te...
Raise SystemExit if not in virtualenv.
#!/usr/bin/python #-*- coding:utf-8 -*- """ Executes the methos in utils.py This file should be running under the original python, not an env one """ import sys from venv_dependencies.venv_dep_utils import * def main(modules): venv = get_active_venv() if not venv: print "No virtual envs" #rais...
#!/usr/bin/python #-*- coding:utf-8 -*- """ Executes the methos in utils.py This file should be running under the original python, not an env one """ import sys from venv_dependencies.venv_dep_utils import * def main(modules): venv = get_active_venv() if not venv: raise SystemExit("No virtual envs") ...
Modify format of address book dictionary
import logging import warnings try: import cPickle as pickle except ImportError: import pickle logger = logging.getLogger(__name__) try: address_book = pickle.load(open('address_book.p', 'rb')) except IOError: logger.debug('Could not load address book!') warnings.warn('Could not load address book!...
import logging import warnings try: import cPickle as pickle except ImportError: import pickle logger = logging.getLogger(__name__) try: address_book = pickle.load(open('address_book.p', 'rb')) except IOError: logger.debug('Could not load address book!') warnings.warn('Could not load address book!...
Set the __name__ on the traversal object
class Root(object): """ The main root object for any traversal """ __name__ = None __parent__ = None def __init__(self, request): pass def __getitem__(self, key): next_ctx = None if key == 'user': next_ctx = User() if key == 'domain': ...
class Root(object): """ The main root object for any traversal """ __name__ = None __parent__ = None def __init__(self, request): pass def __getitem__(self, key): next_ctx = None if key == 'user': next_ctx = User() if key == 'domain': ...
Change project name to cljsbook.
import paver from paver.easy import * import paver.setuputils paver.setuputils.install_distutils_tasks() import os, sys from sphinxcontrib import paverutils sys.path.append(os.getcwd()) updateProgressTables = True try: from runestone.server.chapternames import populateChapterInfob except ImportError: updateP...
import paver from paver.easy import * import paver.setuputils paver.setuputils.install_distutils_tasks() import os, sys from sphinxcontrib import paverutils sys.path.append(os.getcwd()) updateProgressTables = True try: from runestone.server.chapternames import populateChapterInfob except ImportError: updateP...
Use a stylesheet if provided as 2nd arg
from ete2 import Nexml, TreeStyle import sys if len(sys.argv) < 2: print("Command line argument required: NeXML file") exit(-1) nexml = Nexml() nexml.build_from_file(sys.argv[1]) def build_tree_style(tree): # use our simple TSS cascade to prepare an ETE TreeStyle object sheets = gather_tss_stylesheet...
from ete2 import Nexml, TreeStyle import sys if len(sys.argv) < 2: print("Command line argument required: NeXML file") exit(-1) custom_stylesheet = None if len(sys.argv) > 2: if sys.argv[2]: custom_stylesheet = sys.argv[2] nexml = Nexml() nexml.build_from_file(sys.argv[1]) def build_tree_sty...
Use new class name FileLookup
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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...
# Foremast - Pipeline Tooling # # Copyright 2016 Gogo, LLC # # 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...
Make it work in PY3.5 *properly*
import threading import unittest import requests from dmoj.control import JudgeControlRequestHandler try: from unittest import mock except ImportError: import mock try: from http.server import HTTPServer except ImportError: from BaseHTTPServer import HTTPServer class ControlServerTest(unittest.Tes...
import mock import threading import unittest import requests from dmoj.control import JudgeControlRequestHandler try: from http.server import HTTPServer except ImportError: from BaseHTTPServer import HTTPServer class ControlServerTest(unittest.TestCase): @classmethod def setUpClass(cls): cla...
Fix local import of the app
# -*- coding: utf-8 -*- import pytest @pytest.fixture def basic_app(): """Fixture for a default app. Returns: :class:`{{cookiecutter.app_class_name}}`: App instance """ from {{cookiecutter.repo_name}} import {{cookiecutter.app_class_name}} return {{cookiecutter.app_class_name}}() def tes...
# -*- coding: utf-8 -*- import pytest @pytest.fixture def basic_app(): """Fixture for a default app. Returns: :class:`{{cookiecutter.app_class_name}}`: App instance """ from {{cookiecutter.repo_name}}.{{cookiecutter.repo_name}} import {{cookiecutter.app_class_name}} return {{cookiecutter.a...
Change string formatting to use format
from django.db import models from .. import abstract_models from ..manager import PageManager class PageType(abstract_models.AbstractPageType): class Meta: app_label = 'fancypages' class VisibilityType(abstract_models.AbstractVisibilityType): class Meta: app_label = 'fancypages' class Fan...
from django.db import models from .. import abstract_models from ..manager import PageManager class PageType(abstract_models.AbstractPageType): class Meta: app_label = 'fancypages' class VisibilityType(abstract_models.AbstractVisibilityType): class Meta: app_label = 'fancypages' class Fan...
Convert copy_reg test to PyUnit.
import copy_reg class C: pass try: copy_reg.pickle(C, None, None) except TypeError, e: print "Caught expected TypeError:" print e else: print "Failed to catch expected TypeError when registering a class type." print try: copy_reg.pickle(type(1), "not a callable") except TypeError, e: pr...
import copy_reg import test_support import unittest class C: pass class CopyRegTestCase(unittest.TestCase): def test_class(self): self.assertRaises(TypeError, copy_reg.pickle, C, None, None) def test_noncallable_reduce(self): self.assertRaises(TypeError, copy_...
Fix tests failing on long line
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import tempfile __version__ = '0.1.11' DB = os.path.join( tempfile.gettempdir(), 'fake_useragent_{version}.json'.format( version=__version__, ), ) CACHE_SERVER = 'https://fake-useragent.herokuapp.com/brows...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import tempfile __version__ = '0.1.11' DB = os.path.join( tempfile.gettempdir(), 'fake_useragent_{version}.json'.format( version=__version__, ), ) CACHE_SERVER = 'https://fake-useragent.herokuapp.com/brows...
Change calculation for on air now
from django.utils import timezone from show.models import Show def get_current_permitted_show(klass=Show): # does_not_repeat requires a datetime match. All the others operate on # time. # todo: may need to fall back to SQL since we can't cast datetime to date # using the ORM. Or use time fields inst...
from django.utils import timezone from show.models import Show def get_current_permitted_show(klass=Show, now=None): # does_not_repeat requires a datetime match. All the others operate on # time. # todo: may need to fall back to SQL since we can't cast datetime to date # using the ORM. Or use time f...
Add active flag to entities
from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse from engine.entity import Entity class BaseEntity(Widget, Entity): def __init__(self, imageStr, **kwargs): Widget.__init__(self, **kwargs) Entity.__init__(self) with self.canvas: ...
from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.graphics import Ellipse from engine.entity import Entity class BaseEntity(Widget, Entity): def __init__(self, imageStr, **kwargs): self.active = False Widget.__init__(self, **kwargs) Entity.__init__(self) ...
Make mono channel output activation more readable
from keras.layers import Convolution2D, Reshape, Lambda, Activation from eva.layers.masked_convolution2d import MaskedConvolution2D class OutChannels(object): def __init__(self, height, width, channels, masked=False, palette=256): self.height = height self.width = width self.channels = cha...
from keras.layers import Convolution2D, Reshape, Lambda, Activation from eva.layers.masked_convolution2d import MaskedConvolution2D class OutChannels(object): def __init__(self, height, width, channels, masked=False, palette=256): self.height = height self.width = width self.channels = cha...
Add blank line to comply with PEP 8
#!/usr/bin/env python3 """Exception classes specific to pushdown automata.""" from automata.base.exceptions import AutomatonException class PDAException(AutomatonException): """The base class for all PDA-related errors.""" pass class NondeterminismError(PDAException): """A DPDA is exhibiting nondeterm...
#!/usr/bin/env python3 """Exception classes specific to pushdown automata.""" from automata.base.exceptions import AutomatonException class PDAException(AutomatonException): """The base class for all PDA-related errors.""" pass class NondeterminismError(PDAException): """A DPDA is exhibiting nondeterm...
Add get_config to the list of public functions for plotly.py
""" plotly ====== This module defines functionality that requires interaction between your local machine and Plotly. Almost all functionality used here will require a verifiable account (username/api-key pair) and a network connection. """ from . plotly import ( sign_in, update_plot_options, get_plot_options, get...
""" plotly ====== This module defines functionality that requires interaction between your local machine and Plotly. Almost all functionality used here will require a verifiable account (username/api-key pair) and a network connection. """ from . plotly import ( sign_in, update_plot_options, get_plot_options, get...
Fix gomp library dynamic loading issues
''' OpenMP wrapper using a (user provided) libgomp dynamically loaded library ''' import sys import glob import ctypes class omp(object): LD_LIBRARY_PATHS = [ "/usr/lib/x86_64-linux-gnu/", # MacPorts install gcc in a "non standard" path on OSX ] + glob.glob("/opt/local/lib/gcc*/") def __...
''' OpenMP wrapper using a (user provided) libgomp dynamically loaded library ''' import sys import glob import ctypes class omp(object): LD_LIBRARY_PATHS = [ "/usr/lib/x86_64-linux-gnu/", # MacPorts install gcc in a "non standard" path on OSX ] + glob.glob("/opt/local/lib/gcc*/") def __...
Test commit push and pull
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. if __name__ == "__main__": print "Hello World"
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. print("Hello World") print("Hessel is een home")
Add new get_ starcheck methods to exported/init methods
# Licensed under a 3-clause BSD style license - see LICENSE.rst from .starcheck import get_starcheck_catalog, get_starcheck_catalog_at_date, get_mp_dir, get_monitor_windows
# Licensed under a 3-clause BSD style license - see LICENSE.rst from .starcheck import (get_starcheck_catalog, get_starcheck_catalog_at_date, get_mp_dir, get_monitor_windows, get_dither, get_att, get_starcat)
Use http for proxy test
from common_fixtures import * # NOQA import requests def test_proxy(client, admin_user_client): domain = 'releases.rancher.com' s = admin_user_client.by_id_setting('api.proxy.whitelist') if domain not in s.value: s.value += ',{}'.format(domain) admin_user_client.update(s, value=s.value)...
from common_fixtures import * # NOQA import requests def test_proxy(client, admin_user_client): domain = 'releases.rancher.com' s = admin_user_client.by_id_setting('api.proxy.whitelist') if domain not in s.value: s.value += ',{}'.format(domain) admin_user_client.update(s, value=s.value)...
Create new method object generate get riak bucket and generate tuple or list
#!/usr/bin/env python # -*- coding: utf-8 -*- import riak from wtforms.fields import TextField, TextAreaField, SelectField from wtforms.validators import Required from wtforms_tornado import Form class ConnectionForm(Form): name = TextField(validators=[Required()]) conection = TextField(validators=[Required(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import riak from wtforms.fields import TextField, TextAreaField, SelectField from wtforms.validators import Required from wtforms_tornado import Form def ObjGenerate(bucket, key, value=None, _type=tuple): myClient = riak.RiakClient(protocol='http', ...
Fix Brand and Owner public links (missing / would get a 404 on brand/ and owner/)
from django.conf.urls import patterns, url from manager.apps.brand.views import BrandListView, BrandView from manager.apps.brand.views import OwnerListView, OwnerView urlpatterns = patterns( '', url(r'^brand$', BrandListView.as_view(), name='brandlist'), url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.as...
from django.conf.urls import patterns, url from manager.apps.brand.views import BrandListView, BrandView from manager.apps.brand.views import OwnerListView, OwnerView urlpatterns = patterns( '', url(r'^brand/$', BrandListView.as_view(), name='brandlist'), url(r'^brand/(?P<bsin>[1-9A-NP-Z]{6})', BrandView.a...
Remove future-restriction on list_events tag
import datetime from django import template from .. import models register = template.Library() @register.inclusion_tag('events/tags/list_events.html') def list_events(number_of_events=3): now = datetime.datetime.now() events = models.Event.objects.filter(date__gte=now).all()[:number_of_events] has_ra...
from django import template from .. import models register = template.Library() @register.inclusion_tag('events/tags/list_events.html') def list_events(number_of_events=None): events = models.Event.objects.all() if number_of_events is not None: events = events[:number_of_events] has_range = Fal...
Fix estimator loop, consider rest plugins as well.
import logging from flexget.plugin import get_plugins_by_group, register_plugin log = logging.getLogger('est_released') class EstimateRelease(object): """ Front-end for estimator plugins that estimate release times for various things (series, movies). """ def estimate(self, entry): """ ...
import logging from flexget.plugin import get_plugins_by_group, register_plugin log = logging.getLogger('est_released') class EstimateRelease(object): """ Front-end for estimator plugins that estimate release times for various things (series, movies). """ def estimate(self, entry): """ ...
Remove whitespace from blank line
#!/usr/bin/env python import os import sys if __name__ == "__main__": from mezzanine.utils.conf import real_project_name settings_module = "%s.settings" % real_project_name("{{ project_name }}") os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module) from django.core.management import e...
#!/usr/bin/env python import os import sys if __name__ == "__main__": from mezzanine.utils.conf import real_project_name settings_module = "%s.settings" % real_project_name("{{ project_name }}") os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module) from django.core.management import execu...
Add dollar sign to fares, sort by fare type
import tornado.web import ipy_table from transperth.location import Location class BaseRequestHandler(tornado.web.RequestHandler): @property def args(self): args = self.request.arguments return { k: [sv.decode() for sv in v] for k, v in args.items() } def...
import tornado.web import ipy_table from transperth.location import Location class BaseRequestHandler(tornado.web.RequestHandler): @property def args(self): args = self.request.arguments return { k: [sv.decode() for sv in v] for k, v in args.items() } def...
Mark test_default_config as skip; Scheduler needs to be rewritten
# -*- coding: utf-8 -*- """Test Factory Module This module contains the tests for the OpenRecords Application Factory """ import os import flask import json import pytest from app import create_app def test_default_config(): """Test the default config class is the DevelopmentConfig""" assert isinstance(cr...
# -*- coding: utf-8 -*- """Test Factory Module This module contains the tests for the OpenRecords Application Factory """ import os import flask import json import pytest from app import create_app @pytest.mark.skip(reason="Scheduler is not functioning and needs to be replaced.") def test_default_config(): """...
Make known_assertions.txt cross-machine and hopefully also cross-platform.
#!/usr/bin/env python def amiss(logPrefix): global ignoreList foundSomething = False currentFile = file(logPrefix + "-err", "r") # map from (assertion message) to (true, if seen in the current file) seenInCurrentFile = {} for line in currentFile: line = line.strip("\x07").rstrip(...
#!/usr/bin/env python import platform def amiss(logPrefix): global ignoreList foundSomething = False currentFile = file(logPrefix + "-err", "r") # map from (assertion message) to (true, if seen in the current file) seenInCurrentFile = {} for line in currentFile: line = line.stri...
Add Etag header to proxy response from s3
import boto import logging from tpt import private_settings from boto.s3.key import Key from django.http import StreamingHttpResponse from django.http import Http404 logger = logging.getLogger(__name__) def stream_object(key_name): s3 = boto.connect_s3( aws_access_key_id = private_settings.AWS_ACCESS...
import boto import logging from tpt import private_settings from boto.s3.key import Key from django.http import StreamingHttpResponse from django.http import Http404 logger = logging.getLogger(__name__) def stream_object(key_name): s3 = boto.connect_s3( aws_access_key_id = private_settings.AWS_ACCESS...
Fix missing ^ in url patterns
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'admin/', include(admin.site.urls)), url(r'rankedmodel/', include('awl.rankedmodel.urls')), url(r'dform/', include('dform.urls')), url(r'dform_admin/', include('dform.admin_urls')), ]
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^rankedmodel/', include('awl.rankedmodel.urls')), url(r'^dform/', include('dform.urls')), url(r'^dform_admin/', include('dform.admin_urls')), ]
Support setting alpha in colors
# Copyright 2017 Google Inc. All rights reserved. # # 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 ag...
# Copyright 2017 Google Inc. All rights reserved. # # 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 ag...
Add Splunk API for log clustering
from os import system, remove class PySplunk(object): def __init__(self, username, source, host, output_mode, tmp_file='/tmp/pysplunk_cluster.csv'): self.username = username self.source = source.replace(' ', '\ ') self.host = host self.output_mode = output_mode self.tmp_fil...
Fix getting category's descendants before save
from django import forms from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from mptt.forms import TreeNodeChoiceField from unidecode import unidecode from ...product.models import Category class CategoryForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Categ...
from django import forms from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from mptt.forms import TreeNodeChoiceField from unidecode import unidecode from ...product.models import Category class CategoryForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Categ...
Add updated version to PyPi
""" Setup and installation for the package. """ try: from setuptools import setup except ImportError: from distutils.core import setup setup( name="three", version="0.4", url="http://github.com/codeforamerica/three", author="Zach Williams", author_email="hey@zachwill.com", description...
""" Setup and installation for the package. """ try: from setuptools import setup except ImportError: from distutils.core import setup setup( name="three", version="0.4.1", url="http://github.com/codeforamerica/three", author="Zach Williams", author_email="hey@zachwill.com", descripti...
Add Python 3 trove classifiers
#!/usr/bin/env python from setuptools import setup import base32_crockford setup( name='base32-crockford', version='0.2.0', description=("A Python implementation of Douglas Crockford's " "base32 encoding scheme"), long_description=base32_crockford.__doc__, license='BSD', aut...
#!/usr/bin/env python from setuptools import setup import base32_crockford setup( name='base32-crockford', version='0.2.0', description=("A Python implementation of Douglas Crockford's " "base32 encoding scheme"), long_description=base32_crockford.__doc__, license='BSD', aut...
Update classifiers to include python 3.10
import os from setuptools import setup, find_packages def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name='pynubank', version='2.17.0', url='https://github.com/andreroggeri/pynubank', author='André Roggeri Campos', author_emai...
import os from setuptools import setup, find_packages def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name='pynubank', version='2.17.0', url='https://github.com/andreroggeri/pynubank', author='André Roggeri Campos', author_emai...
Add postgres as response processing for travis
DEBUG = False BROKER_URL = 'amqp://guest@localhost' RECORD_HTTP_TRANSACTIONS = False CELERY_EAGER_PROPAGATES_EXCEPTIONS = True RAW_PROCESSING = ['cassandra', 'postgres'] NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres'] RESPONSE_PROCESSING = None SENTRY_DSN = None USE_FLUENTD = False CASSANDRA_U...
DEBUG = False BROKER_URL = 'amqp://guest@localhost' RECORD_HTTP_TRANSACTIONS = False CELERY_EAGER_PROPAGATES_EXCEPTIONS = True RAW_PROCESSING = ['cassandra', 'postgres'] NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres'] RESPONSE_PROCESSING = 'postgres' SENTRY_DSN = None USE_FLUENTD = False CASSA...
Add slightly more descriptive keywords for PyPI
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'pyparsing' ] test_requirements = [ ] setup( name='boolrule', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'pyparsing' ] test_requirements = [ ] setup( name='boolrule', ...
Disable country minimum share limit.
from os import getenv GEOIP_DB_FILE = '/usr/local/share/GeoIP/GeoIP2-City.mmdb' STATSD_HOST = 'graphite1.private.phx1.mozilla.com' STATSD_PORT = 8125 STATSD_PREFIX = 'glow-workers-{}'.format(getenv('DJANGO_SERVER_ENV'))
from os import getenv GEOIP_DB_FILE = '/usr/local/share/GeoIP/GeoIP2-City.mmdb' STATSD_HOST = 'graphite1.private.phx1.mozilla.com' STATSD_PORT = 8125 STATSD_PREFIX = 'glow-workers-{}'.format(getenv('DJANGO_SERVER_ENV')) COUNTRY_MIN_SHARE = 1 # basically off
Use a constant time comparison in the API auth
from django.contrib.auth.models import AnonymousUser from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ProjectKey class KeyAuthentication(BasicAuthentication): def authenticate_credentials(self, userid, password): ...
from django.contrib.auth.models import AnonymousUser from django.utils.crypto import constant_time_compare from rest_framework.authentication import BasicAuthentication from rest_framework.exceptions import AuthenticationFailed from sentry.models import ProjectKey class KeyAuthentication(BasicAuthentication): d...
Make shape a property for LinearAAMAlgorithmResult
from __future__ import division from menpofit.result import ( ParametricAlgorithmResult, MultiFitterResult, SerializableIterativeResult) # TODO: document me! # TODO: handle costs class AAMAlgorithmResult(ParametricAlgorithmResult): r""" """ def __init__(self, image, fitter, shape_parameters, ...
from __future__ import division from menpofit.result import ( ParametricAlgorithmResult, MultiFitterResult, SerializableIterativeResult) # TODO: document me! # TODO: handle costs class AAMAlgorithmResult(ParametricAlgorithmResult): r""" """ def __init__(self, image, fitter, shape_parameters, ...
Add a state not to call the task continuously.
import sys sys.path.append('../py') from iroha import * from iroha.iroha import * d = IDesign() mod = IModule(d, "mod") callee_tab = ITable(mod) task = design_tool.CreateSiblingTask(callee_tab) entry_insn = IInsn(task) st1 = IState(callee_tab) st1.insns.append(entry_insn) callee_tab.states.append(st1) callee_tab.ini...
import sys sys.path.append('../py') from iroha import * from iroha.iroha import * d = IDesign() mod = IModule(d, "mod") callee_tab = ITable(mod) task = design_tool.CreateSiblingTask(callee_tab) entry_insn = IInsn(task) st1 = IState(callee_tab) st1.insns.append(entry_insn) callee_tab.states.append(st1) callee_tab.ini...
Fix extra code sending after loop in rf transmitter
import asyncio from alarme import Action from alarme.extras.common import SingleRFDevice class RfTransmitterAction(Action): def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02): super().__init__(app, id_) self.gpio = gpio self.code = code self.run_count = run_...
import asyncio from alarme import Action from alarme.extras.common import SingleRFDevice class RfTransmitterAction(Action): def __init__(self, app, id_, gpio, code, run_count=1, run_interval=0.02): super().__init__(app, id_) self.gpio = gpio self.code = code self.run_count = run_...
Remove long-running update query in initial migration.
# -*- coding: utf-8 -*- from django.db import models, migrations from django.contrib.postgres import operations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('zerver', '0001_initial'), ] database_setting = settings.DATABASES["default"] if "postgres...
# -*- coding: utf-8 -*- from django.db import models, migrations from django.contrib.postgres import operations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('zerver', '0001_initial'), ] database_setting = settings.DATABASES["default"] if "postgres...
Fix loading bug in ok_test
from client import exceptions as ex from client.sources.ok_test import concept from client.sources.ok_test import doctest from client.sources.ok_test import models from client.sources.common import importing import logging import os log = logging.getLogger(__name__) SUITES = { 'doctest': doctest.DoctestSuite, ...
from client import exceptions as ex from client.sources.ok_test import concept from client.sources.ok_test import doctest from client.sources.ok_test import models from client.sources.common import importing import logging import os log = logging.getLogger(__name__) SUITES = { 'doctest': doctest.DoctestSuite, ...
Add some debug markers for more clearly finding our own rendering code
from PyQt5.QtCore import pyqtProperty, QObject from PyQt5.QtGui import QColor from PyQt5.QtQuick import QQuickWindow, QQuickItem from OpenGL import GL class MainWindow(QQuickWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self._app = None self._backgro...
from PyQt5.QtCore import pyqtProperty, QObject from PyQt5.QtGui import QColor from PyQt5.QtQuick import QQuickWindow, QQuickItem from OpenGL import GL from OpenGL.GL.GREMEDY.string_marker import * class MainWindow(QQuickWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) ...
Update asyncio policy to match newer asyncio version
""" This is a replacement event loop and policy for asyncio that uses FPGA time, rather than native python time. """ from asyncio.events import BaseDefaultEventLoopPolicy from asyncio import SelectorEventLoop, set_event_loop_policy from wpilib import Timer class FPGATimedEventLoop(SelectorEventLoop): """An asynci...
""" This is a replacement event loop and policy for asyncio that uses FPGA time, rather than native python time. """ from asyncio.events import AbstractEventLoopPolicy from asyncio import SelectorEventLoop, set_event_loop_policy from wpilib import Timer class FPGATimedEventLoop(SelectorEventLoop): """An asyncio e...
Make the secure session cookie setting case-insensitive
import os import datetime register_title_api = os.environ['REGISTER_TITLE_API'] login_api = os.environ['LOGIN_API'] logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH'] google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY'] secret_key = os.environ['APPLICATION_SECRET_KEY'] session_cookie_secure...
import os import datetime register_title_api = os.environ['REGISTER_TITLE_API'] login_api = os.environ['LOGIN_API'] logging_config_file_path = os.environ['LOGGING_CONFIG_FILE_PATH'] google_analytics_api_key = os.environ['GOOGLE_ANALYTICS_API_KEY'] secret_key = os.environ['APPLICATION_SECRET_KEY'] session_cookie_secure...
Fix defs for ReadPixels and GetChromiumParametervCR
# Copyright (c) 2001, Stanford University # All rights reserved. # # See the file LICENSE.txt for information on redistributing this software. import sys sys.path.append( "../glapi_parser" ) import apiutil apiutil.CopyrightDef() print """DESCRIPTION "" EXPORTS """ keys = apiutil.GetDispatchedFunctions("../glapi_p...
# Copyright (c) 2001, Stanford University # All rights reserved. # # See the file LICENSE.txt for information on redistributing this software. import sys sys.path.append( "../glapi_parser" ) import apiutil apiutil.CopyrightDef() print """DESCRIPTION "" EXPORTS """ keys = apiutil.GetDispatchedFunctions("../glapi_p...
Fix HardwareDevice docstring to match implementation
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types...
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types...
Add the kmsi script to the install files.
#! /usr/bin/env python3 # -*- coding:Utf8 -*- #-------------------------------------------------------------------------------------------------------------- # All necessary import: #-------------------------------------------------------------------------------------------------------------- import os, sys, glob imp...
#! /usr/bin/env python3 # -*- coding:Utf8 -*- #-------------------------------------------------------------------------------------------------------------- # All necessary import: #-------------------------------------------------------------------------------------------------------------- import os, sys, glob imp...
Fix parsing when style specified, add 'auto' score
"""Docstring parsing.""" from . import rest from .common import ParseError _styles = {"rest": rest.parse} def parse(text: str, style: str = "auto"): """ Parse the docstring into its components. :param str text: docstring text to parse :param text style: docstring style, choose from: 'rest', 'auto'...
"""Docstring parsing.""" from . import rest from .common import ParseError, Docstring _styles = {"rest": rest.parse} def _parse_score(docstring: Docstring) -> int: """ Produce a score for the parsing. :param Docstring docstring: parsed docstring representation :returns int: parse score, higher is ...
Upgrade API to v1.3 and benchmark file to v1.1
##################################################### # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019.08 # ##################################################### # [2020.03.09] Upgrade to v1.2 import os from setuptools import setup def read(fname='README.md'): with open(os.path.join(os.path.dirname(__file__), fname...
##################################################### # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019.08 # ##################################################### # [2020.02.25] Initialize the API as v1.1 # [2020.03.09] Upgrade the API to v1.2 # [2020.03.16] Upgrade the API to v1.3 import os from setuptools import setup...
Add proper Python version classifiers.
# -*- coding: utf-8 -*- VERSION = '0.2' from setuptools import setup setup( name='nutshell', packages=["nutshell"], version=VERSION, description='A minimal python library to access Nutshell CRM:s JSON-RPC API.', author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/Em...
# -*- coding: utf-8 -*- VERSION = '0.2' from setuptools import setup setup( name='nutshell', packages=["nutshell"], version=VERSION, description='A minimal python library to access Nutshell CRM:s JSON-RPC API.', author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/Em...
Update python versions we care about
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-glitter-news', version='0.1', description='Django Glitter News for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-glitter-news', maintainer='Blanc Ltd', mainta...
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-glitter-news', version='0.1', description='Django Glitter News for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-glitter-news', maintainer='Blanc Ltd', mainta...
Add python-coveralls as a test dependency
#!/usr/bin/env python import os import sys from serfclient import __version__ try: from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args ...
#!/usr/bin/env python import os import sys from serfclient import __version__ try: from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args ...
Allow codata tests to be run as script.
import warnings from scipy.constants import find from numpy.testing import assert_equal def test_find(): warnings.simplefilter('ignore', DeprecationWarning) keys = find('weak mixing', disp=False) assert_equal(keys, ['weak mixing angle']) keys = find('qwertyuiop', disp=False) assert_equal(keys,...
import warnings from scipy.constants import find from numpy.testing import assert_equal, run_module_suite def test_find(): warnings.simplefilter('ignore', DeprecationWarning) keys = find('weak mixing', disp=False) assert_equal(keys, ['weak mixing angle']) keys = find('qwertyuiop', disp=False) ...
Fix missing module on __version__
# -*- coding: utf-8 -*- """entry point for zazu""" __author__ = "Nicholas Wiles" __copyright__ = "Copyright 2016, Lily Robotics" import click import git_helper import subprocess import zazu.build import zazu.config import zazu.dev.commands import zazu.repo.commands import zazu.style import zazu.upgrade @click.group(...
# -*- coding: utf-8 -*- """entry point for zazu""" __author__ = "Nicholas Wiles" __copyright__ = "Copyright 2016, Lily Robotics" import click import git_helper import subprocess import zazu.build import zazu.config import zazu.dev.commands import zazu.repo.commands import zazu.style import zazu.upgrade @click.group(...
Exit with nonzero when qq strings are missing
#!/usr/bin/env python import os import xml.etree.ElementTree as ET RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res")) EN_STRINGS = os.path.join(RES_FOLDER, "values/strings.xml") QQ_STRINGS = os.path.join(RES_FOLDER, "values-qq/strings.xml") # Get ElementTree containing all me...
#!/usr/bin/env python import os import sys import xml.etree.ElementTree as ET RES_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "../app/src/main/res")) EN_STRINGS = os.path.join(RES_FOLDER, "values/strings.xml") QQ_STRINGS = os.path.join(RES_FOLDER, "values-qq/strings.xml") # Get ElementTree contai...
Add _coord_to_algebraic() and _algebraic_to_coord() to convert positions between (x, y) coords and 'a1' algebraic chess notation
# Use x, y coords for unit positions # (97, 56) ... (104, 56) # ... ... # (97, 49) ... (104, 49) # # Algebraic notation for a position is: # algebraic_pos = chr(x) + chr(y)
# Use x, y coords for unit positions # (97, 56) ... (104, 56) # ... ... # (97, 49) ... (104, 49) # # Algebraic notation for a position is: # algebraic_pos = chr(x) + chr(y) def _coord_to_algebraic(coord): x, y = coord return chr(x) + chr(y) def _algebraic_to_coord(algebraic): x, y = algebrai...
Set y-axis min to 0
boilerplate = { 'chart': { 'renderTo': 'container', 'plotBackgroundColor': 'none', 'backgroundColor': 'none', 'spacingTop': 5 }, 'title': {'text': None}, 'subtitle': {'text': None}, 'yAxis': { 'title':{ 'text': None }, 'gridLineColo...
boilerplate = { 'chart': { 'renderTo': 'container', 'plotBackgroundColor': 'none', 'backgroundColor': 'none', 'spacingTop': 5 }, 'title': {'text': None}, 'subtitle': {'text': None}, 'yAxis': { 'min': 0, 'title':{ 'text': None }, ...
Add 'cssmin' as a dependency
import os from setuptools import setup, find_packages classifiers = """\ Intended Audience :: Developers License :: OSI Approved :: MIT License Programming Language :: Python Topic :: Utilities Operating System :: Unix """ def read(*rel_names): return open(os.path.join(os.path.dirname(__file__), *rel_names)).re...
import os from setuptools import setup, find_packages classifiers = """\ Intended Audience :: Developers License :: OSI Approved :: MIT License Programming Language :: Python Topic :: Utilities Operating System :: Unix """ def read(*rel_names): return open(os.path.join(os.path.dirname(__file__), *rel_names)).re...
Use wget to fetch a list of categories + short description of each function
#! /usr/bin/env python # -*- coding: utf-8 -*- import wikipedia import sys sample = 'Philosophers' # help(cat_page) def getPagesIn(category): """Should return the list of pages that the provided category contains""" page_name = 'Category:' + category page = wikipedia.page(page_name) return page.lin...
#! /usr/bin/env python # -*- coding: utf-8 -*- import wikipedia import sys import os sample = 'Philosophers' # help(cat_page) def getPagesIn(category): """Return the list of pages contained in the provided category""" # wikipedia module doesn't provide category listing, let's retrieve it # with some qu...
Set zip_safe to False as the stub may be called by a process that does not have a writable egg cache.
# # This file is part of WinPexpect. WinPexpect is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # WinPexpect is copyright (c) 2008-2010 by the WinPexpect authors. See the # file "AUTHORS" for a com...
# # This file is part of WinPexpect. WinPexpect is free software that is made # available under the MIT license. Consult the file "LICENSE" that is # distributed together with this file for the exact licensing terms. # # WinPexpect is copyright (c) 2008-2010 by the WinPexpect authors. See the # file "AUTHORS" for a com...
Update package configuration, pt. ii
from setuptools import setup, find_packages setup( name='tangled.sqlalchemy', version='0.1.dev0', description='Tangled SQLAlchemy integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', ...
from setuptools import setup setup( name='tangled.sqlalchemy', version='0.1.dev0', description='Tangled SQLAlchemy integration', long_description=open('README.rst').read(), url='http://tangledframework.org/', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', install_require...
Fix missing raven module again
from cx_Freeze import setup, Executable packages = [ "encodings", "uvloop", "motor", "appdirs", "packaging", "packaging.version", "_cffi_backend", "asyncio", "asyncio.base_events", "asyncio.compat", "raven.conf", "raven.handlers", "raven.processors" ] # Dependencies...
from cx_Freeze import setup, Executable packages = [ "encodings", "uvloop", "motor", "appdirs", "packaging", "packaging.version", "_cffi_backend", "asyncio", "asyncio.base_events", "asyncio.compat", "raven", "raven.conf", "raven.handlers", "raven.processors" ] #...
Increment version number after RJMCMC addition
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='kombine', version='0.0.1', description='An embarrassingly parallel, kernel-density-based\ ensemble sampler', author='Ben Farr', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='kombine', version='0.1.0', description='An embarrassingly parallel, kernel-density-based\ ensemble sampler', author='Ben Farr', ...
Fix indents, from 2 to 4 spaces.
# -*- coding: utf-8 -*- from flask import current_app, g from flask.ext.script import Manager, Server, prompt_bool from massa import create_app manager = Manager(create_app) manager.add_option('-c', '--config', dest='config', required=False) manager.add_command('runserver', Server( use_debugger = True, use_...
# -*- coding: utf-8 -*- from flask import current_app, g from flask.ext.script import Manager, Server, prompt_bool from massa import create_app manager = Manager(create_app) manager.add_option('-c', '--config', dest='config', required=False) manager.add_command('runserver', Server( use_debugger = True, use_...
Use io.open for py2/py3 compat
import os import json from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding="utf-8") as f: readme = f.read() with open(os.path.join(os.path.dirname(__file__), 'package.json'), encoding="utf-8") as f: package = json.loads(f.read()) setup( name=package['name'...
import os import io import json from setuptools import setup with io.open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding="utf-8") as f: readme = f.read() with io.open(os.path.join(os.path.dirname(__file__), 'package.json'), encoding="utf-8") as f: package = json.loads(f.read()) setup( nam...
Include the run logs app
from distutils.core import setup setup( name = "django-tweetar", url = "http://github.com/adamfast/django-tweetar", author = "Adam Fast", author_email = "adamfast@gmail.com", version = "0.1", license = "BSD", packages = ["djtweetar"], install_requires = ['python-tweetar'], descripti...
from distutils.core import setup setup( name = "django-tweetar", url = "http://github.com/adamfast/django-tweetar", author = "Adam Fast", author_email = "adamfast@gmail.com", version = "0.1", license = "BSD", packages = ["djtweetar", "djtweetar.runlogs"], install_requires = ['python-twe...
Install pycommand.3 manpage with pip
from setuptools import setup import pycommand setup( name='pycommand', version=pycommand.__version__, description=pycommand.__doc__, author=pycommand.__author__, author_email='benjamin@babab.nl', url='https://github.com/babab/pycommand', download_url='http://pypi.python.org/pypi/pycommand/'...
from setuptools import setup import pycommand setup( name='pycommand', version=pycommand.__version__, description=pycommand.__doc__, author=pycommand.__author__, author_email='benjamin@babab.nl', url='https://github.com/babab/pycommand', download_url='http://pypi.python.org/pypi/pycommand/'...
Add finalexam and coverage as dependencies.
import distutils.core # Uploading to PyPI # ================= # $ python setup.py register -r pypi # $ python setup.py sdist upload -r pypi version = '0.0' distutils.core.setup( name='vecrec', version=version, author='Kale Kundert and Alex Mitchell', packages=['vecrec'], url='h...
import distutils.core # Uploading to PyPI # ================= # $ python setup.py register -r pypi # $ python setup.py sdist upload -r pypi version = '0.0' distutils.core.setup( name='vecrec', version=version, author='Kale Kundert and Alex Mitchell', url='https://github.com/kxgames/vec...
Move __version__ declaration before imports
#!/usr/bin/python from __future__ import unicode_literals, division, absolute_import import logging import os from flexget import logger, plugin from flexget.manager import Manager from flexget.options import get_parser __version__ = '{git}' log = logging.getLogger('main') def main(args=None): """Main entry ...
#!/usr/bin/python from __future__ import unicode_literals, division, absolute_import __version__ = '{git}' import logging import os from flexget import logger, plugin from flexget.manager import Manager from flexget.options import get_parser log = logging.getLogger('main') def main(args=None): """Main entry p...
Move data into owner gdb
#!/usr/bin/env python # * coding: utf8 * ''' BemsPallet.py A module that contains a pallet to update the querable layers behind our UTM basemaps ''' from forklift.models import Pallet from os.path import join class BemsPallet(Pallet): def __init__(self): super(BemsPallet, self).__init__() self...
#!/usr/bin/env python # * coding: utf8 * ''' BemsPallet.py A module that contains a pallet to update the querable layers behind our UTM basemaps ''' from forklift.models import Pallet from os.path import join class BemsPallet(Pallet): def __init__(self): super(BemsPallet, self).__init__() self...
Clean Azure images before snapshot
import os import sys import logging _g_logger = logging.getLogger(__name__) def main(bin_path, dcm_basedir, dbfile): dirs_to_clean = [os.path.join(dcm_basedir, 'logs'), os.path.join(dcm_basedir, 'secure')] for clean_dir in dirs_to_clean: for (dirpath, dirname, filenames) in os.w...
import os import sys import logging _g_logger = logging.getLogger(__name__) def main(bin_path, dcm_basedir, dbfile): dirs_to_clean = [os.path.join(dcm_basedir, 'logs'), os.path.join(dcm_basedir, 'secure')] for clean_dir in dirs_to_clean: for (dirpath, dirname, filenames) in os.w...
Fix a compatible bug. Response data is binary in Python 3.
# -*- encoding: utf-8 -*- import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_ENV'] = 'dev' app = AppBuilder().build() self.client = app.test_client() def test_app(self): ...
# -*- encoding: utf-8 -*- import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_ENV'] = 'dev' app = AppBuilder().build() self.client = app.test_client() def test_app(self): ...