commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
46a30fa8d52c1c36e110a8e028444b27e39c9b6d
radio/management/commands/export_talkgroups.py
radio/management/commands/export_talkgroups.py
import sys import datetime import csv from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.utils import timezone from radio.models import * class Command(BaseCommand): help = 'Import talkgroup info' def add_arguments(self, parser): parser.add_...
import sys import datetime import csv from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.utils import timezone from radio.models import * class Command(BaseCommand): help = 'Export talkgroup info' def add_arguments(self, parser): parser.add_...
Update help line and print system number
Update help line and print system number
Python
mit
ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player
--- +++ @@ -8,7 +8,7 @@ from radio.models import * class Command(BaseCommand): - help = 'Import talkgroup info' + help = 'Export talkgroup info' def add_arguments(self, parser): parser.add_argument('file') @@ -21,16 +21,19 @@ def handle(self, *args, **options): - export_tg_fi...
0c29ab9f906ca73605e3626c06dd14f573d5fa8f
TM1py/Exceptions/Exceptions.py
TM1py/Exceptions/Exceptions.py
# -*- coding: utf-8 -*- # TM1py Exceptions are defined here class TM1pyException(Exception): """ The default exception for TM1py """ def __init__(self, response, status_code, reason, headers): self._response = response self._status_code = status_code self._reason = reason ...
# -*- coding: utf-8 -*- # TM1py Exceptions are defined here class TM1pyException(Exception): """ The default exception for TM1py """ def __init__(self, response, status_code, reason, headers): self._response = response self._status_code = status_code self._reason = reason ...
Update to expand exception string
Update to expand exception string
Python
mit
OLAPLINE/TM1py
--- +++ @@ -30,4 +30,7 @@ return self._headers def __str__(self): - return "Text: {} Status Code: {} Reason: {}".format(self._response, self._status_code, self._reason) + return "Text: {} Status Code: {} Reason: {} Headers {}".format(self._response, + ...
188ac85b8e8f82a06426467554d608d713d258ef
test/test_get_new.py
test/test_get_new.py
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os import sys import pytest @needinternet def test_check_get_new(fixture_update_dir): """Test that gets new version f...
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher from .pytest_skipif import needinternet from .pytest_makevers import fixture_update_dir import os @needinternet def test_check_get_new(fixture_update_dir): """Test that gets new version from internet""" packag...
Remove unused imports from test_check_get_new
Remove unused imports from test_check_get_new
Python
lgpl-2.1
rlee287/pyautoupdate,rlee287/pyautoupdate
--- +++ @@ -5,9 +5,6 @@ from .pytest_makevers import fixture_update_dir import os -import sys - -import pytest @needinternet def test_check_get_new(fixture_update_dir):
4cfc0967cef576ab5d6ddd0fff7d648e77739727
test_scriptrunner.py
test_scriptrunner.py
from antZoo.ant import AntJobRunner ant = AntJobRunner( None ) ant.start() class Job: def __init__( self, source ): self.source = source j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" ) ant.push( j ) for i in range( 100 ): ant....
from antZoo.ant import AntJobRunner ant = AntJobRunner( None ) ant.start() class Job: def __init__( self, source ): self.source = source j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" ) ant.push( j ) for i in range( 100 ): ant....
Test runs two jobs and 200 tasks
Test runs two jobs and 200 tasks
Python
mit
streed/antZoo,streed/antZoo
--- +++ @@ -18,3 +18,14 @@ print "Done sending tasks." ant.finish() ant._runner.join() + +j = Job( "/Users/elchupa/code/school/antZoo/localenv/bin/python /Users/elchupa/code/school/antZoo/example_code/word_count.py" ) + +ant.push( j ) + +for i in range( 100 ): + ant.new_task( "this is another test that is to be r...
4661a04d159e0583f16c28d087427fab31c676f6
foodsaving/management/tests/test_makemessages.py
foodsaving/management/tests/test_makemessages.py
from django.test import TestCase from ..commands.makemessages import Command as MakeMessagesCommand class CustomMakeMessagesTest(TestCase): def test_update_options(self): options = { 'locale': [], } modified_options = MakeMessagesCommand.update_options(**options) self...
from unittest.mock import patch from django.test import TestCase from ..commands.makemessages import Command as MakeMessagesCommand from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand makemessages = MakeMessagesCommand django_jinja_makemessages = DjangoJinjaMakeMessages...
Add additional test to increase test coverage
Add additional test to increase test coverage
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend
--- +++ @@ -1,6 +1,11 @@ +from unittest.mock import patch from django.test import TestCase from ..commands.makemessages import Command as MakeMessagesCommand +from django_jinja.management.commands.makemessages import Command as DjangoJinjaMakeMessagesCommand + +makemessages = MakeMessagesCommand +django_jinja_mak...
6f0d09ff5f81518daf30b00311ce4ac052e08c14
admission_notes/models.py
admission_notes/models.py
import datetime #from labsys.patients import Patient from django.db import models class AdmissionNote(models.Model): id_gal = models.CharField(max_length=30) requester = models.CharField( max_length=255, help_text="LACEN ou instituto que solicitou o exame", ) health_unit = models.Char...
import datetime #from labsys.patients import Patient from django.db import models class AdmissionNote(models.Model): id_gal = models.CharField( 'Número da requisição (GAL interno)', max_length=30 ) requester = models.CharField( 'Instituto solicitante', max_length=255, ...
Rename fields and remove verbose_name attr (1st arg is it by default)
:art: Rename fields and remove verbose_name attr (1st arg is it by default)
Python
mit
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys
--- +++ @@ -4,21 +4,27 @@ from django.db import models + class AdmissionNote(models.Model): - id_gal = models.CharField(max_length=30) + id_gal = models.CharField( + 'Número da requisição (GAL interno)', + max_length=30 + ) requester = models.CharField( + 'Instituto solicitant...
85878d23d598b7d7622f8aa70ef82b7a627aed23
integration-test/912-missing-building-part.py
integration-test/912-missing-building-part.py
# http://www.openstreetmap.org/way/287494678 z = 18 x = 77193 y = 98529 while z >= 16: assert_has_feature( z, x, y, 'buildings', { 'kind': 'building', 'id': 287494678 }) z -= 1 x /= 2 y /= 2
# http://www.openstreetmap.org/way/287494678 z = 18 x = 77193 y = 98529 while z >= 16: assert_has_feature( z, x, y, 'buildings', { 'kind': 'building_part', 'id': 287494678, 'min_zoom': 16 }) z -= 1 x /= 2 y /= 2
Update feature kind to account for normalisation and test min_zoom.
Update feature kind to account for normalisation and test min_zoom.
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
--- +++ @@ -5,8 +5,9 @@ while z >= 16: assert_has_feature( z, x, y, 'buildings', - { 'kind': 'building', - 'id': 287494678 }) + { 'kind': 'building_part', + 'id': 287494678, + 'min_zoom': 16 }) z -= 1 x /= 2
2a0c9cc447e1dffe2eb03c49c0c6801f4303a620
plugins/imagetypes.py
plugins/imagetypes.py
# # Copyright (c) SAS Institute 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 w...
# # Copyright (c) SAS Institute 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 w...
Swap order of name and description when listing image types
Swap order of name and description when listing image types Uses the same order as target types, which puts the most important information, the name, in front. Refs APPENG-3419
Python
apache-2.0
sassoftware/rbuild,sassoftware/rbuild
--- +++ @@ -25,7 +25,7 @@ class ListImageTypesCommand(command.ListCommand): help = "List image types" resource = "imagetypes" - listFields = ("description", "name") + listFields = ("name", "description") class ImageTypes(pluginapi.Plugin):
405cc83e1532f5277d180964907e964ded5f5da7
routeros_api/api_communicator/async_decorator.py
routeros_api/api_communicator/async_decorator.py
class AsyncApiCommunicator(object): def __init__(self, inner): self.inner = inner def call(self, *args, **kwargs): tag = self.inner.send(*args, **kwargs) return ResponsePromise(self.inner, tag) class ResponsePromise(object): def __init__(self, receiver, tag): self.receiver ...
class AsyncApiCommunicator(object): def __init__(self, inner): self.inner = inner def call(self, *args, **kwargs): tag = self.inner.send(*args, **kwargs) return ResponsePromise(self.inner, tag) class ResponsePromise(object): def __init__(self, receiver, tag): self.receiver ...
Allow to run get on promise multiple times.
Allow to run get on promise multiple times.
Python
mit
kramarz/RouterOS-api,pozytywnie/RouterOS-api,socialwifi/RouterOS-api
--- +++ @@ -10,6 +10,9 @@ def __init__(self, receiver, tag): self.receiver = receiver self.tag = tag + self.response = None def get(self): - return self.receiver.receive(self.tag) + if self.response is None: + self.response = self.receiver.receive(self.tag...
0ed72241dc9f540615954f58995d96401d954a41
courtreader/opener.py
courtreader/opener.py
import cookielib import os import pickle import urllib2 class Opener: user_agent = u"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; " + \ u"en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11" def __init__(self, name): self.name = name # Create page opener that stores cookie sel...
import cookielib import os import pickle import mechanize class Opener: def __init__(self, name): self.opener = mechanize.Browser() self.opener.set_handle_robots(False) def set_cookie(self, name, value): self.opener.set_cookie(str(name) + '=' + str(value)) def save_cookies(self): ...
Use mechanize instead of urllib2
Use mechanize instead of urllib2
Python
mit
bschoenfeld/va-court-scraper,bschoenfeld/va-court-scraper
--- +++ @@ -1,34 +1,18 @@ import cookielib import os import pickle -import urllib2 +import mechanize class Opener: - user_agent = u"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; " + \ - u"en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11" - def __init__(self, name): - self.name = name - ...
90b9a1e6638fd638450b46c6b12439eeb8e40f90
cumulusci/tasks/github/tests/test_pull_request.py
cumulusci/tasks/github/tests/test_pull_request.py
import mock import unittest from cumulusci.core.config import ServiceConfig from cumulusci.core.config import TaskConfig from cumulusci.tasks.github import PullRequests from cumulusci.tests.util import create_project_config @mock.patch("cumulusci.tasks.github.base.get_github_api_for_user", mock.Mock()) class TestPul...
import mock import unittest from cumulusci.core.config import ServiceConfig from cumulusci.core.config import TaskConfig from cumulusci.tasks.github import PullRequests from cumulusci.tests.util import create_project_config class TestPullRequests(unittest.TestCase): def test_run_task(self): project_confi...
Fix test that wasn't running
Fix test that wasn't running
Python
bsd-3-clause
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
--- +++ @@ -7,24 +7,24 @@ from cumulusci.tests.util import create_project_config -@mock.patch("cumulusci.tasks.github.base.get_github_api_for_user", mock.Mock()) class TestPullRequests(unittest.TestCase): - project_config = create_project_config() - project_config.keychain.set_service( - "github", ...
5839e1e551df96b3766722d8a87d42b12b3cfa5d
cronos/accounts/models.py
cronos/accounts/models.py
from cronos.teilar.models import Departments from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_...
from cronos.teilar.models import Departments, Teachers, EclassLessons, Websites from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.OneToOneField(User, primary_key = True, unique = True) dionysos_username = models.CharField(max_length = 15, un...
Improve db relations: - User->UserProfile is One to One - UserProfile <-> Teachers/Websites/EclassLessons are Many to Many
Improve db relations: - User->UserProfile is One to One - UserProfile <-> Teachers/Websites/EclassLessons are Many to Many
Python
agpl-3.0
LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr
--- +++ @@ -1,22 +1,22 @@ -from cronos.teilar.models import Departments +from cronos.teilar.models import Departments, Teachers, EclassLessons, Websites from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): - user = models.ForeignKey(User, unique = True) + ...
4c7ea928782c976919a055379a921983c5bbf97a
memegen/routes/_cache.py
memegen/routes/_cache.py
import logging import yorm from yorm.types import List, Object log = logging.getLogger(__name__) @yorm.attr(items=List.of_type(Object)) @yorm.sync("data/images/cache.yml") class Cache: SIZE = 9 def __init__(self): self.items = [] def add(self, **kwargs): log.info("Caching: %s", kwarg...
import logging import yorm from yorm.types import List, Object log = logging.getLogger(__name__) @yorm.attr(items=List.of_type(Object)) @yorm.sync("data/images/cache.yml") class Cache: SIZE = 9 def __init__(self): self.items = [] def add(self, **kwargs): if kwargs['key'] == 'custom':...
Disable caching on custom images
Disable caching on custom images
Python
mit
DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen
--- +++ @@ -17,6 +17,9 @@ self.items = [] def add(self, **kwargs): + if kwargs['key'] == 'custom': + return + log.info("Caching: %s", kwargs) self.items.insert(0, kwargs)
fd11e57f736fff6ef23972dee642554c6e8f5495
urls.py
urls.py
from django.conf.urls import url from . import views from django.conf import settings urlpatterns=[ url(r'^login/$', views.login, name='login'), url(r'^logout/$', views.logout, name='logout'), url(r'^users/$', views.users, name='users'), url(r'^users/(?P<username>[^/]*)/$', views.user, name='user'), ]
from django.conf.urls import url from . import views from django.conf import settings urlpatterns=[ url(r'^login/$', views.login, name='login'), url(r'^logout/$', views.logout, name='logout'), url(r'^users/$', views.users, name='users'), url(r'^users/(?P<user>[^/]*)/$', views.user, name='user'), url(r'^users/(?P<...
Add the prefs and pref url
Add the prefs and pref url
Python
apache-2.0
kensonman/webframe,kensonman/webframe,kensonman/webframe
--- +++ @@ -6,5 +6,7 @@ url(r'^login/$', views.login, name='login'), url(r'^logout/$', views.logout, name='logout'), url(r'^users/$', views.users, name='users'), - url(r'^users/(?P<username>[^/]*)/$', views.user, name='user'), + url(r'^users/(?P<user>[^/]*)/$', views.user, name='user'), + url(r'^users/(?P<user>...
db2fdb6a1df9324a4661967069488e981d06b0f1
bi_view_editor/wizard/wizard_ir_model_menu_create.py
bi_view_editor/wizard/wizard_ir_model_menu_create.py
# -*- coding: utf-8 -*- # Copyright 2017 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class WizardModelMenuCreate(models.TransientModel): _inherit = 'wizard.ir.model.menu.create' @api.multi def menu_create(self): ...
# -*- coding: utf-8 -*- # Copyright 2017 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class WizardModelMenuCreate(models.TransientModel): _inherit = 'wizard.ir.model.menu.create' @api.multi def menu_create(self): ...
Refresh page when creating menus, module bi_view_editor
Refresh page when creating menus, module bi_view_editor
Python
agpl-3.0
VitalPet/addons-onestein,VitalPet/addons-onestein,VitalPet/addons-onestein
--- +++ @@ -19,7 +19,7 @@ 'parent_id': self.menu_id.id, 'action': 'ir.actions.act_window,%d' % (bve_view.action_id,) }) - return {'type': 'ir.actions.act_window_close'} + return {'type': 'ir.actions.client', 'tag': 'reload'} return super(Wi...
e01eb66aeb853261c80cb476e71f91a9569b1676
client.py
client.py
import requests from Adafruit_BMP085 import BMP085 import json #initialise sensor print ('Initialising sensor...') bmp = BMP085(0x77, 3) # ULTRAHIRES Mode print ('Reading sensor...') temp = bmp.readTemperature() pressure = bmp.readPressure() payload = {'temperature': temp, 'pressure': pressure} print ('POSTing dat...
import requests from Adafruit_BMP085 import BMP085 import json #initialise sensor print ('Initialising sensor...') bmp = BMP085(0x77, 3) # ULTRAHIRES Mode print ('Reading sensor...') temp = bmp.readTemperature() pressure = bmp.readPressure() payload = {'temperature': temp, 'pressure': pressure} print ('POSTing dat...
Set content-type header of POST.
Set content-type header of POST.
Python
mit
JTKBowers/kelvin
--- +++ @@ -14,5 +14,6 @@ print ('POSTing data...') server_url = 'http://zephos.duckdns.org:5000/temperature_pressure' -r = requests.post(server_url, data=json.dumps(payload)) +headers = {'content-type': 'application/json'} +r = requests.post(server_url, data=json.dumps(payload), headers=headers) print(r.status_...
c7ccfd82298c2c8c90c230f846ca9319bcf40441
lib/tagnews/__init__.py
lib/tagnews/__init__.py
from . import utils from . import crimetype from .crimetype.tag import CrimeTags from .geoloc.tag import GeoCoder, get_lat_longs_from_geostrings from .utils.load_data import load_data from .utils.load_data import load_ner_data from .utils.load_vectorizer import load_glove __version__ = '1.0.2' def test(verbosity=Non...
from . import utils from . import crimetype from .crimetype.tag import CrimeTags from .geoloc.tag import GeoCoder, get_lat_longs_from_geostrings from .utils.load_data import load_data from .utils.load_data import load_ner_data from .utils.load_vectorizer import load_glove __version__ = '1.0.2'
Remove unused test function at top level.
Remove unused test function at top level.
Python
mit
kbrose/article-tagging,kbrose/article-tagging,chicago-justice-project/article-tagging,chicago-justice-project/article-tagging
--- +++ @@ -8,18 +8,3 @@ from .utils.load_vectorizer import load_glove __version__ = '1.0.2' - -def test(verbosity=None, **kwargs): - """run the test suite""" - - import pytest - - args = kwargs.pop('argv', []) - - if verbosity: - args += ['-' + 'v' * verbosity] - - return pytest.main(args, ...
1f8845f89aa936379fbea4d8707fbb4887c62696
examples/pystray_icon.py
examples/pystray_icon.py
from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys if sys.platform == 'darwin': # System tray icon needs to run in it's own process on Mac OS X from multiprocessing import Process as Thread, Queue else: from threading import Thread from queue import Queue """ Thi...
from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys if sys.platform == 'darwin': # System tray icon needs to run in it's own process on Mac OS X import multiprocessing from multiprocessing import Process as Thread, Queue multiprocessing.set_start_method('spawn') els...
Fix process spawn on Mac os, simplify logic
Fix process spawn on Mac os, simplify logic
Python
bsd-3-clause
r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview
--- +++ @@ -5,7 +5,9 @@ import sys if sys.platform == 'darwin': # System tray icon needs to run in it's own process on Mac OS X + import multiprocessing from multiprocessing import Process as Thread, Queue + multiprocessing.set_start_method('spawn') else: from threading import Thread from...
21efff52ebc879134f83c08ab5eed214267b2496
scipy/io/matlab/setup.py
scipy/io/matlab/setup.py
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('matlab', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup ...
#!/usr/bin/env python def configuration(parent_package='io',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('matlab', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup ...
Fix parent package of io.matlab.
Fix parent package of io.matlab. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3963 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor
--- +++ @@ -1,6 +1,6 @@ #!/usr/bin/env python -def configuration(parent_package='',top_path=None): +def configuration(parent_package='io',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('matlab', parent_package, top_path) config.add_data_dir('tests')
256d16c1c31d75442e014554fc0e8ed1d3e96adf
get_value.py
get_value.py
# Domestic-Workers # ================ import csv def read_data(filename): """ Read specified csv file, and return it as a list of dicts. """ with open(filename, 'r') as f: return list(csv.DictReader(f)) dataset=read_data('Nids_w3.csv') print(dataset[1]['food_wgt'])
# Domestic-Workers # ================ import csv def read_data(filename): """ Read specified csv file, and return it as a list of dicts. """ with open(filename, 'r') as f: return list(csv.DictReader(f)) dataset=read_data('Book1.csv') print(dataset[1]['food_wgt'])
Read data from correct CSV file.
Read data from correct CSV file.
Python
apache-2.0
shakermaker/Domestic-Workers,shakermaker/Domestic-Workers,Code4SA/Domestic-Workers,Code4SA/Domestic-Workers
--- +++ @@ -11,6 +11,6 @@ with open(filename, 'r') as f: return list(csv.DictReader(f)) -dataset=read_data('Nids_w3.csv') +dataset=read_data('Book1.csv') print(dataset[1]['food_wgt'])
1cec2df8bcb7f877c813d6470d454244630b050a
semantic_release/pypi.py
semantic_release/pypi.py
"""PyPI """ from invoke import run def upload_to_pypi( dists: str = 'sdist bdist_wheel', username: str = None, password: str = None, skip_existing: bool = False ): """Creates the wheel and uploads to pypi with twine. :param dists: The dists string passed to setup.py. Default: ...
"""PyPI """ from invoke import run def upload_to_pypi( dists: str = 'sdist bdist_wheel', username: str = None, password: str = None, skip_existing: bool = False ): """Creates the wheel and uploads to pypi with twine. :param dists: The dists string passed to setup.py. Default: ...
Add dists to twine call
fix: Add dists to twine call
Python
mit
relekang/python-semantic-release,relekang/python-semantic-release
--- +++ @@ -16,5 +16,12 @@ :param password: PyPI account password string """ run('python setup.py {}'.format(dists)) - run('twine upload -u {} -p {} {}'.format(username, password, '--skip-existing' if skip_existing else '')) + run( + 'twine upload -u {} -p {} {} {}'.format( + us...
f959e9213f27cee5ed5739655d4f85c7d0d442aa
tests/functional/customer/test_notification.py
tests/functional/customer/test_notification.py
from http import client as http_client from oscar.test.testcases import WebTestCase from oscar.apps.customer.notifications import services from oscar.test.factories import UserFactory from django.urls import reverse from oscar.apps.customer.models import Notification class TestAUserWithUnreadNotifications(WebTestCa...
from http import client as http_client from oscar.test.testcases import WebTestCase from oscar.apps.customer.notifications import services from oscar.test.factories import UserFactory from django.urls import reverse from oscar.apps.customer.models import Notification class TestAUserWithUnreadNotifications(WebTestCa...
Update test in case if home page has redirection.
Update test in case if home page has redirection.
Python
bsd-3-clause
solarissmoke/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sasha0/django-oscar,django-oscar/django-oscar
--- +++ @@ -16,6 +16,8 @@ def test_can_see_them_in_page_header(self): homepage = self.app.get('/', user=self.user) + if homepage.status_code == 302: + homepage = homepage.follow() self.assertEqual(1, homepage.context['num_unread_notifications']) def test_notification_...
2ff6e50e0a4db641b026faa324c4cf0204e3a192
src/hotchocolate/templates.py
src/hotchocolate/templates.py
# -*- encoding: utf-8 """ Provides template utilities. """ import jinja2 from . import markdown as md, plugins # TODO: Make this a setting TEMPLATE_DIR = 'templates' # TODO: Make this a setting def locale_date(date): """Render a date in the current locale date.""" return date.strftime('%-d %B %Y') def re...
# -*- encoding: utf-8 """ Provides template utilities. """ import jinja2 from . import markdown as md, plugins # TODO: Make this a setting TEMPLATE_DIR = 'templates' # TODO: Make this a setting def locale_date(date): """Render a date in the current locale date.""" return date.strftime('%d %B %Y').lstrip('0...
Fix locale_date for the Alpine strftime
Fix locale_date for the Alpine strftime
Python
mit
alexwlchan/hot-chocolate,alexwlchan/hot-chocolate
--- +++ @@ -14,7 +14,7 @@ # TODO: Make this a setting def locale_date(date): """Render a date in the current locale date.""" - return date.strftime('%-d %B %Y') + return date.strftime('%d %B %Y').lstrip('0') def render_title(title):
b00d93901a211a35bdb30e00da530dde823c4a2d
frontends/etiquette_flask/etiquette_flask_launch.py
frontends/etiquette_flask/etiquette_flask_launch.py
import gevent.monkey gevent.monkey.patch_all() import logging handler = logging.StreamHandler() log_format = '{levelname}:etiquette.{module}.{funcName}: {message}' handler.setFormatter(logging.Formatter(log_format, style='{')) logging.getLogger().addHandler(handler) import etiquette_flask import gevent.pywsgi import ...
import gevent.monkey gevent.monkey.patch_all() import logging handler = logging.StreamHandler() log_format = '{levelname}:etiquette.{module}.{funcName}: {message}' handler.setFormatter(logging.Formatter(log_format, style='{')) logging.getLogger().addHandler(handler) import etiquette_flask import gevent.pywsgi import ...
Apply werkzeug ProxyFix so that request.remote_addr is correct.
Apply werkzeug ProxyFix so that request.remote_addr is correct.
Python
bsd-3-clause
voussoir/etiquette,voussoir/etiquette,voussoir/etiquette
--- +++ @@ -11,6 +11,11 @@ import gevent.pywsgi import gevent.wsgi import sys + + +import werkzeug.contrib.fixers +etiquette_flask.site.wsgi_app = werkzeug.contrib.fixers.ProxyFix(etiquette_flask.site.wsgi_app) + if len(sys.argv) == 2: port = int(sys.argv[1])
ed0c44ad01a1b88b0e6109a629455ae44ff91011
office365/sharepoint/actions/download_file.py
office365/sharepoint/actions/download_file.py
from office365.runtime.http.http_method import HttpMethod from office365.runtime.queries.service_operation_query import ServiceOperationQuery class DownloadFileQuery(ServiceOperationQuery): def __init__(self, web, file_url, file_object): """ A download file content query :type file_url: ...
from office365.runtime.http.http_method import HttpMethod from office365.runtime.odata.odata_path_parser import ODataPathParser from office365.runtime.queries.service_operation_query import ServiceOperationQuery class DownloadFileQuery(ServiceOperationQuery): def __init__(self, web, file_url, file_object): ...
Support correctly weird characters in filenames when downloading
Support correctly weird characters in filenames when downloading This commit add support for the following: - Correctly encoded oData parameter sent to the endpoint. - Support for # and % in filenames by using a newer 365 endpoint. Summary: Current implementation was injecting an URL directly quoted to the endpoint,...
Python
mit
vgrem/Office365-REST-Python-Client
--- +++ @@ -1,4 +1,5 @@ from office365.runtime.http.http_method import HttpMethod +from office365.runtime.odata.odata_path_parser import ODataPathParser from office365.runtime.queries.service_operation_query import ServiceOperationQuery @@ -23,5 +24,9 @@ """ file_object.write(response....
a2b4b53635ab1188e95efd68f64104a469e7ff66
scheduler/executor.py
scheduler/executor.py
import threading import subprocess class TestExecutor(threading.Thread): """ The general thread to perform the tests executions """ def __init__(self, run_id, test_name, queue): super().__init__() self.run_id = run_id self.test_name = test_name self.queue = queue #...
import threading import subprocess import os class TestExecutor(threading.Thread): """ The general thread to perform the tests executions """ def __init__(self, run_id, test_name, queue): super().__init__() self.run_id = run_id self.test_name = test_name self.queue = q...
Fix bug related to creating the log directory
Fix bug related to creating the log directory
Python
mit
jfelipefilho/test-manager,jfelipefilho/test-manager,jfelipefilho/test-manager
--- +++ @@ -1,5 +1,6 @@ import threading import subprocess +import os class TestExecutor(threading.Thread): @@ -20,10 +21,9 @@ code is enqueued so the scheduler can determine if the run has completed """ - with open( - "runs/static/runs/autotests/runs/{}.txt".fo...
327428de0267de773a850daa9d376891fe02308f
splitword.py
splitword.py
#!/usr/bin/env python3 # encoding: utf-8 # Splits a word into multiple parts def split_word(word): if len(word) < 2: raise Exception( "You obviously need at least two letters to split a word") split_indexes = list(range(1, len(word))) for i in split_indexes: first_part = word[:...
#!/usr/bin/env python3 # encoding: utf-8 # Splits a word into multiple parts def split_word(word): split_indexes = list(range(0, len(word))) for i in split_indexes: first_part = word[:i] second_part = word[i:] yield (first_part, second_part)
Allow splitting to zero-length parts
Allow splitting to zero-length parts
Python
unlicense
andyn/kapunaattori
--- +++ @@ -4,10 +4,7 @@ # Splits a word into multiple parts def split_word(word): - if len(word) < 2: - raise Exception( - "You obviously need at least two letters to split a word") - split_indexes = list(range(1, len(word))) + split_indexes = list(range(0, len(word))) for i in sp...
0887e200f31edd8d61e0dd1d3fefae7e828c9269
mindbender/maya/plugins/validate_single_assembly.py
mindbender/maya/plugins/validate_single_assembly.py
import pyblish.api class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin): """Each asset must have a single top-level group The given instance is test-exported, along with construction history to test whether more than 1 top-level DAG node would be included in the exported file. """ ...
import pyblish.api class SelectAssemblies(pyblish.api.Action): label = "Select Assemblies" on = "failed" def process(self, context, plugin): from maya import cmds cmds.select(plugin.assemblies) class ValidateMindbenderSingleAssembly(pyblish.api.InstancePlugin): """Each asset must ha...
Add action to select the multiple assemblies.
Add action to select the multiple assemblies.
Python
mit
getavalon/core,MoonShineVFX/core,MoonShineVFX/core,mindbender-studio/core,mindbender-studio/core,getavalon/core
--- +++ @@ -1,4 +1,13 @@ import pyblish.api + + +class SelectAssemblies(pyblish.api.Action): + label = "Select Assemblies" + on = "failed" + + def process(self, context, plugin): + from maya import cmds + cmds.select(plugin.assemblies) class ValidateMindbenderSingleAssembly(pyblish.api.In...
92e96c010b54bf4c9e35d49de492cf9f061f345a
micromodels/models.py
micromodels/models.py
from fields import FieldBase class Model(object): class __metaclass__(type): def __init__(cls, name, bases, attrs): fields = {} for name, value in attrs.items(): if isinstance(value, FieldBase): fields[name] = value setattr(cls, '_fie...
from fields import FieldBase class Model(object): class __metaclass__(type): def __init__(cls, name, bases, attrs): cls._fields = {} for name, value in attrs.items(): if isinstance(value, FieldBase): cls._fields[name] = value def __init__(se...
Change to make metaclass clearer
Change to make metaclass clearer
Python
unlicense
j4mie/micromodels
--- +++ @@ -4,11 +4,10 @@ class __metaclass__(type): def __init__(cls, name, bases, attrs): - fields = {} + cls._fields = {} for name, value in attrs.items(): if isinstance(value, FieldBase): - fields[name] = value - set...
7a0da88638c3d0fe0f9088c0d9008ff60503fe06
plotly/plotly/__init__.py
plotly/plotly/__init__.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 __future__ import absolute_import from plotly.plotly.plotly import * __...
""" 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...
Remove `import *`. Replace with explicit public interface.
Remove `import *`. Replace with explicit public interface.
Python
mit
plotly/python-api,ee-in/python-api,plotly/plotly.py,plotly/plotly.py,ee-in/python-api,plotly/plotly.py,ee-in/python-api,plotly/python-api,plotly/python-api
--- +++ @@ -7,10 +7,7 @@ verifiable account (username/api-key pair) and a network connection. """ -from __future__ import absolute_import - -from plotly.plotly.plotly import * - -__all__ = ["sign_in", "update_plot_options", "get_plot_options", - "get_credentials", "iplot", "plot", "iplot_mpl", "plot_mpl...
59927047347b7db3f46ab99152d2d99f60039043
trac/versioncontrol/web_ui/__init__.py
trac/versioncontrol/web_ui/__init__.py
from trac.versioncontrol.web_ui.browser import * from trac.versioncontrol.web_ui.changeset import * from trac.versioncontrol.web_ui.log import *
from trac.versioncontrol.web_ui.browser import * from trac.versioncontrol.web_ui.changeset import * from trac.versioncontrol.web_ui.log import *
Add missing `svn:eol-style : native` prop, which prevented making clean patches against the early 0.9b1 archives (now both the .zip and the .tar.gz have CRLFs for this file)
Add missing `svn:eol-style : native` prop, which prevented making clean patches against the early 0.9b1 archives (now both the .zip and the .tar.gz have CRLFs for this file) git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@2214 af82e41b-90c4-0310-8c96-b1721e28e2e2
Python
bsd-3-clause
jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac,walty8/trac,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,netjunki/trac-Pygit2
4b379e82dd503afc04569a50c08a7cdd9abfe4b0
passpie/validators.py
passpie/validators.py
import click from .history import clone from . import config def validate_remote(ctx, param, value): if value: try: remote, branch = value.split('/') return (remote, branch) except ValueError: raise click.BadParameter('remote need to be in format <remote>/<bran...
import click from .history import clone from . import config def validate_remote(ctx, param, value): if value: try: remote, branch = value.split('/') return (remote, branch) except ValueError: raise click.BadParameter('remote need to be in format <remote>/<bran...
Fix load config from local db config file
Fix load config from local db config file
Python
mit
scorphus/passpie,scorphus/passpie,marcwebbie/passpie,marcwebbie/passpie
--- +++ @@ -37,8 +37,8 @@ if config.is_repo_url(configuration['path']) is True: temporary_path = clone(configuration['path'], depth="1") - configuration.update(config.read(temporary_path)) # Read cloned config configuration['path'] = temporary_path + configuration.update(config.r...
15941639134d4360753607bd488d3c80d15ca825
second/blog/models.py
second/blog/models.py
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(de...
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(de...
Add comments model to blog
Add comments model to blog
Python
mit
ugaliguy/Django-Tutorial-Projects,ugaliguy/Django-Tutorial-Projects
--- +++ @@ -18,3 +18,17 @@ def __str__(self): return self.title + +class Comment(models.Model): + post = models.ForeignKey('blog.Post', related_name='comments') + author = models.CharField(max_length=200) + text = models.TextField() + created_date = models.DateTimeField(default=timezone.no...
b5a71f2142c16b8523da483a6879578522cfd9bb
semesterpage/forms.py
semesterpage/forms.py
from django import forms from django.utils.translation import ugettext_lazy as _ from dal import autocomplete from .models import Course, Options class OptionsForm(forms.ModelForm): """ A form solely used for autocompleting Courses in the admin, using django-autocomplete-light, """ self_chosen_c...
from django import forms from django.utils.translation import ugettext_lazy as _ from dal import autocomplete from .models import Course, Options class OptionsForm(forms.ModelForm): """ A form solely used for autocompleting Courses in the admin, using django-autocomplete-light, """ self_chosen_c...
Clarify that self_chosen_courses == enrolled
Clarify that self_chosen_courses == enrolled Fixes #75.
Python
mit
afriestad/WikiLinks,afriestad/WikiLinks,afriestad/WikiLinks
--- +++ @@ -12,7 +12,7 @@ """ self_chosen_courses = forms.ModelMultipleChoiceField( - label=_('Skriv inn dine fag'), + label=_('Skriv inn fagene du tar nå'), queryset=Course.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='semesterpage-course-autoc...
5f688e5a99c2e4ec476f28306c2cca375934bba7
nvidia_commands_layer.py
nvidia_commands_layer.py
#!/usr/bin/env python3.5 import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a...
#!/usr/bin/env python3 import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a v...
Fix script not working from bash
Fix script not working from bash
Python
mit
radu-nedelcu/nvidia-fan-controller,radu-nedelcu/nvidia-fan-controller
--- +++ @@ -1,4 +1,4 @@ -#!/usr/bin/env python3.5 +#!/usr/bin/env python3 import subprocess @@ -16,14 +16,11 @@ raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100') result = subprocess.run( - [ - 'nvidia-settings', - '-a', - ...
17bb4f62d13838623ac097ef2f2feb88d95f8539
opbeat_pyramid/tweens.py
opbeat_pyramid/tweens.py
import venusian class tween_config(object): """ A decorator which allows developers to annotate tween factories. """ venusian = venusian def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, wrapped_tween_factory): def do_the_thing(con...
import venusian class tween_config(object): """ A decorator which allows developers to annotate tween factories. """ venusian = venusian def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, wrapped_tween_factory): def do_the_thing(con...
Fix issue in Python 2
Fix issue in Python 2
Python
mit
britco/opbeat_pyramid,monokrome/opbeat_pyramid
--- +++ @@ -19,7 +19,7 @@ context.config.with_package(info.module).add_tween( factory_string, *self.args, - **self.kwargs, + **self.kwargs ) info = self.venusian.attach(
cdb8756ead6a61a3fbb3001050091506e16481e5
lexicon/__init__.py
lexicon/__init__.py
from attribute_dict import AttributeDict from alias_dict import AliasDict __version__ = "0.1.2" class Lexicon(AttributeDict, AliasDict): def __init__(self, *args, **kwargs): # Need to avoid combining AliasDict's initial attribute write on # self.aliases, with AttributeDict's __setattr__. Doing s...
from .attribute_dict import AttributeDict from .alias_dict import AliasDict __version__ = "0.1.2" class Lexicon(AttributeDict, AliasDict): def __init__(self, *args, **kwargs): # Need to avoid combining AliasDict's initial attribute write on # self.aliases, with AttributeDict's __setattr__. Doing...
Use explicit relative imports for Python3 Compat
Use explicit relative imports for Python3 Compat
Python
bsd-2-clause
mindw/lexicon,bitprophet/lexicon
--- +++ @@ -1,5 +1,5 @@ -from attribute_dict import AttributeDict -from alias_dict import AliasDict +from .attribute_dict import AttributeDict +from .alias_dict import AliasDict __version__ = "0.1.2"
1e9fb28b1263bb543191d3c44ba39d8311ad7cae
quantecon/__init__.py
quantecon/__init__.py
""" Import the main names to top level. """ from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .k...
""" Import the main names to top level. """ from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae i...
Remove models/ subpackage from api due to migration to QuantEcon.applications
Remove models/ subpackage from api due to migration to QuantEcon.applications
Python
bsd-3-clause
QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py
--- +++ @@ -2,7 +2,6 @@ Import the main names to top level. """ -from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF
ff9fc6e6036ea99af4db6a5760d05a33cf7336e1
solidity/python/constants/PrintLn2ScalingFactors.py
solidity/python/constants/PrintLn2ScalingFactors.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__),'..')) from decimal import Decimal from decimal import getcontext from FormulaSolidityPort import fixedLog2 MIN_PRECISION = 32 MAX_PRECISION = 127 getcontext().prec = MAX_PRECISION ln2 = Decimal(2).ln() fixedLog2MaxInput = ((1<<(256-MA...
from decimal import Decimal from decimal import getcontext from decimal import ROUND_FLOOR from decimal import ROUND_CEILING MIN_PRECISION = 32 MAX_PRECISION = 127 def ln(n): return Decimal(n).ln() def log2(n): return ln(n)/ln(2) def floor(d): return int(d.to_integral_exact(rounding=ROUND_FLOOR)) ...
Make this constant-generating script independent of the solidity emulation module.
Make this constant-generating script independent of the solidity emulation module.
Python
apache-2.0
enjin/contracts
--- +++ @@ -1,28 +1,38 @@ -import os -import sys -sys.path.append(os.path.join(os.path.dirname(__file__),'..')) - - from decimal import Decimal from decimal import getcontext -from FormulaSolidityPort import fixedLog2 +from decimal import ROUND_FLOOR +from decimal import ROUND_CEILING MIN_PRECISION = 32 MAX_P...
6e4fcfeb6da8f4d61731ec2cb77c14b09fe35d31
aurorawatchuk/snapshot.py
aurorawatchuk/snapshot.py
import aurorawatchuk as aw class AuroraWatchUK(object): """Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the aurorawatchuk.AuroraWatchUK class but its fields are evaluated just once, at the time first requested. Thus the values it returns are snapshots of the status. Th...
from aurorawatchuk import AuroraWatchUK __author__ = 'Steve Marple' __version__ = '0.0.8' __license__ = 'MIT' class AuroraWatchUK_SS(object): """Take a snapshot of the AuroraWatch UK status. This class mimics the behaviour of the :class:`.aurorawatchuk.AuroraWatchUK` class but its fields are evaluated ...
Rename class to AuroraWatchUK_SS and add documentation
Rename class to AuroraWatchUK_SS and add documentation
Python
mit
stevemarple/python-aurorawatchuk
--- +++ @@ -1,15 +1,24 @@ -import aurorawatchuk as aw +from aurorawatchuk import AuroraWatchUK -class AuroraWatchUK(object): +__author__ = 'Steve Marple' +__version__ = '0.0.8' +__license__ = 'MIT' + + +class AuroraWatchUK_SS(object): """Take a snapshot of the AuroraWatch UK status. - This class mimics ...
17d9c84b01a6b9adc264164041d4c226355a6943
loadimpact/utils.py
loadimpact/utils.py
# coding=utf-8 __all__ = ['UTC'] from datetime import timedelta, tzinfo _ZERO = timedelta(0) def is_dict_different(d1, d2, epsilon=0.00000000001): s1 = set(d1.keys()) s2 = set(d2.keys()) intersect = s1.intersection(s2) added = s1 - intersect removed = s2 - intersect changed = [] for o ...
# coding=utf-8 __all__ = ['UTC'] from datetime import timedelta, tzinfo _ZERO = timedelta(0) def is_dict_different(d1, d2, epsilon=0.00000000001): s1 = set(d1.keys()) s2 = set(d2.keys()) intersect = s1.intersection(s2) added = s1 - intersect removed = s2 - intersect changed = [] for o ...
Fix float diff comparison in dict differ function.
Fix float diff comparison in dict differ function.
Python
apache-2.0
loadimpact/loadimpact-sdk-python
--- +++ @@ -16,8 +16,9 @@ removed = s2 - intersect changed = [] for o in intersect: - if isinstance(s2, float) and abs(d2[o] - d1[o]) > epsilon: - changed.append(o) + if isinstance(d2[o], float): + if abs(d2[o] - d1[o]) > epsilon: + changed.append(o) ...
1cdf0cd00cbc7006194d07770b3b804dd661500e
t_ai_player.py
t_ai_player.py
#!/usr/bin/env python import unittest import pdb import gui import human_player import rules import game #import profile from ai_player import * class AIPlayerTest(unittest.TestCase): def setUp(self): # TODO player1 = AIPlayer("Blomp") player2 = human_player.HumanPlayer("Kubba") ...
#!/usr/bin/env python import unittest import pdb import gui import human_player import rules import game #import profile from ai_player import * class AIPlayerTest(unittest.TestCase): def setUp(self): # TODO player1 = AIPlayer("Blomp") player2 = human_player.HumanPlayer("Kubba") ...
Change the test board size to make it run faster
Change the test board size to make it run faster
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
--- +++ @@ -17,7 +17,7 @@ # TODO player1 = AIPlayer("Blomp") player2 = human_player.HumanPlayer("Kubba") - r = rules.Rules(13, "standard") + r = rules.Rules(5, "standard") self.game = game.Game(r, player1, player2) self.gui = None ''' @@ -30,7 +30,7 ...
0469ba1f4f1d907013c328bc2834905dd391dba8
simple/bing_images.py
simple/bing_images.py
import requests def get_latest_header_images(idx=0, num=5): resp = requests.get("http://www.bing.com/HPImageArchive.aspx?format=js&n={0}&idx={1}".format(num, idx)).json() if resp is None: return {} return { "images": [ {"url": "http://bing.com" + item["url"], "copyright":...
import requests def get_latest_header_images(idx=0, num=5): resp = requests.get("https://www.bing.com/HPImageArchive.aspx?format=js&n={0}&idx={1}".format(num, idx)).json() if resp is None: return {} return { "images": [ {"url": "https://bing.com" + item["url"], "copyright...
Change url protocol for more secure access
Change url protocol for more secure access
Python
mit
orf/simple,orf/simple,orf/simple
--- +++ @@ -2,14 +2,14 @@ def get_latest_header_images(idx=0, num=5): - resp = requests.get("http://www.bing.com/HPImageArchive.aspx?format=js&n={0}&idx={1}".format(num, idx)).json() + resp = requests.get("https://www.bing.com/HPImageArchive.aspx?format=js&n={0}&idx={1}".format(num, idx)).json() ...
2dec3e5810ef9ba532eaa735d0eac149c240aa2f
pyxrf/api.py
pyxrf/api.py
# from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # combine_data_to_recon, h5file_for_recon, export_to_view) # from .model.load_data_from_db import make_hdf, make_hdf_stitched, export1d # from .model.command_tools import fit_pixel_data_and_save, pyxrf_batch impo...
from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, # noqa: F401 combine_data_to_recon, h5file_for_recon, export_to_view, # noqa: F401 make_hdf_stitched) # noqa: F401 from .model.load_data_from_db import make_hdf, export1d # noqa: F401 ...
Set flake8 to ignore F401 violations
Set flake8 to ignore F401 violations
Python
bsd-3-clause
NSLS-II/PyXRF,NSLS-II-HXN/PyXRF,NSLS-II-HXN/PyXRF
--- +++ @@ -1,7 +1,11 @@ -# from .model.fileio import (stitch_fitted_results, spec_to_hdf, create_movie, -# combine_data_to_recon, h5file_for_recon, export_to_view) -# from .model.load_data_from_db import make_hdf, make_hdf_stitched, export1d -# from .model.command_tools import fit_pixel_d...
dcb8678b8f460ce1b5d5d86e14d567a3bcbaa0d1
riak/util.py
riak/util.py
import collections def quacks_like_dict(object): """Check if object is dict-like""" return isinstance(object, collections.Mapping) def deep_merge(a, b): """Merge two deep dicts non-destructively Uses a stack to avoid maximum recursion depth exceptions >>> a = {'a': 1, 'b': {1: 1, 2: ...
try: from collections import Mapping except ImportError: # compatibility with Python 2.5 Mapping = dict def quacks_like_dict(object): """Check if object is dict-like""" return isinstance(object, Mapping) def deep_merge(a, b): """Merge two deep dicts non-destructively Uses a stack ...
Adjust for compatibility with Python 2.5
Adjust for compatibility with Python 2.5
Python
apache-2.0
basho/riak-python-client,bmess/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,basho/riak-python-client,bmess/riak-python-client,GabrielNicolasAvellaneda/riak-python-client,basho/riak-python-client
--- +++ @@ -1,8 +1,12 @@ -import collections +try: + from collections import Mapping +except ImportError: + # compatibility with Python 2.5 + Mapping = dict def quacks_like_dict(object): """Check if object is dict-like""" - return isinstance(object, collections.Mapping) + return isinstance(obje...
96855ef5baee62f63887d942854c065ad6943f87
micropress/forms.py
micropress/forms.py
from django import forms from micropress.models import Article, Section, Press class ArticleForm(forms.ModelForm): section = forms.ModelChoiceField(Section.objects.all(), empty_label=None) class Meta: model = Article fields = ('title', 'slug', 'byline', 'section', 'body', 'markup_type') cla...
from django import forms from micropress.models import Article, Section, Press class ArticleForm(forms.ModelForm): section = forms.ModelChoiceField(Section.objects.all(), empty_label=None) class Meta: model = Article fields = ('title', 'slug', 'byline', 'section', 'body', 'markup_type') ...
Validate that Article.slug and press are unique_together.
Validate that Article.slug and press are unique_together.
Python
mit
jbradberry/django-micro-press,jbradberry/django-micro-press
--- +++ @@ -9,6 +9,15 @@ model = Article fields = ('title', 'slug', 'byline', 'section', 'body', 'markup_type') + def clean(self): + cleaned_data = self.cleaned_data + slug = cleaned_data.get('slug', '') + press = self.instance.press + if Article.objects.filter(press...
9c34cdd6f82f84a54bedc505ef0ad4b9df40ef6a
tldr/config.py
tldr/config.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from os import path import sys import yaml def get_config(): """Get the configurations from .tldrrc and return it as a dict.""" config_path = path.join(path.expanduser('~'), '.tldrrc') if not path.exists(config_path): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from os import path import sys import yaml def get_config(): """Get the configurations from .tldrrc and return it as a dict.""" config_path = path.join(path.expanduser('~'), '.tldrrc') if not path.exists(config_path): ...
Improve error output when detect unsupported color
Improve error output when detect unsupported color
Python
mit
lord63/tldr.py
--- +++ @@ -25,8 +25,8 @@ supported_colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] if not set(config['colors'].values()).issubset(set(supported_colors)): - sys.exit("Unsupported colors in config file: {0}".format( - ' '.join(set(co...
31a8d7377d46abef6eec6f7eb5b154f948c3388a
spam/ansiInventory.py
spam/ansiInventory.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ AnsibleInventory: INTRO: USAGE: """ import os import ansible.inventory class AnsibleInventory(object): ''' Ansible Inventory wrapper class. ''' def __init__(self, inventory_filename): ''' Initialize Inventory ''' if...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ AnsibleInventory: INTRO: USAGE: """ import os import ansible.inventory class AnsibleInventory(object): ''' Ansible Inventory wrapper class. ''' def __init__(self, inventory_filename): ''' Initialize Inventory ''' se...
Fix get_host() to return host list
Fix get_host() to return host list
Python
apache-2.0
bdastur/spam,bdastur/spam
--- +++ @@ -22,6 +22,7 @@ ''' Initialize Inventory ''' + self.inventory = None if not os.path.exists(inventory_filename): print "Provide a valid inventory filename" return @@ -33,14 +34,23 @@ Get the hosts ''' hostlist = [...
25121b9bdceda0b0a252e2bdec0e76a4eb733a4c
dotsecrets/textsub.py
dotsecrets/textsub.py
# Original algorithm by Xavier Defrang. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # This implementation by alane@sourceforge.net. import re import UserDict class Textsub(UserDict.UserDict): def __init__(self, dict=None): self.re = None self.regex = None UserDict.User...
# Original algorithm by Xavier Defrang. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # This implementation by alane@sourceforge.net. import re try: from UserDict import UserDict except ImportError: from collections import UserDict class Textsub(UserDict): def __init__(self, dict=None)...
Make UserDict usage compatible with Python3
Make UserDict usage compatible with Python3
Python
bsd-3-clause
oohlaf/dotsecrets
--- +++ @@ -3,14 +3,18 @@ # This implementation by alane@sourceforge.net. import re -import UserDict + +try: + from UserDict import UserDict +except ImportError: + from collections import UserDict -class Textsub(UserDict.UserDict): +class Textsub(UserDict): def __init__(self, dict=None): s...
4196131899df6183a612e33427986cff052b2044
addons/project_issue/migrations/8.0.1.0/post-migration.py
addons/project_issue/migrations/8.0.1.0/post-migration.py
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, a suite of business apps # This module Copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General...
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, a suite of business apps # This module Copyright (C) 2014 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General...
Fix import SUPERUSER_ID in project_issue migration scripts
Fix import SUPERUSER_ID in project_issue migration scripts Found error: 2014-07-18 17:04:11,710 8772 ERROR v8mig openerp.modules.migration: module project_issue: Unable to load post-migration file project_issue/migrations/8.0.1.0/post-migration.py Traceback (most recent call last): File "/home/dr/work/openupg/O...
Python
agpl-3.0
0k/OpenUpgrade,blaggacao/OpenUpgrade,0k/OpenUpgrade,csrocha/OpenUpgrade,0k/OpenUpgrade,grap/OpenUpgrade,0k/OpenUpgrade,mvaled/OpenUpgrade,Endika/OpenUpgrade,Endika/OpenUpgrade,damdam-s/OpenUpgrade,csrocha/OpenUpgrade,blaggacao/OpenUpgrade,bwrsandman/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,grap/OpenUpgrade,hifly/OpenUpg...
--- +++ @@ -19,7 +19,7 @@ # ############################################################################## -from openerp import SUPERUSER_UID as uid +from openerp import SUPERUSER_ID as uid from openerp.openupgrade import openupgrade, openupgrade_80
40ac5bc5f8c3f68c0c5b2b6debe19b487893d6f5
ecal_users.py
ecal_users.py
from google.appengine.ext import db import uuid class EmailUser(db.Model): # the email address that the user sends events to: email_address = db.StringProperty(default=str(uuid.uuid4())) # the AuthSub token used to authenticate the user to gcal: auth_token = db.StringProperty() date_added = db.Date...
from google.appengine.ext import db import random import string def make_address(): """ Returns a random alphanumeric string of 10 digits. Since there are 62 choices per digit, this gives: 62 ** 10 = 8.39299366 x 10 ** 17 possible results. When there are a million accounts active, we need: ...
Use a slightly friendlier string than UUID for email addresses.
Use a slightly friendlier string than UUID for email addresses.
Python
mit
eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot
--- +++ @@ -1,9 +1,26 @@ from google.appengine.ext import db -import uuid +import random +import string +def make_address(): + """ + Returns a random alphanumeric string of 10 digits. Since + there are 62 choices per digit, this gives: + 62 ** 10 = 8.39299366 x 10 ** 17 + + possible results. When ...
9310be1429109f5324502f7e66318e23f5ea489d
test/test_terminate_handler.py
test/test_terminate_handler.py
import uuid from handler_fixture import StationHandlerTestCase from groundstation.transfer.request_handlers import handle_fetchobject from groundstation.transfer.response_handlers import handle_terminate class TestHandlerTerminate(StationHandlerTestCase): def test_handle_terminate(self): # Write an objec...
import uuid from handler_fixture import StationHandlerTestCase from groundstation.transfer.request_handlers import handle_fetchobject from groundstation.transfer.response_handlers import handle_terminate class TestHandlerTerminate(StationHandlerTestCase): def test_handle_terminate(self): # Write an objec...
Test that teardown methods are actually called
Test that teardown methods are actually called
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
--- +++ @@ -18,8 +18,14 @@ self.assertEqual(len(self.station.station.registry.contents), 1) handle_fetchobject(self.station) + ret = [0] + + def _teardown(): + ret[0] += 1 + self.station.teardown = _teardown term = self.station.stream.pop() handl...
0b99bf43e02c22f0aa136ca02717521b1f4f2414
salt/runner.py
salt/runner.py
''' Execute salt convenience routines ''' # Import python modules import sys # Import salt modules import salt.loader class Runner(object): ''' Execute the salt runner interface ''' def __init__(self, opts): self.opts = opts self.functions = salt.loader.runner(opts) def _verify_f...
''' Execute salt convenience routines ''' # Import python modules import sys # Import salt modules import salt.loader class Runner(object): ''' Execute the salt runner interface ''' def __init__(self, opts): self.opts = opts self.functions = salt.loader.runner(opts) def _verify_f...
Add doc printing for salt-run
Add doc printing for salt-run
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -29,9 +29,22 @@ sys.stderr.write('%s\n' % err) sys.exit(1) + def _print_docs(self): + ''' + Print out the documentation! + ''' + for fun in sorted(self.functions): + if fun.startswith(self.opts['fun']): + print fun + ':' +...
33fd4bba1f2c44e871051862db8071fadb0e9825
core-plugins/shared/1/dss/reporting-plugins/shared_create_metaproject/shared_create_metaproject.py
core-plugins/shared/1/dss/reporting-plugins/shared_create_metaproject/shared_create_metaproject.py
# -*- coding: utf-8 -*- # Ingestion service: create a metaproject (tag) with user-defined name in given space def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilde...
# -*- coding: utf-8 -*- # Ingestion service: create a metaproject (tag) with user-defined name in given space def process(transaction, parameters, tableBuilder): """Create a project with user-defined name in given space. """ # Prepare the return table tableBuilder.addHeader("success") tableBuilde...
Create metaproject with user-provided description.
Create metaproject with user-provided description.
Python
apache-2.0
aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology,aarpon/obit_shared_core_technology
--- +++ @@ -14,8 +14,11 @@ row = tableBuilder.addRow() # Retrieve parameters from client + username = parameters.get("userName") metaprojectCode = parameters.get("metaprojectCode") - username = parameters.get("userName") + metaprojectDescr = parameters.get("metaprojectDescr") + if metapro...
b345c00b41ade2e12449566f7cb013a7bb8d078f
democracy/migrations/0032_add_language_code_to_comment.py
democracy/migrations/0032_add_language_code_to_comment.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-12-16 15:03 from __future__ import unicode_literals from django.db import migrations, models from democracy.models import SectionComment def forwards_func(apps, schema_editor): for comment in SectionComment.objects.all(): comment._detect_lang(...
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-12-16 15:03 from __future__ import unicode_literals from django.db import migrations, models from democracy.models import SectionComment def forwards_func(apps, schema_editor): for comment in SectionComment.objects.all(): comment._detect_lang(...
Add literal dependency so migration 0031 won't fail if run in the wrong order
Add literal dependency so migration 0031 won't fail if run in the wrong order
Python
mit
City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi
--- +++ @@ -21,6 +21,8 @@ dependencies = [ ('democracy', '0031_remove_untranslated_fields'), + # comment.save() database operations will require a recent user model with all the fields included + ('kerrokantasi', '__latest__'), ] operations = [
cb1d4de41a7de1687041244c126c14ed76fd6959
angular_flask/__init__.py
angular_flask/__init__.py
import os from flask import Flask app = Flask(__name__) basedir = os.path.abspath(os.path.dirname('data')) basedir_img = os.path.abspath(os.path.dirname('angular_flask')) app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e" #app.config["SQLALCHEMY_DATABASE_U...
import os from flask import Flask import psycopg2 import urlparse urlparse.uses_netloc.append("postgres") url = urlparse.urlparse(os.environ["DATABASE_URL"]) conn = psycopg2.connect( database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port ) app = Flask(__...
Connect to psql on server
Connect to psql on server
Python
mit
Clarity-89/blog,Clarity-89/blog,Clarity-89/blog
--- +++ @@ -1,12 +1,25 @@ import os from flask import Flask +import psycopg2 +import urlparse + +urlparse.uses_netloc.append("postgres") +url = urlparse.urlparse(os.environ["DATABASE_URL"]) + +conn = psycopg2.connect( + database=url.path[1:], + user=url.username, + password=url.password, + host=url.host...
17b42f9bcd4168494f529104d3d172cb0310d58a
python2.7libs/CacheManager/define.py
python2.7libs/CacheManager/define.py
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- ## Define Cache Nodes to deal with this script. CACHE_NODES = [ {"name...
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- ## Description """ Define file for Cache Manager Tool. """ #------------------------------------------------------------------------------- ## Define Cache Nodes to deal with this script. CACHE_NODES = [ {"name...
Add some test geometry which includes file node.
Add some test geometry which includes file node.
Python
mit
takavfx/Bento
--- +++ @@ -44,6 +44,10 @@ "indirectlight", "arnold_light", "cam", + "testgeometry_pighead", + "testgeometry_rubbertoy", + "testgeometry_squab", + "testgeometry_ragdoll", ]
423e4cc4b73e7c13d0796069733ee37aaad4c2e4
taar/recommenders/__init__.py
taar/recommenders/__init__.py
from .collaborative_recommender import CollaborativeRecommender from .locale_recommender import LocaleRecommender from .legacy_recommender import LegacyRecommender from .recommendation_manager import RecommendationManager __all__ = [ 'CollaborativeRecommender', 'LegacyRecommender', 'LocaleRecommender', ...
from .collaborative_recommender import CollaborativeRecommender from .locale_recommender import LocaleRecommender from .legacy_recommender import LegacyRecommender from .similarity_recommender import SimilarityRecommender from .recommendation_manager import RecommendationManager __all__ = [ 'CollaborativeRecommen...
Add SimilarityRecommender to init file
Add SimilarityRecommender to init file
Python
mpl-2.0
maurodoglio/taar
--- +++ @@ -1,6 +1,7 @@ from .collaborative_recommender import CollaborativeRecommender from .locale_recommender import LocaleRecommender from .legacy_recommender import LegacyRecommender +from .similarity_recommender import SimilarityRecommender from .recommendation_manager import RecommendationManager @@ -8...
bb87078594d3a3fcdda6e26d644bc9a93dda96cd
test_component/tests/test_component_collection.py
test_component/tests/test_component_collection.py
# -*- coding: utf-8 -*- # Copyright 2013-2017 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo.tests import common from odoo.addons.test_component.components.components import UserTestComponent class TestComponentCollection(common.TransactionCase): at_install = False ...
# -*- coding: utf-8 -*- # Copyright 2013-2017 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) from odoo.tests import common from odoo.addons.test_component.components.components import UserTestComponent class TestComponentCollection(common.TransactionCase): at_install = False ...
Use 2 different methods for single/many lookup
Use 2 different methods for single/many lookup the 'components' method had 2 different return types depending of the 'multi' argument. Now we have 'component' or 'many_components' that return a Component instance or a list of Component instances.
Python
agpl-3.0
OCA/connector,OCA/connector
--- +++ @@ -27,5 +27,5 @@ def test_components_usage(self): work = self.collection.work_on('res.users') - component = work.components(usage='test1') + component = work.component(usage='test1') self.assertEquals(UserTestComponent._name, component._name)
a80f5bad5369ae9a7ae3ab6914d3e9e642062ec3
odl/contrib/param_opt/test/test_param_opt.py
odl/contrib/param_opt/test/test_param_opt.py
import pytest import odl import odl.contrib.fom import odl.contrib.param_opt from odl.util.testutils import simple_fixture space = simple_fixture('space', [odl.rn(3), odl.uniform_discr([0, 0], [1, 1], [9, 11]), odl.uniform_discr(0, 1, 10)]) def te...
import pytest import odl import odl.contrib.fom import odl.contrib.param_opt from odl.util.testutils import simple_fixture space = simple_fixture('space', [odl.rn(3), odl.uniform_discr([0, 0], [1, 1], [9, 11]), odl.uniform_discr(0, 1, 10)]) fom = ...
Add fixture for FOM for test_optimal_parameters
TST: Add fixture for FOM for test_optimal_parameters
Python
mpl-2.0
odlgroup/odl,odlgroup/odl,kohr-h/odl,kohr-h/odl
--- +++ @@ -9,9 +9,13 @@ odl.uniform_discr([0, 0], [1, 1], [9, 11]), odl.uniform_discr(0, 1, 10)]) -def test_optimal_parameters(space): +fom = simple_fixture('fom', + [odl.contrib.fom.mean_squared_error, + odl.contrib.fom.mea...
44fe9bc37b05987c4c323d3be56f69c6f5990b82
enigma.py
enigma.py
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self, notch, wiring): assert...
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self, notch, wiring): assert...
Initialize the machine assignments and assertions
Initialize the machine assignments and assertions
Python
mit
ranisalt/enigma
--- +++ @@ -31,8 +31,17 @@ class Enigma: - def __init__(self): - pass + def __init__(self, rotors, reflector): + # Assert that rotors is a tuple and each tuple element is a Walzen + assert isinstance(rotors, tuple) + for index in range(len(rotors)): + assert isinstanc...
3d8bca4c8f5065342dd2f4c140cc792b2e2d94a1
remo/remozilla/admin.py
remo/remozilla/admin.py
from django.contrib import admin from django.utils.encoding import smart_text from import_export.admin import ExportMixin from remo.remozilla.models import Bug, Status def encode_bugzilla_strings(modeladmin, request, queryset): for obj in queryset: fields = ['component', 'summary', 'whiteboard', 'status...
from django.contrib import admin from django.utils.encoding import smart_text from import_export.admin import ExportMixin from remo.remozilla.models import Bug, Status def encode_bugzilla_strings(modeladmin, request, queryset): for obj in queryset: kwargs = {} fields = ['component', 'summary', '...
Update instead of save when normalizing bug fields.
Update instead of save when normalizing bug fields.
Python
bsd-3-clause
mozilla/remo,tsmrachel/remo,flamingspaz/remo,tsmrachel/remo,akatsoulas/remo,tsmrachel/remo,mozilla/remo,mozilla/remo,flamingspaz/remo,akatsoulas/remo,akatsoulas/remo,Mte90/remo,akatsoulas/remo,tsmrachel/remo,flamingspaz/remo,mozilla/remo,Mte90/remo,Mte90/remo,flamingspaz/remo,Mte90/remo
--- +++ @@ -8,11 +8,11 @@ def encode_bugzilla_strings(modeladmin, request, queryset): for obj in queryset: + kwargs = {} fields = ['component', 'summary', 'whiteboard', 'status', 'resolution', 'first_comment'] for field in fields: - value = smart_text(getattr(obj, field)) -...
0f68fdb37f28f01f21ca42d3bf509dc6138fb157
examples/requirements_check.py
examples/requirements_check.py
"""Example of checking the requirements of bibtext and biblatex.""" from __future__ import print_function import bibpy import os def format_requirements_check(required, optional): s = "" if required: s = "required field(s) " + ", ".join(map(str, required)) if optional: if required: ...
Complete example of checking requirements
Complete example of checking requirements
Python
mit
MisanthropicBit/bibpy,MisanthropicBit/bibpy
--- +++ @@ -0,0 +1,54 @@ +"""Example of checking the requirements of bibtext and biblatex.""" + +from __future__ import print_function + +import bibpy +import os + + +def format_requirements_check(required, optional): + s = "" + + if required: + s = "required field(s) " + ", ".join(map(str, required)) + ...
d55b4b0cd7e160be687129482ecd72792b5c6d81
eventkit/tests/settings.py
eventkit/tests/settings.py
""" Test settings for ``eventkit`` app. """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', ...
""" Test settings for ``eventkit`` app. """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'd...
Create test database in memory.
Create test database in memory.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/icekit-events
--- +++ @@ -5,7 +5,7 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': 'db.sqlite3', + 'NAME': ':memory:', } }
387fd69d034260ceb389c33d0f561967fd902db0
datagrid_gtk3/tests/utils/test_transformations.py
datagrid_gtk3/tests/utils/test_transformations.py
"""Data transformation utilities test cases.""" import unittest from datagrid_gtk3.utils.transformations import degree_decimal_str_transform class DegreeDecimalStrTransformTest(unittest.TestCase): """Degree decimal string transformation test case.""" def test_no_basestring(self): """AssertionError...
"""Data transformation utilities test cases.""" import unittest from datagrid_gtk3.utils.transformations import degree_decimal_str_transform class DegreeDecimalStrTransformTest(unittest.TestCase): """Degree decimal string transformation test case.""" def test_no_basestring(self): """AssertionError...
Update test results using new return type
Update test results using new return type
Python
mit
nowsecure/datagrid-gtk3,jcollado/datagrid-gtk3
--- +++ @@ -30,9 +30,9 @@ """Decimal point is inserted in the expected location.""" self.assertEqual( degree_decimal_str_transform('12345678'), - 12.345678, + '12.345678', ) self.assertEqual( degree_decimal_str_transform('123456'), - ...
722c3dad6d0a0cc34955ab4a5cfafb90a7cf0e64
scaffold/twork_app/twork_app/web/action/not_found.py
scaffold/twork_app/twork_app/web/action/not_found.py
#!/usr/bin/env python # -*- coding: utf-8 -*- '''NotFoundHandler ''' from tornado.web import HTTPError from twork_app.web.action.base import BaseHandler class NotFoundHandler(BaseHandler): '''NotFoundHandler, RESTFUL SUPPORTED. ''' ST_ITEM = 'NOT_FOUND' def post(self, *args, **kwargs): r...
#!/usr/bin/env python # -*- coding: utf-8 -*- '''NotFoundHandler ''' from tornado.web import HTTPError from twork_app.web.action.base import BaseHandler class NotFoundHandler(BaseHandler): '''NotFoundHandler, RESTFUL SUPPORTED. ''' ST_ITEM = 'NOT_FOUND' def post(self, *args, **kwargs): r...
Rewrite put method for not found handler
Rewrite put method for not found handler
Python
apache-2.0
bufferx/twork,bufferx/twork
--- +++ @@ -19,6 +19,9 @@ def post(self, *args, **kwargs): raise HTTPError(404) + def put(self, *args, **kwargs): + raise HTTPError(404) + def delete(self, *args, **kwargs): raise HTTPError(404)
a7946f996d618ad2491f36655f000c513017193c
permamodel/tests/test_package_directories.py
permamodel/tests/test_package_directories.py
"""Tests directories set in the permamodel package definition file.""" import os from nose.tools import assert_true from .. import (permamodel_directory, data_directory, examples_directory, tests_directory) def test_permamodel_directory_is_set(): assert(permamodel_directory is not None) def tes...
"""Tests directories set in the permamodel package definition file.""" import os from .. import data_directory, examples_directory, permamodel_directory, tests_directory def test_permamodel_directory_is_set(): assert permamodel_directory is not None def test_data_directory_is_set(): assert data_directory ...
Remove assert_ functions from nose.
Remove assert_ functions from nose.
Python
mit
permamodel/permamodel,permamodel/permamodel
--- +++ @@ -1,38 +1,37 @@ """Tests directories set in the permamodel package definition file.""" import os -from nose.tools import assert_true -from .. import (permamodel_directory, data_directory, - examples_directory, tests_directory) + +from .. import data_directory, examples_directory, permamod...
8061b8dd4e836e6af16dd93b332f8cea6b55433c
exgrep.py
exgrep.py
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ Usage: exgrep TERM [options] EXCEL_FILE... Options: TERM The term to grep for. Can be any valid (python) regular expression. EXCEL_FILE The list of files to search through -o Only output the matched part """ import re from docopt import docopt import ...
#!/usr/bin/env python3 # -*- coding: utf8 -*- """ Usage: exgrep TERM [options] EXCEL_FILE... Options: TERM The term to grep for. Can be any valid (python) regular expression. EXCEL_FILE The list of files to search through -c COL Only search in the column specified by COL. -o Only output the match...
Add support for only searching specified column
Add support for only searching specified column
Python
mit
Sakartu/excel-toolkit
--- +++ @@ -7,6 +7,7 @@ Options: TERM The term to grep for. Can be any valid (python) regular expression. EXCEL_FILE The list of files to search through +-c COL Only search in the column specified by COL. -o Only output the matched part """ import re @@ -24,7 +25,9 @@ workbook = x...
5d91948e11400253f161be489bb8c9bf13b7ee35
source/main.py
source/main.py
"""updates subreddit css with compiled sass""" import subprocess import praw def css() -> str: """compiles sass and returns css""" res: subprocess.CompletedProcess = subprocess.run( "sass index.scss --style compressed --quiet", stdout=subprocess.PIPE ) return res.stdout def update(reddit: ...
"""updates subreddit css with compiled sass""" import subprocess import time import praw def css() -> str: """compiles sass and returns css""" res: subprocess.CompletedProcess = subprocess.run( "sass index.scss --style compressed --quiet", stdout=subprocess.PIPE ) return res.stdout def ui...
Use direct subreddit stylesheet update function
Use direct subreddit stylesheet update function Instead of updating the wiki, uses the praw-defined function. Also adds an UID function for subreddit reason
Python
mit
neoliberal/css-updater
--- +++ @@ -1,5 +1,7 @@ """updates subreddit css with compiled sass""" import subprocess +import time + import praw def css() -> str: @@ -9,10 +11,13 @@ ) return res.stdout +def uid() -> str: + """return date and time""" + return "Subreddit upload on {}".format(time.strftime("%c")) + def ...
38b2bccc4146226d698f5abd1bed1107fe3bbe68
canon.py
canon.py
from melopy import * m = Melopy('canon', 50) melody = [] for start in ['d4', 'a3', 'b3m', 'f#3m', 'g3', 'd3', 'g3', 'a3']: if start.endswith('m'): scale = generate_minor_triad(start[:-1]) else: scale = generate_major_triad(start) for note in scale: melody.append(note) m.add_melody(melody, 0.2) m.add_not...
from melopy import * m = Melopy('canon', 50) melody = [] for start in ['d4', 'a3', 'bm3', 'f#m3', 'g3', 'd3', 'g3', 'a3']: if start.endswith('m'): scale = m.generate_minor_triad(start[:-1]) else: scale = m.generate_major_triad(start) for note in scale: melody.append(note) m.add_melody(melody, 0.2) m.add_n...
Revert "Added "add_rest(length)" method. Changed iterate and generate functions to be outside of the class."
Revert "Added "add_rest(length)" method. Changed iterate and generate functions to be outside of the class." This reverts commit 672069e8f8f7ded4537362707378f32cccde1ae6.
Python
mit
juliowaissman/Melopy,jdan/Melopy
--- +++ @@ -3,15 +3,15 @@ m = Melopy('canon', 50) melody = [] -for start in ['d4', 'a3', 'b3m', 'f#3m', 'g3', 'd3', 'g3', 'a3']: +for start in ['d4', 'a3', 'bm3', 'f#m3', 'g3', 'd3', 'g3', 'a3']: if start.endswith('m'): - scale = generate_minor_triad(start[:-1]) + scale = m.generate_minor_triad(start[:-1]) ...
768ba3ef82df95e308c1431d17e7173e4ecd2861
vumi/blinkenlights/__init__.py
vumi/blinkenlights/__init__.py
"""Vumi monitoring and control framework.""" from vumi.blinkenlights.metrics_workers import (MetricTimeBucket, MetricAggregator, GraphiteMetricsCollector) __all__ = ["MetricTimeBucket", "MetricAggregator", "GraphiteMetrics...
Add blinkenlights metrics workers to vumi.blinkenlights package namespace (for convenience).
Add blinkenlights metrics workers to vumi.blinkenlights package namespace (for convenience).
Python
bsd-3-clause
vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,harrissoerja/vumi,harrissoerja/vumi,harrissoerja/vumi
--- +++ @@ -0,0 +1,7 @@ +"""Vumi monitoring and control framework.""" + +from vumi.blinkenlights.metrics_workers import (MetricTimeBucket, + MetricAggregator, + GraphiteMetricsCollector) + +__all__ = ["MetricTimeBucket", "Me...
6bd7891e0cfcedc1a5d0813b644b5d6bb941045a
gaphor/abc.py
gaphor/abc.py
from __future__ import annotations import abc from typing import TYPE_CHECKING if TYPE_CHECKING: from gaphor.core.modeling import Element from gaphor.diagram.diagramtoolbox import ToolboxDefinition class Service(metaclass=abc.ABCMeta): """Base interface for all services in Gaphor.""" @abc.abstractm...
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from gaphor.core.modeling import Element from gaphor.diagram.diagramtoolbox import ToolboxDefinition class Service(metaclass=ABCMeta): """Base interface for all services in Gapho...
Remove use of deprecated abstractproperty
Remove use of deprecated abstractproperty Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
--- +++ @@ -1,6 +1,6 @@ from __future__ import annotations -import abc +from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -8,31 +8,33 @@ from gaphor.diagram.diagramtoolbox import ToolboxDefinition -class Service(metaclass=abc.ABCMeta): +class Service(metacla...
880b00a92ac86bb9a5d30392bafb2c019dab7b74
test/unit/test_api_objects.py
test/unit/test_api_objects.py
""" Test api_objects.py """ import unittest from fmcapi import api_objects class TestApiObjects(unittest.TestCase): def test_ip_host_required_for_put(self): self.assertEqual(api_objects.IPHost.REQUIRED_FOR_PUT, ['id', 'name', 'value'])
""" Test api_objects.py """ import mock import unittest from fmcapi import api_objects class TestApiObjects(unittest.TestCase): def test_ip_host_required_for_put(self): self.assertEqual(api_objects.IPHost.REQUIRED_FOR_PUT, ['id', 'name', 'value']) @mock.patch('fmcapi.api_objects.APIClassTemplate.pa...
Add unit test to test for bad response on api delete
Add unit test to test for bad response on api delete
Python
bsd-3-clause
daxm/fmcapi,daxm/fmcapi
--- +++ @@ -1,6 +1,7 @@ """ Test api_objects.py """ +import mock import unittest from fmcapi import api_objects @@ -11,3 +12,16 @@ def test_ip_host_required_for_put(self): self.assertEqual(api_objects.IPHost.REQUIRED_FOR_PUT, ['id', 'name', 'value']) + @mock.patch('fmcapi.api_objects.APIClas...
d6ed0e5925e0793bf4fc84b09e709b3a0d907f58
lc0525_contiguous_array.py
lc0525_contiguous_array.py
"""Leetcode 525. Contiguous Array Medium URL: https://leetcode.com/problems/contiguous-array/ Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Ex...
"""Leetcode 525. Contiguous Array Medium URL: https://leetcode.com/problems/contiguous-array/ Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. Ex...
Complete diffsum idx dict sol w/ time/space complexity
Complete diffsum idx dict sol w/ time/space complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -22,17 +22,45 @@ """ -class Solution(object): +class SolutionDiffsumIdxDict(object): def findMaxLength(self, nums): """ :type nums: List[int] :rtype: int + + Time complexity: O(n). + Space complexity: O(n). """ - pass + # Edge case. ...
7b798d923c5a5af37e9f4c2d92881e907f2c0c74
python/testData/inspections/PyUnresolvedReferencesInspection/ignoredUnresolvedReferenceInUnionType.py
python/testData/inspections/PyUnresolvedReferencesInspection/ignoredUnresolvedReferenceInUnionType.py
class A: pass a = A() print(a.f<caret>oo) x = A() or None print(x.foo)
class A: pass a = A() print(a.f<caret>oo) def func(c): x = A() if c else None return x.foo
Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
Use more reliable test data as pointed in IDEA-COMMUNITY-CR-936
Python
apache-2.0
asedunov/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,caot/intellij-community,diorcety/intellij-community,asedunov/intellij-community,supersven/intellij-community,signed/intel...
--- +++ @@ -4,5 +4,6 @@ a = A() print(a.f<caret>oo) -x = A() or None -print(x.foo) +def func(c): + x = A() if c else None + return x.foo
d0a2f82686158f6610ec5f57f586598be7569c6d
students/psbriant/final_project/clean_data.py
students/psbriant/final_project/clean_data.py
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Code for Final Project """ import pandas from datetime import datetime # Change source to smaller file. data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv") print(data["Date Text"].head())...
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Code for Final Project """ import pandas from datetime import datetime # Change source to smaller file. data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv") print(data["Date Text"].head())...
Comment out code to test first_date variable.
Comment out code to test first_date variable.
Python
unlicense
UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016
--- +++ @@ -23,16 +23,16 @@ # datetime.strptime(first_date, "%Y-%m-%d") # datetime(2012, 3, 10, 0, 0) -data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d")) +# data.date = data.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d")) # print(data.date.head()) -data.index = data.date +# data.index...
218aab63d87d6537c6705f6228a5f49e61d27f8f
protocols/models.py
protocols/models.py
from datetime import datetime from django.db import models class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField() attachment = models.ManyToManyField(Attachment) def __unicode__(self): return self.name class Protocol(models.Model): date = mo...
from datetime import datetime from django.db import models class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField() attachment = models.ManyToManyField('attachments.Attachment') def __unicode__(self): return self.name class Protocol(models.Model):...
Make migration to fix Topic's attachments
Make migration to fix Topic's attachments
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
--- +++ @@ -6,7 +6,7 @@ class Topic(models.Model): name = models.CharField(max_length=100) description = models.TextField() - attachment = models.ManyToManyField(Attachment) + attachment = models.ManyToManyField('attachments.Attachment') def __unicode__(self): return self.name
6cd3e11f6ec84cffc0ea71d15d2e164f499529cf
gidget/util/tumorTypeConfig.py
gidget/util/tumorTypeConfig.py
#!/usr/bin/env python import os.path as path import sys import csv TUMOR_CONFIG_DIALECT = "tumor-type-config" csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n') _relpath_configfile = path.join('config', 'tumorTypesConfig.csv') _configfile = path.expandvars(path.join('${GIDGET_SOURCE_ROOT...
#!/usr/bin/env python import os.path as path import sys import csv TUMOR_CONFIG_DIALECT = "tumor-type-config" csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True) _relpath_configfile = path.join('config', 'tumorTypesConfig.csv') _configfile = path.expandvars(path.joi...
Make sure tumor-type config ignores spaces
Make sure tumor-type config ignores spaces
Python
mit
cancerregulome/gidget,cancerregulome/gidget,cancerregulome/gidget
--- +++ @@ -5,7 +5,7 @@ import csv TUMOR_CONFIG_DIALECT = "tumor-type-config" -csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n') +csv.register_dialect(TUMOR_CONFIG_DIALECT, delimiter=',', lineterminator='\n', skipinitialspace=True) _relpath_configfile = path.join('config', 'tumorTy...
025bd5d3e3d7c80ea7408a6bd9a846c6b36cc88b
test/expression_command/radar_9673664/TestExprHelpExamples.py
test/expression_command/radar_9673664/TestExprHelpExamples.py
""" Test example snippets from the lldb 'help expression' output. """ import os, time import unittest2 import lldb from lldbtest import * import lldbutil class Radar9673644TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). TestBase.setUp(sel...
""" Test example snippets from the lldb 'help expression' output. """ import os, time import unittest2 import lldb from lldbtest import * import lldbutil class Radar9673644TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). TestBase.setUp(sel...
Make this test an expected fail on darwin until we can fix this bug.
Make this test an expected fail on darwin until we can fix this bug. git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@197087 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb
--- +++ @@ -19,7 +19,7 @@ self.main_source = "main.c" self.line = line_number(self.main_source, '// Set breakpoint here.') - # rdar://problem/9673664 + @expectedFailureDarwin(15641319) def test_expr_commands(self): """The following expression commands should just work.""" ...
25064a26fcb674c6cd0165945f5e07cc0b4d2136
medical_prescription_sale_stock_us/__openerp__.py
medical_prescription_sale_stock_us/__openerp__.py
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Prescription Sale Stock - US', 'summary': 'Provides US Locale to Medical Prescription Sale Stock', 'version': '9.0.1.0.0', 'author': "LasLabs, Odoo Community Associatio...
# -*- coding: utf-8 -*- # © 2016 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Medical Prescription Sale Stock - US', 'summary': 'Provides US Locale to Medical Prescription Sale Stock', 'version': '9.0.1.0.0', 'author': "LasLabs, Odoo Community Associatio...
Add dependency * Add dependency on medical_prescription_us to manifest file. This is needed for successful installation.
[FIX] medical_prescription_sale_stock_us: Add dependency * Add dependency on medical_prescription_us to manifest file. This is needed for successful installation.
Python
agpl-3.0
laslabs/vertical-medical,laslabs/vertical-medical
--- +++ @@ -12,6 +12,7 @@ 'depends': [ 'medical_base_us', 'medical_prescription_sale_stock', + 'medical_prescription_us', ], 'data': [ 'views/procurement_order_view.xml',
7341cc7a9049d3650cf8512e6ea32fefd4bf3cee
tensorflow_text/python/keras/layers/__init__.py
tensorflow_text/python/keras/layers/__init__.py
# coding=utf-8 # Copyright 2021 TF.Text Authors. # # 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...
# coding=utf-8 # Copyright 2021 TF.Text Authors. # # 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 missing symbols for tokenization layers
Add missing symbols for tokenization layers Tokenization layers are now exposed by adding them to the list of allowed symbols. Cheers
Python
apache-2.0
tensorflow/text,tensorflow/text,tensorflow/text
--- +++ @@ -19,10 +19,14 @@ # pylint: disable=wildcard-import from tensorflow_text.python.keras.layers.todense import * +from tensorflow_text.python.keras.layers.tokenization_layers import * # Public symbols in the "tensorflow_text.layers" package. _allowed_symbols = [ "ToDense", + "UnicodeScriptToken...
e4cfbe6a60a15041a449fd7717166849136cb48b
stormtracks/settings/default_stormtracks_settings.py
stormtracks/settings/default_stormtracks_settings.py
# *** DON'T MODIFY THIS FILE! *** # # Instead copy it to stormtracks_settings.py # # Default settings for project # This will get copied to $HOME/.stormtracks/ # on install. import os SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) # expandvars expands e.g. $HOME DATA_DIR = os.path.expandvars('$HOME/stormtra...
# *** DON'T MODIFY THIS FILE! *** # # Instead copy it to stormtracks_settings.py # # Default settings for project # This will get copied to $HOME/.stormtracks/ # on install. import os SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) # expandvars expands e.g. $HOME DATA_DIR = os.path.expandvars('$HOME/stormtra...
Remove no longer used setting.
Remove no longer used setting.
Python
mit
markmuetz/stormtracks,markmuetz/stormtracks
--- +++ @@ -10,7 +10,6 @@ SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) # expandvars expands e.g. $HOME DATA_DIR = os.path.expandvars('$HOME/stormtracks_data/data') -TMP_DATA_DIR = None OUTPUT_DIR = os.path.expandvars('$HOME/stormtracks_data/output') LOGGING_DIR = os.path.expandvars('$HOME/stormtrack...
2329886a57a25db56079ff615188b744877f3070
scot/backend_builtin.py
scot/backend_builtin.py
# Released under The MIT License (MIT) # http://opensource.org/licenses/MIT # Copyright (c) 2013-2016 SCoT Development Team """Use internally implemented functions as backend.""" from __future__ import absolute_import import scipy as sp from . import backend from . import datatools, pca, csp from .var import VAR fro...
# Released under The MIT License (MIT) # http://opensource.org/licenses/MIT # Copyright (c) 2013-2016 SCoT Development Team """Use internally implemented functions as backend.""" from __future__ import absolute_import import scipy as sp from . import backend from . import datatools, pca, csp from .var import VAR fro...
Change ICA default to extended Infomax
Change ICA default to extended Infomax
Python
mit
mbillingr/SCoT,scot-dev/scot,scot-dev/scot,cle1109/scot,cbrnr/scot,cle1109/scot,mbillingr/SCoT,cbrnr/scot
--- +++ @@ -16,7 +16,8 @@ def generate(): def wrapper_infomax(data, random_state=None): """Call Infomax (adapted from MNE) for ICA calculation.""" - u = infomax(datatools.cat_trials(data).T, random_state=random_state).T + u = infomax(datatools.cat_trials(data).T, extended=True, + ...
e50f4bd135b41fa49a3f4d4972f1d7ee594e4447
jobs/test_settings.py
jobs/test_settings.py
from decouple import config from jobs.settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test_db', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'db', 'PORT': 5432, } } #DATABASES = { # 'default': { # ...
from decouple import config from jobs.settings import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test_db', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 5432, } } #DATABASES = { # 'default': {...
Replace db host to localhost
Replace db host to localhost
Python
mit
misachi/job_match,misachi/job_match,misachi/job_match
--- +++ @@ -8,7 +8,7 @@ 'NAME': 'test_db', 'USER': 'postgres', 'PASSWORD': '', - 'HOST': 'db', + 'HOST': 'localhost', 'PORT': 5432, } }
fdc4f3bfc1c3e3aa6f6243f0e6bf200025a79103
boto/pyami/scriptbase.py
boto/pyami/scriptbase.py
import os import sys from boto.utils import ShellCommand, get_ts import boto import boto.utils class ScriptBase: def __init__(self, config_file=None): self.instance_id = boto.config.get('Instance', 'instance-id', 'default') self.name = self.__class__.__name__ self.ts = get_ts() if ...
import os import sys from boto.utils import ShellCommand, get_ts import boto import boto.utils class ScriptBase: def __init__(self, config_file=None): self.instance_id = boto.config.get('Instance', 'instance-id', 'default') self.name = self.__class__.__name__ self.ts = get_ts() if ...
Add missing argument specification for cwd argument.
Add missing argument specification for cwd argument.
Python
mit
kouk/boto,jamesls/boto,stevenbrichards/boto,serviceagility/boto,nikhilraog/boto,j-carl/boto,ryansb/boto,acourtney2015/boto,drbild/boto,revmischa/boto,ric03uec/boto,alfredodeza/boto,tpodowd/boto,clouddocx/boto,jindongh/boto,Pretio/boto,kouk/boto,lochiiconnectivity/boto,drbild/boto,zachmullen/boto,pfhayes/boto,podhmo/bot...
--- +++ @@ -28,7 +28,7 @@ self.run('umount %s' % path) def run(self, command, notify=True, exit_on_error=False, cwd=None): - self.last_command = ShellCommand(command, cwd) + self.last_command = ShellCommand(command, cwd=cwd) if self.last_command.status != 0: bot...
906532af9c47072095706fa5a17cae5043ff5f86
api/__init__.py
api/__init__.py
from api.models import BaseTag TAGS = { 'fairness': { 'color': '#bcf0ff', 'description': 'Fairness is ideas of justice, rights, and autonomy.', }, 'cheating': { 'color': '#feffbc', 'description': 'Cheating is acting dishonestly or unfairly in order to gain an advantage.', }, 'loyalty': { ...
Add script to populate Base Tags on app startup
Add script to populate Base Tags on app startup
Python
mit
haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server,haystack/eyebrowse-server
--- +++ @@ -0,0 +1,60 @@ +from api.models import BaseTag + +TAGS = { + 'fairness': { + 'color': '#bcf0ff', + 'description': 'Fairness is ideas of justice, rights, and autonomy.', + }, + 'cheating': { + 'color': '#feffbc', + 'description': 'Cheating is acting dishonestly or unfairly in order to gain an ...
91bf68e26c0fdf7de4209622192f9d57be2d60f8
feincms/views/cbv/views.py
feincms/views/cbv/views.py
from __future__ import absolute_import, unicode_literals from django.http import Http404 from feincms import settings from feincms._internal import get_model from feincms.module.mixins import ContentView class Handler(ContentView): page_model_path = 'page.Page' context_object_name = 'feincms_page' @pro...
from __future__ import absolute_import, unicode_literals from django.http import Http404 from django.utils.functional import cached_property from feincms import settings from feincms._internal import get_model from feincms.module.mixins import ContentView class Handler(ContentView): page_model_path = None c...
Stop invoking get_model for each request
Stop invoking get_model for each request
Python
bsd-3-clause
joshuajonah/feincms,mjl/feincms,matthiask/django-content-editor,michaelkuty/feincms,matthiask/django-content-editor,nickburlett/feincms,feincms/feincms,michaelkuty/feincms,mjl/feincms,mjl/feincms,joshuajonah/feincms,joshuajonah/feincms,nickburlett/feincms,matthiask/django-content-editor,joshuajonah/feincms,feincms/fein...
--- +++ @@ -1,6 +1,7 @@ from __future__ import absolute_import, unicode_literals from django.http import Http404 +from django.utils.functional import cached_property from feincms import settings from feincms._internal import get_model @@ -8,17 +9,13 @@ class Handler(ContentView): - page_model_path = '...
be33ae4e800619e0c50ef9dd7ce5e135e2ebb54b
telethon/errors/__init__.py
telethon/errors/__init__.py
import re from .common import ( ReadCancelledError, InvalidParameterError, TypeNotFoundError, InvalidChecksumError ) from .rpc_errors import ( RPCError, InvalidDCError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, FloodError, ServerError, BadMessageError ) from .rpc_errors_303 i...
import re from .common import ( ReadCancelledError, InvalidParameterError, TypeNotFoundError, InvalidChecksumError ) from .rpc_errors import ( RPCError, InvalidDCError, BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, FloodError, ServerError, BadMessageError ) from .rpc_errors_303 i...
Fix rpc_message_to_error failing to construct them
Fix rpc_message_to_error failing to construct them
Python
mit
LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,kyasabu/Telethon,expectocode/Telethon,andr-04/Telethon
--- +++ @@ -32,12 +32,12 @@ return cls(extra=extra) elif code == 403: - return ForbiddenError() + return ForbiddenError(message) elif code == 404: - return NotFoundError() + return NotFoundError(message) elif code == 500: - return ServerError() ...
f1ba8bf1aeec6579e1830b093485c27bf54ad869
flashcards/main.py
flashcards/main.py
import click import os from flashcards import storage from flashcards.study import BaseStudySession from flashcards.commands import sets as sets_commands from flashcards.commands import cards as cards_commands @click.group() def cli(): """ Main entry point of the application """ # Verify that the storage di...
import click import os from flashcards import storage from flashcards.study import BaseStudySession from flashcards.commands import sets as sets_commands from flashcards.commands import cards as cards_commands @click.group() def cli(): """ Main entry point of the application """ # Verify that the storage di...
Fix an issue where the `_cards` attribute in StudySet was used.
Fix an issue where the `_cards` attribute in StudySet was used.
Python
mit
zergov/flashcards,zergov/flashcards
--- +++ @@ -27,7 +27,7 @@ - number of cards """ studyset = storage.load_selected_studyset() - data = (studyset.title, len(studyset._cards)) + data = (studyset.title, len(studyset)) click.echo('Currently using studyset: %s (%s cards)\n' % data) click.echo('Description: \n%s' % studys...
b12b1245a5a77f2d9373a4878fe07c01335624f7
froide/publicbody/forms.py
froide/publicbody/forms.py
from django import forms from django.utils.translation import ugettext as _ from helper.widgets import EmailInput class PublicBodyForm(forms.Form): name = forms.CharField(label=_("Name of Public Body")) description = forms.CharField(label=_("Short description"), widget=forms.Textarea, required=False) ema...
from django import forms from django.utils.translation import ugettext as _ from haystack.forms import SearchForm from helper.widgets import EmailInput class PublicBodyForm(forms.Form): name = forms.CharField(label=_("Name of Public Body")) description = forms.CharField(label=_("Short description"), widget=...
Add a topic search form (currently not used)
Add a topic search form (currently not used)
Python
mit
stefanw/froide,CodeforHawaii/froide,catcosmo/froide,LilithWittmann/froide,LilithWittmann/froide,ryankanno/froide,okfse/froide,fin/froide,LilithWittmann/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,okfse/froide,fin/froide,stefanw/froide,stefanw/froide,catcosmo/froide,ryankanno/froide,catcosmo/froid...
--- +++ @@ -1,5 +1,7 @@ from django import forms from django.utils.translation import ugettext as _ + +from haystack.forms import SearchForm from helper.widgets import EmailInput @@ -11,4 +13,13 @@ url = forms.URLField(label=_("Homepage URL of Public Body")) +class TopicSearchForm(SearchForm): + ...
7b96c39fc54f17cd52e4b54fb74d21ae66e2d3f0
blockbuster/example_config_files/example_config.py
blockbuster/example_config_files/example_config.py
# General Settings timerestriction = False debug_mode = True log_directory = './logs' # Email Settings # emailtype = "Gmail" emailtype = "Console" # SMS Settings # outboundsmstype = "WebService" outboundsmstype = "Console" # Twilio Auth Keys account_sid = "twilio sid here" auth_token = "auth token here" # SMS Servi...
# General Settings timerestriction = False debug_mode = True log_directory = './logs' # Email Settings # emailtype = "Gmail" emailtype = "Console" # SMS Settings # outboundsmstype = "WebService" outboundsmstype = "Console" # Twilio Auth Keys account_sid = "twilio sid here" auth_token = "auth token here" # SMS Servi...
Remove API User section from example config file
Remove API User section from example config file
Python
mit
mattstibbs/blockbuster-server,mattstibbs/blockbuster-server
--- +++ @@ -46,9 +46,5 @@ mail_password = '' mail_monitoring_addr = '' -# API Variables -api_username = "username here" -api_passphrase = "passphrase here" - # New Number return_number = "+440000111222"
9c1c93dc49f1b5986773164a321cdfcb8e383827
txircd/modules/rfc/cmode_l.py
txircd/modules/rfc/cmode_l.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class LimitMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "Lim...
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import IMode, IModuleData, Mode, ModuleData from txircd.utils import ModeType from zope.interface import implements class LimitMode(ModuleData, Mode): implements(IPlugin, IModuleData, IMode) name = "Lim...
Update +l with new checkSet parameter
Update +l with new checkSet parameter
Python
bsd-3-clause
ElementalAlchemist/txircd,Heufneutje/txircd
--- +++ @@ -25,7 +25,7 @@ return channel.modes["l"] return None - def checkSet(self, param): + def checkSet(self, channel, param): try: return [ int(param) ] except ValueError:
076a129a8468a6c85c8b55a752aca87a60f90d79
ehrcorral/compressions.py
ehrcorral/compressions.py
from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals from jellyfish import soundex, nysiis, metaphone from metaphone import doublemetaphone as dmetaphone def first_letter(name): """A simple name compression that retur...
from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals from jellyfish import soundex, nysiis, metaphone from metaphone import doublemetaphone as dmetaphone def first_letter(name): """A simple name compression that retur...
Add if/else to first_letter compression to handle empty names
Add if/else to first_letter compression to handle empty names
Python
isc
nsh87/ehrcorral
--- +++ @@ -16,4 +16,4 @@ Returns: (str): The upper case of the first letter of the name """ - return name[0].upper() + return name[0].upper() if name else unicode('')
bd7c0a9ac2d357ab635bf2948824256f1e6ddbec
src/carreralib/serial.py
src/carreralib/serial.py
from serial import serial_for_url from .connection import BufferTooShort, Connection, TimeoutError class SerialConnection(Connection): def __init__(self, url, timeout=None): self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout) def close(self): self.__serial.close() def r...
from serial import serial_for_url from .connection import BufferTooShort, Connection, TimeoutError class SerialConnection(Connection): __serial = None def __init__(self, url, timeout=None): self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout) def close(self): if self.__...
Fix SerialConnection.close() with invalid device.
Fix SerialConnection.close() with invalid device.
Python
mit
tkem/carreralib
--- +++ @@ -4,11 +4,15 @@ class SerialConnection(Connection): + + __serial = None + def __init__(self, url, timeout=None): self.__serial = serial_for_url(url, baudrate=19200, timeout=timeout) def close(self): - self.__serial.close() + if self.__serial: + self.__se...
b8c724cb141f6b0757d38b826b5cfd841284a37e
kuryr_libnetwork/server.py
kuryr_libnetwork/server.py
# 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 t...
# 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 t...
Fix no log in /var/log/kuryr/kuryr.log
Fix no log in /var/log/kuryr/kuryr.log code misuse "Kuryr" in log.setup, it should be "kuryr". Change-Id: If36c9e03a01dae710ca12cf340abbb0c5647b47f Closes-bug: #1617863
Python
apache-2.0
celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork
--- +++ @@ -22,11 +22,11 @@ def start(): config.init(sys.argv[1:]) + log.setup(config.CONF, 'kuryr') controllers.neutron_client() controllers.check_for_neutron_ext_support() controllers.check_for_neutron_ext_tag() - log.setup(config.CONF, 'Kuryr') kuryr_uri = parse.urlparse(config....
0d59cf159d9c5f6c64c49cc7ef3cef8feaf5452d
templatetags/coltrane.py
templatetags/coltrane.py
from django.db.models import get_model from django import template from django.contrib.comments.models import Comment, FreeComment from coltrane.models import Entry, Link register = template.Library() class LatestFeaturedNode(template.Node): def __init__(self, varname): self.varname = varname d...
from django.db.models import get_model from django import template from django.contrib.comments.models import Comment, FreeComment from template_utils.templatetags.generic_content import GenericContentNode from coltrane.models import Entry, Link register = template.Library() class LatestFeaturedNode(GenericContent...
Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch
Refactor LatestFeaturedNode to use GenericContentNode and accept a configurable number of entries to fetch git-svn-id: 9770886a22906f523ce26b0ad22db0fc46e41232@54 5f8205a5-902a-0410-8b63-8f478ce83d95
Python
bsd-3-clause
clones/django-coltrane,mafix/coltrane-blog
--- +++ @@ -1,33 +1,53 @@ from django.db.models import get_model from django import template from django.contrib.comments.models import Comment, FreeComment +from template_utils.templatetags.generic_content import GenericContentNode + from coltrane.models import Entry, Link register = template.Library() ...
7321ed72469ad4b9eaf7b1feda370472c294fa97
django_backend_test/noras_menu/forms.py
django_backend_test/noras_menu/forms.py
# -*- encoding: utf-8 -*- #STDLIB importa #Core Django Imports from django import forms #Third Party apps imports #Imports local apps from .models import Menu, MenuItems
# -*- encoding: utf-8 -*- #STDLIB importa from datetime import date #Core Django Imports from django import forms from django.forms.models import inlineformset_factory #Third Party apps imports #Imports local apps from .models import Menu, MenuItems, UserSelectedLunch, Subscribers class MenuForm(forms.ModelForm): ...
Add ModelForm of Menu, MenuItems and Subscriber
Add ModelForm of Menu, MenuItems and Subscriber
Python
mit
semorale/backend-test,semorale/backend-test,semorale/backend-test
--- +++ @@ -1,10 +1,33 @@ # -*- encoding: utf-8 -*- #STDLIB importa +from datetime import date #Core Django Imports from django import forms +from django.forms.models import inlineformset_factory #Third Party apps imports #Imports local apps -from .models import Menu, MenuItems +from .models import Menu, ...
e103ac2a6df36d4236640d36da1a92b6da90e7c5
masters/master.chromium.webrtc/master_builders_cfg.py
masters/master.chromium.webrtc/master_builders_cfg.py
# Copyright (c) 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. from buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler from master.factory import annotator_factor...
# Copyright (c) 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. from buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler from master.factory import annotator_factor...
Switch chromium.webrtc Linux builders to chromium recipe.
WebRTC: Switch chromium.webrtc Linux builders to chromium recipe. With https://codereview.chromium.org/1406253003/ landed this is the first CL in a series of careful rollout to the new recipe. BUG=538259 TBR=phajdan.jr@chromium.org Review URL: https://codereview.chromium.org/1508933002 git-svn-id: 239fca9b83025a0b6...
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
--- +++ @@ -29,14 +29,15 @@ {'name': 'Win10 Tester', 'category': 'win'}, {'name': 'Mac Builder', 'category': 'mac'}, {'name': 'Mac Tester', 'category': 'mac'}, - {'name': 'Linux Builder', 'category': 'linux'}, - {'name': 'Linux Tester', 'category': 'linux'}, + {'name': 'Linux Builder', 'recipe...
a191172016bd6735c5fbb80e130e931f7312e910
csunplugged/config/urls.py
csunplugged/config/urls.py
"""URL configuration for the Django system. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/dev/topics/http/urls/ """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from djan...
"""URL configuration for the Django system. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/dev/topics/http/urls/ """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from djan...
Add coverage ignore to debug URLs
Add coverage ignore to debug URLs
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
--- +++ @@ -21,7 +21,7 @@ url(r"^_ah/health", views.health_check), ] -if settings.DEBUG: +if settings.DEBUG: # pragma: no cover import debug_toolbar urlpatterns += [ url(r"^__debug__/", include(debug_toolbar.urls)),
9ea01cb2f253fefb675a0bfafd05a06f8fe2aca2
eventkit_cloud/tasks/scheduled_tasks.py
eventkit_cloud/tasks/scheduled_tasks.py
# -*- coding: utf-8 -*- from django.utils import timezone from celery import Task from celery.utils.log import get_task_logger logger = get_task_logger(__name__) class PurgeUnpublishedExportsTask(Task): """ Purge unpublished export tasks after 48 hours. """ name = "Purge Unpublished Exports" d...
# -*- coding: utf-8 -*- from django.utils import timezone from celery import Task from celery.utils.log import get_task_logger from celery.app.registry import TaskRegistry logger = get_task_logger(__name__) class PurgeUnpublishedExportsTask(Task): """ Purge unpublished export tasks after 48 hours. """ ...
Install celery beat, register tasks (untested)
Install celery beat, register tasks (untested)
Python
bsd-3-clause
venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud,terranodo/eventkit-cloud,venicegeo/eventkit-cloud
--- +++ @@ -3,6 +3,7 @@ from celery import Task from celery.utils.log import get_task_logger +from celery.app.registry import TaskRegistry logger = get_task_logger(__name__) @@ -22,3 +23,4 @@ logger.debug('Purging {0} unpublished exports.'.format(count)) expired_jobs.delete() +TaskRegistr...