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 |
|---|---|---|---|---|---|---|---|---|---|---|
65b71b6352f07a0ca9a2fdbbbb4f7156b59f59b7 | djangae/contrib/gauth_sql/backends.py | djangae/contrib/gauth_sql/backends.py | from djangae.contrib.gauth.common.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
| from djangae.contrib.gauth.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend):
pass
| Fix bad import on gauth_sql | Fix bad import on gauth_sql
| Python | bsd-3-clause | grzes/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae,potatolondon/djangae | ---
+++
@@ -1,4 +1,4 @@
-from djangae.contrib.gauth.common.backends import BaseAppEngineUserAPIBackend
+from djangae.contrib.gauth.backends import BaseAppEngineUserAPIBackend
class AppEngineUserAPIBackend(BaseAppEngineUserAPIBackend): |
0701e34c76a4ea55b1334c9b48c88fd346f49fa2 | nazs/apps.py | nazs/apps.py | # -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License... | # -*- coding: utf-8 -*-
#
# NAZS
# Copyright (C) 2014 Carlos Pérez-Aradros Herce <exekias@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License... | Stop auto creation of shm database | Stop auto creation of shm database
| Python | agpl-3.0 | exekias/droplet,exekias/droplet,exekias/droplet | ---
+++
@@ -18,7 +18,6 @@
from django.apps import AppConfig
-import os
import pkg_resources
@@ -26,19 +25,8 @@
name = 'nazs'
def ready(self):
- from django.core import management
- from django.conf import settings
-
from .sudo import set_euid
set_euid()
-
- ... |
5e7daffadbd523e1d2a457d10977b1c8a2880d9d | docs/example-plugins/directAPIcall.py | docs/example-plugins/directAPIcall.py | from __future__ import unicode_literals
from client import slack_client as sc
for user in sc.api_call("users.list")["members"]:
print(user["name"], user["id"])
| from __future__ import unicode_literals
from client import slack_client as sc
def process_message(data):
'''If a user passes 'print users' in a message, print the users in the slack
team to the console. (Don't run this in production probably)'''
if 'print users' in data['text']:
for user in sc.ap... | Add a bit more info into the example plugin. | Add a bit more info into the example plugin.
| Python | mit | erynofwales/ubot2,aerickson/python-rtmbot,jammons/python-rtmbot,slackhq/python-rtmbot,ChihChengLiang/python-rtmbot,erynofwales/ubot2 | ---
+++
@@ -1,5 +1,11 @@
from __future__ import unicode_literals
from client import slack_client as sc
-for user in sc.api_call("users.list")["members"]:
- print(user["name"], user["id"])
+
+def process_message(data):
+ '''If a user passes 'print users' in a message, print the users in the slack
+ team t... |
9883a1ac995816160a35fd66107a576289062123 | apis/betterself/v1/events/views.py | apis/betterself/v1/events/views.py | from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = Supple... | from apis.betterself.v1.events.serializers import SupplementEventSerializer
from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1
from events.models import SupplementEvent
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = Supple... | Add queryset, but debate if better options | Add queryset, but debate if better options
| Python | mit | jeffshek/betterself,jeffshek/betterself,jeffshek/betterself,jeffshek/betterself | ---
+++
@@ -6,3 +6,12 @@
class SupplementEventView(BaseGenericListCreateAPIViewV1):
serializer_class = SupplementEventSerializer
model = SupplementEvent
+
+ def get_queryset(self):
+ name = self.request.query_params.get('name')
+ if name:
+ queryset = self.model.objects.filter(n... |
a397f781751536f07e41644f8331990f5e0e8803 | aiofiles/__init__.py | aiofiles/__init__.py | """Utilities for asyncio-friendly file handling."""
from .threadpool import open
__version__ = "0.7.0dev0"
__all__ = ["open"]
| """Utilities for asyncio-friendly file handling."""
from .threadpool import open
from . import tempfile
__version__ = "0.7.0dev0"
__all__ = ['open', 'tempfile']
| Add files via upload Rebase | Add files via upload
Rebase
| Python | apache-2.0 | Tinche/aiofiles | ---
+++
@@ -1,6 +1,7 @@
"""Utilities for asyncio-friendly file handling."""
from .threadpool import open
+from . import tempfile
__version__ = "0.7.0dev0"
-__all__ = ["open"]
+__all__ = ['open', 'tempfile'] |
f83a2dd996ad8f1f0807e4ef877df52d62a4ce45 | tests/test_particle_restart/test_particle_restart.py | tests/test_particle_restart/test_particle_restart.py | #!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE)
returncode = proc.wait()
print(proc.communicate()[0])... | #!/usr/bin/env python
import os
from subprocess import Popen, STDOUT, PIPE
pwd = os.path.dirname(__file__)
def setup():
os.putenv('PWD', pwd)
os.chdir(pwd)
def test_run():
proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE)
stdout, stderr = proc.communicate()
assert stderr != ''... | Change particle restart test to check for output on stderr rather than checking the return status. | Change particle restart test to check for output on stderr rather than checking the return status.
| Python | mit | wbinventor/openmc,shenqicang/openmc,sxds/opemmc,shikhar413/openmc,liangjg/openmc,smharper/openmc,walshjon/openmc,kellyrowland/openmc,amandalund/openmc,samuelshaner/openmc,johnnyliu27/openmc,bhermanmit/cdash,bhermanmit/openmc,mit-crpg/openmc,keadyk/openmc_mg_prepush,smharper/openmc,johnnyliu27/openmc,shenqicang/openmc,a... | ---
+++
@@ -10,20 +10,18 @@
os.chdir(pwd)
def test_run():
- proc = Popen([pwd + '/../../src/openmc'], stderr=STDOUT, stdout=PIPE)
- returncode = proc.wait()
- print(proc.communicate()[0])
- assert returncode != 0
+ proc = Popen([pwd + '/../../src/openmc'], stderr=PIPE, stdout=PIPE)
+ stdout,... |
9d14c70b68eb1b00b8b6826ee6fc2e58fb4a0ab6 | settings_test.py | settings_test.py | # These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
| # These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
| Use only md5 to hash passwords when running tests | Use only md5 to hash passwords when running tests
| Python | bsd-3-clause | peterbe/airmozilla,ehsan/airmozilla,lcamacho/airmozilla,anu7495/airmozilla,anu7495/airmozilla,anu7495/airmozilla,blossomica/airmozilla,lcamacho/airmozilla,EricSekyere/airmozilla,Nolski/airmozilla,tannishk/airmozilla,ehsan/airmozilla,blossomica/airmozilla,anjalymehla/airmozilla,ehsan/airmozilla,zofuthan/airmozilla,chiri... | ---
+++
@@ -1,3 +1,7 @@
# These settings will always be overriding for all test runs
EMAIL_FROM_ADDRESS = 'doesnt@matter.com'
+
+PASSWORD_HASHERS = (
+ 'django.contrib.auth.hashers.MD5PasswordHasher',
+) |
52c78b7498f52d26cd5dc2ea27c6c0f2dc6db117 | pytips/models.py | pytips/models.py | # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
clas... | # -*- coding: utf-8 -*-
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
clas... | Add a helper for retrieving the newest Tip. | Add a helper for retrieving the newest Tip.
| Python | isc | gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips | ---
+++
@@ -18,6 +18,11 @@
"""Retrieve a random ``Tip``."""
return self.order_by(func.random()).first()
+ def newest_tip(self):
+ """Retrieve the ``Tip`` with the newest ``publication_date``."""
+ return self.filter(Tip.url.like('%twitter.com%')).order_by(
+ Tip.publica... |
17fd955a3b4abe5ca751ea05e0cdb30429a9ce04 | ghettoq/backends/pyredis.py | ghettoq/backends/pyredis.py | from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int... | from Queue import Empty
from redis import Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
DEFAULT_DB = 0
class RedisBackend(BaseBackend):
def __init__(self, host=None, port=None, user=None, password=None,
database=None, timeout=None):
if not isinstance(database, int... | Throw Empty exception if BRPOP returns None. Add priority argument so it works with the latest version. | Throw Empty exception if BRPOP returns None.
Add priority argument so it works with the latest version.
| Python | bsd-3-clause | ask/ghettoq | ---
+++
@@ -32,20 +32,30 @@
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
- def put(self, queue, message):
+ def put(self, queue, message, priority = 0):
self.client.lpush(queue, message)
def get(self, queue):
if ... |
91c3eb57ea3b2cd12654cbd6925a681d3450e77e | go/apps/jsbox/definition.py | go/apps/jsbox/definition.py | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
co... | from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinitionBase):
co... | Add start of hook for extra jsbox endpoints. | Add start of hook for extra jsbox endpoints.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -13,3 +13,6 @@
conversation_display_name = 'Javascript App'
actions = (ViewLogsAction,)
+
+ def configured_endpoints(self, config):
+ return [] |
0b8aa961cb8aa6646aa1b660f6f669cf82492225 | helper/windows.py | helper/windows.py | """
Windows platform support for running the application as a detached process.
"""
import subprocess
import sys
DETACHED_PROCESS = 8
class Daemon(object):
"""Daemonize the helper application, putting it in a forked background
process.
"""
def __init__(self, controller):
raise NotImplemente... | """
Windows platform support for running the application as a detached process.
"""
import platform
import subprocess
import sys
DETACHED_PROCESS = 8
def operating_system():
"""Return a string identifying the operating system the application
is running on.
:rtype: str
"""
return '%s %s (%s)' %... | Implement the operating_system() method for Windows | Implement the operating_system() method for Windows
| Python | bsd-3-clause | dave-shawley/helper,gmr/helper,gmr/helper | ---
+++
@@ -2,10 +2,23 @@
Windows platform support for running the application as a detached process.
"""
+import platform
import subprocess
import sys
DETACHED_PROCESS = 8
+
+
+def operating_system():
+ """Return a string identifying the operating system the application
+ is running on.
+
+ :rtype:... |
5eb1fe63bdbf0e6ce4832d70d9971e62c231c7b8 | core/management/commands/run_urlscript.py | core/management/commands/run_urlscript.py | try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandEr... | try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandEr... | Use the site that has scheme also input. | Use the site that has scheme also input.
| Python | mit | theju/urlscript | ---
+++
@@ -14,7 +14,7 @@
def request_url(url):
- urlopen("http://{0}{1}".format(
+ urlopen("{0}{1}".format(
Site.objects.get_current().domain,
reverse("run_fn", kwargs={"slug": url.slug})
)) |
74e9c87f4a6ad9ad6458a1e297460220c587b197 | rbuild/client.py | rbuild/client.py | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | #
# Copyright (c) 2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... | Fix getClient bugs found by smoketest | Fix getClient bugs found by smoketest
| Python | apache-2.0 | fedora-conary/rbuild,sassoftware/rbuild,fedora-conary/rbuild,sassoftware/rbuild | ---
+++
@@ -21,6 +21,9 @@
with each other.
"""
+from rbuild import rbuildcfg
+from rbuild.internal import pluginloader
+
class rBuildClient(object):
def __init__(self, pluginMgr, cfg):
self.cfg = cfg
@@ -28,7 +31,8 @@
for plugin in pluginMgr.plugins:
setattr(self, plugin.__cla... |
6c4178f4b5518568d83523db418d34c36a791852 | skylines/__init__.py | skylines/__init__.py | from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel... | from flask import Flask, g
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader
from skylines.lib import helpers
def create_app():
app = Flask(__name__, static_folder='public')
app.config.from_object('skylines.config.default')
babel = Babel... | Configure webassets environment from app.config | flask: Configure webassets environment from app.config
| Python | agpl-3.0 | RBE-Avionik/skylines,Turbo87/skylines,snip/skylines,Turbo87/skylines,skylines-project/skylines,skylines-project/skylines,RBE-Avionik/skylines,snip/skylines,Harry-R/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,snip/skylines,TobiasLohner/SkyLines,kerel-fs/skylines,kerel-fs/skylines,Harry-R/skylines,shadowoneau/sky... | ---
+++
@@ -13,6 +13,12 @@
bundles = PythonLoader('skylines.assets.bundles').load_bundles()
assets = Environment(app)
+
+ load_path = app.config.get('ASSETS_LOAD_DIR', None)
+ if load_path is not None:
+ load_url = app.config.get('ASSETS_LOAD_URL', None)
+ assets.append_path(load_path,... |
4727991d29bc888611b6eaa403456524785b6338 | highlightjs/testsettings.py | highlightjs/testsettings.py | import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
| import django.conf.global_settings as DEFAULT_SETTINGS
SECRET_KEY = 'highlightjsisawesome'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'highlightjs',
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
TEMPLATES... | Add django backend for test settings | Add django backend for test settings | Python | mit | MounirMesselmeni/django-highlightjs | ---
+++
@@ -16,3 +16,11 @@
)
MIDDLEWARE_CLASSES = DEFAULT_SETTINGS.MIDDLEWARE_CLASSES
+
+TEMPLATES = [
+ {
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
+ 'DIRS': [],
+ 'APP_DIRS': True,
+ },
+] |
97e3309a66c5d84489df4a384552e5b5d75643ea | spotpy/unittests/test_objectivefunctions.py | spotpy/unittests/test_objectivefunctions.py | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
... | import unittest
from spotpy import objectivefunctions as of
import numpy as np
#https://docs.python.org/3/library/unittest.html
class TestObjectiveFunctions(unittest.TestCase):
# How many digits to match in case of floating point answers
tolerance = 10
def setUp(self):
np.random.seed(42)
... | Add tests for pbias and nashsutcliffe | Add tests for pbias and nashsutcliffe
| Python | mit | bees4ever/spotpy,thouska/spotpy,thouska/spotpy,bees4ever/spotpy,thouska/spotpy,bees4ever/spotpy | ---
+++
@@ -14,19 +14,24 @@
self.simulation = np.random.randn(10)
self.evaluation = np.random.randn(10)
- print(self.simulation)
- print(self.evaluation)
-
def test_bias(self):
res = of.bias(self.evaluation, self.simulation)
self.assertAlmostEqual(res, 1.238719... |
63814839642e593e35f8afaf68fc6724b69075b5 | trade_server.py | trade_server.py | import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, asks
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if d... | import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
res... | Add stubs for handling requests to server. | Add stubs for handling requests to server.
| Python | mit | Tribler/decentral-market | ---
+++
@@ -3,9 +3,7 @@
import socket
import SocketServer
-from orderbook import match_bid, offers, asks
-
-messages = []
+from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
@@ -15,13 +13,7 @@
while True:
data = self.request.recv(1... |
8b2cb51c8913737c524e1b922aeb02c07bfb2afc | src/keybar/models/entry.py | src/keybar/models/entry.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = models.TextF... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
id = UUIDField(auto=True, primary_key=True)
created_by = models.ForeignKey('keybar.User')
title = mod... | Add decrypt helper to Entry | Add decrypt helper to Entry
| Python | bsd-3-clause | keybar/keybar | ---
+++
@@ -2,7 +2,7 @@
from django.utils.translation import ugettext_lazy as _
from uuidfield import UUIDField
-from keybar.utils.crypto import encrypt, get_salt
+from keybar.utils.crypto import encrypt, decrypt, get_salt
class Entry(models.Model):
@@ -27,3 +27,6 @@
self.value = encrypt(value, pa... |
87eac064f56c8a617c6aa2412345bb12352432ca | il2fb/ds/airbridge/api/http/responses/rest.py | il2fb/ds/airbridge/api/http/responses/rest.py | # coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
... | # coding: utf-8
import abc
from typing import Any
from aiohttp import web
from il2fb.ds.airbridge import json
class RESTResponse(web.Response, abc.ABC):
detail = None
@property
@abc.abstractmethod
def status(self) -> int:
"""
Status must be explicilty defined by subclasses.
... | Fix indents for minimized JSON | Fix indents for minimized JSON
| Python | mit | IL2HorusTeam/il2fb-ds-airbridge | ---
+++
@@ -35,7 +35,7 @@
if detail:
payload['detail'] = str(detail)
- indent = 2 if pretty else 0
+ indent = 2 if pretty else None
text = json.dumps(payload, indent=indent) + '\n'
kwargs.setdefault('status', self.status) |
91e80dbaba20a914737fa64b0b35cf315bc79f0a | runtests.py | runtests.py | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
... | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
#
"""
File for running tests programmatically.
"""
# Third party imports
import pytest
def main():
"""
Run pytest tests.
"""
errno = pytest.main(['-x', 'spyder_terminal', '-v',
... | Add timeout to all tests | Add timeout to all tests
| Python | mit | spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal,spyder-ide/spyder-terminal | ---
+++
@@ -19,7 +19,7 @@
errno = pytest.main(['-x', 'spyder_terminal', '-v',
'-rw', '--durations=10',
'--cov=spyder_terminal', '--cov-report=term-missing',
- '--timeout=20'])
+ '--timeout=30'])
# sys.exit ... |
cfc95643733244275e605a8ff0c00d4861067a13 | character_shift/character_shift.py | character_shift/character_shift.py | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
if c.isalpha() else c for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1)... | #!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
% 26+1) for c in string)
if __name__ == '__main__':
assert shift('abcz+', 1) == 'bcda+', shift('abcz+', 1)
assert shift('ABCZ+', 1) == 'BC... | Use bitwise operators on ordinals to reduce code size | Use bitwise operators on ordinals to reduce code size
The ASCII standard neatly organizes the characters in such a way
that it is easy to manipulate and classify them using bitwise
operators.
| Python | mit | TotempaaltJ/tiniest-code,TotempaaltJ/tiniest-code | ---
+++
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
def shift(string, key, decipher=False):
return ''.join(
- chr((ord(c.upper())-65+key*(1-2*decipher)) % 26+65+32*c.islower())
- if c.isalpha() else c for c in string)
+ chr((ord(c) & 224)+((ord(c) & 31)+25+key*(-2*decipher+1)*c.isalpha())
+ ... |
1632b64372f2f38a6c43b000ace631d183278375 | observations/forms.py | observations/forms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models import Observer
class BatchUploa... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
from .models import Observation
from stars.models import Star
from observers.models ... | Use transaction.atomic in batch uploader. | Use transaction.atomic in batch uploader.
| Python | mit | zsiciarz/variablestars.net,zsiciarz/variablestars.net,zsiciarz/variablestars.net | ---
+++
@@ -2,6 +2,7 @@
from __future__ import unicode_literals
from django import forms
+from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from pyaavso.formats.visual import VisualFormatReader
@@ -18,33 +19,34 @@
fp = self.cleaned_data['aavso_file']
r... |
a9cf757a0a8dc0bf558492676b1bfb5d630a78c1 | ModRepository/Util.py | ModRepository/Util.py | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
... | __author__ = 'admiral0'
from . import *
from .Exceptions import JsonNotValid
import argparse
import os.path as path
def is_mod_repo(x):
if path.isdir(x):
return x
raise argparse.ArgumentTypeError(x + ' is not a Directory')
def validate(args):
try:
repo = ModRepository(args.mod_repo)
... | Fix a derp on argparse | Fix a derp on argparse
| Python | bsd-2-clause | admiral0/AntaniRepos | ---
+++
@@ -39,7 +39,7 @@
parser = argparse.ArgumentParser(description='TechnicAntani ModRepo Tools')
parser.add_argument('mod_repo', metavar='ModRepoPath', type=is_mod_repo, help='The path to Mod Repo directory',
default='.')
-parser.add_argument('-a', dest='action', type=str, default='validat... |
8394011dc2cd0a6fe682c435b8e09f8accb1311f | web/impact/impact/v1/views/criterion_option_spec_list_view.py | web/impact/impact/v1/views/criterion_option_spec_list_view.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.base_list_view import BaseListView
from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView, PostMixin):
view_name = "criterion_option_spec"
... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.v1.views.post_mixin import PostMixin
from impact.v1.views.base_list_view import BaseListView
from impact.v1.helpers import CriterionOptionSpecHelper
class CriterionOptionSpecListView(BaseListView,
PostMixin):
hel... | Move some code around because code climate said so | [AC-5622] Move some code around because code climate said so
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -1,12 +1,13 @@
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
+from impact.v1.views.post_mixin import PostMixin
from impact.v1.views.base_list_view import BaseListView
-from impact.v1.views.post_mixin import PostMixin
from impact.v1.helpers import CriterionOptionSpecHelper
-class Criterio... |
16dd533f32b3efdbbe9c2f7c6e5e3f42fe6c6b1d | qtpy/tests/test_qtprintsupport.py | qtpy/tests/test_qtprintsupport.py | import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrintDialog is not None
assert QtPrintSupport.QPrin... | """Test QtPrintSupport."""
import os
import sys
import pytest
from qtpy import QtPrintSupport
def test_qtprintsupport():
"""Test the qtpy.QtPrintSupport namespace"""
assert QtPrintSupport.QAbstractPrintDialog is not None
assert QtPrintSupport.QPageSetupDialog is not None
assert QtPrintSupport.QPrint... | Add tests for aliased methods | QtPrintSupport: Add tests for aliased methods
| Python | mit | spyder-ide/qtpy | ---
+++
@@ -1,4 +1,9 @@
+"""Test QtPrintSupport."""
+import os
+import sys
+
import pytest
+
from qtpy import QtPrintSupport
@@ -12,3 +17,22 @@
assert QtPrintSupport.QPrinter is not None
assert QtPrintSupport.QPrinterInfo is not None
assert QtPrintSupport.QPrintPreviewWidget is not None
+
+
+def ... |
3129d72151d81d8745a8e81ab4940dcd56a67b66 | scripts/get-translator-credits.py | scripts/get-translator-credits.py | import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string f... | import subprocess
import re
from collections import defaultdict
from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
... | Sort languages by English name | Sort languages by English name
| Python | bsd-3-clause | zerolab/wagtail,thenewguy/wagtail,timorieber/wagtail,kaedroho/wagtail,kurtrwall/wagtail,nilnvoid/wagtail,nutztherookie/wagtail,kurtw/wagtail,nimasmi/wagtail,torchbox/wagtail,zerolab/wagtail,timorieber/wagtail,FlipperPA/wagtail,rsalmaso/wagtail,zerolab/wagtail,kaedroho/wagtail,mixxorz/wagtail,mikedingjan/wagtail,rsalmas... | ---
+++
@@ -1,6 +1,8 @@
import subprocess
import re
from collections import defaultdict
+
+from babel import Locale
authors_by_locale = defaultdict(set)
@@ -31,9 +33,14 @@
else:
raise Exception("No 'Translators:' heading found in %s" % filename)
-locales = sorted(author... |
c974f7ed5f63278c24165d626e9e5dd63f18f7ae | tensorflow/python/debug/lib/op_callbacks_common.py | tensorflow/python/debug/lib/op_callbacks_common.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs | [tfdbg] Support enable_check_numerics() and enable_dump_debug_info() callback on TPUs
- Skip a set of TPU compilation-specific ops from tfdbg's op callbacks.
PiperOrigin-RevId: 281836861
Change-Id: Ic7ff59a32eba26d5bb3ee2ac4f5f9166c78928c8
| Python | apache-2.0 | renyi533/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,aldian/tensorflow,jhseu/tensorflow,renyi533/tensorflow,sarvex/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ppwwyyxx/tensorflow,tensorflow/tensorflow,aldian/tensorflo... | ---
+++
@@ -28,10 +28,17 @@
b"Exit",
b"Identity",
b"If",
+ b"LoopCond",
b"Merge",
b"NextIteration",
b"StatelessIf",
b"StatefulPartitionedCall",
b"Switch",
b"While",
+ # TPU-specific ops begin.
+ b"TPUReplicatedInput",
+ b"TPUReplicateMetadata",
+ b"TPUCompil... |
a92121cfdbb94d36d021fb8d1386031829ee86a2 | patterns/solid.py | patterns/solid.py | import blinkypattern
class Solid(blinkypattern.BlinkyPattern):
def __init__(self, blinkytape, solid_color):
super(Solid, self).__init__(blinkytape)
self._pixels = [solid_color] * self._blinkytape.pixel_count
def setup(self):
super(Solid, self).setup()
self._blinkytape.set_pixel... | class Solid(object):
def __init__(self, pixel_count, color):
self._pixels = [color] * pixel_count
@property
def pixels(self):
return self._pixels
| Update Solid pattern for refactor | Update Solid pattern for refactor
| Python | mit | jonspeicher/blinkyfun | ---
+++
@@ -1,11 +1,7 @@
-import blinkypattern
+class Solid(object):
+ def __init__(self, pixel_count, color):
+ self._pixels = [color] * pixel_count
-class Solid(blinkypattern.BlinkyPattern):
- def __init__(self, blinkytape, solid_color):
- super(Solid, self).__init__(blinkytape)
- self.... |
c0ce65ccd7db7e7f34e9d6172f7179cf9ee16ef2 | chandra_aca/tests/test_dark_scale.py | chandra_aca/tests/test_dark_scale.py | import numpy as np
from ..dark_model import dark_temp_scale
def test_dark_temp_scale():
scale = dark_temp_scale(-10., -14)
assert np.allclose(scale, 0.70)
scale = dark_temp_scale(-10., -14, scale_4c=2.0)
assert scale == 0.5 # Should be an exact match
| import numpy as np
from ..dark_model import dark_temp_scale, get_warm_fracs
def test_get_warm_fracs():
exp = {(100, '2020:001', -11): 341312,
(100, '2017:001', -11): 278627,
(100, '2020:001', -15): 250546,
(100, '2017:001', -15): 200786,
(1000, '2017:001', -11): 1703,
... | Add regression test of warm fractions calculation | Add regression test of warm fractions calculation
| Python | bsd-2-clause | sot/chandra_aca,sot/chandra_aca | ---
+++
@@ -1,5 +1,25 @@
import numpy as np
-from ..dark_model import dark_temp_scale
+from ..dark_model import dark_temp_scale, get_warm_fracs
+
+
+def test_get_warm_fracs():
+ exp = {(100, '2020:001', -11): 341312,
+ (100, '2017:001', -11): 278627,
+ (100, '2020:001', -15): 250546,
+ ... |
28d5e53da8a92985fa9b1b4a532467dd343cc4b5 | apilisk/junit_formatter.py | apilisk/junit_formatter.py | import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
str(item["id"]): item for item in project_cfg["testcases"]
}
test_cases = []
for ... | # -*- coding: utf-8 -*-
import json
from junit_xml import TestSuite, TestCase
class JunitFormatter(object):
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
unicode(item["id"]): item for item in project_cfg["testcases"]
}
... | Fix junit utf-8 output to file | Fix junit utf-8 output to file
| Python | mit | apiwatcher/apilisk | ---
+++
@@ -1,3 +1,5 @@
+# -*- coding: utf-8 -*-
+
import json
from junit_xml import TestSuite, TestCase
@@ -7,13 +9,13 @@
def __init__(self, project_cfg, project_result):
"""Initialize the stuff"""
self.testcases = {
- str(item["id"]): item for item in project_cfg["testcases"]
+... |
f74ce9c077054119c04ab65fc0afa4c137204770 | comics/comics/basicinstructions.py | comics/comics/basicinstructions.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(Cr... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Basic Instructions"
language = "en"
url = "http://www.basicinstructions.net/"
start_date = "2006-07-01"
rights = "Scott Meyer"
class Crawler(Cr... | Update "Basic Instructions" after feed change | Update "Basic Instructions" after feed change
| Python | agpl-3.0 | datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics | ---
+++
@@ -20,6 +20,6 @@
"http://basicinstructions.net/basic-instructions/rss.xml"
)
for entry in feed.for_date(pub_date):
- url = entry.summary.src('img[src*="/storage/"][src*=".gif"]')
+ url = entry.summary.src("img")
title = entry.title
... |
7c847513155b1bdc29c04a10dbfd2efd669d1507 | async/spam_echo_clients.py | async/spam_echo_clients.py | import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
s... | import socket
import sys
import time
SERVER_HOST = 'localhost'
SERVER_PORT = 40404
sockets = []
msg = b'first message'
for i in range(20):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_HOST, SERVER_PORT))
sockets.append(sock)
time.sleep(0.1)
for sock in sockets:
s... | Add reply checks to the spam client too | Add reply checks to the spam client too
| Python | unlicense | eliben/python3-samples | ---
+++
@@ -19,6 +19,12 @@
time.sleep(0.1)
for sock in sockets:
+ data = sock.recv(1024)
+ if data != msg:
+ print('Error! No reply to', sock.getsockname())
+ time.sleep(0.1)
+
+for sock in sockets:
sock.close()
time.sleep(0.1)
|
8ffc8cabd5a2ba20997337c101018f3c25faef4e | onadata/apps/fsforms/management/commands/save_version_in_finstance.py | onadata/apps/fsforms/management/commands/save_version_in_finstance.py | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def add_arguments(self, parser):
parser.add_argument('username', type=str)
def handle(self, *args, **options):
... | from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
from onadata.apps.logger.models import Instance
from onadata.settings.local_settings import XML_VERSION_MAX_ITER
import re
class Command(BaseCommand):
help = 'Set version in FInstance for given user'
def... | Update command to save version in finstance | Update command to save version in finstance
| Python | bsd-2-clause | awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat | ---
+++
@@ -1,5 +1,8 @@
from django.core.management.base import BaseCommand
from onadata.apps.fsforms.models import FInstance
+from onadata.apps.logger.models import Instance
+from onadata.settings.local_settings import XML_VERSION_MAX_ITER
+import re
class Command(BaseCommand):
@@ -15,6 +18,7 @@
stop... |
296b343699a2a37c661937f60d854f6fd4e53e69 | src/waldur_mastermind/common/serializers.py | src/waldur_mastermind/common/serializers.py | from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
fie... | from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
field_type = option.get('type', '')
if field_type == 'string':
field = serializers.CharField()
elif field_type == 'integer':
fie... | Fix typo in options serializer. | Fix typo in options serializer.
| Python | mit | opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur | ---
+++
@@ -33,7 +33,7 @@
field.max_value = option.get('max')
if 'choices' in option:
- fields.choices = option.get('choices')
+ field.choices = option.get('choices')
field.required = option.get('required', False)
field.label = option.get('label') |
ff6fbf0821112a0144fbe2d14768cd7a03907438 | rst2pdf/utils.py | rst2pdf/utils.py | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (ca... | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of f... | Add unit support for spacers | Add unit support for spacers
| Python | mit | thomaspurchas/rst2pdf,thomaspurchas/rst2pdf | ---
+++
@@ -9,7 +9,7 @@
from reportlab.platypus import Spacer
from flowables import *
-
+from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
@@ -34,7 +34,8 @@
else:
elements.append(MyPageBreak(tokens[1]))
... |
ead5a941efd8b8a41b81f679ad3e6c98e2248409 | dipy/io/tests/test_dicomreaders.py | dipy/io/tests/test_dicomreaders.py | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, ass... | """ Testing reading DICOM files
"""
import numpy as np
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
... | TEST - added more explicit tests for directory read | TEST - added more explicit tests for directory read
| Python | bsd-3-clause | FrancoisRheaultUS/dipy,sinkpoint/dipy,StongeEtienne/dipy,samuelstjean/dipy,rfdougherty/dipy,demianw/dipy,samuelstjean/dipy,JohnGriffiths/dipy,mdesco/dipy,rfdougherty/dipy,maurozucchelli/dipy,demianw/dipy,jyeatman/dipy,oesteban/dipy,beni55/dipy,StongeEtienne/dipy,mdesco/dipy,matthieudumont/dipy,FrancoisRheaultUS/dipy,jy... | ---
+++
@@ -7,6 +7,7 @@
from .. import dicomreaders as didr
from .test_dicomwrappers import (EXPECTED_AFFINE,
+ EXPECTED_PARAMS,
DATA)
from nose.tools import assert_true, assert_false, \
@@ -29,7 +30,10 @@
def test_read_dwis():
data, aff, ... |
697bf0c23786794e35b0b9f72c878bb762d296b9 | benches/cprofile_pyproj.py | benches/cprofile_pyproj.py | import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
osgb36 = Proj(init='epsg:27700')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords])
lat_ls = np.random... | import numpy as np
from pyproj import Proj, transform
# London bounding box
N = 51.691874116909894
E = 0.3340155643740321
S = 51.28676016315085
W = -0.5103750689005356
# osgb36 = Proj(init='epsg:27700')
osgb36 = Proj('+init=EPSG:27700 +nadgrids=OSTN02_NTv2.gsb')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon... | Use NTv2 transform for Pyproj | Use NTv2 transform for Pyproj
| Python | mit | urschrei/lonlat_bng,urschrei/rust_bng,urschrei/lonlat_bng,urschrei/rust_bng,urschrei/lonlat_bng | ---
+++
@@ -7,7 +7,8 @@
S = 51.28676016315085
W = -0.5103750689005356
-osgb36 = Proj(init='epsg:27700')
+# osgb36 = Proj(init='epsg:27700')
+osgb36 = Proj('+init=EPSG:27700 +nadgrids=OSTN02_NTv2.gsb')
wgs84 = Proj(init='epsg:4326')
num_coords = 1000000
lon_ls = np.random.uniform(W, E, [num_coords]) |
98f4ca1cdf5b5f68a3d8e785ec50756653444843 | pyconcz_2016/speakers/views.py | pyconcz_2016/speakers/views.py | from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(re... | from django.db.models import Case
from django.db.models import IntegerField
from django.db.models import Value
from django.db.models import When
from django.template import RequestContext
from django.template.response import TemplateResponse
from pyconcz_2016.speakers.models import Speaker, Slot
def speakers_list(re... | Fix sorting of rooms in schedule | Fix sorting of rooms in schedule
| Python | mit | pyvec/cz.pycon.org-2016,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2016,pyvec/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,benabraham/cz.pycon.org-2017,pyvec/cz.pycon.org-2017,pyvec/cz.pycon.org-2017 | ---
+++
@@ -27,8 +27,8 @@
.prefetch_related('talk__speakers')
.annotate(order=Case(
When(room='d105', then=Value(1)),
- When(room='d0207', then=Value(2)),
- When(room='d0206', then=Value(3)),
+ When(room='d... |
1fce663e37823d985d00d1700aba5e067157b789 | profiles/tests.py | profiles/tests.py | from django.contrib.auth.models import User
from django.test import TestCase
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)... | from django.contrib.auth.models import User
import factory
from .models import Profile
class UserFactory(factory.Factory):
FACTORY_FOR = User
first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n))
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequenc... | Add password handling to default factory. | Add password handling to default factory.
| Python | bsd-2-clause | incuna/django-extensible-profiles | ---
+++
@@ -1,5 +1,5 @@
from django.contrib.auth.models import User
-from django.test import TestCase
+
import factory
from .models import Profile
@@ -11,6 +11,16 @@
last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n))
username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower())
... |
d369b2ba967643d16c58fbad0be5b3a24785f602 | neurodsp/tests/test_spectral_utils.py | neurodsp/tests/test_spectral_utils.py | """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
##########################################################################... | """Test the utility function from spectral."""
import numpy as np
from numpy.testing import assert_equal
from neurodsp.spectral.utils import *
###################################################################################################
##########################################################################... | Add smoke test for trim_spectrogram | Add smoke test for trim_spectrogram
| Python | apache-2.0 | voytekresearch/neurodsp | ---
+++
@@ -17,6 +17,20 @@
assert_equal(freqs_new, np.array([6, 7, 8]))
assert_equal(pows_new, np.array([2, 3, 4]))
+def test_trim_spectrogram():
+
+ freqs = np.array([5, 6, 7, 8])
+ times = np.array([0, 1, 2,])
+ pows = np.array([[1, 2, 3],
+ [4, 5, 6],
+ ... |
325256e7be56e5be951c98583ff79ca44ae14940 | server/server.py | server/server.py | from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts ... | from flask import Flask, url_for , request
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# ... | Add methods to change the beat and volume of tone | Add methods to change the beat and volume of tone
| Python | artistic-2.0 | axay/eigen,axay/eigen | ---
+++
@@ -1,4 +1,4 @@
-from flask import Flask, url_for
+from flask import Flask, url_for , request
app = Flask(__name__)
@app.route('/')
@@ -27,5 +27,13 @@
# Stop the tone
return 'Stopped Playing ' + tone_id
+@app.route('/beat/<tone_id>' , methods=['POST'])
+def api_change_beat(tone_id):
+ return 'Chan... |
5ac1dce80d0bfe4c52a2de5de4beefe235b8ad66 | post_process.py | post_process.py | #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import tr... | #!/usr/bin/env python
"""
Load a neural network model from a data frame
"""
import pickle
import numpy as np
import pandas as pd
from lasagne import nonlinearities
from lasagne.layers import DenseLayer
from lasagne.layers import InputLayer
from nolearn.lasagne import NeuralNet
from sklearn.cross_validation import tr... | Load SVM pickle and print metrics | Load SVM pickle and print metrics
| Python | bsd-3-clause | BeckResearchLab/USP-inhibition,pearlphilip/USP-inhibition | ---
+++
@@ -15,10 +15,12 @@
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
-PICKLE = 'data.pkl'
+NN_PICKLE = 'nn_data.pkl'
+SVM_PICKLE = 'svm_data.pkl'
+
def results():
- with open(PICKLE, 'rb') as file:
+ with open(NN_PICKLE, 'rb') as file:
gr... |
9bd044297e1ef0f6383e39f376eec92885897406 | kansha/alembic/versions/2b0edcfa57b4_add_templates.py | kansha/alembic/versions/2b0edcfa57b4_add_templates.py | """Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2b0edcfa57b4'
down_revision = '24be36b8c67'
def upgrade():
op.add_column('board', sa.Column('is_templa... | """Add templates
Revision ID: 2b0edcfa57b4
Revises: 24be36b8c67
Create Date: 2015-11-24 17:50:13.280722
"""
from alembic import op
import elixir
import sqlalchemy as sa
from nagare import database, local, security
from kansha.board.boardsmanager import BoardsManager
from kansha.security import SecurityManager
from... | Add default template creation into migration script | Add default template creation into migration script
| Python | bsd-3-clause | Net-ng/kansha,bcroq/kansha,bcroq/kansha,Net-ng/kansha,Net-ng/kansha,bcroq/kansha,Net-ng/kansha,bcroq/kansha | ---
+++
@@ -6,16 +6,40 @@
"""
+from alembic import op
+import elixir
import sqlalchemy as sa
-from alembic import op
+from nagare import database, local, security
+
+from kansha.board.boardsmanager import BoardsManager
+from kansha.security import SecurityManager
+from kansha.services.dummyassetsmanager.dummy... |
19ce6528a722deec9f0080c229c329e15b843614 | src/pyqa.py | src/pyqa.py | def main():
pass
if __name__ == '__main__':
main()
| from __future__ import with_statement
import yaml
def load_file(source):
with open(source) as f:
return map(lambda a: a, yaml.load_all(f))
def main():
pass
if __name__ == '__main__':
main()
| Make it possible to load questions | Make it possible to load questions
| Python | mit | bebraw/pyqa | ---
+++
@@ -1,3 +1,10 @@
+from __future__ import with_statement
+import yaml
+
+def load_file(source):
+ with open(source) as f:
+ return map(lambda a: a, yaml.load_all(f))
+
def main():
pass
|
5fc393a96cb580b7c4ec617cdc33f1e9ccbbb1c6 | core/descriptives.py | core/descriptives.py | from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['cr... | from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['cr... | Refactor timeline method call to use kwargs | Refactor timeline method call to use kwargs
| Python | mit | HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core | ---
+++
@@ -32,7 +32,7 @@
for name, count in counter.items():
print( '-', name, count )
- return timeline.create_timeline( data )
+ return timeline.create_timeline( datasets = [data] )
if __name__ == '__main__': |
28bc35bc8ed2646faf0d6662b54a5324c0fd1e31 | pspec/cli.py | pspec/cli.py | """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
arguments = docopt(__doc__)
paths = arguments['<path>']
if not paths:
... | """
Python testing for humans.
Usage: pspec [<path>...]
Options:
-h --help show this
"""
from attest.hook import AssertImportHook
from docopt import docopt
import os
import sys
from .collectors import PSpecTests
def main():
# When run as a console script (i.e. ``pspec``), the CWD isn't
# ``sys.path[0]`... | Put CWD at start of sys.path | Put CWD at start of sys.path
| Python | bsd-3-clause | bfirsh/pspec | ---
+++
@@ -14,6 +14,12 @@
from .collectors import PSpecTests
def main():
+ # When run as a console script (i.e. ``pspec``), the CWD isn't
+ # ``sys.path[0]``, but it should be.
+ cwd = os.getcwd()
+ if sys.path[0] not in ('', cwd):
+ sys.path.insert(0, cwd)
+
arguments = docopt(__doc__)
... |
6e9e6c0fbba6b1f6e97c40181ec58c55e4980995 | pyipmi/fw.py | pyipmi/fw.py | """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
class FWDownloadResult(object):
"""Object to ho... | """FW records
"""
class FWInfo(object):
"""Object to hold device-reported SPI flash table"""
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
def __eq__(self, other):
if isinstance(o... | Add equality operator to FWInfo | Add equality operator to FWInfo
| Python | bsd-3-clause | Cynerva/pyipmi,emaadmanzoor/pyipmi | ---
+++
@@ -8,6 +8,16 @@
def __str__(self):
return "%s | %s | %s | %s | %s" % (self.slot, self.type, self.offset,
self.size, self.flags)
+
+ def __eq__(self, other):
+ if isinstance(other, self.__class__):
+ return (self.slot == other.slot... |
c870f68c77652a11f8401bbbb981797694174288 | src/py/crankshaft/setup.py | src/py/crankshaft/setup.py |
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Se... |
"""
CartoDB Spatial Analysis Python Library
See:
https://github.com/CartoDB/crankshaft
"""
from setuptools import setup, find_packages
setup(
name='crankshaft',
version='0.0.0',
description='CartoDB Spatial Analysis Python Library',
url='https://github.com/CartoDB/crankshaft',
author='Data Se... | Revert "Declare scipy as dep" | Revert "Declare scipy as dep"
This reverts commit 1e8bc12e0a6ea2ffefe580b63133b88f4db045a7.
| Python | bsd-3-clause | CartoDB/crankshaft,CartoDB/crankshaft | ---
+++
@@ -40,9 +40,9 @@
# The choice of component versions is dictated by what's
# provisioned in the production servers.
- install_requires=['scipy==0.17.1', 'pysal==1.9.1', 'scikit-learn==0.17.1'],
+ install_requires=['pysal==1.9.1', 'scikit-learn==0.17.1'],
- requires=['scipy', 'pysal', 'n... |
ff800f11b948808e4574ec3a893ed4e259707dcf | stubs/python2-urllib2/run.py | stubs/python2-urllib2/run.py | import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except ssl.Cert... | import sys
import ssl
import urllib2
if len(sys.argv) < 3 or len(sys.argv) > 4:
exit("Usage: %s <HOST> <PORT> [CA_FILE]" % sys.argv[0])
host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
except getattr(... | Make python2-urllib2 compatible with more Python 2.7 versions | Make python2-urllib2 compatible with more Python 2.7 versions
Try to catch ssl.CertificateError only if CertificateError is
defined. Otherwise bail out by effectively doing a dummy
"catch ():".
| Python | mit | ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls | ---
+++
@@ -11,7 +11,7 @@
try:
urllib2.urlopen("https://" + host + ":" + port, cafile=cafile)
-except ssl.CertificateError:
+except getattr(ssl, "CertificateError", ()):
print("REJECT")
except urllib2.URLError as exc:
if not isinstance(exc.reason, ssl.SSLError): |
4f1354f6e917a4a90a56f3c2545aa678809334c3 | scripts/release/rethreshold_family.py | scripts/release/rethreshold_family.py | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 a... | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 a... | Add function to run rfsearch on the cluster | Add function to run rfsearch on the cluster
| Python | apache-2.0 | Rfam/rfam-production,Rfam/rfam-production,Rfam/rfam-production | ---
+++
@@ -31,7 +31,7 @@
rfam_acc: A valid Rfam accession
- return:
+ return: None
"""
cmd = "rfco.pl %s" % rfam_acc
@@ -42,6 +42,22 @@
# ----------------------------------------------------------------------------------
-if __name__== '__main__':
+def submit_new_rfsearch_job(family_d... |
76bda324fcd617677a3f107e6b7c162a81e88db9 | tests/test_vector2_negation.py | tests/test_vector2_negation.py | import pytest
from ppb_vector import Vector2
negation_data = (
(Vector2(1, 1), Vector2(-1, -1)),
(Vector2(2, -3), Vector2(-2, 3)),
(Vector2(-4, 18), Vector2(4, -18))
)
@pytest.mark.parametrize('test_vector, expected_result', negation_data)
def test_negation(test_vector, expected_result):
assert -te... | from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
@given(vector=vectors())
def test_negation_coordinates(vector: Vector2):
assert - vector.x == (- vector).x
assert - vector.y == (- vector).y
| Replace with an Hypothesis test | tests/negation: Replace with an Hypothesis test
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | ---
+++
@@ -1,15 +1,9 @@
-import pytest
+from hypothesis import given
from ppb_vector import Vector2
+from utils import vectors
-
-negation_data = (
- (Vector2(1, 1), Vector2(-1, -1)),
- (Vector2(2, -3), Vector2(-2, 3)),
- (Vector2(-4, 18), Vector2(4, -18))
-)
-
-
-@pytest.mark.parametrize('test_vector,... |
8bb60a82f903126068434df3a464cdde5d894d0c | serverless_helpers/__init__.py | serverless_helpers/__init__.py | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `path`
Usage: from your Lambda function, call load... | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import os
import logging
logger = logging.getLogger()
from dotenv import load_dotenv, get_key, set_key, unset_key
from cfn_detect import load_cfn_outputs
def load_envs(path):
"""Recursively load .env files starting from `... | Add logger to env loader | Add logger to env loader
| Python | mit | serverless/serverless-helpers-py | ---
+++
@@ -1,8 +1,11 @@
# -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
+import os
+import logging
+logger = logging.getLogger()
+
from dotenv import load_dotenv, get_key, set_key, unset_key
-
from cfn_detect import load_cfn_outputs
def load_envs(path): |
8dadb34bdfe6d85d3016a59a9441ed8a552d1149 | octane_fuelclient/octaneclient/commands.py | octane_fuelclient/octaneclient/commands.py | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... | from fuelclient.commands import base
from fuelclient.commands import environment as env_commands
from fuelclient.common import data_utils
class EnvClone(env_commands.EnvMixIn, base.BaseShowCommand):
"""Clone environment and translate settings to the given release."""
columns = env_commands.EnvShow.columns
... | Fix endpoint for clone operation | Fix endpoint for clone operation
| Python | apache-2.0 | stackforge/fuel-octane,Mirantis/octane,Mirantis/octane,stackforge/fuel-octane | ---
+++
@@ -20,7 +20,7 @@
def take_action(self, parsed_args):
new_env = self.client.connection.post_request(
- "clusters/{0}/changes".format(parsed_args.id),
+ "clusters/{0}/upgrade/clone".format(parsed_args.id),
{
'name': parsed_args.name,
... |
d0cc528f7e69422515ae1507b01266b1686d1452 | ddsc/sdk/__init__.py | ddsc/sdk/__init__.py | from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = [Client]
| from __future__ import absolute_import
from ddsc.sdk.client import Client
__all__ = ['Client']
| Fix sdk module all declaration | Fix sdk module all declaration
| Python | mit | Duke-GCB/DukeDSClient,Duke-GCB/DukeDSClient | ---
+++
@@ -1,3 +1,3 @@
from __future__ import absolute_import
from ddsc.sdk.client import Client
-__all__ = [Client]
+__all__ = ['Client'] |
e538f2862a875afc58071a9fc6419e4290f8b00d | rouver/types.py | rouver/types.py | from types import TracebackType
from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping, Optional, Type
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
_exc_info = Tuple[Optional[Type[BaseException]],
Optional... | from typing import \
Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping
from werkzeug.wrappers import Request
# (name, value)
Header = Tuple[str, str]
WSGIEnvironment = Dict[str, Any]
# (body) -> None
StartResponseReturnType = Callable[[bytes], None]
# (status: str, headers: List[Headers], exc_info) -> re... | Remove obsolete aliases and imports | Remove obsolete aliases and imports
| Python | mit | srittau/rouver | ---
+++
@@ -1,6 +1,5 @@
-from types import TracebackType
from typing import \
- Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping, Optional, Type
+ Callable, Tuple, Dict, Any, Iterable, Sequence, Mapping
from werkzeug.wrappers import Request
@@ -8,10 +7,6 @@
Header = Tuple[str, str]
WSGIEnvironm... |
e7724935ce4d07cd28a231c5e849be2a123a5502 | tools/encrypt.py | tools/encrypt.py | #!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
passphrase = getpass("Choose a passphrase: ")
verifypass = getpass("Re-enter passphrase: ")
if passphrase... | #!/usr/bin/env python
from __future__ import print_function
import hashlib
from getpass import getpass
import sys
from Cryptodome.Cipher import AES
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
import codecs
passphrase = getpass("Choose a passphrase: ").encode('utf-8')
verifypass = getpass("Re-e... | Update for Python 3 encoding | Update for Python 3 encoding
Fixes https://github.com/cranklin/crankycoin/issues/12 | Python | mit | cranklin/crankycoin | ---
+++
@@ -10,9 +10,10 @@
_PY3 = sys.version_info[0] > 2
if _PY3:
raw_input = input
+ import codecs
-passphrase = getpass("Choose a passphrase: ")
-verifypass = getpass("Re-enter passphrase: ")
+passphrase = getpass("Choose a passphrase: ").encode('utf-8')
+verifypass = getpass("Re-enter passphrase: ").e... |
e69962de56cb5eaa12f908a74edca4c225dcee9c | run-tests.py | run-tests.py | #!/usr/bin/python
import os;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def runNode(sourceFilename, destinationFilename, markupFilename):
markup = readMarkupFile(markupFilename);
cmd... | #!/usr/bin/python
import os;
import subprocess;
import glob;
import re as regex;
testDirectory = "./test/";
def readMarkupFile(markupFilename):
f = open(markupFilename, 'r');
markup = f.read();
return markup;
def compareOutputs(oracleFilename, destinationFilename):
metric = "mae";
cmd = ["gm","compar... | Add automated 'gm compare' invocation | Add automated 'gm compare' invocation
| Python | mit | iFixit/node-markup,iFixit/node-markup,iFixit/node-markup | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/python
import os;
+import subprocess;
import glob;
import re as regex;
@@ -10,6 +11,14 @@
f = open(markupFilename, 'r');
markup = f.read();
return markup;
+
+def compareOutputs(oracleFilename, destinationFilename):
+ metric = "mae";
+ cmd = ["gm","compare","-... |
e22360f13fd3b582e7b0898549f656a76a038306 | scripting.py | scripting.py | #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message, color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", *args, ... | #!/usr/bin/env python2
import os, shutil
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
print_warning(message + " Aborting...", ... | Fix a formatting error in print_error_and_die(). | Fix a formatting error in print_error_and_die().
| Python | mit | Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab | ---
+++
@@ -5,7 +5,7 @@
def print_warning(message, *args, **kwargs):
import colortext
if args or kwargs: message = message.format(*args, **kwargs)
- colortext.write(message, color='red')
+ colortext.write(message + '\n', color='red')
def print_error_and_die(message, *args, **kwargs):
print_wa... |
ccda4cd859b512d8694eba4261439bb52574f099 | cities/Sample_City.py | cities/Sample_City.py | from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
f... | from bs4 import BeautifulSoup
import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes thi... | Add geodata parsing to sample city file | Add geodata parsing to sample city file
| Python | mit | Mic92/ParkAPI,Mic92/ParkAPI,offenesdresden/ParkAPI,offenesdresden/ParkAPI | ---
+++
@@ -1,4 +1,5 @@
from bs4 import BeautifulSoup
+import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
@@ -15,3 +16,25 @@
# Do everything necessary to scrape the contents of the html
# into a dictionary of the format specified by the schema.
+
+
+d... |
fca9028a189b55e2c6b6775999e98c9d453477be | config.sample.py | config.sample.py | # -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash)
HOST_NAME = ''
# Google Analytics ID ... | # -*- coding: utf-8 -*-
import urllib
# -----------------------------
# RENAME THIS FILE TO config.py
# -----------------------------
# Flask debug mode. Always set False on production
DEBUG = True
# Disable Flask's swallowing of unhandled exceptions
PROPAGATE_EXCEPTIONS = True
# URL where the app is hosted e.g... | Add non-dangerous debugging option to config | Add non-dangerous debugging option to config
| Python | mit | raquo/hnapp,raquo/hnapp,raquo/hnapp | ---
+++
@@ -9,6 +9,10 @@
# Flask debug mode. Always set False on production
DEBUG = True
+
+
+# Disable Flask's swallowing of unhandled exceptions
+PROPAGATE_EXCEPTIONS = True
# URL where the app is hosted e.g. http://hnapp.com (without trailing slash) |
51029137cddaebeb3d84b7fa766c5e3914a02504 | multilingual_model/admin.py | multilingual_model/admin.py | import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationStackedInline(admin.StackedInline):
def __init__(self, *args, **kwargs):
super(TranslationStackedInline, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:... | import warnings
from django.contrib import admin
from .forms import TranslationFormSet
from . import settings
class TranslationInlineMixin(object):
def __init__(self, *args, **kwargs):
super(TranslationInlineMixin, self).__init__(*args, **kwargs)
if settings.AUTO_HIDE_LANGUAGE:
self... | Use a Mixin for Admin inlines; less code duplication. | Use a Mixin for Admin inlines; less code duplication.
| Python | agpl-3.0 | dokterbob/django-multilingual-model | ---
+++
@@ -6,9 +6,9 @@
from . import settings
-class TranslationStackedInline(admin.StackedInline):
+class TranslationInlineMixin(object):
def __init__(self, *args, **kwargs):
- super(TranslationStackedInline, self).__init__(*args, **kwargs)
+ super(TranslationInlineMixin, self).__init__(*arg... |
5e4b9c8c056f16613440c92945fe25e75c952b79 | src/boarbot/modules/groups/cmd.py | src/boarbot/modules/groups/cmd.py | import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise ... | import argparse
from boarbot.common.log import LOGGER
class GroupsParserException(Exception): pass
class GroupsParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
LOGGER.warn('GroupsParser.exit called with %s %s' % (status, message))
def error(self, message: str):
raise ... | Add group list command to docs | Add group list command to docs
| Python | mit | fsufitch/discord-boar-bot,fsufitch/discord-boar-bot | ---
+++
@@ -12,7 +12,7 @@
raise GroupsParserException(message)
GROUPS_PARSER = GroupsParser(prog='!groups', description='Manage server "ping" groups', add_help=False)
-GROUPS_PARSER.add_argument('command', metavar='CMD', type=str, nargs='?', default='<no command>', help='group command (create | delete | j... |
c362d5477eb2bcd8720149c84e2a0f8578975fb7 | tests/test_file.py | tests/test_file.py | # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_fi... | # -*- coding: utf-8 -*-
from blox.file import File
from pytest import raises_regexp
class TestFile(object):
def test_mode(self, tmpfile):
raises_regexp(ValueError, 'invalid mode', File, tmpfile, 'foo')
assert File(tmpfile).mode == 'r'
assert File(tmpfile, 'w').mode == 'w'
def test_fi... | Fix exception type in a test | Fix exception type in a test
| Python | mit | aldanor/blox | ---
+++
@@ -15,5 +15,5 @@
assert File(tmpfile).filename == tmpfile
def test_create_dataset(self, tmpfile):
- raises_regexp(ValueError, 'file is not writable',
+ raises_regexp(IOError, 'file is not writable',
File(tmpfile).create_dataset, 'a', []) |
3e20365624f02b70d8332ba7ff7da23961337f86 | quickstart/python/understand/example-3/create_joke_samples.6.x.py | quickstart/python/understand/example-3/create_joke_samples.6.x.py | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a j... | # Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
phrases = [
'Tell me a j... | Update samples creation for intent rename | Update samples creation for intent rename
Update intent --> task, code comment | Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | ---
+++
@@ -22,10 +22,11 @@
]
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/autopilot/list
+# Replace 'UDXXX...' with the SID for the task you just created.
for phrase in phrases:
sample = client.preview.understand \
.assistants('UAXXXXXXXXX... |
9144e6011df4aebd74db152dad2bb07a8eebf6ee | setup_egg.py | setup_egg.py | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
execfile('setup.py', dict(__name__='__main__',
__file__='setup.py', # need... | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
exec('setup.py', dict(__name__='__main__',
__file__='setup.py', # needed in se... | Use `exec` instead of `execfile`. | Use `exec` instead of `execfile`.
| Python | bsd-3-clause | FrancoisRheaultUS/dipy,FrancoisRheaultUS/dipy | ---
+++
@@ -4,6 +4,6 @@
"""Wrapper to run setup.py using setuptools."""
if __name__ == '__main__':
- execfile('setup.py', dict(__name__='__main__',
- __file__='setup.py', # needed in setup.py
- force_setuptools=True))
+ exec('setup.py', dict(__name__... |
27557975023003e2d56943221f422a148cb0efa2 | models/scorefeedback.py | models/scorefeedback.py | from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(10, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_ke... | from models.basemodel import BaseModel
from peewee import CharField, DateTimeField
ALLOWED_VERDICTS = (
'NOT_AN_EXPL',
'VIOLATION',
'NOT_IMPRESSED',
'GOOD',
'EXACT',
)
class ScoreFeedback(BaseModel):
verdict = CharField(20, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_ke... | Fix verdict field max length | Fix verdict field max length
| Python | mit | hatbot-team/hatbot,hatbot-team/hatbot,hatbot-team/hatbot,hatbot-team/hatbot | ---
+++
@@ -11,6 +11,6 @@
class ScoreFeedback(BaseModel):
- verdict = CharField(10, choices=ALLOWED_VERDICTS)
+ verdict = CharField(20, choices=ALLOWED_VERDICTS)
timestamp = DateTimeField()
expl_key = CharField(50) |
f800d11aa5a198fcb2193773b30e4e066a226321 | code/handle-output.py | code/handle-output.py | import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
| import synthetic_data_experiments as sde
import logging
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
for repeat_idx in xrange(args.num_repeats) :
resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx)
data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
... | Set resu dir and data dir | Set resu dir and data dir
| Python | mit | chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan,chagaz/sfan | ---
+++
@@ -4,3 +4,9 @@
if __name__ == "__main__":
args = sde.get_integrous_arguments_values()
+ for repeat_idx in xrange(args.num_repeats) :
+
+ resu_dir = "%s/repeat_%d" % (args.resu_dir, repeat_idx)
+ data_dir = '%s/repeat_%d' % (args.data_dir, repeat_idx)
+
+ |
2fe315e1753aca8215228091e3a64af057020bc2 | celery/loaders/__init__.py | celery/loaders/__init__.py | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loa... | import os
from celery.loaders.djangoapp import Loader as DjangoLoader
from celery.loaders.default import Loader as DefaultLoader
from django.conf import settings
from django.core.management import setup_environ
"""
.. class:: Loader
The current loader class.
"""
Loader = DefaultLoader
if settings.configured:
Loa... | Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command. | Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
| Python | bsd-3-clause | frac/celery,WoLpH/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,cbrepo/celery,ask/celery | ---
+++
@@ -14,24 +14,32 @@
if settings.configured:
Loader = DjangoLoader
else:
- if not callable(getattr(os, "fork", None)):
- # Platform doesn't support fork()
- # XXX On systems without fork, multiprocessing seems to be launching
- # the processes in some other way which does not cop... |
7d130a447786c61c7bfbe6bfe2d87b2c28e32eb6 | shut-up-bird.py | shut-up-bird.py | #!/usr/bin/env python
#
from __future__ import print_function
import os
import sys
import argparse
import logging
| #!/usr/bin/env python
from __future__ import print_function
import os
import sys
import argparse
import json
import tweepy
import pystache
import webbrowser
CONFIG_FILE = '.shut-up-bird.conf'
def tweep_login(consumer_key, consumer_secret, token='', secret=''):
auth = tweepy.OAuthHandler(consumer_key, consumer_se... | Add OAuth authentication and config settings load/save | Add OAuth authentication and config settings load/save
| Python | mit | petarov/shut-up-bird | ---
+++
@@ -1,7 +1,86 @@
#!/usr/bin/env python
-#
+
from __future__ import print_function
import os
import sys
import argparse
-import logging
+import json
+import tweepy
+import pystache
+import webbrowser
+
+CONFIG_FILE = '.shut-up-bird.conf'
+
+def tweep_login(consumer_key, consumer_secret, token='', secret='... |
f2a31c4a203d06fd83086f3789e52be94320c691 | tests/test_utils/__init__.py | tests/test_utils/__init__.py | import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
self.app = app.app.test_client()
configobj.backup()
def tearDown(self):
configobj.restore()
super(Test... | import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "deployment"))
import fix_paths
import requests
import unittest
from flask_app import app
from config import configobj
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self).setUp()
config... | Fix tests for new deployment | Fix tests for new deployment
| Python | mit | getslash/mailboxer,getslash/mailboxer,getslash/mailboxer,vmalloc/mailboxer,vmalloc/mailboxer,vmalloc/mailboxer | ---
+++
@@ -1,3 +1,7 @@
+import sys
+import os
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "deployment"))
+import fix_paths
import requests
import unittest
from flask_app import app
@@ -6,8 +10,9 @@
class TestCase(unittest.TestCase):
def setUp(self):
super(TestCase, self)... |
7f9c9b947948654d7557aa0fcfbb1c015521da9b | tests/modular_templates/routing.py | tests/modular_templates/routing.py | import unittest
from framework.routing import Rule
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', vf),... | import unittest
from framework.routing import Rule, json_renderer
class RuleTestCase(unittest.TestCase):
def _make_rule(self, **kwargs):
def vf():
return {}
return Rule(
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('v... | Fix RuleTestCase -> tests passing | Fix RuleTestCase -> tests passing
| Python | apache-2.0 | caneruguz/osf.io,brandonPurvis/osf.io,rdhyee/osf.io,KAsante95/osf.io,pattisdr/osf.io,KAsante95/osf.io,barbour-em/osf.io,HarryRybacki/osf.io,mluke93/osf.io,aaxelb/osf.io,jinluyuan/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,sbt9uc/osf.io,ticklemepierce/osf.io,jnayak1/osf.io,caseyrygt/osf.io,kwierman/osf.io,adlius/osf.io... | ---
+++
@@ -1,5 +1,5 @@
import unittest
-from framework.routing import Rule
+from framework.routing import Rule, json_renderer
class RuleTestCase(unittest.TestCase):
@@ -12,7 +12,7 @@
kwargs.get('routes', ['/', ]),
kwargs.get('methods', ['GET', ]),
kwargs.get('view_func', ... |
507b8bb0910ef6fae9c7d9cb1405a33c4e4b6e8e | synapse/config/password.py | synapse/config/password.py | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Add comment to prompt changing of pepper | Add comment to prompt changing of pepper
| Python | apache-2.0 | matrix-org/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,TribeMedia/synapse,TribeMedia/synapse,TribeMedia/synapse,TribeMedia/synapse,matrix-org/synapse,matrix-org/synapse | ---
+++
@@ -31,6 +31,7 @@
password_config:
enabled: true
# Uncomment for extra security for your passwords.
+ # Change to a secret random string.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyF... |
389679c0fc575bb03bfa4e625de16eb7ed9c3a04 | testdoc/formatter.py | testdoc/formatter.py | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class ... | """Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class ... | Put a blank line before section headings, courtesy spiv. | Put a blank line before section headings, courtesy spiv.
| Python | mit | testing-cabal/testdoc | ---
+++
@@ -20,6 +20,7 @@
self.writeln('= %s =\n' % (name,))
def section(self, name):
+ self.writeln('')
self.writeln('== %s ==\n' % (name,))
def subsection(self, name): |
20ed56d04f029fa4121b23db94dda19167fd054e | uchicagohvz/production_settings.py | uchicagohvz/production_settings.py | from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'pos... | from local_settings import *
DEBUG = False
ALLOWED_HOSTS = ['uchicagohvz.org']
ADMINS = (
('Administrator', 'admin@uchicagohvz.org'),
)
SERVER_EMAIL = 'noreply@uchicagohvz.org'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'pos... | Change over to local email server in production | Change over to local email server in production
| Python | mit | kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz | ---
+++
@@ -30,7 +30,8 @@
# Mandrill email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
-EMAIL_HOST = 'smtp.mandrillapp.com'
-from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
-EMAIL_PORT = '587'
-EMAIL_USE_TLS = True
+#from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD
+#EM... |
30b6d886670b7ba65aee9b130ec50d577c778649 | run_server.py | run_server.py | #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
... | #!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
... | Add a message with a socket on server start | Add a message with a socket on server start
| Python | mit | bondarevts/flucalc,bondarevts/flucalc,bondarevts/flucalc | ---
+++
@@ -18,6 +18,7 @@
if arg.isdigit():
port = int(arg)
+ print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), s... |
dc09143973640b2873dae7434ce654535fbfdd8c | qtpy/tests/test_qtwebenginewidgets.py | qtpy/tests/test_qtwebenginewidgets.py | from __future__ import absolute_import
import pytest
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
from qtpy import QtWebEngineWidgets
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.Q... | from __future__ import absolute_import
import pytest
from qtpy import QtWebEngineWidgets
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
assert QtWebEngineWidgets.QWebEnginePage is not None
assert QtWebEngineWidgets.QWebEngineView is not None
assert QtWebEngineWidgets.QWebE... | Fix failing tests in Python 2 | Tesitng: Fix failing tests in Python 2
| Python | mit | goanpeca/qtpy,goanpeca/qtpy,davvid/qtpy,spyder-ide/qtpy,davvid/qtpy | ---
+++
@@ -1,11 +1,11 @@
from __future__ import absolute_import
import pytest
+from qtpy import QtWebEngineWidgets
def test_qtwebenginewidgets():
"""Test the qtpy.QtWebSockets namespace"""
- from qtpy import QtWebEngineWidgets
assert QtWebEngineWidgets.QWebEnginePage is not None
assert Q... |
722b588629fa0986e8d7c06ff135d81c08ad8fab | tensorflow_datasets/object_detection/waymo_open_dataset_test.py | tensorflow_datasets/object_detection/waymo_open_dataset_test.py | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... | # coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... | Add doc string for waymo open dataset | Add doc string for waymo open dataset | Python | apache-2.0 | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets | ---
+++
@@ -13,7 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""TODO(waymo_open_dataset): Add a description here."""
+# Lint as: python3
+"""Test for waymo_open_dataset."""
from __future__ import absolute_import
from __future__ import divisi... |
3d83904e409eecfd44b0c0ca053f78da5c9c89a4 | tests/test-vext-cmdline.py | tests/test-vext-cmdline.py | import unittest
from vext.cmdline import do_check
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
if __name__ == "__main__":
unittest.main()
| import unittest
from vext.cmdline import do_check, do_status
class TestVextCommandLineHelpers(unittest.TestCase):
def test_do_check(self):
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
def test_do_status(self):
# Stub check: verifies no exceptions are thrown.
... | Add stub test for do_status | Add stub test for do_status
| Python | mit | stuaxo/vext | ---
+++
@@ -1,6 +1,6 @@
import unittest
-from vext.cmdline import do_check
+from vext.cmdline import do_check, do_status
class TestVextCommandLineHelpers(unittest.TestCase):
@@ -8,6 +8,12 @@
# Stub check: verifies no exceptions are thrown.
do_check(["*"])
+ def test_do_status(self):
+ ... |
35a7e3e892135d805dfe73b8ce66f986651354f5 | tests/test_gutenbergweb.py | tests/test_gutenbergweb.py | from nose import *
import gutenberweb
def test_foo():
print "BAR"
if __name__ == "__main__":
main()
| import gutenbrowse.gutenbergweb as gutenbergweb
def test_search_author():
r = gutenbergweb.search(author='Nietzsche')
assert len(r) >= 4, r
assert any(eid == 19634 for eid,au,tt,lng in r), r
assert all(isinstance(eid, int) and isinstance(au, unicode)
and isinstance(tt, unicode) and isins... | Add proper tests for gutenbergweb | Add proper tests for gutenbergweb
| Python | bsd-3-clause | pv/mgutenberg,pv/mgutenberg | ---
+++
@@ -1,10 +1,35 @@
-from nose import *
+import gutenbrowse.gutenbergweb as gutenbergweb
-import gutenberweb
+def test_search_author():
+ r = gutenbergweb.search(author='Nietzsche')
+ assert len(r) >= 4, r
+ assert any(eid == 19634 for eid,au,tt,lng in r), r
+ assert all(isinstance(eid, int) and i... |
c1928c65c308410205ff89a4be8910cd54614be0 | bbb/adc.py | bbb/adc.py | """Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysfs = glob.g... | """Access ADCs vias SysFS interface."""
import glob
class ADC(object):
def __init__(self, num, repeat=8, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
# TODO: Verify num is reasonable (0-6)
self.sysf... | Add repeat support when reading ADC values. | Add repeat support when reading ADC values.
- There is a bug in the ADC driver which allows reads to return stale or
otherwise incorrect readings. Though there doesn't appear to be a
guaranteed minimum count, repeating the read a number of times will
eventually yeild the correct value.
- Object initializtion no... | Python | mit | IEEERobotics/pybbb | ---
+++
@@ -5,25 +5,30 @@
class ADC(object):
- def __init__(self, num, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
+ def __init__(self, num, repeat=8, base_filename='/sys/devices/ocp.*/helper.*/AIN'):
self.num = num
# Need to read a glob here, since numbering is not consistent
... |
730aaf64635268df8d3c5cd3e1d5e2448644c907 | problem-static/Intro-Eval_50/admin/eval.py | problem-static/Intro-Eval_50/admin/eval.py | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def... | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def... | Make Intro Eval use input instead of raw_input | Make Intro Eval use input instead of raw_input
| Python | mit | james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF | ---
+++
@@ -21,11 +21,10 @@
print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
try:
- command = str(raw_input("What would you like to do? "))
- result = str(eval(command))
- print "This is the result:... |
4b687d702face412330580ed88f71c897dfa5e6a | nipy/core/image/__init__.py | nipy/core/image/__init__.py | """
The L{Image<image.Image>} class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
Class structure::
Application Level
TODO: I think this graph is unnecessary and wrong after removing
BaseImage, JT
-----------------... | """
The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
"""
__docformat__ = 'restructuredtext'
import image, roi, generators
from image import Image
from nipy.testing import Tester
test = Tester().test
bench = Tester... | Remove old doc. Import Image into core.image | Remove old doc. Import Image into core.image | Python | bsd-3-clause | bthirion/nipy,arokem/nipy,alexis-roche/register,alexis-roche/nireg,alexis-roche/register,arokem/nipy,nipy/nipy-labs,arokem/nipy,alexis-roche/niseg,alexis-roche/nipy,alexis-roche/nipy,alexis-roche/nireg,nipy/nireg,alexis-roche/register,bthirion/nipy,arokem/nipy,alexis-roche/niseg,nipy/nireg,bthirion/nipy,alexis-roche/ni... | ---
+++
@@ -1,37 +1,13 @@
"""
-The L{Image<image.Image>} class provides the interface which should be used
+The Image class provides the interface which should be used
by users at the application level. The image provides a coordinate map,
and the data itself.
-
-Class structure::
-
- Application Level
-
-TODO... |
b682ff69d5cbfa0529e4d231d5337be7f8fbfaf4 | non_logged_in_area/views.py | non_logged_in_area/views.py | # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__n... | # coding=utf-8
import logging
from django.db.models.aggregates import Count
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
from django.urls import reverse
from organizations.models import Facility
from places.models import Region
logger = logging.getLogger(__n... | Add filter do not display facilities without shifts | Add filter do not display facilities without shifts
| Python | agpl-3.0 | coders4help/volunteer_planner,christophmeissner/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_planner,volunteer-planner/volunteer_planner,christophmeissner/volunteer_planner,volunteer-planner/volunteer_planner,pitpalme/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_p... | ---
+++
@@ -26,7 +26,12 @@
context['regions'] = Region.objects.annotate(
facility_count=Count('areas__places__facilities')).exclude(
facility_count=0).prefetch_related('areas', 'areas__region').all()
- context['facilities'] = Facility.objects.select_related('place',
+ ... |
13c6748313e1114853a45e25bcc8135a8b5f5240 | slowpoke/decorator.py | slowpoke/decorator.py | # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
settings.CURRENT_SLOWPOKE_STANDARD = standard
... | # modified from http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods
import time
from django.conf import settings
from slowpoke.models import *
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
self.CURRENT_SLOWPOKE_STANDARD = standard
d... | Store the standard on the class, not in settings - or else it's captured incorrectly as things process. | Store the standard on the class, not in settings - or else it's captured incorrectly as things process. | Python | bsd-3-clause | adamfast/django-slowpoke | ---
+++
@@ -9,7 +9,7 @@
class time_my_test(object):
def __init__(self, standard, *args, **kwargs):
- settings.CURRENT_SLOWPOKE_STANDARD = standard
+ self.CURRENT_SLOWPOKE_STANDARD = standard
def __call__(self, func):
@@ -22,7 +22,7 @@
sr = TestSuiteRun.objects.using('slowpo... |
2995accb21d9b8c45792d12402470cfcf322d6a1 | models/phase3_eval/process_sparser.py | models/phase3_eval/process_sparser.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170210')
def get_file_names(base_dir):
fnames ... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames ... | Update Sparser script for phase3 | Update Sparser script for phase3
| Python | bsd-2-clause | johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy | ---
+++
@@ -5,7 +5,7 @@
from indra import sparser
base_folder = os.path.join(os.environ['HOME'],
- 'data/darpa/phase3_eval/sources/sparser-20170210')
+ 'data/darpa/phase3_eval/sources/sparser-20170330')
def get_file_names(base_dir):
fnames = glob.glob(os... |
f758513880cca46937833779ddf099b2ac88afc9 | utilities/ticker-update.py | utilities/ticker-update.py | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = "ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities
def u... | import requests
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list():
with open(CONF_FILE, "r") as conf_file:
securities = conf_file.readlines()
securities = [s.strip() for s in securities]
return securities... | Fix config PATH for windows batch file | Fix config PATH for windows batch file | Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various | ---
+++
@@ -2,7 +2,7 @@
from bs4 import BeautifulSoup
URL = 'https://finance.yahoo.com/quote/'
-CONF_FILE = "ticker-updates.conf"
+CONF_FILE = r"G:\system\ticker-updates.conf"
def get_securities_list(): |
3ffaf00e18208a1877c3d2286ba284071d5d3e09 | wafer/pages/serializers.py | wafer/pages/serializers.py | from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
class Meta:
model = Page
exclude = ('_content_rendered',)
@revisions.create_revision()
def create(self, validated_data):
... | from django.contrib.auth import get_user_model
from rest_framework import serializers
from reversion import revisions
from wafer.pages.models import Page
class PageSerializer(serializers.ModelSerializer):
people = serializers.PrimaryKeyRelatedField(
many=True, allow_null=True,
queryset=get_user... | Add people and other fields to page update options | Add people and other fields to page update options
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | ---
+++
@@ -1,3 +1,5 @@
+from django.contrib.auth import get_user_model
+
from rest_framework import serializers
from reversion import revisions
@@ -5,6 +7,10 @@
class PageSerializer(serializers.ModelSerializer):
+
+ people = serializers.PrimaryKeyRelatedField(
+ many=True, allow_null=True,
+ ... |
3570f3a1681cf2b5ad1ba31026ae9d13fcc3e9c2 | test_base.py | test_base.py | import pytest
from pynoaa import PyNOAA
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = startdate, locationid =... | import pytest
from pynoaa import PyNOAA
from time import sleep
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
['1994-05-20',None],
[None,['FIPS:36','FIPS:37']],
))
def test_datasets(startdate, locationid):
datasets = noaa.datasets(limit = 1, startdate = ... | Add some sleep in tests to not exceed allowed request limits | Add some sleep in tests to not exceed allowed request limits
| Python | mit | lincis/pynoaa | ---
+++
@@ -1,5 +1,6 @@
import pytest
from pynoaa import PyNOAA
+from time import sleep
noaa = PyNOAA("KEQrNcMDIrZMyWtDslGKEkgETXbgIvjZ")
@pytest.mark.parametrize('startdate,locationid',(
@@ -11,6 +12,7 @@
results = datasets["results"]
assert datasets["metadata"]["resultset"]["limit"] == 1
assert... |
ef2f5bf541ab2938f19b11c0845610ccce5e496e | test/__init__.py | test/__init__.py | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | # Copyright (C) 2014 SEE AUTHORS FILE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | Make unit tests run on RHEL boxes better via the python-unittest2 library | Make unit tests run on RHEL boxes better via the python-unittest2 library
| Python | agpl-3.0 | pombredanne/re-core,RHInception/re-core | ---
+++
@@ -13,7 +13,12 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-import unittest
+import platform
+(major, minor, patch) = platform.python_version_tuple()
+if int(major) == 2 and int(minor) < 7:
+ impo... |
6d52364c44cf7244b920d04fe6f5917cd99b7377 | linkatos/utils.py | linkatos/utils.py | import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no r... | import re
yes_re = re.compile("(\s|^)(Yes|YES|yes)(\s|[,.]|$)")
no_re = re.compile("(\s|^)(No|NO|no)(\s|[,.]|$)")
def has_a_yes(message):
"""
Returns True if it matches the yes regex
"""
return yes_re.search(message) is not None
def has_a_no(message):
"""
Returns True if it matches the no r... | Add back is_fresh_url which was deleted by mistake | fix: Add back is_fresh_url which was deleted by mistake
| Python | mit | iwi/linkatos,iwi/linkatos | ---
+++
@@ -44,3 +44,7 @@
'channel' in message['item'] and \
'user' in message and \
'item_user' in message)
+
+
+def is_fresh_url(expecting_confirmation, message_type):
+ return (not expecting_confirmation) and message_type is 'url' |
f6d17ba769357ad0dfb8766728349d0fce60efe8 | Bookie/fabfile/development.py | Bookie/fabfile/development.py | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
bootstrap_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.p... | """Fabric commands useful for working on developing Bookie are loaded here"""
import os
from fabric.api import hosts
from fabric.api import local
from fabric.contrib.project import rsync_project
upload_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
... | Add fab functions to build the chrome extension and upload to bmark.us | Add fab functions to build the chrome extension and upload to bmark.us
| Python | agpl-3.0 | bookieio/Bookie,wangjun/Bookie,charany1/Bookie,pombredanne/Bookie,wangjun/Bookie,GreenLunar/Bookie,charany1/Bookie,teodesson/Bookie,charany1/Bookie,teodesson/Bookie,wangjun/Bookie,adamlincoln/Bookie,pombredanne/Bookie,wangjun/Bookie,skmezanul/Bookie,teodesson/Bookie,bookieio/Bookie,GreenLunar/Bookie,bookieio/Bookie,ada... | ---
+++
@@ -5,9 +5,15 @@
from fabric.api import local
from fabric.contrib.project import rsync_project
-bootstrap_host = 'ubuntu@bmark'
+upload_host = 'ubuntu@bmark'
bootstrap_server = '/var/www/bootstrap.py'
bootstrap_local = 'scripts/bootstrap/bootstrap.py'
+
+chrome_bin = '/usr/bin/google-chrome'
+chrome_pat... |
e811b1ca77f7b8ae090be369fd89d4fe8c7c3f6e | test/functional/rpc_deprecated.py | test/functional/rpc_deprecated.py | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
# from... | #!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
clas... | Add a test for the banscore deprecation | Add a test for the banscore deprecation
Summary: This is what the `rpc_deprecated.py` test is for.
Test Plan:
./test/functional/test_runner.py rpc_deprecated
Reviewers: #bitcoin_abc, majcosta
Reviewed By: #bitcoin_abc, majcosta
Differential Revision: https://reviews.bitcoinabc.org/D8915
| Python | mit | Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc | ---
+++
@@ -4,14 +4,13 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test deprecation of RPC calls."""
from test_framework.test_framework import BitcoinTestFramework
-# from test_framework.util import assert_raises_rpc_error
class DeprecatedRpcTest(BitcoinTestFramework):
def... |
3a7f9520fce968d8292581caf6b94a6ce833b335 | migrations/versions/51775a13339d_patch_hash_column.py | migrations/versions/51775a13339d_patch_hash_column.py | """patch hash column
Revision ID: 51775a13339d
Revises: 016f138b2da8
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('... | """patch hash column
Revision ID: 51775a13339d
Revises: 187eade64ef0
Create Date: 2016-06-17 13:46:10.921685
"""
# revision identifiers, used by Alembic.
revision = '51775a13339d'
down_revision = '187eade64ef0'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('revision', sa.Column('... | Fix revision number in comment | Fix revision number in comment
Summary:
The revision number in the comment of the alembic revision didn't
match the actual revision number.
Reviewers: amandine, paulruan
Reviewed By: paulruan
Subscribers: changesbot, kylec
Differential Revision: https://tails.corp.dropbox.com/D209280
| Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes | ---
+++
@@ -1,7 +1,7 @@
"""patch hash column
Revision ID: 51775a13339d
-Revises: 016f138b2da8
+Revises: 187eade64ef0
Create Date: 2016-06-17 13:46:10.921685
""" |
ce86f13553e97e3e86f8c07bf09228895aacd3c5 | scripts/master/factory/syzygy_commands.py | scripts/master/factory/syzygy_commands.py | # Copyright (c) 2011 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.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps impor... | # Copyright (c) 2011 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.
"""Set of utilities to add commands to a buildbot factory.
This is based on commands.py and adds Syzygy-specific commands."""
from buildbot.steps impor... | Fix typos and paths broken in previous CL. | Fix typos and paths broken in previous CL.
Review URL: http://codereview.chromium.org/7085037
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@87249 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -24,12 +24,14 @@
def AddRandomizeChromeStep(self, timeout=600):
# Randomization script path.
- script_path = self.PathJoin('internal', 'build', 'randomize_chrome.py')
+ script_path = self.PathJoin(self._build_dir, 'internal', 'build',
+ 'randomize_chrome.py'... |
c94b8ce6bc451fbc0740120e0cf6e6680e97f69c | src/settings.py | src/settings.py | DEBUG = True
STOPS = [
{'line_name':'12', 'stop_id':'14657', 'stop_name':'Folsom St & 3rd St'},
{'line_name':'10', 'stop_id':'13009', 'stop_name':'2nd St & Harrison St'},
{'line_name':'8X', 'stop_id':'13723', 'stop_name':'Bryan St & 4th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobu... | DEBUG = True
STOPS = [
{'line_name':'KT', 'stop_id':'17361', 'stop_name':'KT Inbound'},
{'line_name':'22', 'stop_id':'16657', 'stop_name':'Tennessee St & 18th St'},
]
# Each dict in STOPS is:
# line_name - id from http://proximobus.appspot.com/agencies/sf-muni/routes.json
# stop_id - id from http://proximobus.a... | Update stops for new office | Update stops for new office
| Python | mit | albertyw/wilo,albertyw/wilo,albertyw/wilo,albertyw/wilo,albertyw/wilo | ---
+++
@@ -1,8 +1,7 @@
DEBUG = True
STOPS = [
- {'line_name':'12', 'stop_id':'14657', 'stop_name':'Folsom St & 3rd St'},
- {'line_name':'10', 'stop_id':'13009', 'stop_name':'2nd St & Harrison St'},
- {'line_name':'8X', 'stop_id':'13723', 'stop_name':'Bryan St & 4th St'},
+ {'line_name':'KT', 'stop_id':... |
49d7260f2454693c511a0f5124f412e987454dba | matches/models.py | matches/models.py | from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models... | from django.contrib.auth.models import User
from django.db import models
from promotions.models import Promotion
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
clas... | Add name and promotion to Card. | Add name and promotion to Card.
| Python | agpl-3.0 | OddBloke/moore | ---
+++
@@ -1,6 +1,7 @@
from django.contrib.auth.models import User
from django.db import models
+from promotions.models import Promotion
from wrestlers.models import WrestlingEntity
@@ -16,6 +17,9 @@
class Card(models.Model):
date = models.DateField()
+ promotion = models.ForeignKey(Promotion)
+
... |
dc1130766d356e1e9a613ba924e4af942631428c | distutils/tests/test_ccompiler.py | distutils/tests/test_ccompiler.py |
from distutils import ccompiler
def test_set_include_dirs(tmp_path):
"""
Extensions should build even if set_include_dirs is invoked.
In particular, compiler-specific paths should not be overridden.
"""
c_file = tmp_path / 'foo.c'
c_file.write_text('void PyInit_foo(void) {}\n')
compiler =... | import os
import sys
from distutils import ccompiler
def _make_strs(paths):
"""
Convert paths to strings for legacy compatibility.
"""
if sys.version_info > (3, 8):
return paths
return list(map(os.fspath, paths))
def test_set_include_dirs(tmp_path):
"""
Extensions should build e... | Add compatibility for Python 3.7 | Add compatibility for Python 3.7
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -1,5 +1,16 @@
+import os
+import sys
from distutils import ccompiler
+
+
+def _make_strs(paths):
+ """
+ Convert paths to strings for legacy compatibility.
+ """
+ if sys.version_info > (3, 8):
+ return paths
+ return list(map(os.fspath, paths))
def test_set_include_dirs(tmp_p... |
742ce33b0acc576aab72d625d2accc86a53b4023 | comrade/cronjobs/management/commands/cron.py | comrade/cronjobs/management/commands/cron.py | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
import cronjobs
import commonware.log
log = commonware.log.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts):... | import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from comrade import cronjobs
import logging
logger = logging.getLogger('comrade.cron')
class Command(BaseCommand):
help = 'Run a script, often a cronjob'
args = '[name args...]'
def handle(self, *args, **opts... | Fix import now that this is renamed. | Fix import now that this is renamed.
| Python | mit | bueda/django-comrade | ---
+++
@@ -2,10 +2,10 @@
from django.conf import settings
from django.core.management.base import BaseCommand
-import cronjobs
+from comrade import cronjobs
-import commonware.log
-log = commonware.log.getLogger('comrade.cron')
+import logging
+logger = logging.getLogger('comrade.cron')
class Command(BaseCo... |
1fd73a2c07ce66a8dba0ef08210612a2535538ea | jesusmtnez/python/koans/koans/about_decorating_with_functions.py | jesusmtnez/python/koans/koans/about_decorating_with_functions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_de... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutDecoratingWithFunctions(Koan):
def addcowbell(fn):
fn.wow_factor = 'COWBELL BABY!'
return fn
@addcowbell
def mediocre_song(self):
return "o/~ We all live in a broken submarine o/~"
def test_de... | Complete 'About Decorating with functions' koans | [Python] Complete 'About Decorating with functions' koans
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge | ---
+++
@@ -14,8 +14,8 @@
return "o/~ We all live in a broken submarine o/~"
def test_decorators_can_modify_a_function(self):
- self.assertRegex(self.mediocre_song(), __)
- self.assertEqual(__, self.mediocre_song.wow_factor)
+ self.assertRegex(self.mediocre_song(), "o/~ We all liv... |
97f59c20ca5bcb2388cada55044e0ab5bdc79669 | src/client/packaging/pypi/delphi_epidata/__init__.py | src/client/packaging/pypi/delphi_epidata/__init__.py | from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.0.12'
| from .delphi_epidata import Epidata
name = 'delphi_epidata'
__version__ = '0.1.0'
| Set self-reported python client version to 0.1.0 | Set self-reported python client version to 0.1.0 | Python | mit | cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata | ---
+++
@@ -1,4 +1,4 @@
from .delphi_epidata import Epidata
name = 'delphi_epidata'
-__version__ = '0.0.12'
+__version__ = '0.1.0' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.