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 |
|---|---|---|---|---|---|---|---|---|---|---|
64d838897a38398074433ce1e6a50393fc414a03 | test_project/urls.py | test_project/urls.py | from django.conf.urls.defaults import patterns, include, url
import settings
import os
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
'django.views.generic.simple.direct_to_template',
{'template': 'index.html'}
),
url(r'^test/', 'test_app.... | try:
from django.conf.urls.defaults import patterns, include, url
except ImportError:
from django.conf.urls import patterns, url, include
import settings
import os
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
'django.views.generic.simple.direct_to_t... | Fix for 1.6 & 1.7 | Fix for 1.6 & 1.7
| Python | mit | nikolas/django-interval-field,mpasternak/django-interval-field,mpasternak/django-interval-field,nikolas/django-interval-field | ---
+++
@@ -1,4 +1,8 @@
-from django.conf.urls.defaults import patterns, include, url
+try:
+ from django.conf.urls.defaults import patterns, include, url
+except ImportError:
+ from django.conf.urls import patterns, url, include
+
import settings
import os
|
935552df10dc3a17cf3edb897e83861bbeaae803 | tests/test_thread.py | tests/test_thread.py | import os
import unittest
from common import gobject, gtk, testhelper
# Enable PyGILState API
os.environ['PYGTK_USE_GIL_STATE_API'] = ''
gobject.threads_init()
class TestThread(unittest.TestCase):
def from_thread_cb(self, test, enum):
assert test == self.obj
assert int(enum) == 0
assert ... | import os
import unittest
from common import gobject, gtk, testhelper
# Enable PyGILState API
os.environ['PYGTK_USE_GIL_STATE_API'] = ''
gobject.threads_init()
class TestThread(unittest.TestCase):
def from_thread_cb(self, test, enum):
assert test == self.obj
assert int(enum) == 0
assert ... | Add pygtk_postinstall.py Updated Deprecate gtk.idle_add and friends. Merge | Add pygtk_postinstall.py Updated Deprecate gtk.idle_add and friends. Merge
* Makefile.am: Add pygtk_postinstall.py
* docs/random/missing-symbols: Updated
* gtk/__init__.py: Deprecate gtk.idle_add and friends.
* gtk/gtk.defs: Merge in 2.6 api, for GtkLabel functions,
thanks to Gian Mario Tagliaretti, fixes bug #16... | Python | lgpl-2.1 | choeger/pygobject-cmake,GNOME/pygobject,nzjrs/pygobject,atizo/pygobject,pexip/pygobject,jdahlin/pygobject,davibe/pygobject,Distrotech/pygobject,sfeltman/pygobject,pexip/pygobject,choeger/pygobject-cmake,MathieuDuponchelle/pygobject,alexef/pygobject,alexef/pygobject,alexef/pygobject,sfeltman/pygobject,davidmalcolm/pygob... | ---
+++
@@ -20,8 +20,8 @@
self.obj.emit('emit-signal')
def testExtensionModule(self):
- gtk.idle_add(self.idle_cb)
- gtk.timeout_add(50, self.timeout_cb)
+ gobject.idle_add(self.idle_cb)
+ gobject.timeout_add(50, self.timeout_cb)
gtk.main()
def timeout_cb(se... |
6621bef05b2d4cb3fc138622194fe39765ebcb7c | tests/unit/helper.py | tests/unit/helper.py | import mock
import github3
import unittest
MockedSession = mock.create_autospec(github3.session.GitHubSession)
def build_url(self, *args, **kwargs):
# We want to assert what is happening with the actual calls to the
# Internet. We can proxy this.
return github3.session.GitHubSession().build_url(*args, **... | import mock
import github3
import unittest
def build_url(self, *args, **kwargs):
# We want to assert what is happening with the actual calls to the
# Internet. We can proxy this.
return github3.session.GitHubSession().build_url(*args, **kwargs)
class UnitHelper(unittest.TestCase):
# Sub-classes must... | Fix the issue where the mock is persisting calls | Fix the issue where the mock is persisting calls
| Python | bsd-3-clause | krxsky/github3.py,jim-minter/github3.py,agamdua/github3.py,degustaf/github3.py,christophelec/github3.py,wbrefvem/github3.py,h4ck3rm1k3/github3.py,sigmavirus24/github3.py,ueg1990/github3.py,icio/github3.py,balloob/github3.py,itsmemattchung/github3.py | ---
+++
@@ -1,8 +1,6 @@
import mock
import github3
import unittest
-
-MockedSession = mock.create_autospec(github3.session.GitHubSession)
def build_url(self, *args, **kwargs):
@@ -17,8 +15,12 @@
# Sub-classes must also assign a dictionary to this during definition
example_data = {}
+ def create... |
ededa7c9c616ac97dd6ce8638c6b959a0c51663c | examples/oauth/jupyterhub_config.py | examples/oauth/jupyterhub_config.py | # Configuration file for Jupyter Hub
c = get_config()
# spawn with Docker
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
# The docker instances need access to the Hub, so the default loopback port doesn't work:
from IPython.utils.localinterfaces import public_ips
c.JupyterHub.hub_ip = public_ips()[0]
# ... | # Configuration file for Jupyter Hub
c = get_config()
# spawn with Docker
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
# The docker instances need access to the Hub, so the default loopback port doesn't work:
from jupyter_client.localinterfaces import public_ips
c.JupyterHub.hub_ip = public_ips()[0]
#... | Replace legacy ipython import with jupyter_client | Replace legacy ipython import with jupyter_client | Python | bsd-3-clause | jhamrick/dockerspawner,jupyter/dockerspawner,quantopian/dockerspawner,Fokko/dockerspawner,Fokko/dockerspawner,minrk/dockerspawner,quantopian/dockerspawner,minrk/dockerspawner,jupyter/dockerspawner,jhamrick/dockerspawner | ---
+++
@@ -6,7 +6,7 @@
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
# The docker instances need access to the Hub, so the default loopback port doesn't work:
-from IPython.utils.localinterfaces import public_ips
+from jupyter_client.localinterfaces import public_ips
c.JupyterHub.hub_ip = public_ip... |
5831ce15a94d1941e0521bae328f0ede48bfbe8b | juliet_importer.py | juliet_importer.py | import os
import imp
modules = {}
def load_modules(path="./modules/"): # Consider adding recursive searching at some point in the future
modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py")
names = os.listdir(path)
for name in names:
if not name.endswith(".py"): c... | import os
import imp
modules = {}
def load_modules(path="./modules/"):
try:
modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py")
except ImportError as e:
print("Error importing module {0} from directory {1}".format(name,os.getcwd()))
print(e)
... | Add recursive search to import function | Add recursive search to import function
| Python | bsd-2-clause | halfbro/juliet | ---
+++
@@ -3,18 +3,23 @@
modules = {}
-def load_modules(path="./modules/"): # Consider adding recursive searching at some point in the future
- modules['juliet_module'] = imp.load_source('juliet_module', path + "juliet_module.py")
- names = os.listdir(path)
- for name in names:
- if not name.end... |
381e89972bf4d12daae7aa399f1348a215fa85d9 | jira/exceptions.py | jira/exceptions.py | import json
class JIRAError(Exception):
"""General error raised for all problems in operation of the client."""
def __init__(self, status_code=None, text=None, url=None):
self.status_code = status_code
self.text = text
self.url = url
def __str__(self):
if self.text:
... | import json
class JIRAError(Exception):
"""General error raised for all problems in operation of the client."""
def __init__(self, status_code=None, text=None, url=None):
self.status_code = status_code
self.text = text
self.url = url
def __str__(self):
if self.text:
... | Fix for empty errorMessages, moved length check to main logic for deciding which error message to use and added check for 'errors' in the response. | Fix for empty errorMessages, moved length check to main logic for deciding which error
message to use and added check for 'errors' in the response. | Python | bsd-2-clause | pycontribs/jira,jameskeane/jira-python,rayyen/jira,pycontribs/jira,dbaxa/jira,coddingtonbear/jira,milo-minderbinder/jira,systemadev/jira-python,tsarnowski/jira-python,kinow/jira,jameskeane/jira-python,awurster/jira,stevencarey/jira,VikingDen/jira,awurster/jira,kinow/jira,m42e/jira,VikingDen/jira,tsarnowski/jira-python,... | ---
+++
@@ -24,13 +24,17 @@
if 'message' in response:
# JIRA 5.1 errors
error = response['message']
- elif 'errorMessages' in response:
+ elif 'errorMessages' in response and len(response['errorMessages']) > 0:
... |
9bdd2cbb545c56c660be9933a06f7eea2f9ad059 | shallow_appify/_version.py | shallow_appify/_version.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__version_info__ = (0, 4, 1)
__version__ = '.'.join(map(str, __version_info__))
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__version_info__ = (0, 4, 2)
__version__ = '.'.join(map(str, __version_info__))
| Increase the version number to `0.4.2` | Increase the version number to `0.4.2`
| Python | mit | IngoHeimbach/shallow-appify | ---
+++
@@ -5,5 +5,5 @@
from __future__ import print_function
from __future__ import unicode_literals
-__version_info__ = (0, 4, 1)
+__version_info__ = (0, 4, 2)
__version__ = '.'.join(map(str, __version_info__)) |
2050385a5f5fdcffe333ae17463d6469af0b5cd8 | mopidy/__init__.py | mopidy/__init__.py | from __future__ import unicode_literals
import sys
import warnings
from distutils.version import StrictVersion as SV
import pykka
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'Mopidy requires Python >= 2.7, < 3, but found %s' %
'.'.join(map(str, sys.version_info[:3])))
if (isinstance(pyk... | from __future__ import unicode_literals
import platform
import sys
import warnings
from distutils.version import StrictVersion as SV
import pykka
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
'ERROR: Mopidy requires Python 2.7, but found %s.' %
platform.python_version())
if (isinstance(py... | Update Python and Pykka version check error messages | Update Python and Pykka version check error messages
| Python | apache-2.0 | jmarsik/mopidy,adamcik/mopidy,priestd09/mopidy,woutervanwijk/mopidy,glogiotatidis/mopidy,tkem/mopidy,bencevans/mopidy,hkariti/mopidy,jcass77/mopidy,pacificIT/mopidy,vrs01/mopidy,ali/mopidy,bencevans/mopidy,mokieyue/mopidy,rawdlite/mopidy,swak/mopidy,tkem/mopidy,rawdlite/mopidy,jcass77/mopidy,woutervanwijk/mopidy,swak/m... | ---
+++
@@ -1,5 +1,6 @@
from __future__ import unicode_literals
+import platform
import sys
import warnings
from distutils.version import StrictVersion as SV
@@ -9,13 +10,14 @@
if not (2, 7) <= sys.version_info < (3,):
sys.exit(
- 'Mopidy requires Python >= 2.7, < 3, but found %s' %
- '.'.... |
780f7f2b9546bc7f1c87ad3744559de3287fee21 | src/streamlink/plugins/europaplus.py | src/streamlink/plugins/europaplus.py | from __future__ import print_function
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.plugin.api.utils import itertags
from streamlink.stream import HLSStream
class EuropaPlusTV(Plugin):
url_re = re.compile(r"https?://(?:www\.)?europaplus\.ru/europaplustv")
... | from __future__ import print_function
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http
from streamlink.plugin.api.utils import itertags
from streamlink.stream import HLSStream
from streamlink.utils import update_scheme
class EuropaPlusTV(Plugin):
url_re = re.compile(r"https?... | Fix for "No connection adapters were found" | plugins.EuropaPlusTV: Fix for "No connection adapters were found"
| Python | bsd-2-clause | back-to/streamlink,streamlink/streamlink,gravyboat/streamlink,melmorabity/streamlink,back-to/streamlink,chhe/streamlink,bastimeyer/streamlink,beardypig/streamlink,wlerin/streamlink,wlerin/streamlink,streamlink/streamlink,chhe/streamlink,beardypig/streamlink,bastimeyer/streamlink,melmorabity/streamlink,gravyboat/streaml... | ---
+++
@@ -6,6 +6,7 @@
from streamlink.plugin.api import http
from streamlink.plugin.api.utils import itertags
from streamlink.stream import HLSStream
+from streamlink.utils import update_scheme
class EuropaPlusTV(Plugin):
@@ -24,6 +25,7 @@
m = self.src_re.search(iframe_res.text)
su... |
a10c02e6bac0ff87576e359316901d576bed8d9d | rest_framework_simplejwt/settings.py | rest_framework_simplejwt/settings.py | from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
... | from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None)
DEFAULTS = {
'AUTH_HEADER_TYPE': 'Bearer',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
... | Update AUTH_TOKEN_CLASS setting default value | Update AUTH_TOKEN_CLASS setting default value
| Python | mit | davesque/django-rest-framework-simplejwt,davesque/django-rest-framework-simplejwt | ---
+++
@@ -27,7 +27,7 @@
# Undocumented settings. Changing these may lead to unexpected behavior.
# Make sure you know what you're doing. These might become part of the
# public API eventually but that would require some adjustments.
- 'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.SlidingT... |
c953a1435b6f20b337ee1d7410d29868d17bc6d9 | pdf_generator/pdf_generator.py | pdf_generator/pdf_generator.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import collections
from reportlab.platypus import (
PageBreak,
FrameBreak,
NextPageTemplate,
)
class Story(collections.MutableSequence):
def __init__(self, template):
self._template = template
self.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import collections
from reportlab.platypus import (
PageBreak,
FrameBreak,
NextPageTemplate,
)
class Story(collections.MutableSequence):
def __init__(self, template):
self._template = template
self.... | Add a property to access to the template | Add a property to access to the template
| Python | mit | cecedille1/PDF_generator | ---
+++
@@ -17,6 +17,10 @@
self._template = template
self._story = list()
self._index = 0
+
+ @property
+ def template(self):
+ return self._template
def next_page(self):
self._story.append(PageBreak()) |
fb042cd3ff15f35672e543f040053859c18cff24 | timedelta/templatetags/timedelta.py | timedelta/templatetags/timedelta.py | from django import template
register = template.Library()
# Don't really like using relative imports, but no choice here!
from ..helpers import nice_repr, iso8601_repr, total_seconds as _total_seconds
@register.filter(name='timedelta')
def timedelta(value, display="long"):
return nice_repr(value, display)
@regis... | from django import template
register = template.Library()
# Don't really like using relative imports, but no choice here!
from ..helpers import nice_repr, iso8601_repr, total_seconds as _total_seconds
@register.filter(name='timedelta')
def timedelta(value, display="long"):
if value is None:
return value
... | Allow for calling our filters on objects that are None | Allow for calling our filters on objects that are None
| Python | bsd-3-clause | sookasa/django-timedelta-field | ---
+++
@@ -6,17 +6,25 @@
@register.filter(name='timedelta')
def timedelta(value, display="long"):
+ if value is None:
+ return value
return nice_repr(value, display)
@register.filter(name='iso8601')
def iso8601(value):
+ if value is None:
+ return value
return iso8601_repr(value... |
e000f5db7bf8aee6b3ae267824491d03b20fbb36 | saau/sections/transportation/data.py | saau/sections/transportation/data.py | from operator import attrgetter, itemgetter
from itertools import chain
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def men... | from operator import itemgetter
from itertools import chain
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(ext... | Remove map and filter use | Remove map and filter use
| Python | mit | Mause/statistical_atlas_of_au | ---
+++
@@ -1,4 +1,4 @@
-from operator import attrgetter, itemgetter
+from operator import itemgetter
from itertools import chain
from ...utils.py3_hook import with_hook
@@ -35,9 +35,11 @@
def get_paths(request_layers):
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
- pa... |
fc6806608c5e407882248185bca57afa712e065a | byceps/blueprints/news_admin/forms.py | byceps/blueprints/news_admin/forms.py | """
byceps.blueprints.news_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import re
from wtforms import StringField, TextAreaField
from wtforms.validators import InputRequired, Length, Optional, Regexp
from ...util.l10n ... | """
byceps.blueprints.news_admin.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import re
from wtforms import StringField, TextAreaField
from wtforms.validators import InputRequired, Length, Optional, Regexp
from ...util.l10n ... | Fix validation of news creation form | Fix validation of news creation form
| Python | bsd-3-clause | m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -20,7 +20,7 @@
class ItemCreateForm(LocalizedForm):
slug = StringField('Slug', [InputRequired(), Length(max=80), Regexp(SLUG_REGEX, message='Nur Kleinbuchstaben, Ziffern und Bindestrich sind erlaubt.')])
title = StringField('Titel', [InputRequired(), Length(max=80)])
- body = TextAreaField('T... |
4bd41e0e9381ef1c29b1a912a5d8d6ac99b03f4c | capstone/rl/learners/qlearning.py | capstone/rl/learners/qlearning.py | from ..learner import Learner
from ..policies import RandomPolicy
from ..util import max_action_value
from ..value_functions import TabularF
from ...utils import check_random_state
class QLearning(Learner):
def __init__(self, env, policy=None, qf=None, alpha=0.1, gamma=0.99,
n_episodes=1000, ran... | from ..learner import Learner
from ..policies import RandomPolicy
from ..util import max_action_value
from ..value_functions import TabularF
from ...utils import check_random_state
class QLearning(Learner):
def __init__(self, env, policy=None, qf=None, learning_rate=0.1,
discount_factor=0.99, n_... | Rename alpha -> learning_rate and gamma -> discount_factor | Rename alpha -> learning_rate and gamma -> discount_factor
| Python | mit | davidrobles/mlnd-capstone-code | ---
+++
@@ -7,11 +7,12 @@
class QLearning(Learner):
- def __init__(self, env, policy=None, qf=None, alpha=0.1, gamma=0.99,
- n_episodes=1000, random_state=None, verbose=None):
+ def __init__(self, env, policy=None, qf=None, learning_rate=0.1,
+ discount_factor=0.99, n_episod... |
0167e246b74789cc0181b603520ec7f58ef7b5fe | pandas/core/api.py | pandas/core/api.py |
# pylint: disable=W0614,W0401,W0611
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
... |
# pylint: disable=W0614,W0401,W0611
import numpy as np
from pandas.core.algorithms import factorize, match, unique, value_counts
from pandas.core.common import isnull, notnull, save, load
from pandas.core.categorical import Categorical, Factor
from pandas.core.format import (set_printoptions, reset_printoptions,
... | Add new core.config API functions to the pandas top level module | ENH: Add new core.config API functions to the pandas top level module
| Python | bsd-3-clause | pandas-dev/pandas,GuessWhoSamFoo/pandas,TomAugspurger/pandas,toobaz/pandas,MJuddBooth/pandas,cython-testbed/pandas,TomAugspurger/pandas,nmartensen/pandas,cython-testbed/pandas,DGrady/pandas,DGrady/pandas,datapythonista/pandas,kdebrab/pandas,dsm054/pandas,Winand/pandas,linebp/pandas,dsm054/pandas,toobaz/pandas,jmmease/p... | ---
+++
@@ -29,3 +29,6 @@
# legacy
from pandas.core.daterange import DateRange # deprecated
import pandas.core.datetools as datetools
+
+from pandas.core.config import get_option,set_option,reset_option,\
+ reset_options,describe_options |
a12a027ba027ebb23e18da38e444dc51e57a91bc | aero/adapters/brew.py | aero/adapters/brew.py | # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
adapter_command = 'brew'
def search(self, query):
response = self._execute_command(self.adapter_command, ['search', quer... | # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
adapter_command = 'brew'
def search(self, query):
response = self._execute_command(self.adapter_command, ['search', quer... | Fix bew 'No info available' | Fix bew 'No info available'
| Python | bsd-3-clause | Aeronautics/aero | ---
+++
@@ -30,7 +30,7 @@
if 'Error:' not in response:
response = response.replace(query + ': ', 'version: ')
return [line.split(': ', 1) for line in response.splitlines() if 'homebrew' not in line]
- return 'No info available'
+ return [['No info available']]
d... |
ebcdf90a44d3ae87be8032f89bec26697e22cbf3 | alexandra/__init__.py | alexandra/__init__.py | """
Python support for Alexa applications.
Because like everything Amazon it involves a ton of tedious boilerplate.
"""
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
from alexandra.app import Application
from alexandra.session import Session
from alexandra.util import respond, repromp... | # flake8: noqa
"""
Python support for Alexa applications.
Because like everything Amazon it involves a ton of tedious boilerplate.
"""
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
from alexandra.app import Application
from alexandra.session import Session
from alexandra.util import r... | Add a noqa to init | Add a noqa to init
| Python | isc | erik/alexandra | ---
+++
@@ -1,3 +1,4 @@
+# flake8: noqa
"""
Python support for Alexa applications.
|
2cb7c80bc4358631b897e3ea91d3c7eff684f69b | pmxbot/__init__.py | pmxbot/__init__.py | # -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
from __future__ import absolute_import
import socket
import logging
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
password = No... | # -*- coding: utf-8 -*-
# vim:ts=4:sw=4:noexpandtab
from __future__ import absolute_import
import socket
import logging as _logging
from .dictlib import ConfigDict
config = ConfigDict(
bot_nickname = 'pmxbot',
database = 'sqlite:pmxbot.sqlite',
server_host = 'localhost',
server_port = 6667,
use_ssl = False,
p... | Fix issue with conflated pmxbot.logging | Fix issue with conflated pmxbot.logging
| Python | bsd-3-clause | jawilson/pmxbot,jawilson/pmxbot | ---
+++
@@ -4,7 +4,7 @@
from __future__ import absolute_import
import socket
-import logging
+import logging as _logging
from .dictlib import ConfigDict
@@ -30,6 +30,6 @@
librarypaste = 'http://paste.jaraco.com',
)
config['logs URL'] = 'http://' + socket.getfqdn()
-config['log level'] = logging.INFO
+con... |
513fa57c8062310a1e852316f51a4382acf6f9b0 | retdec/__init__.py | retdec/__init__.py | #
# Project: retdec-python
# Copyright: (c) 2015-2016 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""The main package of a Python library and tools providing easy access to the
`retdec.com <https://retdec.com>`_ decompilation service through their publi... | #
# Project: retdec-python
# Copyright: (c) 2015-2016 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""The main package of a Python library and tools providing easy access to the
`retdec.com <https://retdec.com>`_ decompilation service through their publi... | Bump the version number to 0.3-dev. | Bump the version number to 0.3-dev.
| Python | mit | s3rvac/retdec-python | ---
+++
@@ -9,7 +9,7 @@
`REST API <https://retdec.com/api/>`_.
"""
-__version__ = '0.2'
+__version__ = '0.3-dev'
#: Default API URL.
DEFAULT_API_URL = 'https://retdec.com/service/api' |
c5c2d3c411ba38a7b110044e04657ae6584be861 | scripts/helpers.py | scripts/helpers.py |
def printSnapshot(doc):
print(u'Created {} => {}'.format(doc.id, doc.to_dict()))
def queryUsers(db):
users_ref = db.collection(u'users')
docs = users_ref.get()
docList = list()
for doc in docs:
docList.append(doc)
return docList
def queryRequests(db):
requests_ref = db.collection(u'requests')
doc... |
def printSnapshot(doc):
print(u'Created {} => {}'.format(doc.id, doc.to_dict()))
def queryUsers(db):
users_ref = db.collection(u'users')
docs = users_ref.get()
docList = list()
for doc in docs:
docList.append(doc)
return docList
def queryRequests(db):
requests_ref = db.collection(u'requests')
doc... | Add script to clean the message table | Add script to clean the message table
| Python | mit | frinder/frinder-app,frinder/frinder-app,frinder/frinder-app | ---
+++
@@ -18,6 +18,14 @@
docList.append(doc)
return docList
+def queryMessages(db):
+ messages_ref = db.collection(u'messages')
+ docs = messages_ref.get()
+ docList = list()
+ for doc in docs:
+ docList.append(doc)
+ return docList
+
def getUser(userId, users):
for user in users:
if user... |
2f6c82d74592c80b5042c0b808a658650896cbec | rebulk/__init__.py | rebulk/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Define simple search patterns in bulk to perform advanced matching on any string
"""
from .rebulk import Rebulk
from .match import Match
from .rules import Rule
from .pattern import REGEX_AVAILABLE
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Define simple search patterns in bulk to perform advanced matching on any string
"""
from .rebulk import Rebulk
from .match import Match
from .rules import Rule, AppendMatchRule, RemoveMatchRule
from .pattern import REGEX_AVAILABLE
| Add global imports for rules classes | Add global imports for rules classes
| Python | mit | Toilal/rebulk | ---
+++
@@ -6,5 +6,5 @@
from .rebulk import Rebulk
from .match import Match
-from .rules import Rule
+from .rules import Rule, AppendMatchRule, RemoveMatchRule
from .pattern import REGEX_AVAILABLE |
75092d41fc93306ddc640463886e80620cbcbf46 | pemi/transforms.py | pemi/transforms.py | def isblank(value):
return (
value is not False
and value != 0
and value != float(0)
and not bool(value)
)
def concatenate(delimiter=''):
def _concatenate(row):
return delimiter.join(row)
return _concatenate
def nvl(default=''):
def _nvl(r... | import pandas as pd
def isblank(value):
return (
value is not False
and value != 0
and value != float(0)
and (value is None or pd.isnull(value) or not value)
)
def concatenate(delimiter=''):
def _concatenate(row):
return delimiter.join(row)
return _concatenate
... | Revert "DE-1903 - fix isblank() error" | Revert "DE-1903 - fix isblank() error"
This reverts commit 27fd096d9641971f34cb0811fc2240ebc4f3450b.
| Python | mit | inside-track/pemi | ---
+++
@@ -1,21 +1,19 @@
+import pandas as pd
+
def isblank(value):
return (
- value is not False
- and value != 0
- and value != float(0)
- and not bool(value)
+ value is not False
+ and value != 0
+ and value != float(0)
+ and (value is ... |
fd7fb7ade0fc879e24543f13c39b00de073004bc | setuptools/tests/py26compat.py | setuptools/tests/py26compat.py | import sys
import tarfile
import contextlib
def _tarfile_open_ex(*args, **kwargs):
"""
Extend result as a context manager.
"""
return contextlib.closing(tarfile.open(*args, **kwargs))
tarfile_open = _tarfile_open_ex if sys.version_info < (2,7) else tarfile.open
| import sys
import tarfile
import contextlib
def _tarfile_open_ex(*args, **kwargs):
"""
Extend result as a context manager.
"""
return contextlib.closing(tarfile.open(*args, **kwargs))
if sys.version_info[:2] < (2, 7) or (3, 0) <= sys.version_info[:2] < (3, 2):
tarfile_open = _tarfile_open_ex
else:
tarfile... | Fix "AttributeError: 'TarFile' object has no attribute '__exit__'" with Python 3.1. | Fix "AttributeError: 'TarFile' object has no attribute '__exit__'" with Python 3.1.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -8,4 +8,7 @@
"""
return contextlib.closing(tarfile.open(*args, **kwargs))
-tarfile_open = _tarfile_open_ex if sys.version_info < (2,7) else tarfile.open
+if sys.version_info[:2] < (2, 7) or (3, 0) <= sys.version_info[:2] < (3, 2):
+ tarfile_open = _tarfile_open_ex
+else:
+ tarfile_open = tarfil... |
b19707479410c04a19e6cf224e048260edbf0155 | cc/settings/default.py | cc/settings/default.py | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | Add debug console root logging handler. | Add debug console root logging handler.
| Python | bsd-2-clause | mozilla/moztrap,shinglyu/moztrap,shinglyu/moztrap,mozilla/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mozilla/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,mozilla/moztrap... | ---
+++
@@ -28,6 +28,13 @@
MIDDLEWARE_CLASSES.insert(
0, "cc.debug.middleware.AjaxTracebackMiddleware")
+ LOGGING["handlers"]["console"] = {
+ "level": "DEBUG",
+ "class": "logging.StreamHandler",
+ }
+
+ LOGGING["root"] = {"handlers": ["console"]}
+
try:
HMAC_KEYS
ex... |
4f1f5b22a92876f9eb61058fc1911dda73a2acf7 | installer/terraform/jazz-terraform-unix-noinstances/scripts/configure-gitlab.py | installer/terraform/jazz-terraform-unix-noinstances/scripts/configure-gitlab.py | from gitlab_personalaccesstoken import generate_personal_access_token
from terraform_external_data import terraform_external_data
import gitlab
@terraform_external_data
def get_gitlab_group(query):
token = generate_personal_access_token('mytoken', query['passwd'], query['gitlab-ip'])
gl = gitlab.Gitlab('htt... | from gitlab_personalaccesstoken import generate_personal_access_token
from terraform_external_data import terraform_external_data
import gitlab
@terraform_external_data
def get_gitlab_group(query):
token = generate_personal_access_token('mytoken', query['passwd'], query['gitlab_ip'])
gl = gitlab.Gitlab('htt... | Fix key error due to lack of underscore | Fix key error due to lack of underscore
| Python | apache-2.0 | tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer,tmobile/jazz-installer | ---
+++
@@ -6,7 +6,7 @@
@terraform_external_data
def get_gitlab_group(query):
- token = generate_personal_access_token('mytoken', query['passwd'], query['gitlab-ip'])
+ token = generate_personal_access_token('mytoken', query['passwd'], query['gitlab_ip'])
gl = gitlab.Gitlab('http://'.format(query['gi... |
916affcb04fe24f353da918aa707685f7768ea62 | pyleus/__init__.py | pyleus/__init__.py | import os
import sys
__version__ = '0.1.3'
BASE_JAR = "pyleus-base.jar"
BASE_JAR_INSTALL_DIR = "share/pyleus"
BASE_JAR_PATH = os.path.join(sys.prefix, BASE_JAR_INSTALL_DIR, BASE_JAR)
| import os
import sys
__version__ = '0.1.4'
BASE_JAR = "pyleus-base.jar"
BASE_JAR_INSTALL_DIR = "share/pyleus"
BASE_JAR_PATH = os.path.join(sys.prefix, BASE_JAR_INSTALL_DIR, BASE_JAR)
| Bump pyleus version to 0.1.4 | Bump pyleus version to 0.1.4
| Python | apache-2.0 | ecanzonieri/pyleus,imcom/pyleus,imcom/pyleus,patricklucas/pyleus,patricklucas/pyleus,jirafe/pyleus,dapuck/pyleus,mzbyszynski/pyleus,jirafe/pyleus,dapuck/pyleus,imcom/pyleus,stallman-cui/pyleus,mzbyszynski/pyleus,poros/pyleus,stallman-cui/pyleus,Yelp/pyleus,Yelp/pyleus,poros/pyleus,ecanzonieri/pyleus | ---
+++
@@ -1,7 +1,7 @@
import os
import sys
-__version__ = '0.1.3'
+__version__ = '0.1.4'
BASE_JAR = "pyleus-base.jar"
BASE_JAR_INSTALL_DIR = "share/pyleus" |
6830f29022746838677ecca420aeff190943c5ed | random/__init__.py | random/__init__.py | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Remove remnants of internal project naming in one docstring. | Remove remnants of internal project naming in one docstring.
PiperOrigin-RevId: 263530441
| Python | apache-2.0 | google/tf-quant-finance,google/tf-quant-finance | ---
+++
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Nomisma Quantitative Finance random number samplers."""
+"""Random number samplers."""
from __future__ import absolute_import
from __future__ import division |
0eb7ddce9f425c30c70bc1442618deb72c530911 | networks/models.py | networks/models.py | from django.db import models
from helpers import models as helpermodels
# Create your models here.
class Networks(models.Model):
POLICIES = (
('reject', 'Reject'),
('drop', 'Ignore'),
('accept', 'Accept'),
)
name = models.CharField(max_length=30)
interface... | from django.db import models
from helpers.models import IPNetworkField
# Create your models here.
class Network(models.Model):
POLICIES = (
('reject', 'Reject'),
('drop', 'Ignore'),
('accept', 'Accept'),
)
name = models.CharField(max_length=30)
interface =... | Fix Network model name; better import | Fix Network model name; better import
| Python | mit | Kromey/piroute,Kromey/piroute,Kromey/piroute | ---
+++
@@ -1,11 +1,11 @@
from django.db import models
-from helpers import models as helpermodels
+from helpers.models import IPNetworkField
# Create your models here.
-class Networks(models.Model):
+class Network(models.Model):
POLICIES = (
('reject', 'Reject'),
('drop', 'Ig... |
563e7d5bc2fadd35b0fc71d45c949aa0b2e872a9 | example/example/tasksapp/run_tasks.py | example/example/tasksapp/run_tasks.py | import os
import time
from dj_experiment.tasks.tasks import longtime_add, netcdf_save
from example.settings import (DJ_EXPERIMENT_BASE_DATA_DIR,
DJ_EXPERIMENT_DATA_DIR)
if __name__ == '__main__':
result = longtime_add.delay(1, 2)
# at this time, our task is not finished, so it wi... | import os
import time
from dj_experiment.tasks.tasks import longtime_add, netcdf_save
from example.settings import DJ_EXPERIMENT_BASE_DATA_DIR
if __name__ == '__main__':
result = longtime_add.delay(1, 2)
# at this time, our task is not finished, so it will return False
print 'Task finished? ', result.read... | Fix wrong path composition for data directory | Fix wrong path composition for data directory
| Python | mit | francbartoli/dj-experiment,francbartoli/dj-experiment | ---
+++
@@ -2,8 +2,7 @@
import time
from dj_experiment.tasks.tasks import longtime_add, netcdf_save
-from example.settings import (DJ_EXPERIMENT_BASE_DATA_DIR,
- DJ_EXPERIMENT_DATA_DIR)
+from example.settings import DJ_EXPERIMENT_BASE_DATA_DIR
if __name__ == '__main__':
result... |
64750693969bda63dae28db0b43eaca09c549ab4 | scripts/lib/logger.py | scripts/lib/logger.py | # logger module
from datetime import datetime
import os
logfile = None
logbuf = []
def init(analysis_path):
global logfile
if not os.path.isdir(analysis_path):
log("logger: analysis_path missing:", analysis_path)
use_log_dir = False
if use_log_dir:
logdir = os.path.join(analysis_path,... | # logger module
from datetime import datetime
import os
logfile = None
logbuf = []
def init(analysis_path):
global logfile
if not os.path.isdir(analysis_path):
log("logger: analysis_path missing:", analysis_path)
use_log_dir = False
if use_log_dir:
logdir = os.path.join(analysis_path,... | Add a fancy log mode. | Add a fancy log mode.
| Python | mit | UASLab/ImageAnalysis | ---
+++
@@ -21,7 +21,7 @@
logfile = os.path.join(analysis_path, "messages")
# log a message to messages files (and to stdout by default)
-def log(*args, quiet=False):
+def log(*args, quiet=False, fancy=False):
global logbuf
# timestamp
now = datetime.now()
@@ -30,7 +30,14 @@
msg = []
... |
28d933b351f58fabad464deedb57af55b499b7c8 | tag_release.py | tag_release.py | #!/usr/bin/env python
import os
import sys
def main():
if len(sys.argv) != 2:
print('Usage: %s version' % sys.argv[0])
os.system('git tag | sort -n | tail -n 1')
sys.exit()
version = sys.argv[1]
with open('floo/version.py', 'r') as fd:
version_py = fd.read().split('\n')
... | #!/usr/bin/env python
import os
import re
import sys
from distutils.version import StrictVersion
def main():
if len(sys.argv) != 2:
print('Usage: %s version' % sys.argv[0])
versions = os.popen('git tag').read().split('\n')
versions = [v for v in versions if re.match("\\d\\.\\d\\.\\d", v)]... | Tag release script now works with semvers. | Tag release script now works with semvers.
| Python | apache-2.0 | Floobits/floobits-sublime,Floobits/floobits-sublime | ---
+++
@@ -1,13 +1,18 @@
#!/usr/bin/env python
import os
+import re
import sys
+from distutils.version import StrictVersion
def main():
if len(sys.argv) != 2:
print('Usage: %s version' % sys.argv[0])
- os.system('git tag | sort -n | tail -n 1')
+ versions = os.popen('git tag').r... |
348b79cfd68afa91a71009a6481f2d45495909cf | test/server.py | test/server.py | #!/usr/bin/env python
import sys
import logging
from os.path import abspath, dirname
basepath = abspath(dirname(abspath(__file__)) + '/..')
sys.path.insert(0, basepath)
from server import Server
from deflate_frame import DeflateFrame
class EchoServer(Server):
def onmessage(self, client, message):
Server... | #!/usr/bin/env python
import sys
import logging
from os.path import abspath, dirname
basepath = abspath(dirname(abspath(__file__)) + '/..')
sys.path.insert(0, basepath)
from async import AsyncServer
from deflate_message import DeflateMessage
from deflate_frame import DeflateFrame
class EchoServer(AsyncServer):
... | Test EchoServer now uses AsyncServer and deflate extensions | Test EchoServer now uses AsyncServer and deflate extensions
| Python | bsd-3-clause | taddeus/wspy,taddeus/wspy | ---
+++
@@ -6,19 +6,18 @@
basepath = abspath(dirname(abspath(__file__)) + '/..')
sys.path.insert(0, basepath)
-from server import Server
+from async import AsyncServer
+from deflate_message import DeflateMessage
from deflate_frame import DeflateFrame
-class EchoServer(Server):
+class EchoServer(AsyncServer):... |
e50b95143ce4a807c434eaa0e6ef38d36f91a77a | pylons/__init__.py | pylons/__init__.py | """Base objects to be exported for use in Controllers"""
# Import pkg_resources first so namespace handling is properly done so the
# paste imports work
import pkg_resources
from paste.registry import StackedObjectProxy
from pylons.configuration import config
__all__ = ['app_globals', 'cache', 'config', 'request', 'r... | """Base objects to be exported for use in Controllers"""
# Import pkg_resources first so namespace handling is properly done so the
# paste imports work
import pkg_resources
from paste.registry import StackedObjectProxy
from pylons.configuration import config
from pylons.controllers.util import Request
from pylons.con... | Add Request/Response import points for pylons. | Add Request/Response import points for pylons.
--HG--
branch : trunk
| Python | bsd-3-clause | Pylons/pylons,Pylons/pylons,moreati/pylons,moreati/pylons,Pylons/pylons,moreati/pylons | ---
+++
@@ -5,9 +5,11 @@
from paste.registry import StackedObjectProxy
from pylons.configuration import config
+from pylons.controllers.util import Request
+from pylons.controllers.util import Response
__all__ = ['app_globals', 'cache', 'config', 'request', 'response',
- 'session', 'tmpl_context', 'u... |
9f0b77ba9d98c6f78e5320d2b4515f3152a6f38c | db-integrity-tests/src/cliargs.py | db-integrity-tests/src/cliargs.py | """Module with specification of all supported command line arguments."""
import argparse
cli_parser = argparse.ArgumentParser()
cli_parser.add_argument('--log-level',
help='log level as defined in ' +
'https://docs.python.org/3.5/library/logging.html#logging-level... | """Module with specification of all supported command line arguments."""
import argparse
cli_parser = argparse.ArgumentParser()
cli_parser.add_argument('--log-level',
help='log level as defined in ' +
'https://docs.python.org/3/library/logging.html#logging-levels'... | Fix wrong URL to Python logging lib documentation | Fix wrong URL to Python logging lib documentation
| Python | apache-2.0 | jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common | ---
+++
@@ -6,5 +6,5 @@
cli_parser.add_argument('--log-level',
help='log level as defined in ' +
- 'https://docs.python.org/3.5/library/logging.html#logging-level',
+ 'https://docs.python.org/3/library/logging.html#logging-levels',
... |
0519824c537a96474e0501e1ac45f7a626391a31 | tests/test_model_object.py | tests/test_model_object.py | # encoding: utf-8
from marathon.models.base import MarathonObject
import unittest
class MarathonObjectTest(unittest.TestCase):
def test_hashable(self):
"""
Regression test for issue #203
MarathonObject defined __eq__ but not __hash__, meaning that in
in Python2.7 MarathonObjects... | # encoding: utf-8
from marathon.models.base import MarathonObject
from marathon.models.base import MarathonResource
import unittest
class MarathonObjectTest(unittest.TestCase):
def test_hashable(self):
"""
Regression test for issue #203
MarathonObject defined __eq__ but not __hash__, me... | Add regression test for MarathonResource | Add regression test for MarathonResource
| Python | mit | thefactory/marathon-python,thefactory/marathon-python | ---
+++
@@ -1,6 +1,7 @@
# encoding: utf-8
from marathon.models.base import MarathonObject
+from marathon.models.base import MarathonResource
import unittest
@@ -19,3 +20,21 @@
collection = {}
collection[obj] = True
assert collection[obj]
+
+
+class MarathonResourceHashable(unittest... |
1e19a78652e8fed32eb6e315fca3346b3bc31044 | bamova/bamov2npy.py | bamova/bamov2npy.py | import sys
import numpy as np
def read_phi(flname, n_steps, n_loci):
sampled_phis = np.zeros((n_steps, n_loci))
fl = open(flname)
current_iter_idx = 0 # index used for storage
last_iter_idx = 0 # index used to identify when we finish a step
for ln in fl:
cols = ln.strip().split(",")
iter_idx = int(cols[0])
... | import sys
import numpy as np
def read_phi(flname, n_steps, n_loci):
sampled_phis = np.zeros((n_steps, n_loci))
fl = open(flname)
current_iter_idx = 0 # index used for storage
last_iter_idx = 0 # index used to identify when we finish a step
for ln in fl:
cols = ln.strip().split(",")
iter_idx = int(cols[0])
... | Fix ordering of parameters to save | Fix ordering of parameters to save
| Python | apache-2.0 | rnowling/pop-gen-models | ---
+++
@@ -28,4 +28,4 @@
matrix = read_phi(bamova_phi_output_flname, n_steps, n_loci)
- np.save(matrix, npy_flname)
+ np.save(npy_flname, matrix) |
3747158af790a38ccfce217426ee5261877e9f0e | project/api/management/commands/seed_database.py | project/api/management/commands/seed_database.py | # Django
from django.core.management.base import BaseCommand
from api.factories import (
InternationalFactory,
)
class Command(BaseCommand):
help = "Command to seed database."
def handle(self, *args, **options):
InternationalFactory()
| # Django
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Command to seed database."
from api.factories import (
InternationalFactory,
)
def handle(self, *args, **options):
self.InternationalFactory()
| Fix seeding in management command | Fix seeding in management command
| Python | bsd-2-clause | barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,dbinetti/barberscore-django,dbinetti/barberscore | ---
+++
@@ -1,14 +1,13 @@
# Django
from django.core.management.base import BaseCommand
-
-
-from api.factories import (
- InternationalFactory,
-)
class Command(BaseCommand):
help = "Command to seed database."
+ from api.factories import (
+ InternationalFactory,
+ )
+
def handle(se... |
13f78350b42e48bc8195d6ec05c8b4342866d8e3 | unit_tests/test_analyse_idynomics.py | unit_tests/test_analyse_idynomics.py | from nose.tools import *
from analyse_idynomics import *
class TestAnalyseiDynomics:
def setUp(self):
self.directory = 'test_data'
self.analysis = AnalyseiDynomics(self.directory)
def test_init(self):
assert_is(self.directory, self.analysis.directory)
| from nose.tools import *
from analyse_idynomics import *
from os.path import join, dirname, realpath
class TestAnalyseiDynomics:
expected_solutes = ['MyAtmos', 'pressure']
expected_species = ['MyBact']
def setUp(self):
self.directory = join(dirname(realpath(__file__)), 'test_data')
sel... | Add unit tests for solute and species names | Add unit tests for solute and species names
| Python | mit | fophillips/pyDynoMiCS | ---
+++
@@ -1,10 +1,22 @@
from nose.tools import *
from analyse_idynomics import *
+from os.path import join, dirname, realpath
class TestAnalyseiDynomics:
+ expected_solutes = ['MyAtmos', 'pressure']
+ expected_species = ['MyBact']
+
def setUp(self):
- self.directory = 'test_data'
+ ... |
aea5b07357ba06811e085d79d1ea4a62726ce8e4 | sgext/drivers/devices/loadbalancers/amazonelb.py | sgext/drivers/devices/loadbalancers/amazonelb.py | from clusto.drivers.devices.appliance.basicappliance import BasicAppliance
import boto.ec2.elb
class AmazonELB(BasicAppliance):
_driver_name = 'amazonelb'
def __init__(self, name, elbname, **kwargs):
BasicAppliance.__init__(self, name, **kwargs)
self.set_attr(key='elb', subkey='name', value='e... | from clusto.drivers.devices.appliance.basicappliance import BasicAppliance
import boto.ec2.elb
class AmazonELB(BasicAppliance):
_driver_name = 'amazonelb'
def __init__(self, name, elbname, **kwargs):
BasicAppliance.__init__(self, name, **kwargs)
self.set_attr(key='elb', subkey='name', value=el... | Fix bug setting the key='elb', subkey='name' attribute. | Fix bug setting the key='elb', subkey='name' attribute.
| Python | bsd-2-clause | simplegeo/clusto-sgext | ---
+++
@@ -6,7 +6,7 @@
def __init__(self, name, elbname, **kwargs):
BasicAppliance.__init__(self, name, **kwargs)
- self.set_attr(key='elb', subkey='name', value='elbname')
+ self.set_attr(key='elb', subkey='name', value=elbname)
def get_boto_connection(self):
region = s... |
3fb41919ebfd73fe1199e95f7ee9b8fa7557ea18 | tests/test_vane.py | tests/test_vane.py | import os
import unittest
import vane
class TestFetch(unittest.TestCase):
def test_owm_good_fetch(self):
loc = 'New York, NY'
w = vane.fetch_weather(loc)
self.assertTrue('temperature' in w['current'])
self.assertTrue('summary' in w['current'])
def test_owm_bad_fetch(self):
... | import os
import unittest
import vane
class TestFetch(unittest.TestCase):
def test_owm_good_fetch(self):
loc = 'New York, NY'
w = vane.fetch_weather(loc)
self.assertTrue('temperature' in w['current'])
self.assertTrue('summary' in w['current'])
def test_owm_bad_fetch(self):
... | Remove geolocation test for now | Remove geolocation test for now
Geolocation doesn't always work, and since location is the one
absolutely required parameter to get anything useful out of vane,
there's no way to gracefully fall back. I'm going to leave the test
out until I have time to write a proper one.
| Python | bsd-3-clause | trevorparker/vane | ---
+++
@@ -28,10 +28,5 @@
w = vane.fetch_weather(
location=loc, provider='wund', api_key=api_key)
- def test_geolocation(self):
- w = vane.fetch_weather()
- self.assertTrue('temperature' in w['current'])
- self.assertTrue('summary' in w['current'])
-
if __name... |
a53df8062680b017d7cd0cf61cfef0e53b2364b1 | src/loaders/npzpck.py | src/loaders/npzpck.py | # -*- coding: utf-8 -*-
# Copyright (c) 2019 shmilee
'''
Contains Npz pickled file loader class.
'''
import numpy
import zipfile
from ..glogger import getGLogger
from .base import BasePckLoader
__all__ = ['NpzPckLoader']
log = getGLogger('L')
class NpzPckLoader(BasePckLoader):
'''
Load pickled data from ... | # -*- coding: utf-8 -*-
# Copyright (c) 2019 shmilee
'''
Contains Npz pickled file loader class.
'''
import numpy
import zipfile
from ..glogger import getGLogger
from .base import BasePckLoader
__all__ = ['NpzPckLoader']
log = getGLogger('L')
class NpzPckLoader(BasePckLoader):
'''
Load pickled data from ... | Revert "fix: NpzPckLoader meddle one-element array" | Revert "fix: NpzPckLoader meddle one-element array"
This reverts commit b3bf178ed07d789282a05fa4efac799c9e0c5910.
NpzPckLoader:
* 1 vs array(1)
* 'a' vs array('a', dtype='<U1')
NpzPckSaver np.asanyarray:
* 1 vs np.void(pickle.dumps('1'))
* 'a' vs np.void(pickle.dumps('a'))
Note:
* type(np.asanyarray(np.void(pi... | Python | mit | shmilee/gdpy3,shmilee/gdpy3,shmilee/gdpy3,shmilee/gdpy3 | ---
+++
@@ -49,6 +49,6 @@
def _special_get(self, tmpobj, key):
value = tmpobj[key]
- # if value.size == 1:
- # value = value.item()
+ if value.size == 1:
+ value = value.item()
return value |
ea43ab87dbb66e0f3da3b9c5345a134b7c001d50 | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
# Start a flask application context.
app = Flask(__name__)
# Load configuration from file.
app.config.from_object('config')
# Setup Db object.
db = MongoEngine(app)
# Setup logging.
logging.basicConfig(level = logging.INFO)
logger... | from flask import Flask
from flask.ext.mongoengine import MongoEngine
import logging
# Start a flask application context.
app = Flask(__name__)
# Load configuration from file.
app.config.from_object('config')
# Setup Db object.
db = MongoEngine(app)
# Setup logging.
logging.basicConfig(level = logging.DEBUG)
logge... | Set logging level to DEBUG | Set logging level to DEBUG
| Python | mit | Zillolo/mana-vault,Zillolo/mana-vault,Zillolo/mana-vault | ---
+++
@@ -13,7 +13,7 @@
db = MongoEngine(app)
# Setup logging.
-logging.basicConfig(level = logging.INFO)
+logging.basicConfig(level = logging.DEBUG)
logger = logging.getLogger(__name__)
# Import auth module and register blueprint. |
78e6cd5fc57c338ac9c61b6e50a5ac4355a5d8b7 | json-templates/create-template.py | json-templates/create-template.py | #!/bin/env python
import blank_template
import json
import os
import subprocess
import sys
import tarfile
if __name__ == '__main__':
# Load template
fname = sys.argv[1]
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'golm-2', 'date': '2016-04-29', 'produ... | #!/bin/env python
import blank_template
import json
import os
import subprocess
import sys
import tarfile
if __name__ == '__main__':
# Load template
fname = sys.argv[1]
template = blank_template.load_template(fname)
# Generate ova.xml
version = {'hostname': 'localhost', 'date': '1970-01-01', 'pr... | Use more generic values for version | Use more generic values for version
| Python | bsd-2-clause | xenserver/guest-templates,xenserver/guest-templates | ---
+++
@@ -14,7 +14,7 @@
template = blank_template.load_template(fname)
# Generate ova.xml
- version = {'hostname': 'golm-2', 'date': '2016-04-29', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '125122c', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'}
+ version... |
842b128dd4fb3b93492578008de0969e85e3039a | qcfractal/alembic/versions/1604623c481a_id_pirmary_key_for_torsion_init_mol.py | qcfractal/alembic/versions/1604623c481a_id_pirmary_key_for_torsion_init_mol.py | """id(pirmary key) for torsion_init_mol
Revision ID: 1604623c481a
Revises: fb5bd88ae2f3
Create Date: 2020-07-02 18:42:17.267792
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "1604623c481a"
down_revision = "fb5bd88ae2f3"
branch_labels = None
depends_on = None
... | """id(pirmary key) for torsion_init_mol
Revision ID: 1604623c481a
Revises: fb5bd88ae2f3
Create Date: 2020-07-02 18:42:17.267792
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "1604623c481a"
down_revision = "fb5bd88ae2f3"
branch_labels = None
depends_on = None
... | Fix missing table name in alter_table | Fix missing table name in alter_table
| Python | bsd-3-clause | psi4/mongo_qcdb,psi4/mongo_qcdb,psi4/DatenQM,psi4/DatenQM | ---
+++
@@ -18,6 +18,7 @@
def upgrade():
+ # Removes (harmless) duplicate rows
op.execute(
"DELETE FROM torsion_init_mol_association a USING \
(SELECT MIN(ctid) as ctid, torsion_id, molecule_id \
@@ -28,8 +29,8 @@
AND a.ctid <> b.ctid"
)
- op.execute("alter table add primar... |
6cdcb7f089c0440ad551ec44b3667a1a5cd380d1 | kafka/tools/assigner/batcher.py | kafka/tools/assigner/batcher.py | from kafka.tools.assigner.exceptions import ProgrammingException
def split_partitions_into_batches(partitions, batch_size=10, use_class=None):
# Currently, this is a very simplistic implementation that just breaks the list of partitions down
# into even sized chunks. While it could be implemented as a generat... | from kafka.tools.assigner.exceptions import ProgrammingException
def split_partitions_into_batches(partitions, batch_size=10, use_class=None):
# Currently, this is a very simplistic implementation that just breaks the list of partitions down
# into even sized chunks. While it could be implemented as a generat... | Remove used of xrange to support python 3 | Remove used of xrange to support python 3
| Python | apache-2.0 | toddpalino/kafka-tools | ---
+++
@@ -8,5 +8,5 @@
if use_class is None:
raise ProgrammingException("split_partitions_into_batches called with no use_class")
- batches = [use_class(partitions[i:i + batch_size]) for i in xrange(0, len(partitions), batch_size)]
+ batches = [use_class(partitions[i:i + batch_size]) for i in r... |
3048fa2883d79a706599ccc6828cb1512acea35d | kolibri/utils/tests/test_cli.py | kolibri/utils/tests/test_cli.py | """
Tests for `kolibri` module.
"""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import shutil
import tempfile
from kolibri.utils.cli import main
from .base import KolibriTestBase
logger = logging.getLogger(__name__)
class TestKolibriCLI(KolibriTestBase):
... | """
Tests for `kolibri` module.
"""
from __future__ import absolute_import, print_function, unicode_literals
import logging
from kolibri.utils.cli import main
from .base import KolibriTestBase
logger = logging.getLogger(__name__)
class TestKolibriCLI(KolibriTestBase):
def test_cli(self):
logger.debug... | Remove what's already done in KolibriTestBase | Remove what's already done in KolibriTestBase
| Python | mit | lyw07/kolibri,rtibbles/kolibri,DXCanas/kolibri,mrpau/kolibri,christianmemije/kolibri,learningequality/kolibri,DXCanas/kolibri,christianmemije/kolibri,christianmemije/kolibri,DXCanas/kolibri,MingDai/kolibri,lyw07/kolibri,MingDai/kolibri,MingDai/kolibri,rtibbles/kolibri,benjaoming/kolibri,benjaoming/kolibri,mrpau/kolibri... | ---
+++
@@ -4,9 +4,6 @@
from __future__ import absolute_import, print_function, unicode_literals
import logging
-import os
-import shutil
-import tempfile
from kolibri.utils.cli import main
@@ -17,19 +14,8 @@
class TestKolibriCLI(KolibriTestBase):
- @classmethod
- def setup_class(cls):
- os... |
ea0c9a977cdf7611138599c54e28ccc4848f2eb5 | troposphere/ivs.py | troposphere/ivs.py | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 25.0.0
from troposphere import Tags
from . import AWSObject
from .validators import boolean
class Channel(AWSOb... | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 35.0.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import boolean
class ... | Update IVS per 2021-04-15 changes | Update IVS per 2021-04-15 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -4,12 +4,12 @@
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
-# Resource specification version: 25.0.0
+# Resource specification version: 35.0.0
from troposphere import Tags
-from . import AWSObject
+from . import AWSObject, AWSProperty
from .validat... |
61b38528b60203003b9595f7ba2204c287dc6970 | string/compress.py | string/compress.py | # Compress string using counts of repeated characters
def compress_str(str):
output = ""
curr_char = ""
char_count = ""
for i in str:
if curr_char != str[i]:
output = output + curr_char + char_count # add new unique character and its count to our output
curr_char = str[i] # move on to the next character ... | # Compress string using counts of repeated characters
def compress_str(str):
output = ""
curr_char = ""
char_count = ""
for i in str:
if curr_char != str[i]:
output = output + curr_char + char_count # add new unique character and its count to our output
curr_char = str[i] # move on to the next character ... | Add to current count if there is a match | Add to current count if there is a match
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -11,3 +11,5 @@
output = output + curr_char + char_count # add new unique character and its count to our output
curr_char = str[i] # move on to the next character in string
char_count = 1 # reset count to 1
+ else: # add to repeated count if there is a match
+ char_count += 1 |
58f5d541da1e9e234258985b3362967a9c0d7b67 | Discord/utilities/errors.py | Discord/utilities/errors.py |
from discord.ext.commands.errors import CommandError
class NotServerOwner(CommandError):
'''Not Server Owner'''
pass
class VoiceNotConnected(CommandError):
'''Voice Not Connected'''
pass
class PermittedVoiceNotConnected(VoiceNotConnected):
'''Permitted, but Voice Not Connected'''
pass
class NotPermittedVoice... |
from discord.ext.commands.errors import CommandError
class NotServerOwner(CommandError):
'''Not Server Owner'''
pass
class VoiceNotConnected(CommandError):
'''Voice Not Connected'''
pass
class PermittedVoiceNotConnected(VoiceNotConnected):
'''Permitted, but Voice Not Connected'''
pass
class NotPermittedVoice... | Remove no longer used custom Missing Permissions error | [Discord] Remove no longer used custom Missing Permissions error
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot | ---
+++
@@ -17,10 +17,6 @@
'''Voice Not Connected, and Not Permitted'''
pass
-class MissingPermissions(CommandError):
- '''Missing Permissions'''
- pass
-
class NotPermitted(CommandError):
'''Not Permitted'''
pass |
91ffbe22e56387491775a569e237c4e46495c6a9 | nyuki/workflow/tasks/task_selector.py | nyuki/workflow/tasks/task_selector.py | import logging
from tukio import Workflow
from tukio.task import register
from tukio.task.holder import TaskHolder
from nyuki.utils.evaluate import ConditionBlock
from nyuki.workflow.tasks.utils import generate_schema
log = logging.getLogger(__name__)
class TaskConditionBlock(ConditionBlock):
"""
Override... | import logging
from tukio import Workflow
from tukio.task import register
from tukio.task.holder import TaskHolder
from nyuki.utils.evaluate import ConditionBlock
from nyuki.workflow.tasks.utils import generate_schema
log = logging.getLogger(__name__)
class TaskConditionBlock(ConditionBlock):
"""
Override... | Fix an issue with the child-task selector. | Fix an issue with the child-task selector.
| Python | apache-2.0 | optiflows/nyuki,gdraynz/nyuki,optiflows/nyuki,gdraynz/nyuki | ---
+++
@@ -25,7 +25,8 @@
"""
Set next workflow tasks upon validating a condition.
"""
- self._workflow.set_next_tasks(condition['tasks'])
+ if condition['rules']:
+ self._workflow.set_next_tasks(condition['rules'][0]['tasks'])
@register('task_selector', 'execu... |
417ffca6a10edc87fc36b1c7c47e7dea36cecd2e | test/test_basic.py | test/test_basic.py | import random
import markovify
import sys, os
HERE = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(HERE, "texts/sherlock.txt")) as f:
sherlock = f.read()
def test_text_too_small():
text = u"Example phrase. This is another example sentence."
text_model = markovify.Text(text)
assert... | import random
import markovify
import sys, os
import operator
HERE = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(HERE, "texts/sherlock.txt")) as f:
sherlock = f.read()
def test_text_too_small():
text = u"Example phrase. This is another example sentence."
text_model = markovify.Text(... | Add test for chain-JSON equality | Add test for chain-JSON equality
| Python | mit | jsvine/markovify,orf/markovify | ---
+++
@@ -1,6 +1,7 @@
import random
import markovify
import sys, os
+import operator
HERE = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(HERE, "texts/sherlock.txt")) as f:
@@ -16,10 +17,14 @@
sent = text_model.make_sentence()
assert(len(sent) != 0)
+def get_sorted(chain_json... |
db13b52924a96bdfe8e38c20df07b62b6c455aa8 | Instanssi/dblog/handlers.py | Instanssi/dblog/handlers.py | # -*- coding: utf-8 -*-
from logging import Handler
from datetime import datetime
class DBLogHandler(Handler, object):
def __init__(self):
super(DBLogHandler, self).__init__()
def emit(self, record):
from models import DBLogEntry as _LogEntry
entry = _LogEntry()
... | # -*- coding: utf-8 -*-
from logging import Handler
from datetime import datetime
class DBLogHandler(Handler, object):
def __init__(self):
super(DBLogHandler, self).__init__()
def emit(self, record):
from models import DBLogEntry as _LogEntry
entry = _LogEntry()
... | Allow event saving by id | dblog: Allow event saving by id
| Python | mit | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | ---
+++
@@ -17,7 +17,10 @@
try:
entry.event = record.event
except:
- pass
+ try:
+ entry.event_id = record.event_id
+ except:
+ pass
try:
entry.user = record.user
except: |
91b3891078b889db98d3832f0c06e465a86e52ef | django_tenants/staticfiles/storage.py | django_tenants/staticfiles/storage.py | import os
from django.contrib.staticfiles.storage import StaticFilesStorage
from django_tenants.files.storages import TenantStorageMixin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage):
"""
Implemen... | import os
from django.contrib.staticfiles.storage import StaticFilesStorage
from django_tenants.files.storages import TenantStorageMixin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage):
"""
Implemen... | Fix regression in path handling of TenantStaticFileStorage. | Fix regression in path handling of TenantStaticFileStorage.
Fixes #197.
| Python | mit | tomturner/django-tenants,tomturner/django-tenants,tomturner/django-tenants | ---
+++
@@ -15,12 +15,12 @@
if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"):
self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT)
+ """
def path(self, name):
- """
if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or... |
fccc7b59e742bc887580c91c2c2dbeae2c85caee | wagtailannotatedimage/views.py | wagtailannotatedimage/views.py | from django.http import HttpResponse
from wagtail.wagtailimages.models import Filter, Image
def get_full_image_url(request, image_id):
image = Image.objects.get(id=image_id)
if image:
filter, _ = Filter.objects.get_or_create(spec='original')
orig_rendition = image.get_rendition(filter)
... | from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from wagtail.wagtailimages.models import Filter, get_iamge_model
Image = get_iamge_model()
def get_full_image_url(request, image_id):
image = get_object_or_404(Image, id=image_id)
if image:
filter, _ = Filter.objects.... | Allow for custom image models, 404 on image not found intead of error | Allow for custom image models, 404 on image not found intead of error
| Python | bsd-3-clause | takeflight/wagtailannotatedimage,takeflight/wagtailannotatedimage,takeflight/wagtailannotatedimage | ---
+++
@@ -1,9 +1,12 @@
from django.http import HttpResponse
-from wagtail.wagtailimages.models import Filter, Image
+from django.shortcuts import get_object_or_404
+from wagtail.wagtailimages.models import Filter, get_iamge_model
+
+Image = get_iamge_model()
def get_full_image_url(request, image_id):
- ima... |
97b07af6c6bcdd1a3b6c751a1462d88667c9e529 | tests/test_core.py | tests/test_core.py | import pytest
from mock import Mock
from saleor.core.utils import (
Country, get_country_by_ip, get_currency_for_country)
@pytest.mark.parametrize('ip_data, expected_country', [
({'country': {'iso_code': 'PL'}}, Country('PL')),
({'country': {'iso_code': 'UNKNOWN'}}, None),
(None, None),
({}, None... | import pytest
from mock import Mock
from saleor.core.utils import (
Country, get_country_by_ip, get_currency_for_country)
@pytest.mark.parametrize('ip_data, expected_country', [
({'country': {'iso_code': 'PL'}}, Country('PL')),
({'country': {'iso_code': 'UNKNOWN'}}, None),
(None, None),
({}, None... | Fix country ISO code for US | Fix country ISO code for US | Python | bsd-3-clause | UITools/saleor,HyperManTT/ECommerceSaleor,jreigel/saleor,tfroehlich82/saleor,UITools/saleor,UITools/saleor,tfroehlich82/saleor,itbabu/saleor,jreigel/saleor,KenMutemi/saleor,car3oon/saleor,mociepka/saleor,jreigel/saleor,KenMutemi/saleor,HyperManTT/ECommerceSaleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,itbabu/sal... | ---
+++
@@ -21,7 +21,7 @@
@pytest.mark.parametrize('country, expected_currency', [
(Country('PL'), 'PLN'),
- (Country('USA'), 'USD'),
+ (Country('US'), 'USD'),
(Country('GB'), 'GBP')])
def test_get_currency_for_country(country, expected_currency, monkeypatch):
currency = get_currency_for_coun... |
202fba50c287d3df99b22a4f30a96a3d8d9c8141 | tests/test_pypi.py | tests/test_pypi.py | from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
... | from unittest import TestCase
from semantic_release.pypi import upload_to_pypi
from . import mock
class PypiTests(TestCase):
@mock.patch('semantic_release.pypi.run')
def test_upload_without_arguments(self, mock_run):
upload_to_pypi(username='username', password='password')
self.assertEqual(
... | Update test after adding cleaning of dist | test: Update test after adding cleaning of dist
| Python | mit | relekang/python-semantic-release,relekang/python-semantic-release | ---
+++
@@ -12,6 +12,7 @@
self.assertEqual(
mock_run.call_args_list,
[
+ mock.call('rm -rf build dist'),
mock.call('python setup.py sdist bdist_wheel'),
mock.call('twine upload -u username -p password dist/*'),
mock.... |
fd2bd48ca9da96e894031f7979798672e1cebdea | tests/test_util.py | tests/test_util.py | # Copyright 2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | # Copyright 2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | Test util - unicode removal | Test util - unicode removal
| Python | apache-2.0 | ohagendorf/project_generator,project-generator/project_generator,sarahmarshy/project_generator,0xc0170/project_generator | ---
+++
@@ -13,14 +13,6 @@
# limitations under the License.
from project_generator.util import *
-def test_unicode_detection():
- try:
- print(u'\U0001F648')
- except UnicodeEncodeError:
- assert not unicode_available()
- else:
- assert unicode_available()
-
def test_flatten():
... |
2423958016d552a6f696b7124454c7b362c84a5f | pylearn2/scripts/dbm/dbm_metrics.py | pylearn2/scripts/dbm/dbm_metrics.py | #!/usr/bin/env python
import argparse
if __name__ == '__main__':
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("metric", help="the desired metric",
choices=["ais"])
parser.add_argument("model_path", help="path to the pickled DBM model")
args = par... | #!/usr/bin/env python
import argparse
from pylearn2.utils import serial
def compute_ais(model):
pass
if __name__ == '__main__':
# Possible metrics
metrics = {'ais': compute_ais}
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("metric", help="the desired metric",
... | Make the script recuperate the correct method | Make the script recuperate the correct method
| Python | bsd-3-clause | pkainz/pylearn2,KennethPierce/pylearnk,abergeron/pylearn2,alexjc/pylearn2,pombredanne/pylearn2,cosmoharrigan/pylearn2,bartvm/pylearn2,mclaughlin6464/pylearn2,ashhher3/pylearn2,se4u/pylearn2,abergeron/pylearn2,skearnes/pylearn2,lisa-lab/pylearn2,lamblin/pylearn2,fulmicoton/pylearn2,alexjc/pylearn2,matrogers/pylearn2,jam... | ---
+++
@@ -1,13 +1,23 @@
#!/usr/bin/env python
import argparse
+from pylearn2.utils import serial
+
+
+def compute_ais(model):
+ pass
if __name__ == '__main__':
+ # Possible metrics
+ metrics = {'ais': compute_ais}
+
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argume... |
6c0212b004aef96c305406352810bd40f3d5500e | censusreporter/config/prod/settings.py | censusreporter/config/prod/settings.py | from config.base.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
ALLOWED_HOSTS = [
'174.129.183.221',
'54.173.179.176',
'.censusreporter.org',
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.bac... | from config.base.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
ALLOWED_HOSTS = [
'.censusreporter.org',
'.compute-1.amazonaws.com', # allows viewing of instances directly
]
# From https://dryan.com/articles/elb-dja... | Add support for ELB to ALLOWED_HOSTS | Add support for ELB to ALLOWED_HOSTS
| Python | mit | censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter | ---
+++
@@ -5,11 +5,22 @@
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
+
ALLOWED_HOSTS = [
- '174.129.183.221',
- '54.173.179.176',
'.censusreporter.org',
+ '.compute-1.amazonaws.com', # allows viewing of instances directly
]
+
+# From https://dryan.com/arti... |
9c381721f4b4febef64276a2eb83c5a9169f7b8c | meta-analyze.py | meta-analyze.py | #!/usr/bin/env python
import argparse
def parsed_command_line():
"""Returns an object that results from parsing the command-line for this program argparse.ArgumentParser(...).parse_ags()
"""
parser = argparse.ArgumentParser(
description='Run multiple network snp analysis algorithms');
parse... | #!/usr/bin/env python
import argparse
class InputFile:
"""Represents a data in a specified format"""
def __init__(self, file_format, path):
self.file_format = file_format
self.path = path
def __repr__(self):
return "InputFile('{}','{}')".format(self.file_format, self.path)
def pa... | Add input file and converter abstraction | Add input file and converter abstraction
| Python | cc0-1.0 | NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs | ---
+++
@@ -2,13 +2,20 @@
import argparse
+class InputFile:
+ """Represents a data in a specified format"""
+ def __init__(self, file_format, path):
+ self.file_format = file_format
+ self.path = path
+ def __repr__(self):
+ return "InputFile('{}','{}')".format(self.file_format, sel... |
9a988056944700d6188f6e7164e68dcd35c342d8 | databench/analysis.py | databench/analysis.py | """Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should n... | """Analysis module for Databench."""
from flask import Blueprint, render_template
import databench.signals
LIST_ALL = []
class Analysis(object):
"""Databench's analysis class.
An optional :class:`databench.Signals` instance and :class:`flask.Blueprint`
can be dependency-injected, however that should n... | Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask. | Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask.
| Python | mit | svenkreiss/databench,svenkreiss/databench,svenkreiss/databench,svenkreiss/databench | ---
+++
@@ -33,6 +33,8 @@
blueprint=None
):
LIST_ALL.append(self)
+ self.show_in_index = True
+
self.name = name
self.import_name = import_name
@@ -51,9 +53,8 @@
else:
self.blueprint = blueprint
- self.show_in_index = True
+ s... |
90375db8488bc50b57bce9b10a2274ec3dc81787 | cyder/base/forms.py | cyder/base/forms.py | from django import forms
class BugReportForm(forms.Form):
bug = forms.CharField(label="Bug (required)", required=True)
description = forms.CharField(
label="Description (required)",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=True)
reproduce = forms.CharField(
l... | from django import forms
class BugReportForm(forms.Form):
bug = forms.CharField(label="Bug (required)", required=True)
description = forms.CharField(
label="Description (required)",
widget=forms.Textarea(attrs={'rows': 4, 'cols': 50}), required=True)
reproduce = forms.CharField(
l... | Check for strip attr for none values | Check for strip attr for none values
| Python | bsd-3-clause | murrown/cyder,akeym/cyder,murrown/cyder,OSU-Net/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,drkitty/cyder,zeeman/cyder,drkitty/cyder,drkitty/cyder,murrown/cyder,drkitty/cyder,akeym/cyder,OSU-Net/cyder,OSU-Net/cyder,zeeman/cyder,zeeman/cyder,murrown/cyder,zeeman/cyder | ---
+++
@@ -30,9 +30,13 @@
('Delete', 'Permanently delete user')))
-def strip_charfield(self, value):
- return charfield_clean(self, value.strip())
+charfield_clean = forms.fields.CharField.clean
-charfield_clean = forms.fields.CharField.clean
+def strip_charfield(self, value):
+ if hasattr... |
c23787680c40cc7f871f23e920486d07452d2cf3 | traits/__init__.py | traits/__init__.py | from __future__ import absolute_import
__version__ = '4.3.0'
| from __future__ import absolute_import
__version__ = '4.3.0'
# Add a NullHandler so 'traits' loggers don't complain when they get used.
import logging
class NullHandler(logging.Handler):
def handle(self, record):
pass
def emit(self, record):
pass
def createLock(self):
self.loc... | Use a NullHandler for all 'traits' loggers per best practice for logging. | FIX: Use a NullHandler for all 'traits' loggers per best practice for logging.
| Python | bsd-3-clause | burnpanck/traits,burnpanck/traits | ---
+++
@@ -1,3 +1,23 @@
from __future__ import absolute_import
__version__ = '4.3.0'
+
+
+# Add a NullHandler so 'traits' loggers don't complain when they get used.
+import logging
+
+class NullHandler(logging.Handler):
+
+ def handle(self, record):
+ pass
+
+ def emit(self, record):
+ pass
+... |
667294dcc3b8ab34618ad674c2b6ac8efeec0620 | places/admin.py | places/admin.py | from django.contrib.gis import admin
from models import Place
admin.site.register(Place, admin.OSMGeoAdmin)
| from django.contrib.gis import admin
from models import Place
try:
_model_admin = admin.OSMGeoAdmin
except AttributeError:
_model_admin = admin.ModelAdmin
admin.site.register(Place, _model_admin)
| Make it possible to run dev server on my desktop. | Make it possible to run dev server on my desktop.
While I'm accessing a suitable database remotely, I don't have enough
stuff installed locally to have OSMGeoAdmin (no GDAL installed, for
example).
| Python | bsd-3-clause | MAPC/masshealth,MAPC/masshealth | ---
+++
@@ -1,4 +1,9 @@
from django.contrib.gis import admin
from models import Place
-admin.site.register(Place, admin.OSMGeoAdmin)
+try:
+ _model_admin = admin.OSMGeoAdmin
+except AttributeError:
+ _model_admin = admin.ModelAdmin
+
+admin.site.register(Place, _model_admin) |
e8b44733ff44162f4a01de76b66046af23a9c946 | tcconfig/_error.py | tcconfig/_error.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
class NetworkInterfaceNotFoundError(Exception):
"""
Exception raised when network interface not found.
"""
class ModuleNotFoundError(Exception):
"""
Exception raised... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
class NetworkInterfaceNotFoundError(Exception):
"""
Exception raised when network interface not found.
"""
class ModuleNotFoundError(Exception):
"""
Exception raised... | Add custom arguments for InvalidParameterError | Add custom arguments for InvalidParameterError
| Python | mit | thombashi/tcconfig,thombashi/tcconfig | ---
+++
@@ -43,6 +43,30 @@
a traffic shaping rule.
"""
+ def __init__(self, *args, **kwargs):
+ self.__value = kwargs.pop("value", None)
+ self.__expected = kwargs.pop("expected", None)
+
+ super(ValueError, self).__init__(*args)
+
+ def __str__(self, *args, **kwargs):
+ ... |
1dd8e7ddfccd657fde2697fc1e39da7fb9c3548f | alg_insertion_sort.py | alg_insertion_sort.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def insertion_sort(a_list):
"""Insertion Sort algortihm."""
for index in range(1, len(a_list)):
current_value = a_list[index]
position = index
while position > 0 and a_list[pos... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def insertion_sort(a_list):
"""Insertion Sort algortihm.
Time complexity: O(n^2).
"""
for index in range(1, len(a_list)):
current_value = a_list[index]
position = index
... | Add to doc string: time complexity | Add to doc string: time complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -4,7 +4,10 @@
def insertion_sort(a_list):
- """Insertion Sort algortihm."""
+ """Insertion Sort algortihm.
+
+ Time complexity: O(n^2).
+ """
for index in range(1, len(a_list)):
current_value = a_list[index]
position = index |
1cbab715a647689aeda4679d7dcf4e60ff9ab5b1 | api/webview/models.py | api/webview/models.py | from django.db import models
from django_pgjson.fields import JsonField
class Document(models.Model):
source = models.CharField(max_length=100)
docID = models.CharField(max_length=100)
providerUpdatedDateTime = models.DateTimeField(null=True)
raw = JsonField()
normalized = JsonField()
| import json
import six
from requests.structures import CaseInsensitiveDict
from django.db import models
from django_pgjson.fields import JsonField
class Document(models.Model):
source = models.CharField(max_length=100)
docID = models.CharField(max_length=100)
providerUpdatedDateTime = models.DateTimeFi... | Add harvester response model in django ORM | Add harvester response model in django ORM
| Python | apache-2.0 | felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,mehanig/scrapi,felliott/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,fabianvf/scrapi | ---
+++
@@ -1,5 +1,9 @@
+import json
+
+import six
+from requests.structures import CaseInsensitiveDict
+
from django.db import models
-
from django_pgjson.fields import JsonField
@@ -11,3 +15,28 @@
raw = JsonField()
normalized = JsonField()
+
+
+class HarvesterResponse(models.Model):
+
+ method ... |
d1fd045791ad4d7c3544352faf68361637213f57 | product_onepage/templatetags/onepage_tags.py | product_onepage/templatetags/onepage_tags.py | """Gallery templatetags"""
from django.template import Library
from django.core.exceptions import ObjectDoesNotExist
register = Library()
@register.filter(name='divide')
def divide(dividend, divisor):
return dividend / divisor
@register.filter(name='get_language')
def get_language(list, language):
try:
... | """Gallery templatetags"""
from django.template import Library
from django.core.exceptions import ObjectDoesNotExist
register = Library()
@register.filter(name='divide')
def divide(dividend, divisor):
return dividend / divisor
@register.filter(name='get_language')
def get_language(queryset, language):
try:... | Fix variable name in get_language tag | Fix variable name in get_language tag
| Python | mit | emencia/emencia-product-onepage,emencia/emencia-product-onepage | ---
+++
@@ -11,11 +11,11 @@
@register.filter(name='get_language')
-def get_language(list, language):
+def get_language(queryset, language):
try:
- return list.get(language=language)
+ return queryset.get(language=language)
except ObjectDoesNotExist:
try:
- return list.... |
b5785cbd9586a767b37da2e0c71bcb1fcfed0604 | tests/main_test.py | tests/main_test.py | #!/usr/bin/env python3
from libpals.util import (
xor_find_singlechar_key,
hamming_distance,
fixed_xor
)
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphert... | #!/usr/bin/env python3
from libpals.util import (
xor_find_singlechar_key,
hamming_distance,
fixed_xor,
transpose
)
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlec... | Add test for the transpose function. | Add test for the transpose function.
| Python | bsd-2-clause | cpach/cryptopals-python3 | ---
+++
@@ -3,7 +3,8 @@
from libpals.util import (
xor_find_singlechar_key,
hamming_distance,
- fixed_xor
+ fixed_xor,
+ transpose
)
def test_xor_find_singlechar_key():
@@ -22,3 +23,8 @@
input = bytes.fromhex("1c0111001f010100061a024b53535009181c")
key = bytes.fromhex("68697420746865... |
2cc1f3dc699258fa7a571cde96a434b450bc0cf8 | phonenumber_field/formfields.py | phonenumber_field/formfields.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import CharField
from django.core.exceptions import ValidationError
from phonenumber_field.validators import validate_international_phonenumber
from phonenumber_field.phonen... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.forms.fields import CharField
from django.core.exceptions import ValidationError
from phonenumber_field.validators import validate_international_phonenumber
from phonenumber_field.phonen... | Support HTML5's input type 'tel' | Support HTML5's input type 'tel'
| Python | mit | hovel/django-phonenumber-field,hovel/django-phonenumber-field,stefanfoulis/django-phonenumber-field | ---
+++
@@ -15,6 +15,10 @@
}
default_validators = [validate_international_phonenumber]
+ def __init__(self, *args, **kwargs):
+ super(PhoneNumberField, self).__init__(*args, **kwargs)
+ self.widget.input_type = 'tel'
+
def to_python(self, value):
phone_number = to_python(val... |
21319fc8d22469911c1cbcc41ec7320b1d6141e9 | powerline/bindings/i3/powerline-i3.py | powerline/bindings/i3/powerline-i3.py | #!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from powerline import Powerline
from powerline.lib.monotonic import monotonic
import sys
import time
import i3
from threading import Lock
name = 'wm'
if len( sys.argv ) > 1:
name = sys.argv[1]
powerline = Powerline(name, renderer_module='i3bgbar')
powerline.update... | #!/usr/bin/env python
# vim:fileencoding=utf-8:noet
from powerline import Powerline
from powerline.lib.monotonic import monotonic
import sys
import time
import i3
from threading import Lock
name = 'wm'
if len( sys.argv ) > 1:
name = sys.argv[1]
powerline = Powerline(name, renderer_module='i3bgbar')
powerline.update... | Use 'with' instead of lock.acquire/release() | Use 'with' instead of lock.acquire/release()
| Python | mit | DoctorJellyface/powerline,bartvm/powerline,areteix/powerline,russellb/powerline,seanfisk/powerline,s0undt3ch/powerline,IvanAli/powerline,cyrixhero/powerline,blindFS/powerline,keelerm84/powerline,kenrachynski/powerline,IvanAli/powerline,darac/powerline,xfumihiro/powerline,Liangjianghao/powerline,darac/powerline,QuLogic/... | ---
+++
@@ -25,12 +25,11 @@
def render( event=None, data=None, sub=None ):
global lock
- lock.acquire()
- s = '[\n' + powerline.render(side='right')[:-2] + '\n]\n'
- s += ',[\n' + powerline.render(side='left' )[:-2] + '\n]'
- print ',[\n' + s + '\n]'
- sys.stdout.flush()
- lock.release()
+ with lock:
+ s = '[... |
5a39d00cf39e80a4e9f1ca8bbf0eac767d39f61d | nbgrader/tests/apps/test_nbgrader.py | nbgrader/tests/apps/test_nbgrader.py | import os
import sys
from .. import run_nbgrader, run_command
from .base import BaseTestApp
class TestNbGrader(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_nbgrader(["--help-all"])
def test_no_subapp(self):
"""Is the help displayed when no subapp... | import os
import sys
from .. import run_nbgrader, run_command
from .base import BaseTestApp
class TestNbGrader(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_nbgrader(["--help-all"])
def test_no_subapp(self):
"""Is the help displayed when no subapp... | Use sys.executable when executing nbgrader | Use sys.executable when executing nbgrader
| Python | bsd-3-clause | jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader | ---
+++
@@ -31,7 +31,7 @@
def test_check_version(self, capfd):
"""Is the version the same regardless of how we run nbgrader?"""
out1 = '\n'.join(
- run_command(["nbgrader", "--version"]).splitlines()[-3:]
+ run_command([sys.executable, "-m", "nbgrader", "--version"]).split... |
5212d6eabf199ed9ddd34bd6fd2b159f7b2e6a02 | tviserrys/views.py | tviserrys/views.py | from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from djan... | from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.template import RequestContext, loader
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from djan... | Add functionality to get latest tviits | Add functionality to get latest tviits
| Python | mit | DeWaster/Tviserrys,DeWaster/Tviserrys | ---
+++
@@ -6,6 +6,8 @@
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response, render
from tviit.models import Tviit, TviitForm
+from django.contrib.auth.models import User
+from user_profile.models import UserProfile
class IndexView(View)... |
409c69dd967f18ef99658ed63d54dc9723f84250 | anchorhub/builtin/github/collector.py | anchorhub/builtin/github/collector.py | """
File that initializes a Collector object designed for GitHub style markdown
files.
"""
from anchorhub.collector import Collector
from anchorhub.builtin.github.cstrategies import MarkdownATXCollectorStrategy
import anchorhub.builtin.github.converter as converter
import anchorhub.builtin.github.switches as ghswitche... | """
File that initializes a Collector object designed for GitHub style markdown
files.
"""
from anchorhub.collector import Collector
from anchorhub.builtin.github.cstrategies import \
MarkdownATXCollectorStrategy, MarkdownSetextCollectorStrategy
import anchorhub.builtin.github.converter as converter
import anchorh... | Use Setext strategy in GitHub built in Collector | Use Setext strategy in GitHub built in Collector
| Python | apache-2.0 | samjabrahams/anchorhub | ---
+++
@@ -4,7 +4,8 @@
"""
from anchorhub.collector import Collector
-from anchorhub.builtin.github.cstrategies import MarkdownATXCollectorStrategy
+from anchorhub.builtin.github.cstrategies import \
+ MarkdownATXCollectorStrategy, MarkdownSetextCollectorStrategy
import anchorhub.builtin.github.converter as ... |
e9f25dd0c9028613ef7317ad3a8287dc60b9a217 | slave/skia_slave_scripts/chromeos_install.py | slave/skia_slave_scripts/chromeos_install.py | #!/usr/bin/env python
# Copyright (c) 2013 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.
""" Install all executables, and any runtime resources that are needed by
*both* Test and Bench builders. """
from build_step ... | #!/usr/bin/env python
# Copyright (c) 2013 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.
""" Install all executables, and any runtime resources that are needed by
*both* Test and Bench builders. """
from build_step ... | Kill running Skia processes in ChromeOS Install step | Kill running Skia processes in ChromeOS Install step
(RunBuilders:Test-ChromeOS-Alex-GMA3150-x86-Debug,Test-ChromeOS-Alex-GMA3150-x86-Release,Perf-ChromeOS-Alex-GMA3150-x86-Release)
R=rmistry@google.com
Review URL: https://codereview.chromium.org/17599009
git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9748 2b... | Python | bsd-3-clause | google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbo... | ---
+++
@@ -16,6 +16,9 @@
class ChromeOSInstall(ChromeOSBuildStep, Install):
def _PutSCP(self, executable):
+ # First, make sure that the program isn't running.
+ ssh_utils.RunSSH(self._ssh_username, self._ssh_host, self._ssh_port,
+ ['killall', 'skia_%s' % executable])
ssh_utils.... |
182f070c69e59907eeda3c261d833a492af46967 | rojak-database/generate_media_data.py | rojak-database/generate_media_data.py | import MySQLdb as mysql
from faker import Factory
# Open database connection
db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database')
# Create new db cursor
cursor = db.cursor()
sql = '''
INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`,
`slogan`)
VALUES ('{}', '{}', '{}', '{}'... | import MySQLdb as mysql
from faker import Factory
# Open database connection
db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database')
# Create new db cursor
cursor = db.cursor()
sql = '''
INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`,
`slogan`)
VALUES ('{}', '{}', '{}', '{}'... | Update the default language for the media generator | Update the default language for the media generator
| Python | bsd-3-clause | CodeRiderz/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,CodeRiderz/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,CodeRiderz/rojak,pyk/rojak,pyk/rojak,bobbypriambodo/rojak,pyk/rojak,bobbypriambodo/rojak,rawgni/rojak,bobbypriambodo/rojak,CodeRiderz/rojak,pyk/rojak,pyk/rojak,... | ---
+++
@@ -14,12 +14,11 @@
'''
MAX_MEDIA=100
-fake = Factory.create('it_IT')
+fake = Factory.create()
for i in xrange(MAX_MEDIA):
# Generate random data for the media
media_name = fake.name() + ' Media ' + str(i)
website_name = media_name.lower().replace(' ', '')
- website_name = website_name.... |
5bc0226fe1ad03495e97dc2933fa17d18cd38bb9 | meetup_facebook_bot/models/speaker.py | meetup_facebook_bot/models/speaker.py | from sqlalchemy import Column, BIGINT, String, Integer
from meetup_facebook_bot.models.base import Base
class Speaker(Base):
__tablename__ = 'speakers'
id = Column(Integer, primary_key=True, autoincrement=True)
page_scoped_id = Column(BIGINT, unique=True)
name = Column(String(128), nullable=False)
... | from sqlalchemy import Column, BIGINT, String, Integer
from meetup_facebook_bot.models.base import Base
class Speaker(Base):
__tablename__ = 'speakers'
id = Column(Integer, primary_key=True, autoincrement=True)
page_scoped_id = Column(BIGINT)
name = Column(String(128), nullable=False)
token = Col... | Remove uniqueness constraint from page_scoped_id | Remove uniqueness constraint from page_scoped_id
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | ---
+++
@@ -6,7 +6,7 @@
class Speaker(Base):
__tablename__ = 'speakers'
id = Column(Integer, primary_key=True, autoincrement=True)
- page_scoped_id = Column(BIGINT, unique=True)
+ page_scoped_id = Column(BIGINT)
name = Column(String(128), nullable=False)
token = Column(String(128), unique=T... |
a87010c4c7ba6c9f1f295c8da688946d149c7fbd | metal/mmtl/glue/make_glue_datasets.py | metal/mmtl/glue/make_glue_datasets.py | import argparse
import os
import dill
from metal.mmtl.glue.glue_datasets import get_glue_dataset
def make_datasets(task, bert_version):
datasets = {}
for split in ["train", "dev", "test"]:
datasets[split] = get_glue_dataset(task, split, bert_version, run_spacy=True)
return datasets
def pickle_... | import argparse
import os
import dill
from metal.mmtl.glue.glue_datasets import get_glue_dataset
def make_datasets(task, bert_version):
datasets = {}
for split in ["train", "dev", "test"]:
datasets[split] = get_glue_dataset(
task, split, bert_version, max_len=200, run_spacy=True
... | Set max_len default to 200 when making glue datasets | Set max_len default to 200 when making glue datasets
| Python | apache-2.0 | HazyResearch/metal,HazyResearch/metal | ---
+++
@@ -9,7 +9,9 @@
def make_datasets(task, bert_version):
datasets = {}
for split in ["train", "dev", "test"]:
- datasets[split] = get_glue_dataset(task, split, bert_version, run_spacy=True)
+ datasets[split] = get_glue_dataset(
+ task, split, bert_version, max_len=200, run_sp... |
e5bda294e291a2d96b4f703a89128de9ee53a495 | src/geelweb/django/editos/models.py | src/geelweb/django/editos/models.py | from django.db import models
from geelweb.django.editos import settings
class Edito(models.Model):
title = models.CharField(max_length=100)
link = models.URLField()
button_label = models.CharField(max_length=20, default="Go !",
Required=False)
image = models.FileField(upload_to="editos")
... | from django.db import models
from geelweb.django.editos import settings
class Edito(models.Model):
title = models.CharField(max_length=100)
link = models.URLField()
button_label = models.CharField(max_length=20, default="Go !",
Required=False)
image = models.FileField(upload_to="editos")
... | Add date_created and date_updated to editos.Edito model | Add date_created and date_updated to editos.Edito model
| Python | mit | geelweb/django-editos,geelweb/django-editos | ---
+++
@@ -14,5 +14,8 @@
text_theme = models.CharField(max_length=10, choices=settings.EDITOS_THEMES,
default=settings.EDITOS_DEFAULT_THEME)
+ date_created = models.DateTimeField(auto_now_add=True)
+ date_updated = models.DateTimeField(auto_now=True)
+
def __unicode__(self):
r... |
a292c87137386bfdc7bc09b1f16269fe1c382858 | bedrock/mozorg/templatetags/qrcode.py | bedrock/mozorg/templatetags/qrcode.py | from hashlib import sha1
from django.conf import settings
import qrcode as qr
from django_jinja import library
from jinja2 import Markup
from qrcode.image.svg import SvgPathImage
QR_CACHE_PATH = settings.DATA_PATH.joinpath('qrcode_cache')
QR_CACHE_PATH.mkdir(exist_ok=True)
@library.global_function
def qrcode(data... | from hashlib import sha1
from pathlib import Path
import qrcode as qr
from django_jinja import library
from jinja2 import Markup
from qrcode.image.svg import SvgPathImage
QR_CACHE_PATH = Path('/tmp/qrcode_cache')
QR_CACHE_PATH.mkdir(exist_ok=True)
@library.global_function
def qrcode(data, box_size=20):
name = ... | Move QR Code cache to /tmp | Move QR Code cache to /tmp
| Python | mpl-2.0 | sylvestre/bedrock,craigcook/bedrock,alexgibson/bedrock,flodolo/bedrock,mozilla/bedrock,mozilla/bedrock,craigcook/bedrock,MichaelKohler/bedrock,MichaelKohler/bedrock,craigcook/bedrock,alexgibson/bedrock,pascalchevrel/bedrock,flodolo/bedrock,pascalchevrel/bedrock,MichaelKohler/bedrock,pascalchevrel/bedrock,alexgibson/bed... | ---
+++
@@ -1,6 +1,5 @@
from hashlib import sha1
-
-from django.conf import settings
+from pathlib import Path
import qrcode as qr
from django_jinja import library
@@ -8,7 +7,7 @@
from qrcode.image.svg import SvgPathImage
-QR_CACHE_PATH = settings.DATA_PATH.joinpath('qrcode_cache')
+QR_CACHE_PATH = Path('/t... |
b89115165c55e51e76a533ba4eb9637897319e0a | oidc_provider/management/commands/creatersakey.py | oidc_provider/management/commands/creatersakey.py | from Crypto.PublicKey import RSA
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Randomly generate a new RSA key for the OpenID server'
def handle(self, *args, **options):
try:
key = RSA.generate(1024)
f... | from Crypto.PublicKey import RSA
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Randomly generate a new RSA key for the OpenID server'
def handle(self, *args, **options):
try:
key = RSA.generate(1024)
f... | Fix use of deprecated Exception.message in Python 3 | Fix use of deprecated Exception.message in Python 3
| Python | mit | torreco/django-oidc-provider,ByteInternet/django-oidc-provider,wojtek-fliposports/django-oidc-provider,wayward710/django-oidc-provider,bunnyinc/django-oidc-provider,juanifioren/django-oidc-provider,wojtek-fliposports/django-oidc-provider,ByteInternet/django-oidc-provider,torreco/django-oidc-provider,bunnyinc/django-oid... | ---
+++
@@ -15,4 +15,4 @@
f.write(key.exportKey('PEM'))
self.stdout.write('RSA key successfully created at: ' + file_path)
except Exception as e:
- self.stdout.write('Something goes wrong: ' + e.message)
+ self.stdout.write('Something goes wrong: {0}'.forma... |
4de72b4bd349ebf16c0046c4ed9034914c03ffb5 | cea/interfaces/dashboard/api/utils.py | cea/interfaces/dashboard/api/utils.py |
from flask import current_app
import cea.config
import cea.inputlocator
def deconstruct_parameters(p):
params = {'name': p.name, 'type': p.typename,
'value': p.get(), 'help': p.help}
if isinstance(p, cea.config.ChoiceParameter):
params['choices'] = p._choices
if p.typename == 'We... |
from flask import current_app
import cea.config
import cea.inputlocator
def deconstruct_parameters(p: cea.config.Parameter):
params = {'name': p.name, 'type': p.typename, 'help': p.help}
try:
params["value"] = p.get()
except cea.ConfigError as e:
print(e)
params["value"] = ""
... | Fix `weather_helper` bug when creating new scenario | Fix `weather_helper` bug when creating new scenario
| Python | mit | architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst | ---
+++
@@ -7,9 +7,13 @@
import cea.inputlocator
-def deconstruct_parameters(p):
- params = {'name': p.name, 'type': p.typename,
- 'value': p.get(), 'help': p.help}
+def deconstruct_parameters(p: cea.config.Parameter):
+ params = {'name': p.name, 'type': p.typename, 'help': p.help}
+ try:
+... |
a390f3b711df89b2552bf059c89b1fd4f7ab1fa7 | towel/templatetags/modelview_list.py | towel/templatetags/modelview_list.py | from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_row(instance, fields):
for name in fields.split(','):
f = instance._meta.get_field(name)
if isinstance(f, models.ForeignKey):
... | from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_row(instance, fields):
for name in fields.split(','):
try:
f = instance._meta.get_field(name)
except models.FieldDoesNotExis... | Handle methods and non-field attributes | model_row: Handle methods and non-field attributes
| Python | bsd-3-clause | matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel | ---
+++
@@ -9,7 +9,14 @@
@register.filter
def model_row(instance, fields):
for name in fields.split(','):
- f = instance._meta.get_field(name)
+ try:
+ f = instance._meta.get_field(name)
+ except models.FieldDoesNotExist:
+ attr = getattr(instance, name)
+ ... |
266105d371193ccf0f02a3975ebdca04980b675b | eche/special_forms.py | eche/special_forms.py | from funcy.seqs import partition
from eche.eche_types import Symbol, List
def def_exclamation_mark(ast):
from eche.eval import eval_ast
_, key, val = ast
l = List()
l.append(key)
l.append(val)
l.env = ast.env
_, val = eval_ast(l, ast.env)
ast.env[key] = val
# if not isinstance(a... | from funcy.seqs import partition
from eche.eche_types import Symbol, List
def def_exclamation_mark(ast, env=None):
from eche.eval import eval_ast
_, key, val = ast
l = List()
l.append(key)
l.append(val)
l.env = ast.env
_, val = eval_ast(l, ast.env)
ast.env[key] = val
# if not is... | Add missing env keyword arg. | Add missing env keyword arg.
| Python | mit | skk/eche | ---
+++
@@ -3,7 +3,7 @@
from eche.eche_types import Symbol, List
-def def_exclamation_mark(ast):
+def def_exclamation_mark(ast, env=None):
from eche.eval import eval_ast
_, key, val = ast |
e2e1ea416d38565a419fff75f6ad4b776b74bc8e | blog/models.py | blog/models.py | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL conf... | from django.db import models
from organizer.models import Startup, Tag
# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/
class Post(models.Model):
title = models.CharField(max_length=63)
slug = models.SlugField(
max_length=63,
help_text='A label for URL conf... | Declare Meta class in Post model. | Ch03: Declare Meta class in Post model. [skip ci]
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | ---
+++
@@ -22,6 +22,11 @@
startups = models.ManyToManyField(
Startup, related_name='blog_posts')
+ class Meta:
+ verbose_name = 'blog post'
+ ordering = ['-pub_date', 'title']
+ get_latest_by = 'pub_date'
+
def __str__(self):
return "{} on {}".format(
... |
47c74590587e1e2ff5c79fd33c0019724ca96818 | tasty_rest_framework/renderers.py | tasty_rest_framework/renderers.py | from django.utils import timezone
from rest_framework.renderers import JSONRenderer
from rest_framework.utils import encoders
import datetime
import warnings
class TastyPieJSONEncoder(encoders.JSONEncoder):
def default(self, o):
if isinstance(o, datetime.datetime):
# TastyPie doesn't modify t... | from django.utils import timezone
from rest_framework.renderers import JSONRenderer
from rest_framework.utils import encoders
import datetime
import warnings
class TastyPieJSONEncoder(encoders.JSONEncoder):
def default(self, o):
if isinstance(o, datetime.datetime):
# TastyPie doesn't modify t... | Handle exception generated by timezone naive datetime objects. | Handle exception generated by timezone naive datetime objects.
| Python | mit | erikcw/tasty_rest_framework | ---
+++
@@ -13,7 +13,11 @@
# Remove TZ -- this has got to be a bug in TastyPie!
warning_message = "TastyPieJSONEncoder strips timezone information from datetime objects and converts them to the timezone in settings.TIME_ZONE. It is recommended that you don't use the TastyPieJSONRenderer unl... |
8aa6b13ca491d65a0519e429727073f082993aac | tests/framework/test_bmi_ugrid.py | tests/framework/test_bmi_ugrid.py | """Unit tests for the pymt.framwork.bmi_ugrid module."""
import xarray as xr
from pymt.framework.bmi_ugrid import Scalar, Vector
from pymt.framework.bmi_bridge import _BmiCap
grid_id = 0
class TestScalar:
def get_grid_rank(self, grid_id):
return 0
class ScalarBmi(_BmiCap):
_cls = TestScalar
de... | """Unit tests for the pymt.framwork.bmi_ugrid module."""
import xarray as xr
from pymt.framework.bmi_ugrid import Scalar, Vector
from pymt.framework.bmi_bridge import _BmiCap
grid_id = 0
class TestScalar:
def get_grid_rank(self, grid_id):
return 0
class ScalarBmi(_BmiCap):
_cls = TestScalar
de... | Test that attrs are passed to 'mesh' DataArray | Test that attrs are passed to 'mesh' DataArray
| Python | mit | csdms/pymt | ---
+++
@@ -25,6 +25,7 @@
assert grid.ndim == 0
assert grid.metadata["type"] == "scalar"
+ assert grid.data_vars["mesh"].attrs["type"] == "scalar"
assert isinstance(grid, xr.Dataset)
@@ -45,4 +46,5 @@
assert grid.ndim == 1
assert grid.metadata["type"] == "vector"
+ assert grid.d... |
18a0be3abb34c84c16c7cbd86ac25c984c1ab15e | thatforum/settings/home_server.py | thatforum/settings/home_server.py | from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'ENGINE': 'django.contrib.sqlite3',
'NAME': 'db_thatforum.sqlite3', # Or path to datab... | from .base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db_thatforum.sqlite3', # Or path to database file if using sqlite3.
}
}
| Update database settings in home server | Update database settings in home server
| Python | mit | hellsgate1001/thatforum_django,hellsgate1001/thatforum_django,hellsgate1001/thatforum_django | ---
+++
@@ -5,9 +5,7 @@
DATABASES = {
'default': {
- #'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
- 'ENGINE': 'django.contrib.sqlite3',
+ 'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db_thatforum.sqlite3', ... |
b913963f58f2e3a6842518b1cf0344ca262ecdde | src/shelltoprocess/__init__.py | src/shelltoprocess/__init__.py | """
This package implements a wxPython shell, based on PyShell,
which controls a seperate Python process, creating with the
`multiprocessing` package.
Here is the canonical way to use it:
1. Subclass multiprocessing.Process:
import multiprocessing
class CustomProcess(multiprocessing.Process):
def __init__(self,*... | """
This package implements a wxPython shell, based on PyShell,
which controls a seperate Python process, creating with the
`multiprocessing` package.
Here is the canonical way to use it:
1. Subclass multiprocessing.Process:
import multiprocessing
class CustomProcess(multiprocessing.Process):
def __init__(self,*... | Add supposedly unused imports back again | Add supposedly unused imports back again
| Python | mit | bittner/PythonTurtle,cool-RR/PythonTurtle | ---
+++
@@ -29,6 +29,9 @@
"""
import multiprocessing
+from shell import Shell
+from console import Console
+
def make_queue_pack():
""" |
c668bf1179e91be66f12857fc7b31ef66d287a42 | downstream_node/lib/node.py | downstream_node/lib/node.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from downstream_node.config import config
from downstream_node.models import Challenges, Files
from heartbeat import Heartbeat
from downstream_node.startup import db
__all__ = ['create_token', 'delete_token', 'add_file', 'remove_file',
'gen_challenges', 'updat... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from downstream_node.config import config
from downstream_node.models import Challenges, Files
from heartbeat import Heartbeat
from downstream_node.startup import db
__all__ = ['create_token', 'delete_token', 'add_file', 'remove_file',
'gen_challenge... | Insert filename only, not path | Insert filename only, not path
| Python | mit | Storj/downstream-node,Storj/downstream-node | ---
+++
@@ -1,5 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+import os
from downstream_node.config import config
from downstream_node.models import Challenges, Files
@@ -31,7 +32,7 @@
secret = getattr(config, 'HEARTBEAT_SECRET')
hb = Heartbeat(filepath, secret=secret)
hb.generate_challe... |
d754e44c725ff2b390d2f4ea52d29475b6e11f82 | src/akllt/management/commands/akllt_importnews.py | src/akllt/management/commands/akllt_importnews.py | from django.core.management.base import BaseCommand
from wagtail.wagtailcore.models import Page
from akllt.dataimport.news import import_news
from akllt.models import NewsStory
class Command(BaseCommand):
args = '<directory name>'
help = 'Imports data from old akl.lt website'
def handle(self, news_fold... | from django.core.management.base import BaseCommand
from wagtail.wagtailcore.models import Page
from akllt.dataimport.news import import_news
from akllt.models import NewsStory
class Command(BaseCommand):
args = '<directory name>'
help = 'Imports data from old akl.lt website'
def handle(self, news_fold... | Increment item count in news import mgmt command | Increment item count in news import mgmt command
| Python | agpl-3.0 | python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt | ---
+++
@@ -24,5 +24,6 @@
blurb=news_story['blurb'],
body=news_story['body'],
))
+ news_count += 1
self.stdout.write('Successfully imported %d news items\n' % news_count) |
810961f65c37d27c5e2d99cf102064d0b4e300f3 | project/apiv2/views.py | project/apiv2/views.py | from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.generics import ListAPIView
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import RetrieveUpdateDestroyAPIView
from bookmarks.m... | from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework_json_api.renderers import JSONRenderer
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from bookmarks.models import Bookmark
from bo... | Use ListCreateAPIView as base class to support bookmark creation | Use ListCreateAPIView as base class to support bookmark creation
| Python | mit | hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example | ---
+++
@@ -1,14 +1,13 @@
from django.db.models import Q
from django.shortcuts import render
from rest_framework.filters import OrderingFilter, SearchFilter
-from rest_framework.generics import ListAPIView
from rest_framework_json_api.renderers import JSONRenderer
-from rest_framework.generics import RetrieveUpda... |
65dd9b35b75dd4ccc6dbc34d53071716a377d532 | thecut/authorship/factories.py | thecut/authorship/factories.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
try:
from faker import Factory as FakerFactory
except ImportError, error:
message = '{0}. Try running `pip install fake-factory`.'.format(error)
raise ImportError(message)
try:
import factory
except ImportError, error:
... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
try:
from faker import Factory as FakerFactory
except ImportError as error:
message = '{0}. Try running `pip install fake-factory`.'.format(error)
raise ImportError(message)
try:
import factory
except ImportError as error... | Update exception handling syntax for python 3 compatibility. | Update exception handling syntax for python 3 compatibility.
| Python | apache-2.0 | thecut/thecut-authorship | ---
+++
@@ -3,13 +3,13 @@
try:
from faker import Factory as FakerFactory
-except ImportError, error:
+except ImportError as error:
message = '{0}. Try running `pip install fake-factory`.'.format(error)
raise ImportError(message)
try:
import factory
-except ImportError, error:
+except ImportE... |
3dfe299893a5c4259b2f6abd3f9e2e458a32ef44 | src/sentry/web/frontend/react_page.py | src/sentry/web/frontend/react_page.py | from __future__ import absolute_import
from django.http import HttpResponse
from django.template import loader, Context
from sentry.web.frontend.base import BaseView, OrganizationView
class ReactMixin(object):
def handle_react(self, request):
context = Context({'request': request})
template = lo... | from __future__ import absolute_import
from django.core.context_processors import csrf
from django.http import HttpResponse
from django.template import loader, Context
from sentry.web.frontend.base import BaseView, OrganizationView
class ReactMixin(object):
def handle_react(self, request):
context = Con... | Make sure all React pages have a CSRF token in session | Make sure all React pages have a CSRF token in session
Fixes GH-2419
| Python | bsd-3-clause | mitsuhiko/sentry,zenefits/sentry,gencer/sentry,daevaorn/sentry,daevaorn/sentry,alexm92/sentry,fotinakis/sentry,looker/sentry,JamesMura/sentry,gencer/sentry,mvaled/sentry,JackDanger/sentry,ifduyue/sentry,nicholasserra/sentry,jean/sentry,mvaled/sentry,mvaled/sentry,BuildingLink/sentry,JackDanger/sentry,JamesMura/sentry,i... | ---
+++
@@ -1,5 +1,6 @@
from __future__ import absolute_import
+from django.core.context_processors import csrf
from django.http import HttpResponse
from django.template import loader, Context
@@ -9,6 +10,8 @@
class ReactMixin(object):
def handle_react(self, request):
context = Context({'request... |
b5bb360a78eb3493a52a4f085bb7ae2ef1355cdd | scavenger/net_utils.py | scavenger/net_utils.py | import subprocess
import requests
def logged_in():
"""Check whether the device has logged in.
Return a dictionary containing:
username
byte
duration (in seconds)
Return False if no logged in
"""
r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login',
... | import subprocess
import requests
def check_online():
"""Check whether the device has logged in.
Return a dictionary containing:
username
byte
duration (in seconds)
Return False if no logged in
"""
r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login',
... | Change name: logged_in => check_online | Change name: logged_in => check_online
| Python | mit | ThomasLee969/scavenger | ---
+++
@@ -1,7 +1,7 @@
import subprocess
import requests
-def logged_in():
+def check_online():
"""Check whether the device has logged in.
Return a dictionary containing:
username |
ad87d1d9860ea394af261c3298403016d78dc1e1 | bitcoin/__init__.py | bitcoin/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2012-2013 by its contributors. See AUTHORS for details.
#
# Distributed under the MIT/X11 software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#
VERSION = (0,0,1, 'alpha', 0)
def get_version():
v... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2012-2013 by its contributors. See AUTHORS for details.
#
# Distributed under the MIT/X11 software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#
VERSION = (0,0,1, 'alpha', 0)
def get_version():
v... | Remove spaces from version string. | Remove spaces from version string. | Python | mit | monetizeio/python-bitcoin | ---
+++
@@ -15,10 +15,10 @@
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
- version = '%s pre-alpha' % version
+ version = '%spre-alpha' % version
else:
if VERSION[3] != 'final':
- version = "%s %s" % (version, VERSIO... |
643634e96554b00214ca4f0d45343e61b0df8e5a | foxybot/bot_help.py | foxybot/bot_help.py | """Provide a class to load and parse the help file and
Provide a simple interface for retrieving help entries"""
import json
import os
class HelpManager(object):
_help_dict = {}
_last_modified = 0
@staticmethod
def get_help(lang, key):
""" Retrieve a given commands help text with given lang... | """Provide a class to load and parse the help file and
Provide a simple interface for retrieving help entries"""
import json
import os
class HelpManager(object):
_help_dict = {}
_last_modified = 0
@staticmethod
def get_help(lang, key):
""" Retrieve a given commands help text with given lang... | Remove unneeded debug cod e | Remove unneeded debug cod
e
| Python | bsd-2-clause | 6180/foxybot | ---
+++
@@ -42,5 +42,3 @@
except OSError as ex:
print("[ERROR] Cannot find `help.json`")
print(ex)
-
- print(HelpManager._help_dict) |
c434cf202de60d052f61f8608e48b5d7645be1c0 | dear_astrid/test/test_rtm_importer.py | dear_astrid/test/test_rtm_importer.py | # pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring
from __future__ import absolute_import
from unittest import TestCase
from nose.tools import *
from mock import *
from dear_astrid.rtm.importer import Importer as rtmimp
class TestRTMImport(TestCase):
def setUp(self):
self.patches = di... | # pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring
from __future__ import absolute_import
from unittest import TestCase
from nose.tools import *
from mock import *
from dear_astrid.rtm.importer import *
class TestRTMImport(TestCase):
def setUp(self):
self.patches = dict(
time = ... | Clean up names and comments for consistency | Clean up names and comments for consistency
| Python | mit | rwstauner/dear_astrid,rwstauner/dear_astrid | ---
+++
@@ -7,7 +7,7 @@
from nose.tools import *
from mock import *
-from dear_astrid.rtm.importer import Importer as rtmimp
+from dear_astrid.rtm.importer import *
class TestRTMImport(TestCase):
def setUp(self):
@@ -20,26 +20,26 @@
self.mocks[k] = v.start()
def test_sleep_before_rtm(self):
- ... |
3a72b9164fc31e4e7f29715729160a48a7ce2f84 | source/tyr/migrations/versions/266658781c00_instances_nullable_in_equipments_provider.py | source/tyr/migrations/versions/266658781c00_instances_nullable_in_equipments_provider.py | """
column 'instances' will be deleted later. Has to be nullable for transition
Revision ID: 266658781c00
Revises: 204aae05372a
Create Date: 2019-04-15 16:27:22.362244
"""
# revision identifiers, used by Alembic.
revision = '266658781c00'
down_revision = '204aae05372a'
from alembic import op
import sqlalchemy as sa... | """
column 'instances' will be deleted later. Has to be nullable for transition
Revision ID: 266658781c00
Revises: 204aae05372a
Create Date: 2019-04-15 16:27:22.362244
"""
# revision identifiers, used by Alembic.
revision = '266658781c00'
down_revision = '204aae05372a'
from alembic import op
import sqlalchemy as sa... | Add required default value before downgrade migration | Add required default value before downgrade migration
| Python | agpl-3.0 | xlqian/navitia,kinnou02/navitia,xlqian/navitia,Tisseo/navitia,kinnou02/navitia,xlqian/navitia,xlqian/navitia,Tisseo/navitia,Tisseo/navitia,CanalTP/navitia,kinnou02/navitia,Tisseo/navitia,CanalTP/navitia,CanalTP/navitia,xlqian/navitia,CanalTP/navitia,CanalTP/navitia,Tisseo/navitia,kinnou02/navitia | ---
+++
@@ -21,6 +21,7 @@
def downgrade():
+ op.execute("UPDATE equipments_provider SET instances = '{null_instance}';")
op.alter_column(
'equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=False
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.