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 |
|---|---|---|---|---|---|---|---|---|---|---|
c64060482a34036615805b13416c78bb78a3058a | swh/web/common/urlsindex.py | swh/web/common/urlsindex.py | # Copyright (C) 2017-2018 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from django.conf.urls import url
class UrlsIndex(object):
"""
... | # Copyright (C) 2017-2018 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from django.conf.urls import url
class UrlsIndex(object):
"""
... | Allow to register unnamed django views | common: Allow to register unnamed django views
| Python | agpl-3.0 | SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui | ---
+++
@@ -30,8 +30,11 @@
"""
if cls.scope not in cls.urlpatterns:
cls.urlpatterns[cls.scope] = []
- cls.urlpatterns[cls.scope].append(url(url_pattern, view,
- name=view_name))
+ if view_name:
+ cls.urlpatterns[cls.s... |
ee1e19b023bfed3dfec606bc2bbe08876caf80ef | parse-demo.py | parse-demo.py | #!/usr/bin/python3
import sys, os
import nltk
if len(sys.argv) < 2:
print("Please supply a filename.")
sys.exit(1)
filename = sys.argv[1]
with open(filename, 'r') as f:
data = f.read()
# Break the input down into sentences, then into words, and position tag
# those words.
raw_sentences = nltk.sent_toke... | #!/usr/bin/python3
import sys, os
import nltk
if len(sys.argv) < 2:
print("Please supply a filename.")
sys.exit(1)
filename = sys.argv[1]
with open(filename, 'r') as f:
data = f.read()
# Break the input down into sentences, then into words, and position tag
# those words.
raw_sentences = nltk.sent_toke... | Use better syntax for unpacking tuples | Use better syntax for unpacking tuples
| Python | mit | alexander-bauer/syllabus-summary | ---
+++
@@ -36,4 +36,4 @@
print("Key elements:")
for subtree in tree.subtrees(filter = lambda t: t.label() == 'NP'):
- print(" %s" % ' '.join(wordtag[0] for wordtag in subtree.leaves()))
+ print(" %s" % ' '.join(word for (word, tag) in subtree.leaves())) |
28c8dfd6e3da8525d8379a46244a510db9c34aa5 | pytablewriter/writer/text/_spacealigned.py | pytablewriter/writer/text/_spacealigned.py | import copy
import dataproperty
from ._csv import CsvTableWriter
class SpaceAlignedTableWriter(CsvTableWriter):
"""
A table writer class for space aligned format.
:Example:
:ref:`example-space-aligned-table-writer`
.. py:method:: write_table
|write_table| with space aligne... | import copy
import dataproperty
from ._csv import CsvTableWriter
class SpaceAlignedTableWriter(CsvTableWriter):
"""
A table writer class for space aligned format.
:Example:
:ref:`example-space-aligned-table-writer`
.. py:method:: write_table
|write_table| with space aligne... | Fix constructor for SpaceAlignedTableWriter class | Fix constructor for SpaceAlignedTableWriter class
| Python | mit | thombashi/pytablewriter | ---
+++
@@ -30,6 +30,8 @@
super().__init__()
self.column_delimiter = " "
+ self.char_cross_point = " "
+
self.is_padding = True
self.is_formatting_float = True
|
9d70dc1f82fb807c02f4ccfa04bef7f6da36cbc6 | cluster/context_processors.py | cluster/context_processors.py | from models import Job
def running_jobs(request):
if request.user.is_authenticated():
temp = len(Job.get_running_jobs(user=request.user))
return {"running_jobs": temp}
else:
return {"running_jobs": None}
| from models import Job
from interface import get_all_jobs
def running_jobs(request):
if request.user.is_authenticated():
# hack to get numbers to update
get_all_jobs(request.user)
temp = len(Job.get_running_jobs(user=request.user))
return {"running_jobs": temp}
else:
re... | Add a hack so that the number of jobs running will update correctly | Add a hack so that the number of jobs running will update correctly
| Python | mit | crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp | ---
+++
@@ -1,8 +1,11 @@
from models import Job
+from interface import get_all_jobs
def running_jobs(request):
if request.user.is_authenticated():
+ # hack to get numbers to update
+ get_all_jobs(request.user)
temp = len(Job.get_running_jobs(user=request.user))
return {"runn... |
e46c0f037e88c245f3c4dfa94c155b6a0a58d90a | sunpy/data/setup_package.py | sunpy/data/setup_package.py | def get_package_data():
return {'sunpy.data': ['sunpyrc'],
'sunpy.data.test': ['*.*', '*/*.*']}
| def get_package_data():
return {'sunpy.data': ['sunpyrc'],
'sunpy.data.test': ['*', '*/*']}
| Fix the timeseries tests in the installed package | Fix the timeseries tests in the installed package
| Python | bsd-2-clause | dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy | ---
+++
@@ -1,3 +1,3 @@
def get_package_data():
return {'sunpy.data': ['sunpyrc'],
- 'sunpy.data.test': ['*.*', '*/*.*']}
+ 'sunpy.data.test': ['*', '*/*']} |
9ce80d4b4a27e5a32504c6b00ffcff846c53a649 | froide/publicbody/widgets.py | froide/publicbody/widgets.py | import json
from django import forms
from .models import PublicBody
class PublicBodySelect(forms.Widget):
input_type = "text"
template_name = 'publicbody/_chooser.html'
initial_search = None
class Media:
extend = False
js = ('js/publicbody.js',)
def set_initial_search(self, sea... | import json
from django import forms
from .models import PublicBody
class PublicBodySelect(forms.Widget):
input_type = "text"
template_name = 'publicbody/_chooser.html'
initial_search = None
class Media:
extend = False
js = ('js/publicbody.js',)
def set_initial_search(self, sea... | Fix super call for Python 2.7 | Fix super call for Python 2.7 | Python | mit | fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide | ---
+++
@@ -25,7 +25,7 @@
pb_desc = pb.get_label()
except (ValueError, PublicBody.DoesNotExist):
pass
- context = super().get_context(name, value, attrs)
+ context = super(PublicBodySelect, self).get_context(name, value, attrs)
context['widget'].up... |
fa01bae61830e501e62997f456f9533b654eb425 | utils.py | utils.py | import numpy as np
def overwrite_labels(y):
classes = np.unique(y)
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
| import numpy as np
from sklearn import cross_validation
def overwrite_labels(y):
classes = np.unique(y)
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
def train_test_split(X, y, test_size=0.2):
data = cross_validation.train_test_split(X, y, test_size=test_size)
training = data[0], data[... | Add data splitter for cross validation | Add data splitter for cross validation
| Python | mit | IshitaTakeshi/SCW | ---
+++
@@ -1,4 +1,5 @@
import numpy as np
+from sklearn import cross_validation
def overwrite_labels(y):
@@ -6,3 +7,10 @@
y[y==classes[0]] = -1
y[y==classes[1]] = 1
return y
+
+
+def train_test_split(X, y, test_size=0.2):
+ data = cross_validation.train_test_split(X, y, test_size=test_size)
+... |
62edeb51184758d29be07fbee6deaed0f931760f | word-count/word_count.py | word-count/word_count.py | def word_count(s):
words = strip_punc(s.lower()).split()
return {word: words.count(word) for word in set(words)}
def strip_punc(s):
return "".join(ch if ch.isalnum() else " " for ch in s)
| def word_count(s):
words = strip_punc(s).lower().split()
return {word: words.count(word) for word in set(words)}
def strip_punc(s):
return "".join(ch if ch.isalnum() else " " for ch in s)
| Move .lower() method call for readability | Move .lower() method call for readability
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,5 +1,5 @@
def word_count(s):
- words = strip_punc(s.lower()).split()
+ words = strip_punc(s).lower().split()
return {word: words.count(word) for word in set(words)}
|
86d4aa3e5895d5f7ac029df82c63e2b1e29e8c2d | spc/types.py | spc/types.py | """
All the different types that the compiler handles.
"""
from collections import namedtuple
IntegerType = namedtuple('IntegerType', [])
Integer = IntegerType()
ByteType = namedtuple('ByteType', [])
Byte = ByteType()
PointerTo = namedtuple('PointerTo', ['type'])
ArrayOf = namedtuple('ArrayOf', ['type', 'count'])
Fu... | """
All the different types that the compiler handles.
"""
from collections import namedtuple
IntegerType = namedtuple('IntegerType', [])
Integer = IntegerType()
ByteType = namedtuple('ByteType', [])
Byte = ByteType()
PointerTo = namedtuple('PointerTo', ['type'])
ArrayOf = namedtuple('ArrayOf', ['type', 'count'])
Fu... | Add note that Struct's field collection is an OrderedDict | Add note that Struct's field collection is an OrderedDict
| Python | mit | adamnew123456/spc,adamnew123456/spc | ---
+++
@@ -15,7 +15,9 @@
TypeName = namedtuple('TypeName', ['name'])
# Structure is a bit of an oddity - it can't actually be used in 'raw form'
-# by the user, but is always aliased in a declare block
+# by the user, but is always aliased in a declare block.
+#
+# Also, fields is an OrderedDict, since the order... |
1ab00dba5c52b90d3c54ab7832abe7bd785575b4 | bdo_platform/settings_management/development_sskalidakis.py | bdo_platform/settings_management/development_sskalidakis.py | from bdo_platform.settings_management.development import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bdo_platform',
'USER': 'postgres',
'PASSWORD': 'sssshmmy',
'HOST': 'localhost',
'PORT': '5432',
},
'UBITECH_POSTG... | from bdo_platform.settings_management.development import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bdo_local_database',
'USER': 'postgres',
'PASSWORD': 'sssshmmy',
'HOST': 'localhost',
'PORT': '5432',
},
'UBITECH... | Change in database configuration file | Change in database configuration file
| Python | mit | dipapaspyros/bdo_platform,dipapaspyros/bdo_platform,dipapaspyros/bdo_platform | ---
+++
@@ -2,7 +2,7 @@
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
- 'NAME': 'bdo_platform',
+ 'NAME': 'bdo_local_database',
'USER': 'postgres',
'PASSWORD': 'sssshmmy',
'HOST': 'localhost', |
f75d30c7c6fe56bb3e4b97cbdc9ff9deba6e211e | astroquery/open_exoplanet_catalogue/tests/test_open_exoplanet_catalogue_local.py | astroquery/open_exoplanet_catalogue/tests/test_open_exoplanet_catalogue_local.py | import os
import urllib
from xml.etree import ElementTree as ET
from astropy.tests.helper import pytest
from ...utils.testing_tools import MockResponse
from ... import open_exoplanet_catalogue as oec
@pytest.fixture(autouse=True)
def patch_urlopen(request):
mp = request.getfuncargvalue("monkeypatch")
mp.setatt... | import os
import urllib
from xml.etree import ElementTree as ET
from astropy.tests.helper import pytest
from ...utils.testing_tools import MockResponse
from ... import open_exoplanet_catalogue as oec
@pytest.fixture(autouse=True)
def patch_urlopen(request):
mp = request.getfuncargvalue("monkeypatch")
mp.setatt... | Fix to local data filepath | Fix to local data filepath
| Python | bsd-3-clause | ceb8/astroquery,imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery | ---
+++
@@ -14,7 +14,7 @@
def get_mock_return(url, params=None, timeout=10,**kwargs):
# dummy function to replace urllib get functionality
# function returns what the http request would but with local data
- content = open(data_path('systems.xml.gz'), "r").read()
+ content = open('data/systems.xml.gz... |
6dea77fa9693a4e6c934e92d56c3fb43fc13bb13 | pronto_praise/pronto_praise/urls.py | pronto_praise/pronto_praise/urls.py | """pronto_praise URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... | """pronto_praise URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... | Set praise list as home | Set praise list as home
| Python | mit | prontotools/pronto-praise,prontotools/pronto-praise,prontotools/pronto-praise,prontotools/pronto-praise | ---
+++
@@ -19,5 +19,5 @@
urlpatterns = [
url(r'^admin/', admin.site.urls),
- url(r'^praises/', include('praises.urls')),
+ url(r'^', include('praises.urls')),
] |
4dceb440069d63133bffe928b5c8aa756574a41c | lowfat/validator.py | lowfat/validator.py | """
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as excepti... | """
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as excepti... | Fix problem with sites that blocks bots | Fix problem with sites that blocks bots
| Python | bsd-3-clause | softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat | ---
+++
@@ -15,6 +15,11 @@
except HTTPError as exception:
if exception.code == 410:
raise ValidationError("Online document was removed.") # This is the code returned by Google Drive
+ elif exception.code == 403:
+ req = request.Request(url, headers={'User-Agent' : "lowFAT... |
02a975356d6a6b36cc565e8f4b771497867f09dd | tests/test_factorization.py | tests/test_factorization.py | import random
import unittest
from algorithms.factorization.pollard_rho import pollard_rho
from algorithms.factorization.trial_division import trial_division
from algorithms.factorization.fermat import fermat
class TestFermat(unittest.TestCase):
def test_fermat(self):
x = random.randint(1, 100000000)
... | import random
import unittest
from algorithms.factorization.pollard_rho import pollard_rho
from algorithms.factorization.trial_division import trial_division
from algorithms.factorization.fermat import fermat
class TestFermat(unittest.TestCase):
def test_fermat(self):
x = random.randint(1, 100000000)
... | Add test case for Pollard's Rho at zero to bump test coverage | Add test case for Pollard's Rho at zero to bump test coverage
| Python | bsd-3-clause | stphivos/algorithms | ---
+++
@@ -27,6 +27,14 @@
res *= j
self.assertEqual(x, res)
+ def test_pollard_rho_x_is_zero(self):
+ x = 0
+ factors = pollard_rho(x)
+ res = 1
+ for j in factors:
+ res *= j
+ self.assertEqual(x, res)
+
class TestTrialDivision(unittest.Tes... |
d5d33f9fb77fd0d9bb4410971e0acd54b8cbf084 | latest_tweets/management/commands/latest_tweets_update.py | latest_tweets/management/commands/latest_tweets_update.py | from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
from ..models import Tweet
from ..utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_... | from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from twitter import OAuth, Twitter
from latest_tweets.models import Tweet
from latest_tweets.utils import update_tweets
@transaction.atomic
def update_user(user):
t = Twitter(auth=OAuth(
... | Fix imports for management command | Fix imports for management command
| Python | bsd-3-clause | blancltd/django-latest-tweets | ---
+++
@@ -3,8 +3,8 @@
from django.db import transaction
from twitter import OAuth, Twitter
-from ..models import Tweet
-from ..utils import update_tweets
+from latest_tweets.models import Tweet
+from latest_tweets.utils import update_tweets
@transaction.atomic |
fc8672f3fc8f70f570f3a85fccf5625d3f514c12 | osrframework/__init__.py | osrframework/__init__.py | # -*- coding: utf-8 -*-
#
##################################################################################
#
# Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# OSRFramework is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gener... | # -*- coding: utf-8 -*-
#
##################################################################################
#
# Copyright 2014-2017 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com)
#
# OSRFramework is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gener... | Prepare 0.17.0 Vegas for BlackHat Arsenal | Prepare 0.17.0 Vegas for BlackHat Arsenal
| Python | agpl-3.0 | i3visio/osrframework | ---
+++
@@ -23,4 +23,4 @@
# Calling the logger when being imported
osrframework.utils.logger.setupLogger(loggerName="osrframework")
-__version__="0.17.0b"
+__version__="0.17.0" |
6c6f6ec6c5a895f083ff8c9b9a0d76791bb13ce9 | app/eve_api/tasks/static.py | app/eve_api/tasks/static.py | from celery.decorators import task
from eve_proxy.models import CachedDocument
from eve_api.utils import basic_xml_parse_doc
from eve_api.models import EVESkill, EVESkillGroup
@task()
def import_eve_skills():
"""
Imports the skill tree and groups
"""
char_doc = CachedDocument.objects.api_query('/eve/S... | from celery.decorators import task
from eve_proxy.models import CachedDocument
from eve_api.utils import basic_xml_parse_doc
from eve_api.models import EVESkill, EVESkillGroup
@task()
def import_eve_skills():
"""
Imports the skill tree and groups
"""
char_doc = CachedDocument.objects.api_query('/eve/S... | Support if skill group/types are changed | Support if skill group/types are changed
| Python | bsd-3-clause | nikdoof/test-auth | ---
+++
@@ -17,13 +17,13 @@
for group in values['skillGroups']:
gobj, created = EVESkillGroup.objects.get_or_create(id=group['groupID'])
- if created:
+ if created or not gobj.name or not gobj.name == group['groupName']:
gobj.name = group['groupName']
gobj.save(... |
f94110a91db9f0e52209e470b6ed8c4b4b3fe30c | common/helpers.py | common/helpers.py | from django.core.mail import EmailMessage
from django.template import loader, Context
from django.conf import settings
def send_email(to_list, subject, message_template, message_context):
message_context.update({
'BASE_URL': settings.BASE_URL
})
context = Context(message_context)
message = loa... | from django.core.mail import EmailMessage
from django.template import loader, Context
from django.conf import settings
def send_email(to_list, subject, message_template, message_context):
message_context.update({
'BASE_URL': settings.BASE_URL
})
# Turn a single email into a list of one element
... | Allow a single email as the to email field | Allow a single email as the to email field
| Python | mit | Socialsquare/RunningCause,Socialsquare/RunningCause,Socialsquare/RunningCause,Socialsquare/RunningCause | ---
+++
@@ -7,6 +7,9 @@
message_context.update({
'BASE_URL': settings.BASE_URL
})
+ # Turn a single email into a list of one element
+ if isinstance(to_list, str) or isinstance(to_list, unicode):
+ to_list = [to_list, ]
context = Context(message_context)
message = loader.get_... |
94cae9c13ac90a7de50cfaf998b9b423e7a2eaf1 | csunplugged/resources/utils/resource_valid_configurations.py | csunplugged/resources/utils/resource_valid_configurations.py | """Create list of all possible valid resource combinations."""
import itertools
from utils.bool_to_yes_no import bool_to_yes_no
def resource_valid_configurations(valid_options, header_text=True):
"""Return list of all possible valid resource combinations.
Args:
valid_options: A dictionary containing... | """Create list of all possible valid resource combinations."""
import itertools
from utils.bool_to_yes_no import bool_to_yes_no
def resource_valid_configurations(valid_options, header_text=True):
"""Return list of all possible valid resource combinations.
Args:
valid_options: A dictionary containing... | Fix bug where boolean combination values were not changed to strings | Fix bug where boolean combination values were not changed to strings
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -18,9 +18,10 @@
if header_text:
valid_options["header_text"] = ["", "Example header"]
# Change all booleans to text to mimic forms
- for (key, value) in valid_options.items():
- if isinstance(value, bool):
- valid_options[key] = bool_to_yes_no(value)
+ for (key, v... |
61cf3a2f99c01d5da0d75a5ff6b0b2c4cac83487 | plugins/random/plugin.py | plugins/random/plugin.py | import random
from cardinal.decorators import command
class RandomPlugin:
@command('roll')
def roll(self, cardinal, user, channel, msg):
args = msg.split(' ')
args.pop(0)
dice = []
for arg in args:
try:
sides = int(arg)
dice.append(... | import random
import re
from cardinal.decorators import command
def parse_roll(arg):
# some people might separate with commas
arg = arg.rstrip(',')
if match := re.match(r'^(\d+)?d(\d+)$', arg):
num_dice = match.group(1)
sides = match.group(2)
elif match := re.match(r'^d?(\d+)$', arg)... | Add support for 5d20 instead of d20 | Add support for 5d20 instead of d20
| Python | mit | JohnMaguire/Cardinal | ---
+++
@@ -1,6 +1,23 @@
import random
+import re
from cardinal.decorators import command
+
+
+def parse_roll(arg):
+ # some people might separate with commas
+ arg = arg.rstrip(',')
+
+ if match := re.match(r'^(\d+)?d(\d+)$', arg):
+ num_dice = match.group(1)
+ sides = match.group(2)
+ ... |
86ff9a791290455cd169cca7697587a2ad9f350b | services/flickr.py | services/flickr.py | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/o... | Rewrite Flickr to use the new scope selection system | Rewrite Flickr to use the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/oauth-proxy,foauth/foauth.org | ---
+++
@@ -14,17 +14,21 @@
api_domain = 'api.flickr.com'
available_permissions = [
- # (None, 'access only your public photos'),
- # ('read', 'access your public and private photos'),
- # ('write', 'upload, edit and replace your photos'),
+ (None, 'access only your public phot... |
f5ddffdf4c0cf85dcade939ff4e3b9b72b968d38 | mfr/image/render.py | mfr/image/render.py | """Image renderer module."""
def render_img_tag(fp, src=None, alt=''):
"""A simple image tag renderer.
:param str:
"""
# Default src to the filename
if src is None:
src = fp.name
return '<img src="/{src}" alt="{alt}" />'.format(src=src, alt=alt)
| """Image renderer module."""
def render_img_tag(fp, src=None, alt=''):
"""A simple image tag renderer.
:param str:
"""
# Default src to the filename
if src is None:
src = fp.name
return '<img src="{src}" alt="{alt}" />'.format(src=src, alt=alt)
| Remove implicit addition of leading slash | Remove implicit addition of leading slash
| Python | apache-2.0 | icereval/modular-file-renderer,AddisonSchiller/modular-file-renderer,mfraezz/modular-file-renderer,icereval/modular-file-renderer,chrisseto/modular-file-renderer,chrisseto/modular-file-renderer,Johnetordoff/modular-file-renderer,rdhyee/modular-file-renderer,rdhyee/modular-file-renderer,haoyuchen1992/modular-file-render... | ---
+++
@@ -8,4 +8,4 @@
# Default src to the filename
if src is None:
src = fp.name
- return '<img src="/{src}" alt="{alt}" />'.format(src=src, alt=alt)
+ return '<img src="{src}" alt="{alt}" />'.format(src=src, alt=alt) |
8f4e61667a7bee4ec847fd8921dccd291d59388c | scripts/slave/chromium/test_webkitpy_wrapper.py | scripts/slave/chromium/test_webkitpy_wrapper.py | #!/usr/bin/env python
# Copyright 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave ... | #!/usr/bin/env python
# Copyright 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave ... | Revert 232677 "Revert 232670 "Fix script after r232641"" | Revert 232677 "Revert 232670 "Fix script after r232641""
False alarm, tests we failing due to PDT switch.
> Revert 232670 "Fix script after r232641"
>
> Needs to be out to speculatively revert r232641.
>
> > Fix script after r232641
> >
> > BUG=314253
> > TBR=pfeldman@chromium.org
> >
> > Review URL: https://code... | Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -24,7 +24,7 @@
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
- options.build_dir, _ = build_directory.GetBuildOutputDirectory()
+ options.build_dir = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.buil... |
0ef7061bb0661efd101efddc98d55cf819eba219 | scmtiles/test/unit/util/__init__.py | scmtiles/test/unit/util/__init__.py | """Tests for the `scmtiles.util`."""
# Copyright 2016 Andrew Dawson
#
# 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 appli... | """Tests for `scmtiles.util`."""
# Copyright 2016 Andrew Dawson
#
# 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 applicabl... | Improve the util module unit test docstring. | Improve the util module unit test docstring.
| Python | apache-2.0 | aopp-pred/scmtiles | ---
+++
@@ -1,4 +1,4 @@
-"""Tests for the `scmtiles.util`."""
+"""Tests for `scmtiles.util`."""
# Copyright 2016 Andrew Dawson
#
# Licensed under the Apache License, Version 2.0 (the "License"); |
68480f191167573e32853427c37049fc6f7d1279 | nsfw_dl/__init__.py | nsfw_dl/__init__.py | """
Read the license at:
https://github.com/IzunaDevs/nsfw_dl/blob/master/LICENSE
"""
from .dl import NSFWDL # noqa
__title__ = 'nsfw_dl'
__author__ = 'IzunaDevs'
__license__ = 'MIT'
__copyright__ = 'Copyright 2017 IzunaDevs'
__version__ = '0.2.0'
__build__ = 0x000100
| Revert "Make it find this" | Revert "Make it find this"
This reverts commit f4d8589a9c424d32ae403eddd7d97366c27cb8fd.
| Python | mit | IzunaDevs/nsfw_dl | ---
+++
@@ -1 +1,13 @@
+"""
+Read the license at:
+https://github.com/IzunaDevs/nsfw_dl/blob/master/LICENSE
+"""
+from .dl import NSFWDL # noqa
+
+__title__ = 'nsfw_dl'
+__author__ = 'IzunaDevs'
+__license__ = 'MIT'
+__copyright__ = 'Copyright 2017 IzunaDevs'
+__version__ = '0.2.0'
+__build__ = 0x000100 | |
452b67fa4fe5d9f34a98971e377bbaa1b978907b | superblock.py | superblock.py | #!/usr/bin/env python2
"""
Analyze superblock in ext2 filesystem.
Usage:
superblock.py <filename>
"""
import sys
import string
from binascii import hexlify
BLOCKSIZE = 512
def block_printer(filename, offset, block_count):
def nonprintable_replace(char):
if char not in string.printable:
... | #!/usr/bin/env python2
"""
Analyze superblock in ext2 filesystem.
Usage:
superblock.py <filename>
"""
import sys
import string
from binascii import hexlify
BLOCKSIZE = 512
def nonprintable_replace(char):
if char not in string.printable:
return '.'
if char in '\n\r\t\x0b\x0c':
return '.'... | Print 16 bit per line | Print 16 bit per line
| Python | mit | dbrgn/superblock | ---
+++
@@ -13,14 +13,15 @@
BLOCKSIZE = 512
+def nonprintable_replace(char):
+ if char not in string.printable:
+ return '.'
+ if char in '\n\r\t\x0b\x0c':
+ return '.'
+ return char
+
+
def block_printer(filename, offset, block_count):
-
- def nonprintable_replace(char):
- if c... |
3744a620bddde501c0b2634b7cd54a755433c17a | djangopeoplenet/manage.py | djangopeoplenet/manage.py | #!/usr/bin/env python
import sys
paths = (
'/home/simon/sites/djangopeople.net',
'/home/simon/sites/djangopeople.net/djangopeoplenet',
'/home/simon/sites/djangopeople.net/djangopeoplenet/djangopeople/lib',
)
for path in paths:
if not path in sys.path:
sys.path.insert(0, path)
from django.core.m... | #!/usr/bin/env python
import sys, os
root = os.path.dirname(__file__)
paths = (
os.path.join(root),
os.path.join(root, "djangopeople", "lib"),
)
for path in paths:
if not path in sys.path:
sys.path.insert(0, path)
from django.core.management import execute_manager
try:
import settings # Assume... | Make the lib imports work on other computers than Simon's | Make the lib imports work on other computers than Simon's | Python | mit | brutasse/djangopeople,django/djangopeople,brutasse/djangopeople,polinom/djangopeople,brutasse/djangopeople,polinom/djangopeople,polinom/djangopeople,django/djangopeople,brutasse/djangopeople,polinom/djangopeople,django/djangopeople | ---
+++
@@ -1,9 +1,10 @@
#!/usr/bin/env python
-import sys
+
+import sys, os
+root = os.path.dirname(__file__)
paths = (
- '/home/simon/sites/djangopeople.net',
- '/home/simon/sites/djangopeople.net/djangopeoplenet',
- '/home/simon/sites/djangopeople.net/djangopeoplenet/djangopeople/lib',
+ os.path.join... |
5ead9e24ec73ee66886858bf70f357ae170bdf3b | spillway/mixins.py | spillway/mixins.py | class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
def get_serializer_class(self):
if self.serializer_class:
return self.serializer_class
class DefaultSerializer(self.model_serializer_class):
cl... | from rest_framework.exceptions import ValidationError
class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
def get_serializer_class(self):
if self.serializer_class:
return self.serializer_class
class Defaul... | Throw ValidationError for invalid form, drop get_query_form() | Throw ValidationError for invalid form, drop get_query_form()
| Python | bsd-3-clause | kuzmich/django-spillway,barseghyanartur/django-spillway,bkg/django-spillway | ---
+++
@@ -1,3 +1,6 @@
+from rest_framework.exceptions import ValidationError
+
+
class ModelSerializerMixin(object):
"""Provides generic model serializer classes to views."""
model_serializer_class = None
@@ -15,13 +18,11 @@
"""Provides form based handling of GET or POST requests."""
query_form... |
6676a47806c3c35d800450ff9480cabdc52928e8 | tedx/views.py | tedx/views.py | from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import RegistrationForm
from .models import Registration
import utils
def handle_registration(request):
if request.method == 'POST':
form = RegistrationForm(request.POST... | from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.shortcuts import render
from clubs.models import Team
from .forms import RegistrationForm
from .models import Registration
import utils
def handle_regis... | Add permission check for TEDx | Add permission check for TEDx
| Python | agpl-3.0 | osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz | ---
+++
@@ -1,6 +1,8 @@
-from django.core.urlresolvers import reverse
+from django.contrib.auth.decorators import login_required
+from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.shortcuts import render
+from clubs.models import Team
from .forms import Re... |
c4bd1d33a69979ba71e4f15145d154b9d986f10c | ci/ci-deploy-data-center.py | ci/ci-deploy-data-center.py | #!/usr/bin/env python
import click
from Cosmic.CI import *
from Cosmic.NSX import *
@click.command()
@click.option('--marvin-config', '-m', help='Marvin config file', required=True)
@click.option('--debug', help="Turn on debugging output", is_flag=True)
def main(**kwargs):
ci = CI(marvin_config=kwargs.get('marvi... | #!/usr/bin/env python
import click
from Cosmic.CI import *
from Cosmic.NSX import *
@click.command()
@click.option('--marvin-config', '-m', help='Marvin config file', required=True)
@click.option('--debug', help="Turn on debugging output", is_flag=True)
def main(**kwargs):
ci = CI(marvin_config=kwargs.get('marvi... | Fix setting connectivity for NSX offerings | Fix setting connectivity for NSX offerings
| Python | apache-2.0 | MissionCriticalCloud/bubble,schubergphilis/MCT-shared,MissionCriticalCloud/bubble-toolkit,MissionCriticalCloud/bubble,MissionCriticalCloud/bubble-toolkit,schubergphilis/MCT-shared | ---
+++
@@ -15,7 +15,8 @@
ci.copy_marvin_config()
ci.deploy_dc()
- if nsx:
+ if nsx is not None:
+ print("Setting connectivity for NSX offerings")
nsx.add_connectivy_to_offerings()
ci.wait_for_templates() |
3ad466fc9b1971f3c10123db7b962bc93f79eb78 | sahara_dashboard/enabled/_1810_data_processing_panel_group.py | sahara_dashboard/enabled/_1810_data_processing_panel_group.py | from django.utils.translation import ugettext_lazy as _
# The slug of the panel group to be added to HORIZON_CONFIG. Required.
PANEL_GROUP = 'data_processing'
# The display name of the PANEL_GROUP. Required.
PANEL_GROUP_NAME = _('Data Processing')
# The slug of the dashboard the PANEL_GROUP associated with. Required.
... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed u... | Add Apache 2.0 license to source file | Add Apache 2.0 license to source file
As per OpenStack licensing guide lines [1]:
[H102 H103] Newly contributed Source Code should be licensed under
the Apache 2.0 license.
[H104] Files with no code shouldnt contain any license header nor
comments, and must be left completely empty.
[1] http://docs.openstack.org/dev... | Python | apache-2.0 | openstack/sahara-dashboard,openstack/sahara-dashboard,openstack/sahara-dashboard,openstack/sahara-dashboard | ---
+++
@@ -1,3 +1,14 @@
+# 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 ... |
3fc9588a0f689a01ac8da0f43551418d3b3649b5 | extractor_train/assets.py | extractor_train/assets.py | # -*- coding: utf-8 -*-
from flask.ext.assets import Bundle, Environment
css = Bundle(
"libs/bootstrap/dist/css/bootstrap.css",
"css/style.css",
"libs/annotator.1.2.9/annotator.min.css",
filters="cssmin",
output="public/css/common.css"
)
js = Bundle(
"libs/jQuery/dist/jquery.js",
"libs/boo... | # -*- coding: utf-8 -*-
from flask.ext.assets import Bundle, Environment
css = Bundle(
"libs/bootstrap/dist/css/bootstrap.css",
"css/style.css",
# "libs/annotator.1.2.9/annotator.min.css",
filters="cssmin",
output="public/css/common.css"
)
js = Bundle(
"libs/jQuery/dist/jquery.js",
"libs/bo... | Remove inlcudes for no longer needed libraries. | Remove inlcudes for no longer needed libraries.
| Python | bsd-3-clause | dlarochelle/extractor_train,dlarochelle/extractor_train,dlarochelle/extractor_train | ---
+++
@@ -4,7 +4,7 @@
css = Bundle(
"libs/bootstrap/dist/css/bootstrap.css",
"css/style.css",
- "libs/annotator.1.2.9/annotator.min.css",
+# "libs/annotator.1.2.9/annotator.min.css",
filters="cssmin",
output="public/css/common.css"
)
@@ -13,15 +13,15 @@
"libs/jQuery/dist/jquery.js",... |
7a88109ec8cb5d44bfac3d6b2216a11eb710f0c3 | dcu/active_memory/__init__.py | dcu/active_memory/__init__.py | from dcu.active_memory.rotate import rotate
from dcu.active_memory.rotate import splitext
from dcu.active_memory.upload import multipart_upload
import os.path
import reimport logging
logger = logging.getLogger(__name__)
def upload_rotate(file_path, s3_bucket, s3_key_prefix, aws_key=None, aws_secret=None):
'''
... | Implement function to upload and rotate a file with an existing timestamp | Implement function to upload and rotate a file with an existing timestamp
| Python | mit | dirkcuys/active-memory | ---
+++
@@ -0,0 +1,31 @@
+from dcu.active_memory.rotate import rotate
+from dcu.active_memory.rotate import splitext
+from dcu.active_memory.upload import multipart_upload
+
+import os.path
+import reimport logging
+
+logger = logging.getLogger(__name__)
+
+
+def upload_rotate(file_path, s3_bucket, s3_key_prefix, aws... | |
dde9b3808b3e85f5513cc3604fd219a90774c047 | bot.py | bot.py |
import tweepy
from secrets import *
from voyager_distance import get_distance
from NEO_flyby import NEO
# standard for accessing Twitter API
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
for distance in get_distance():
try:
voyager_messa... |
import tweepy
from secrets import *
from voyager_distance import get_distance
from NEO_flyby import NEO
# standard for accessing Twitter API
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
for distance in get_distance():
try:
voyager_messa... | Update 0.4.2 - Added hashtags | Update 0.4.2
- Added hashtags
| Python | mit | FXelix/space_facts_bot | ---
+++
@@ -11,14 +11,14 @@
for distance in get_distance():
try:
- voyager_message = "Voyager I is now {:,} km from Earth. \nVoyager II is now {:,} km from Earth.".format(*distance)
+ voyager_message = "Voyager I is now {:,} km from Earth. \nVoyager II is now {:,} km from Earth. \n#bot #space #v... |
734903c777fb237509c21a988f79318ec14e997d | st2api/st2api/controllers/sensors.py | st2api/st2api/controllers/sensors.py | import six
from pecan import abort
from pecan.rest import RestController
from mongoengine import ValidationError
from st2common import log as logging
from st2common.persistence.reactor import SensorType
from st2common.models.base import jsexpose
from st2common.models.api.reactor import SensorTypeAPI
http_client = six... | import six
from st2common import log as logging
from st2common.persistence.reactor import SensorType
from st2common.models.api.reactor import SensorTypeAPI
from st2api.controllers.resource import ResourceController
http_client = six.moves.http_client
LOG = logging.getLogger(__name__)
class SensorTypeController(Reso... | Use ResourceController instead of duplicating logic. | Use ResourceController instead of duplicating logic.
| Python | apache-2.0 | pinterb/st2,armab/st2,peak6/st2,pixelrebel/st2,Plexxi/st2,armab/st2,Plexxi/st2,punalpatel/st2,grengojbo/st2,jtopjian/st2,jtopjian/st2,StackStorm/st2,alfasin/st2,dennybaa/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,pinterb/st2,grengojbo/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,pixelrebel/st2,alfasin/st2,emedvedev/st2,... | ---
+++
@@ -1,50 +1,22 @@
import six
-from pecan import abort
-from pecan.rest import RestController
-from mongoengine import ValidationError
-
from st2common import log as logging
from st2common.persistence.reactor import SensorType
-from st2common.models.base import jsexpose
from st2common.models.api.reactor im... |
4dc2d5710f5f34a0611c8d38a84ee3c5ecf79463 | uliweb/contrib/rbac/tags.py | uliweb/contrib/rbac/tags.py | from uliweb.core.template import BaseBlockNode
from uliweb import functions
class PermissionNode(BaseBlockNode):
def __init__(self, name='', content=None):
super(PermissionNode, self).__init__(name, content)
self.nodes = ['if functions.has_permission(request.user, "%s"):\n' % self.name]
... | from uliweb.core.template import BaseBlockNode
from uliweb import functions
class PermissionNode(BaseBlockNode):
def __init__(self, name='', content=None):
super(PermissionNode, self).__init__(name, content)
self.nodes = ['if functions.has_permission(request.user, %s):\n' % self.name]
... | Change role and permission tag parameter format, no need "" | Change role and permission tag parameter format, no need ""
| Python | bsd-2-clause | wwfifi/uliweb,wwfifi/uliweb,wwfifi/uliweb,limodou/uliweb,limodou/uliweb,wwfifi/uliweb,limodou/uliweb,limodou/uliweb | ---
+++
@@ -4,7 +4,7 @@
class PermissionNode(BaseBlockNode):
def __init__(self, name='', content=None):
super(PermissionNode, self).__init__(name, content)
- self.nodes = ['if functions.has_permission(request.user, "%s"):\n' % self.name]
+ self.nodes = ['if functions.has_permission(reques... |
dfe475837d7942f05c9366819ee57ccc8aa0e58a | dmp/__init__.py | dmp/__init__.py | """
.. Copyright 2016 EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... | """
.. Copyright 2016 EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... | Change to try and improve importability - Undone | Change to try and improve importability - Undone
| Python | apache-2.0 | Multiscale-Genomics/mg-dm-api,Multiscale-Genomics/mg-dm-api | ---
+++
@@ -14,8 +14,8 @@
limitations under the License.
"""
-import dmp.dmp
-import rest.rest
+import dmp
+import rest
__author__ = 'Mark McDowall'
__version__ = '0.0' |
d0b40c90bd5af1ba9ef0d617c10700566d4e3775 | tests/unit/directory/test_directory.py | tests/unit/directory/test_directory.py | """Contains the unit tests for the inner directory package"""
import unittest
class TestDirectory(unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main() | """Contains the unit tests for the inner directory package"""
import unittest
class TestDirectory(unittest.TestCase):
def setUp(self):
self.fake_path = os.path.abspath("hello-world-dir")
return
if __name__ == "__main__":
unittest.main() | Add TestDirectory.setUp() to the directory package's test file | Add TestDirectory.setUp() to the directory package's test file
| Python | mit | SizzlingVortex/classyfd | ---
+++
@@ -4,7 +4,9 @@
class TestDirectory(unittest.TestCase):
- pass
+ def setUp(self):
+ self.fake_path = os.path.abspath("hello-world-dir")
+ return
if __name__ == "__main__": |
24c6b759c1e8898946cdae591bce236e3ddbc2d8 | topStocks.py | topStocks.py | """Find top stocks and post them to Twitter."""
import sys
import tweetPoster
import stockPrices
from stockList import getStockList
import time
def main():
# Get the list of stock symobls
currentStockList = getStockList()
# Get the stock prices
oldStockPrices = stockPrices.getStockPrices(currentStockL... | """Find top stocks and post them to Twitter."""
import sys
import tweetPoster
import stockPrices
from stockList import getStockList
import time
def main():
# Get the list of stock symobls
currentStockList = getStockList()
# Get the stock prices
oldStockPrices = stockPrices.getStockPrices(currentStockL... | Make sure "percentage" is a string before concatenating it. | Make sure "percentage" is a string before concatenating it.
| Python | mit | trswany/topStocks | ---
+++
@@ -30,6 +30,8 @@
percentage = round(float(stockPrice[1]), 2)
if percentage > 0:
percentage = '+' + str(percentage)
+ else:
+ percentage = str(percentage)
tweetText = tweetText + '#' + symbol + " : " + percentage + '%, '
# Post a tweet of the to... |
23c699e1be6c7d779491b62811913a0c73b45a39 | utilities/test_parse_vcf.py | utilities/test_parse_vcf.py | import pytest
import parse_vcf as pv
def test_openfile():
assert pv.openfile('test_parse_vcf.py')[0] == True
| import pytest
import parse_vcf as pv
def test_openfile():
# The real input file is called: 001.vcfmod
assert pv.openfile('001.vcfmod')[0] == True
| Use one of the real data files in test | Use one of the real data files in test
| Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various | ---
+++
@@ -4,4 +4,5 @@
def test_openfile():
- assert pv.openfile('test_parse_vcf.py')[0] == True
+ # The real input file is called: 001.vcfmod
+ assert pv.openfile('001.vcfmod')[0] == True |
2e5c0b1507dcfac46c380102ff338a4be9f25d97 | tests/sentry/auth/providers/test_oauth2.py | tests/sentry/auth/providers/test_oauth2.py | from __future__ import absolute_import, print_function
import pytest
from sentry.auth.exceptions import IdentityNotValid
from sentry.auth.providers.oauth2 import OAuth2Provider
from sentry.models import AuthIdentity, AuthProvider
from sentry.testutils import TestCase
class OAuth2ProviderTest(TestCase):
def setU... | from __future__ import absolute_import, print_function
import pytest
from sentry.auth.exceptions import IdentityNotValid
from sentry.auth.providers.oauth2 import OAuth2Provider
from sentry.models import AuthIdentity, AuthProvider
from sentry.testutils import TestCase
class OAuth2ProviderTest(TestCase):
def setU... | Correct identity data in test | Correct identity data in test
| Python | bsd-3-clause | daevaorn/sentry,ewdurbin/sentry,mvaled/sentry,daevaorn/sentry,imankulov/sentry,llonchj/sentry,looker/sentry,BayanGroup/sentry,felixbuenemann/sentry,jean/sentry,vperron/sentry,BuildingLink/sentry,argonemyth/sentry,mvaled/sentry,boneyao/sentry,nicholasserra/sentry,gencer/sentry,JTCunning/sentry,imankulov/sentry,JamesMura... | ---
+++
@@ -29,7 +29,7 @@
auth_provider=self.auth_provider,
user=self.user,
data={
- 'access_token': 'access_token',
+ 'data': {'access_token': 'access_token'},
}
)
|
115c9343e4aa6bf39dd2038a53a32fb5695fce2b | tools/pygments_k3/pygments_k3/lexer.py | tools/pygments_k3/pygments_k3/lexer.py | from pygments.token import Keyword, Text, Token
from pygments.lexer import RegexLexer
class K3Lexer(RegexLexer):
name = 'K3'
aliases = ['k3']
filenames = ['*.k3']
keywords = {
'preprocessor': "include",
"declaration": [
"annotation", "declare", "feed", "provides", "require... | from pygments.token import Comment, Keyword, Literal, Operator, Text
from pygments.lexer import RegexLexer
class K3Lexer(RegexLexer):
name = 'K3'
aliases = ['k3']
filenames = ['*.k3']
keywords = {
'preprocessor': "include",
"declaration": [
"annotation", "declare", "feed",... | Add more syntactic construct lexing. | Add more syntactic construct lexing.
| Python | apache-2.0 | DaMSL/K3,DaMSL/K3,yliu120/K3 | ---
+++
@@ -1,4 +1,4 @@
-from pygments.token import Keyword, Text, Token
+from pygments.token import Comment, Keyword, Literal, Operator, Text
from pygments.lexer import RegexLexer
class K3Lexer(RegexLexer):
@@ -17,16 +17,23 @@
"expression": [
"if", "then", "else", "let", "in", "case", "of... |
b20cfef1e54d9f22769f6d0ec6ae06031bf86ec3 | tests/CrawlerProcess/asyncio_deferred_signal.py | tests/CrawlerProcess/asyncio_deferred_signal.py | import asyncio
import sys
from scrapy import Spider
from scrapy.crawler import CrawlerProcess
from scrapy.utils.defer import deferred_from_coro
from twisted.internet.defer import Deferred
class UppercasePipeline:
async def _open_spider(self, spider):
spider.logger.info("async pipeline opened!")
a... | import asyncio
import sys
from scrapy import Spider
from scrapy.crawler import CrawlerProcess
from scrapy.utils.defer import deferred_from_coro
from twisted.internet.defer import Deferred
class UppercasePipeline:
async def _open_spider(self, spider):
spider.logger.info("async pipeline opened!")
a... | Remove unnecessary line from test | Remove unnecessary line from test
| Python | bsd-3-clause | dangra/scrapy,pablohoffman/scrapy,scrapy/scrapy,pablohoffman/scrapy,elacuesta/scrapy,pawelmhm/scrapy,dangra/scrapy,pawelmhm/scrapy,elacuesta/scrapy,elacuesta/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,dangra/scrapy,scrapy/scrapy,scrapy/scrapy | ---
+++
@@ -13,7 +13,6 @@
await asyncio.sleep(0.1)
def open_spider(self, spider):
- loop = asyncio.get_event_loop()
return deferred_from_coro(self._open_spider(spider))
def process_item(self, item, spider): |
819e34fb8cd60a25b7796508f72a1e9ba00b5faf | incuna_test_utils/factories/user.py | incuna_test_utils/factories/user.py | import factory
from django.contrib.auth import get_user_model
class UserFactory(factory.DjangoModelFactory):
FACTORY_FOR = get_user_model()
email = factory.Sequence(lambda i: 'email{}@example.com'.format(i))
name = factory.Sequence(lambda i: 'Test User {}'.format(i))
| import factory
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError: # Django 1.4
from django.contrib.auth.models import User
class UserFactory(factory.DjangoModelFactory):
FACTORY_FOR = User
email = factory.Sequence(lambda i: 'email{}@example.com'.forma... | Fix UserFactory for django 1.4 | Fix UserFactory for django 1.4
| Python | bsd-2-clause | incuna/incuna-test-utils,incuna/incuna-test-utils | ---
+++
@@ -1,9 +1,13 @@
import factory
-from django.contrib.auth import get_user_model
+try:
+ from django.contrib.auth import get_user_model
+ User = get_user_model()
+except ImportError: # Django 1.4
+ from django.contrib.auth.models import User
class UserFactory(factory.DjangoModelFactory):
- ... |
d953055801c8d618c70cea81e3e35684122c66a7 | setuptools/config/__init__.py | setuptools/config/__init__.py | """For backward compatibility, expose main functions from
``setuptools.config.setupcfg``
"""
import warnings
from functools import wraps
from textwrap import dedent
from typing import Callable, TypeVar, cast
from .._deprecation_warning import SetuptoolsDeprecationWarning
from . import setupcfg
Fn = TypeVar("Fn", boun... | """For backward compatibility, expose main functions from
``setuptools.config.setupcfg``
"""
import warnings
from functools import wraps
from textwrap import dedent
from typing import Callable, TypeVar, cast
from .._deprecation_warning import SetuptoolsDeprecationWarning
from . import setupcfg
Fn = TypeVar("Fn", boun... | Add stacklevel=2 to make calling code clear | Add stacklevel=2 to make calling code clear | Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -25,7 +25,7 @@
to access a backward compatible API, but this module is provisional
and might be removed in the future.
"""
- warnings.warn(dedent(msg), SetuptoolsDeprecationWarning)
+ warnings.warn(dedent(msg), SetuptoolsDeprecationWarning, stacklevel=2)
re... |
ef544497b3d595582e51f545c5250d1e92373577 | lexos/models/bct_model.py | lexos/models/bct_model.py | """This is a model to produce dendrograms of the dtm."""
import pandas as pd
from typing import NamedTuple, Optional
from lexos.models.base_model import BaseModel
from lexos.models.matrix_model import MatrixModel, IdTempLabelMap
from lexos.receivers.bct_receiver import BCTOption, BCTReceiver
class BCTTestOptions(Nam... | Set up the bct model | Set up the bct model
| Python | mit | WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos | ---
+++
@@ -0,0 +1,55 @@
+"""This is a model to produce dendrograms of the dtm."""
+
+import pandas as pd
+from typing import NamedTuple, Optional
+from lexos.models.base_model import BaseModel
+from lexos.models.matrix_model import MatrixModel, IdTempLabelMap
+from lexos.receivers.bct_receiver import BCTOption, BCTR... | |
67c68065fbe0ffffc6a72f1d67d23c583b03a6fe | neuroimaging/algorithms/tests/test_onesample.py | neuroimaging/algorithms/tests/test_onesample.py | from neuroimaging.testing import *
from neuroimaging.algorithms.onesample import ImageOneSample
from neuroimaging.core.api import load_image
from neuroimaging.utils.tests.data import repository
class test_OneSample(TestCase):
@dec.slow
@dec.data
def test_onesample1(self):
im1 = load_image('FIAC/fi... | from neuroimaging.testing import *
from neuroimaging.algorithms.onesample import ImageOneSample
from neuroimaging.core.api import load_image
from neuroimaging.utils.tests.data import repository
class test_OneSample(TestCase):
@dec.skipknownfailure
@dec.slow
@dec.data
def test_onesample1(self):
... | Update data file references. Skip known test failure to undefined image iterator. | Update data file references. Skip known test failure to undefined image iterator. | Python | bsd-3-clause | yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD | ---
+++
@@ -5,14 +5,29 @@
from neuroimaging.utils.tests.data import repository
class test_OneSample(TestCase):
+ @dec.skipknownfailure
@dec.slow
@dec.data
def test_onesample1(self):
- im1 = load_image('FIAC/fiac3/fonc3/fsl/fmristat_run/contrasts/speaker/effect.nii.gz',
- reposi... |
2611f7a4e4ef8fba25e45932c774a302299fd311 | tests/test_webob_middleware.py | tests/test_webob_middleware.py | # Test various types of WebOb middleware
import sys
from fireside import WSGIFilter
from webob.dec import wsgify
from servlet_support import * # FIXME be explicit
from javax.servlet import FilterChain
@wsgify.middleware
def all_caps(req, app):
resp = req.get_response(app)
resp.body = resp.body.upper()
... | # Test various types of WebOb middleware
import sys
from fireside import WSGIFilter
from webob.dec import wsgify
from servlet_support import * # FIXME be explicit
from javax.servlet import FilterChain
@wsgify.middleware
def all_caps(req, app):
resp = req.get_response(app)
resp.body = resp.body.upper()
... | Change test to show WebOb filters consume completely before resulting in a body | Change test to show WebOb filters consume completely before resulting in a body
| Python | apache-2.0 | jythontools/fireside,jythontools/fireside,jythontools/fireside | ---
+++
@@ -28,7 +28,8 @@
class UnitChain(FilterChain):
def doFilter(self, req, resp):
- resp.outputStream.write("hi, there!\n")
+ resp.outputStream.write("hi, ")
+ resp.outputStream.write("there!\n")
filter.doFilter(req_wrapper, resp_mock, UnitChain())
ass... |
1fb77715c4766e3e437970a048154a5a9fe1b2c8 | tools/httpdtest.py | tools/httpdtest.py | #! /bin/env python3
#
# Simple HTTP server for testing purposes.
import http.server
import sys
from argparse import ArgumentParser
class RequestHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.requestline)
for (key, header) in self.headers.items():
print("{}... | #! /bin/env python3
#
# Simple HTTP server for testing purposes.
import http.server
import json
import sys
from argparse import ArgumentParser
class RequestHandler(http.server.BaseHTTPRequestHandler):
# Handle GET requests
def do_GET(self):
response = {}
# Capture the URL request
r... | Send back GET request in response | Send back GET request in response
The response to a GET request now returns the request string
and all header fields as a JSON encoded response.
| Python | bsd-3-clause | rolfmichelsen/Just4Fun | ---
+++
@@ -3,6 +3,7 @@
# Simple HTTP server for testing purposes.
import http.server
+import json
import sys
from argparse import ArgumentParser
@@ -10,16 +11,24 @@
class RequestHandler(http.server.BaseHTTPRequestHandler):
+ # Handle GET requests
def do_GET(self):
- print(self.requestline... |
cfc734a1b349f2ec32cd51523f583dae6c820a8a | tweepy/__init__.py | tweepy/__init__.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy Twitter API library
"""
__version__ = '3.1'
__author__ = 'Joshua Roesslein'
__license__ = 'MIT'
from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category
from tweepy.error ... | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy Twitter API library
"""
__version__ = '3.1.0'
__author__ = 'Joshua Roesslein'
__license__ = 'MIT'
from tweepy.models import Status, User, DirectMessage, Friendship, SavedSearch, SearchResults, ModelFactory, Category
from tweepy.erro... | Fix version to include 3 digits. | Fix version to include 3 digits.
| Python | mit | yared-bezum/tweepy,zhenv5/tweepy,vikasgorur/tweepy,sidewire/tweepy,arunxarun/tweepy,srimanthd/tweepy,edsu/tweepy,elijah513/tweepy,wjt/tweepy,awangga/tweepy,IsaacHaze/tweepy,techieshark/tweepy,vivek8943/tweepy,takeshineshiro/tweepy,obskyr/tweepy,hackebrot/tweepy,cogniteev/tweepy,tweepy/tweepy,iamjakob/tweepy,kylemanna/t... | ---
+++
@@ -5,7 +5,7 @@
"""
Tweepy Twitter API library
"""
-__version__ = '3.1'
+__version__ = '3.1.0'
__author__ = 'Joshua Roesslein'
__license__ = 'MIT'
|
44650a0b3d395b4201a039bd2f3eb916987dce8d | _grains/osqueryinfo.py | _grains/osqueryinfo.py | # -*- coding: utf-8 -*-
import salt.utils
import salt.modules.cmdmod
__salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet}
def osquerygrain():
'''
Return osquery version in grain
'''
# Provides:
# osqueryversion
# osquerybinpath
grains = {}
option = '--version'
# Prefer our... | # -*- coding: utf-8 -*-
import salt.utils
import salt.modules.cmdmod
__salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet}
def osquerygrain():
'''
Return osquery version in grain
'''
# Provides:
# osqueryversion
# osquerybinpath
grains = {}
option = '--version'
# Prefer our... | Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0 | DeprecationWarning: Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0
| Python | apache-2.0 | hubblestack/hubble-salt | ---
+++
@@ -19,11 +19,11 @@
# Prefer our /opt/osquery/osqueryi if present
osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi')
for path in osqueryipaths:
- if salt.utils.which(path):
+ if salt.utils.path.which(path):
for item in __salt__['cmd.run']('{0} ... |
eed33b6ba9a3d5cf5d841d451ad03fd2f57c43bf | openfisca_senegal/senegal_taxbenefitsystem.py | openfisca_senegal/senegal_taxbenefitsystem.py | # -*- coding: utf-8 -*-
import os
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities, scenarios
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
class SenegalTaxBenefitSystem(TaxBenefitSystem):
"""Senegalese tax and benefit system"""
CURRENCY = u"FCFA"
def _... | # -*- coding: utf-8 -*-
import os
import xml.etree.ElementTree
from openfisca_core import conv, legislationsxml
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities, scenarios
COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__))
class SenegalTaxBenefitSystem(TaxBenefitSystem):... | Implement adding legislation XML from string | Implement adding legislation XML from string
| Python | agpl-3.0 | openfisca/senegal | ---
+++
@@ -1,7 +1,9 @@
# -*- coding: utf-8 -*-
import os
+import xml.etree.ElementTree
+from openfisca_core import conv, legislationsxml
from openfisca_core.taxbenefitsystems import TaxBenefitSystem
from . import entities, scenarios
@@ -17,3 +19,14 @@
def __init__(self):
super(SenegalTaxBenef... |
448d4697803ad6993d81ca556a63977f1c039a7f | requestsexceptions/__init__.py | requestsexceptions/__init__.py | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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 applicabl... | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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 applicabl... | Add SubjectAltNameWarning and a helper function | Add SubjectAltNameWarning and a helper function
shade hits the SubjectAltName problem when talking to Rackspace. Also,
one of the things you want to do is turn off the warnings - so add a
function for that.
Change-Id: I3a55c66e5a4033a47a9d8704dd30709a5c53edc9
| Python | apache-2.0 | openstack-infra/requestsexceptions | ---
+++
@@ -11,6 +11,8 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
+
+import warnings
try:
from requests.packages.urllib3.exceptions import InsecurePlatformWarning
@@ -27,3 +29,2... |
54db30c6db4df1f8a0e9030258cfcab4937d0c13 | python/castle-on-the-grid.py | python/castle-on-the-grid.py | #!/bin/python3
import math
import os
import random
import re
import sys
class CastleOnGrid:
def __init__(self, grid, start, goal):
self.grid = grid
self.start = start
self.goal = goal
def min_moves(self):
pass
if __name__ == '__main__':
grid_size = int(input())
grid ... | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
class CastleOnGrid:
def __init__(self, grid, grid_size, start, goal):
self.grid = grid
self.grid_size = grid_size
self.start = start
self.goal = goal
def min_moves(self):
... | Solve castle on grid (timeout test case 11) | Solve castle on grid (timeout test case 11)
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank | ---
+++
@@ -5,16 +5,64 @@
import random
import re
import sys
+from collections import deque
class CastleOnGrid:
- def __init__(self, grid, start, goal):
+ def __init__(self, grid, grid_size, start, goal):
self.grid = grid
+ self.grid_size = grid_size
self.start = start
... |
aacfe5de01dd11486f7f39bb414c87853c8c8857 | likert_field/templatetags/likert_star_tools.py | likert_field/templatetags/likert_star_tools.py | #-*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import string_types
def render_stars(num, max_stars, star_set):
"""
Star renderer returns a HTML string of stars
If num is None or a blank string, it returns the unanswered tag
Otherwise, the returned string will contain num so... | #-*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.six import string_types
def render_stars(num, max_stars, star_set):
"""
Star renderer returns a HTML string of stars
If num is None or a blank string, it returns the unanswered tag
Otherwise, the returned string will c... | Use Dj provided compat tools | Use Dj provided compat tools
| Python | bsd-3-clause | kelvinwong-ca/django-likert-field,kelvinwong-ca/django-likert-field | ---
+++
@@ -1,7 +1,7 @@
#-*- coding: utf-8 -*-
from __future__ import unicode_literals
-from six import string_types
+from django.utils.six import string_types
def render_stars(num, max_stars, star_set): |
5bbdfb6d38878e2e1688fe37415662ec0dc176ee | sphinxcontrib/openstreetmap.py | sphinxcontrib/openstreetmap.py | # -*- coding: utf-8 -*-
"""
sphinxcontrib.openstreetmap
===========================
Embed OpenStreetMap on your documentation.
:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphi... | # -*- coding: utf-8 -*-
"""
sphinxcontrib.openstreetmap
===========================
Embed OpenStreetMap on your documentation.
:copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com>
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import directives
from sphi... | Check whether required id parameter is specified | Check whether required id parameter is specified
| Python | bsd-2-clause | kenhys/sphinxcontrib-openstreetmap,kenhys/sphinxcontrib-openstreetmap | ---
+++
@@ -26,6 +26,11 @@
def run(self):
node = openstreetmap()
+ if 'id' in self.options:
+ node['id'] = self.options['id']
+ else:
+ msg = ('openstreetmap directive needs uniqueue id for map data')
+ return [document.reporter.warning(msg, line=self.lin... |
ac04cd5301d6aa4788fbd2d6bdaeb207f77a489e | alfred_listener/views.py | alfred_listener/views.py | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
pa... | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
pa... | Change the way to instaniate models | Change the way to instaniate models
| Python | isc | alfredhq/alfred-listener | ---
+++
@@ -21,10 +21,11 @@
name=hook_data['repo_name'], user=hook_data['repo_user']
).first()
if repository is None:
- repository = Repository()
- repository.name = hook_data['repo_name']
- repository.user = hook_data['repo_user']
- repository.url = hook_data['repo_url'... |
bc4d11a6b5584975c3e9f16c2a4e25b26ff3da11 | mooc_aggregator_restful_api/mooc_aggregator.py | mooc_aggregator_restful_api/mooc_aggregator.py | '''
This module aggregates all the course information from different MOOC platforms
and stores them in the database (MongoDB)
'''
from mongoengine import connect
from flask.ext.mongoengine import MongoEngine
from udacity import UdacityAPI
from coursera import CourseraAPI
class MOOCAggregator(object):
'''
Thi... | '''
This module aggregates all the course information from different MOOC platforms
and stores them in the database (MongoDB)
'''
from mongoengine import connect
from flask.ext.mongoengine import MongoEngine
from udacity import UdacityAPI
from coursera import CourseraAPI
from models import Mooc
class MOOCAggregator(... | Add functionality to store courses in database | Add functionality to store courses in database
| Python | mit | ueg1990/mooc_aggregator_restful_api | ---
+++
@@ -7,6 +7,7 @@
from udacity import UdacityAPI
from coursera import CourseraAPI
+from models import Mooc
class MOOCAggregator(object):
@@ -19,7 +20,14 @@
def __init__(self):
self.udacity = UdacityAPI()
self.coursera = CourseraAPI()
- connect('moocs')
+ #connect('m... |
80933bcefcb686f7fa49cf91283b1f6a619d77c3 | examples/django_demo/generic_foreignkey/apps.py | examples/django_demo/generic_foreignkey/apps.py | from __future__ import unicode_literals
from django.apps import AppConfig
class GenericForenikeyConfig(AppConfig):
name = 'generic_foreignkey'
| from __future__ import unicode_literals
from django.apps import AppConfig
class GenericForeignKeyConfig(AppConfig):
name = 'generic_foreignkey'
| Fix typo: GenericForenikeyConfig → GenericForeignKeyConfig | Fix typo: GenericForenikeyConfig → GenericForeignKeyConfig
| Python | mit | FactoryBoy/factory_boy | ---
+++
@@ -3,5 +3,5 @@
from django.apps import AppConfig
-class GenericForenikeyConfig(AppConfig):
+class GenericForeignKeyConfig(AppConfig):
name = 'generic_foreignkey' |
0ca4e0898fc6ee84109b458dfd505cdf42a5bae3 | tests/shared/core/test_constants.py | tests/shared/core/test_constants.py | from typing import Text, Type
import pytest
from rasa.core.policies.rule_policy import RulePolicy
from rasa.nlu.classifiers.fallback_classifier import FallbackClassifier
from rasa.shared.core.constants import (
CLASSIFIER_NAME_FALLBACK,
POLICY_NAME_RULE,
)
@pytest.mark.parametrize(
"name_in_constant, po... | from typing import Text, Type
import pytest
from rasa.core.policies.rule_policy import RulePolicy
from rasa.nlu.classifiers.fallback_classifier import FallbackClassifier
from rasa.shared.core.constants import (
CLASSIFIER_NAME_FALLBACK,
POLICY_NAME_RULE,
)
@pytest.mark.parametrize(
"name_in_constant, po... | Fix some code quality issues. | Fix some code quality issues.
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu | ---
+++
@@ -12,10 +12,7 @@
@pytest.mark.parametrize(
"name_in_constant, policy_class",
- [
- (POLICY_NAME_RULE, RulePolicy),
- (CLASSIFIER_NAME_FALLBACK, FallbackClassifier),
- ],
+ [(POLICY_NAME_RULE, RulePolicy), (CLASSIFIER_NAME_FALLBACK, FallbackClassifier),],
)
def test_policy_na... |
0f2950fcb44efc9b629242743574af503e8230d4 | tip/algorithms/sorting/mergesort.py | tip/algorithms/sorting/mergesort.py | def merge(a, b):
if len(a) * len(b) == 0:
return a + b
v = (a[0] < b[0] and a or b).pop(0)
return [v] + merge(a, b)
def mergesort(list):
if len(list) < 2:
return list
m = len(list) / 2
return merge(mergesort(list[:m]), mergesort(list[m:]))
| def merge(a, b):
if len(a) * len(b) == 0:
return a + b
v = (a[0] < b[0] and a or b).pop(0)
return [v] + merge(a, b)
def mergesort(list):
if len(list) < 2:
return list
m = len(list) / 2
return merge(mergesort(list[:int(m)]), mergesort(list[int(m):]))
| Fix slices for Python 3 | Fix slices for Python 3
| Python | unlicense | davidgasquez/tip | ---
+++
@@ -11,4 +11,4 @@
return list
m = len(list) / 2
- return merge(mergesort(list[:m]), mergesort(list[m:]))
+ return merge(mergesort(list[:int(m)]), mergesort(list[int(m):])) |
cda7f19ac24fe9217e4f5a655de1a6085cf75b12 | api/users/serializers.py | api/users/serializers.py | from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, Link
class UserSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'fullname',
'given_name',
'middle_name',
'family_name',
'id'
])
id = ser.Char... | from rest_framework import serializers as ser
from api.base.serializers import JSONAPISerializer, LinksField, Link
class UserSerializer(JSONAPISerializer):
filterable_fields = frozenset([
'fullname',
'given_name',
'middle_name',
'family_name',
'id'
])
id = ser.Char... | Check for parent filterable fields as well as local filterable fields | Check for parent filterable fields as well as local filterable fields
| Python | apache-2.0 | Nesiehr/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,ZobairAlijan/osf.io,KAsante95/osf.io,barbour-em/osf.io,chennan47/osf.io,icereval/osf.io,chrisseto/osf.io,erinspace/osf.io,erinspace/osf.io,kwierman/osf.io,cslzchen/osf.io,KAsante95/osf.io,felliott/osf.io,cslzchen/osf.io,alexschiller/osf.io,jmcarp/osf.io,danielneis/o... | ---
+++
@@ -43,7 +43,8 @@
class ContributorSerializer(UserSerializer):
- filterable_fields = frozenset(['bibliographic'])
+ local_filterable = frozenset(['bibliographic'])
+ filterable_fields = frozenset.union(UserSerializer.filterable_fields, local_filterable)
bibliographic = ser.SerializerMetho... |
85f9886e9a9cfddaa9cc8d90355647f5f8db53c4 | touchdown/tests/test_aws_ec2_ami.py | touchdown/tests/test_aws_ec2_ami.py | # Copyright 2015 Isotoma Limited
#
# 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... | # Copyright 2015 Isotoma Limited
#
# 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... | Update tests to match new metadata | Update tests to match new metadata
| Python | apache-2.0 | yaybu/touchdown,mitchellrj/touchdown | ---
+++
@@ -21,4 +21,4 @@
def test_waiter_waity_enough(self):
waiter = session.get_waiter_model("ec2")
- self.assertEqual(waiter.get_waiter("ImageAvailable").max_attempts, 80)
+ self.assertEqual(waiter.get_waiter("ImageAvailable").max_attempts, 160) |
58ce7f451263616c19599171305965b03807a853 | thinglang/foundation/definitions.py | thinglang/foundation/definitions.py | from thinglang.lexer.values.identifier import Identifier
"""
The internal ordering of core types used by the compiler and runtime
"""
INTERNAL_TYPE_ORDERING = {
Identifier("text"): 1,
Identifier("number"): 2,
Identifier("bool"): 3,
Identifier("list"): 4,
Identifier("Console"): 5,
Identifier("F... | from thinglang.lexer.values.identifier import Identifier
"""
The internal ordering of core types used by the compiler and runtime
"""
INTERNAL_TYPE_ORDERING = {
Identifier("text"): 1,
Identifier("number"): 2,
Identifier("bool"): 3,
Identifier("list"): 4,
Identifier("Console"): 5,
Identifier("F... | Add new types to INTERNAL_TYPE_ORDERING | Add new types to INTERNAL_TYPE_ORDERING
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -10,5 +10,7 @@
Identifier("bool"): 3,
Identifier("list"): 4,
Identifier("Console"): 5,
- Identifier("File"): 6
+ Identifier("File"): 6,
+ Identifier("Time"): 7,
+ Identifier("Exception"): 8
} |
aca7c4ef6998786abfd2119fee26e1d94d501c16 | _build/drake-build.py | _build/drake-build.py | #!/usr/bin/python
import sys
sys.path.append('../src')
import drake
drake.run('..')
| #!/usr/bin/python
import os
import sys
sys.path.append('../src')
if 'PYTHONPATH' in os.environ:
os.environ['PYTHONPATH'] = '../src:%s' % os.environ['PYTHONPATH']
else:
os.environ['PYTHONPATH'] = '../src'
import drake
drake.run('..')
| Add drake in the PYTHONPATH for the tests. | Add drake in the PYTHONPATH for the tests.
| Python | agpl-3.0 | mefyl/drake,mefyl/drake,mefyl/drake,infinit/drake,infinit/drake,infinit/drake | ---
+++
@@ -1,7 +1,13 @@
#!/usr/bin/python
+import os
import sys
+
sys.path.append('../src')
+if 'PYTHONPATH' in os.environ:
+ os.environ['PYTHONPATH'] = '../src:%s' % os.environ['PYTHONPATH']
+else:
+ os.environ['PYTHONPATH'] = '../src'
import drake
|
f751b95912b5cc03c3fd60742de9159b00d92b79 | echonest/utils.py | echonest/utils.py | from django.conf import settings
from purl import Template
import requests
from .models import SimilarResponse
API_URL = Template("http://developer.echonest.com/api/v4/artist/similar"
"?api_key=%s&results=100&name={name}"
% settings.ECHONEST_API_KEY)
def get_similar_from_api(n... | from django.conf import settings
from purl import Template
import requests
from .models import SimilarResponse
API_URL = Template("http://developer.echonest.com/api/v4/artist/similar"
"?api_key=%s&results=100&name={name}"
% settings.ECHONEST_API_KEY)
def get_similar_from_api(n... | Fix bug in The Echo Nest API call | Fix bug in The Echo Nest API call
| Python | bsd-3-clause | FreeMusicNinja/api.freemusic.ninja | ---
+++
@@ -12,7 +12,7 @@
def get_similar_from_api(name):
url = API_URL.expand({'name': name})
- r = requests.get(url)
+ r = requests.get(str(url))
r.raise_for_status()
return SimilarResponse.objects.create(name=name, response=r.json())
|
a4e9c3c47ff3999b56d769208106d3a605e1b50e | tests/test_client.py | tests/test_client.py | from __future__ import unicode_literals
import balanced
from . import utils
class TestClient(utils.TestCase):
def setUp(self):
super(TestClient, self).setUp()
def test_configure(self):
balanced.configure('XXX')
expected_headers = {
'content-type': 'application/vnd.api+j... | from __future__ import unicode_literals
import balanced
from . import utils
class TestClient(utils.TestCase):
def setUp(self):
super(TestClient, self).setUp()
def test_configure(self):
expected_headers = {
'content-type': 'application/vnd.api+json;revision=1.1',
'ac... | Fix 401 in test suite | Fix 401 in test suite | Python | mit | balanced/balanced-python,trenton42/txbalanced | ---
+++
@@ -11,7 +11,6 @@
super(TestClient, self).setUp()
def test_configure(self):
- balanced.configure('XXX')
expected_headers = {
'content-type': 'application/vnd.api+json;revision=1.1',
'accept': 'application/json;revision=1.1', |
0c405fd30d059164509308dee604f50d9857202d | scripts/slave/recipe_modules/webrtc/resources/cleanup_files.py | scripts/slave/recipe_modules/webrtc/resources/cleanup_files.py | #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script that deletes all files (but not directories) in a given directory."""
import os
import sys
def main(args):
if not args o... | #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script that deletes all files (but not directories) in a given directory."""
import os
import sys
def main(args):
if not args o... | Make clean script return successful if clean dir is missing. | WebRTC: Make clean script return successful if clean dir is missing.
I thought it would be good to have the script fail for an
incorrectly specified directory, but the out/ dir is missing
on fresh installed slave machines, so better just skip cleaning
with a line printed to stdout instead when the dir is missing.
TES... | Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -16,8 +16,8 @@
clean_dir = args[0]
if not os.path.isdir(clean_dir):
- print >> sys.stderr, '%s does not exist or is not a directory!' % clean_dir
- return 2
+ print 'Cannot find any directory at %s. Skipping cleaning.' % clean_dir
+ return 0
for filename in os.listdir(clean_dir):
... |
a0bc95155bc3aed691793afb8fec639661cb9d5b | polyaxon/polyaxon/config_settings/events_handlers/__init__.py | polyaxon/polyaxon/config_settings/events_handlers/__init__.py | from polyaxon.config_settings.volume_claims import *
from .apps import *
| from polyaxon.config_settings.volume_claims import *
from polyaxon.config_settings.spawner import *
from .apps import *
| Add spawner to event handlers | Add spawner to event handlers
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -1,2 +1,3 @@
from polyaxon.config_settings.volume_claims import *
+from polyaxon.config_settings.spawner import *
from .apps import * |
00bfddc9317660f6e7464288fc070d40a1ebad6b | server/constants.py | server/constants.py | """App constants"""
STUDENT_ROLE = 'student'
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
LAB_ASSISTANT_ROLE = 'lab assistant'
VALID_ROLES = [STUDENT_ROLE, LAB_ASSISTANT_ROLE, GRADER_ROLE, STAFF_ROLE,
INSTRUCTOR_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE]... | """App constants"""
STUDENT_ROLE = 'student'
GRADER_ROLE = 'grader'
STAFF_ROLE = 'staff'
INSTRUCTOR_ROLE = 'instructor'
LAB_ASSISTANT_ROLE = 'lab assistant'
VALID_ROLES = [STUDENT_ROLE, LAB_ASSISTANT_ROLE, GRADER_ROLE, STAFF_ROLE,
INSTRUCTOR_ROLE]
STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE]... | Add /rq to banned course names | Add /rq to banned course names
| Python | apache-2.0 | Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok | ---
+++
@@ -30,6 +30,7 @@
'login',
'logout',
'oauth',
+ 'rq',
'testing-login',
]
FORBIDDEN_ASSIGNMENT_NAMES = [] |
c5103eea181455afded264528bb97ac8a9982db0 | enable/__init__.py | enable/__init__.py | # Copyright (c) 2007-2014 by Enthought, Inc.
# All rights reserved.
""" A multi-platform object drawing library.
Part of the Enable project of the Enthought Tool Suite.
"""
from __future__ import absolute_import
from ._version import full_version as __version__
__requires__ = [
'traitsui',
'PIL',
'... | # Copyright (c) 2007-2014 by Enthought, Inc.
# All rights reserved.
""" A multi-platform object drawing library.
Part of the Enable project of the Enthought Tool Suite.
"""
from enable._version import full_version as __version__
__requires__ = [
'traitsui',
'PIL',
'kiwisolver',
]
| Use an absolute import to avoid breaking the docs build. | Use an absolute import to avoid breaking the docs build.
| Python | bsd-3-clause | tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable | ---
+++
@@ -4,9 +4,7 @@
Part of the Enable project of the Enthought Tool Suite.
"""
-from __future__ import absolute_import
-
-from ._version import full_version as __version__
+from enable._version import full_version as __version__
__requires__ = [
'traitsui', |
926c4662c7b3059503bd0a22ee9624bb39ab40fd | sharepa/__init__.py | sharepa/__init__.py | from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
from sharepa.helpers import source_agg, source_counts
| from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
| Remove helper functions from sharepa init | Remove helper functions from sharepa init
| Python | mit | samanehsan/sharepa,erinspace/sharepa,CenterForOpenScience/sharepa,fabianvf/sharepa | ---
+++
@@ -1,3 +1,2 @@
from sharepa.search import ShareSearch, basic_search # noqa
from sharepa.analysis import bucket_to_dataframe, merge_dataframes # noqa
-from sharepa.helpers import source_agg, source_counts |
658839e09d17180d9c6564af8fc92f120a4b5bd8 | parserscripts/collect_accessions.py | parserscripts/collect_accessions.py | # -*- coding: utf-8 -*-
'''
Created on Tue Aug 15 11:26:23 2017
This script processes NCBI data exports (from ftp://ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/IDS/)
to extract lists of organism accession IDs, later used for downloading complete genome sequences.
@author: mbonsma / thisisjaid
'''
import os
import pan... | # -*- coding: utf-8 -*-
'''
Created on Tue Aug 15 11:26:23 2017
This script processes NCBI data exports (from ftp://ftp.ncbi.nlm.nih.gov/genomes/GENOME_REPORTS/IDS/)
to extract lists of organism accession IDs, later used for downloading complete genome sequences.
@author: mbonsma / thisisjaid
'''
import os
import pan... | Fix typo: `succesfully` -> `successfully` | Fix typo: `succesfully` -> `successfully`
| Python | mit | mbonsma/phageParser,phageParser/phageParser,goyalsid/phageParser,mbonsma/phageParser,mbonsma/phageParser,goyalsid/phageParser,goyalsid/phageParser,phageParser/phageParser,phageParser/phageParser,phageParser/phageParser,mbonsma/phageParser | ---
+++
@@ -24,4 +24,4 @@
records = pd.read_csv(args.file,sep='\t', header=None)
records.to_csv(args.o,header=False,sep=',',columns=[1],index=False)
-print('Accession file succesfully written out at:',args.o)
+print('Accession file successfully written out at:',args.o) |
2d534b7be13bda60646815e16a91e778da71c3f8 | auditlog/__manifest__.py | auditlog/__manifest__.py | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | # -*- coding: utf-8 -*-
# © 2015 ABF OSIELL <http://osiell.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': "Audit Log",
'version': "9.0.1.0.0",
'author': "ABF OSIELL,Odoo Community Association (OCA)",
'license': "AGPL-3",
'website': "http://www.osiell.com",
'categ... | Remove pre_init_hook reference from openerp, no pre_init hook exists any more | auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
| Python | agpl-3.0 | Vauxoo/server-tools,Vauxoo/server-tools,Vauxoo/server-tools | ---
+++
@@ -22,5 +22,4 @@
'images': [],
'application': True,
'installable': True,
- 'pre_init_hook': 'pre_init_hook',
} |
b02c36bc23af41ee82414f36eb6cf20ffa5a4a46 | edx_data_research/reporting/basic/user_info.py | edx_data_research/reporting/basic/user_info.py | '''
This module will retrieve info about students registered in the course
'''
def user_info(edx_obj):
edx_obj.collections = ['certificates_generatedcertificate', 'auth_userprofile','user_id_map','student_courseenrollment']
cursor = edx_obj.collections['auth_userprofile'].find()
result = []
for item ... | '''
This module will retrieve info about students registered in the course
'''
def user_info(edx_obj):
edx_obj.collections = ['certificates_generatedcertificate', 'auth_userprofile','user_id_map','student_courseenrollment']
cursor = edx_obj.collections['auth_userprofile'].find()
result = []
for item ... | Add hash_id column to user-info output | Add hash_id column to user-info output
| Python | mit | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research | ---
+++
@@ -11,9 +11,11 @@
user_id = item['user_id']
try:
final_grade = edx_obj.collections['certificates_generatedcertificate'].find_one({'user_id' : user_id})['grade']
- username = edx_obj.collections['user_id_map'].find_one({'id' : user_id})['username']
+ user_id_map =... |
1607082857eb38da54d448ef1a6f48a8459d44a4 | imager/ImagerProfile/admin.py | imager/ImagerProfile/admin.py | from django.contrib import admin
from ImagerProfile.models import ImagerProfile
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
# admin.site.unregister(User)
class ImagerUserInline(admin.StackedInline):
model = ImagerProfile
can_delete = False
verbose_name_plur... | from django.contrib import admin
from imagerprofile.models import ImagerProfile
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
# admin.site.unregister(User)
class ImagerUserInline(admin.StackedInline):
model = ImagerProfile
can_delete = False
verbose_name_plur... | Change app name in import to lowercase | Change app name in import to lowercase
| Python | mit | nbeck90/django-imager,nbeck90/django-imager | ---
+++
@@ -1,5 +1,5 @@
from django.contrib import admin
-from ImagerProfile.models import ImagerProfile
+from imagerprofile.models import ImagerProfile
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
|
8af2699f6d0f190081254243e2c90369b4541e34 | happening/db.py | happening/db.py | """ Custom happening database manipulation. """
from django.contrib.sites.managers import CurrentSiteManager as Manager
from django.db import models
from django.contrib.sites.models import Site
from multihost import sites
import os
class Model(models.Model):
""" Custom model for use in happening.
Ensures t... | """ Custom happening database manipulation. """
from django.contrib.sites.managers import CurrentSiteManager as Manager
from django.db import models
from django.contrib.sites.models import Site
from multihost import sites
import os
class Model(models.Model):
""" Custom model for use in happening.
Ensures t... | Make travis tests work with sites | Make travis tests work with sites
| Python | mit | happeninghq/happening,happeninghq/happening,jscott1989/happening,happeninghq/happening,jscott1989/happening,jscott1989/happening,jscott1989/happening,happeninghq/happening | ---
+++
@@ -22,7 +22,7 @@
def save(self, *args, **kwargs):
""" Ensure there is a site for this instance. """
- if 'scdtest' in os.environ:
+ if 'scdtest' in os.environ or 'travis' in os.environ:
self.site = Site.objects.first()
else:
self.site = sites.b... |
db6222adea234921f82a843846778f5327566aaf | homebrew/logger.py | homebrew/logger.py | import logging
import sys
logger = logging.getLogger()
logFormatter = logging.Formatter("%(message)s")
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)
logger.setLevel(logging.INFO)
UNDERLINE_SYMBOL = "-"
def log_title(logline):
logge... | import logging
import sys
logger = logging.getLogger()
formatter = logging.Formatter("%(message)s")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
UNDERLINE_SYMBOL = "-"
def log_title(logline):
logger.info(logline)
logger.... | Rename variables used for setting up logging | Rename variables used for setting up logging
| Python | isc | igroen/homebrew | ---
+++
@@ -2,10 +2,10 @@
import sys
logger = logging.getLogger()
-logFormatter = logging.Formatter("%(message)s")
-consoleHandler = logging.StreamHandler(sys.stdout)
-consoleHandler.setFormatter(logFormatter)
-logger.addHandler(consoleHandler)
+formatter = logging.Formatter("%(message)s")
+handler = logging.Stre... |
7558f0ed7c14cd4a1cfb87fdefc631adf8d1aff0 | server/dummy/dummy_server.py | server/dummy/dummy_server.py | #!/usr/bin/env python
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def do_POST(self):
print '---> dummy server: got post!'
print 'command... | #!/usr/bin/env python
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def do_POST(self):
print '\n---> dummy server: got post!'
print 'comma... | Clean up post formatting and response code | Clean up post formatting and response code
| Python | mit | jonspeicher/Puddle,jonspeicher/Puddle,jonspeicher/Puddle | ---
+++
@@ -10,16 +10,17 @@
class JsonPostResponder(RequestHandlerClass):
def do_POST(self):
- print '---> dummy server: got post!'
+ print '\n---> dummy server: got post!'
print 'command:', self.command
print 'path:', self.path
print 'headers:\n\n', self.headers
+ ... |
49015e6d1a4c8670172ea00776e168f6cec0092b | openedx/core/djangoapps/user_api/accounts/forms.py | openedx/core/djangoapps/user_api/accounts/forms.py | """
Django forms for accounts
"""
from django import forms
from django.core.exceptions import ValidationError
class RetirementQueueDeletionForm(forms.Form):
"""
Admin form to facilitate learner retirement cancellation
"""
cancel_retirement = forms.BooleanField(required=True)
def save(self, retir... | """
Django forms for accounts
"""
from django import forms
from django.core.exceptions import ValidationError
from openedx.core.djangoapps.user_api.accounts.utils import generate_password
class RetirementQueueDeletionForm(forms.Form):
"""
Admin form to facilitate learner retirement cancellation
"""
c... | Reset learners password when user is unGDPRed/unretired via django admin. | Reset learners password when user is unGDPRed/unretired via django admin.
| Python | agpl-3.0 | cpennington/edx-platform,a-parhom/edx-platform,philanthropy-u/edx-platform,arbrandes/edx-platform,msegado/edx-platform,eduNEXT/edunext-platform,ESOedX/edx-platform,philanthropy-u/edx-platform,jolyonb/edx-platform,jolyonb/edx-platform,edx/edx-platform,stvstnfrd/edx-platform,EDUlib/edx-platform,edx/edx-platform,angelappe... | ---
+++
@@ -4,6 +4,7 @@
from django import forms
from django.core.exceptions import ValidationError
+from openedx.core.djangoapps.user_api.accounts.utils import generate_password
class RetirementQueueDeletionForm(forms.Form):
@@ -33,6 +34,8 @@
# Load the user record using the retired email address... |
d66a412efad62d47e7df8d2ff4922be4c268a93e | hunittest/utils.py | hunittest/utils.py | # -*- encoding: utf-8 -*-
"""Utility routines
"""
import os
import re
from enum import Enum
from contextlib import contextmanager
def pyname_join(seq):
return ".".join(seq)
def is_pkgdir(dirpath):
return os.path.isdir(dirpath) \
and os.path.isfile(os.path.join(dirpath, "__init__.py"))
def mod_spli... | # -*- encoding: utf-8 -*-
"""Utility routines
"""
import os
import re
from enum import Enum
from contextlib import contextmanager
import unittest
def pyname_join(seq):
return ".".join(seq)
def is_pkgdir(dirpath):
return os.path.isdir(dirpath) \
and os.path.isfile(os.path.join(dirpath, "__init__.py"... | Add helper to load a single test case. | Add helper to load a single test case.
| Python | bsd-2-clause | nicolasdespres/hunittest | ---
+++
@@ -7,6 +7,7 @@
import re
from enum import Enum
from contextlib import contextmanager
+import unittest
def pyname_join(seq):
@@ -58,3 +59,8 @@
return os.getcwd()
except FileNotFoundError:
return None
+
+def load_single_test_case(test_name):
+ test_suite = list(unittest.defaul... |
4de3b357101b3c304a6d89fd02175156ffecc656 | src/mailme/constants.py | src/mailme/constants.py |
# Folder name mappings, based on http://tools.ietf.org/html/rfc6154
INBOX = 'inbox'
DRAFTS = 'drafts'
SPAM = 'spam'
ARCHIVE = 'archive'
SENT = 'sent'
TRASH = 'trash'
ALL = 'all'
IMPORTANT = 'important'
# Default mapping to unify various provider behaviors
DEFAULT_FOLDER_MAPPING = {
'inbox': INBOX,
'drafts': D... |
# Folder name mappings, based on http://tools.ietf.org/html/rfc6154
INBOX = 'inbox'
DRAFTS = 'drafts'
SPAM = 'spam'
ARCHIVE = 'archive'
SENT = 'sent'
TRASH = 'trash'
ALL = 'all'
IMPORTANT = 'important'
# Default mapping to unify various provider behaviors
DEFAULT_FOLDER_MAPPING = {
'inbox': INBOX,
'drafts': D... | Add 'sent items' to default folder mapping | Add 'sent items' to default folder mapping
| Python | bsd-3-clause | mailme/mailme,mailme/mailme | ---
+++
@@ -18,6 +18,7 @@
'spam': SPAM,
'archive': ARCHIVE,
'sent': SENT,
+ 'sent items': SENT,
'trash': TRASH,
'all': ALL,
'important': IMPORTANT, |
75632e699b6b83eba3d87506b2fed2de45f695bc | ai/STA/Strategy/stay_away.py | ai/STA/Strategy/stay_away.py | # Under MIT license, see LICENSE.txt
from ai.STA.Tactic.stay_away_from_ball import StayAwayFromBall
from ai.STA.Strategy.Strategy import Strategy
from ai.Util.role import Role
class StayAway(Strategy):
def __init__(self, p_game_state):
super().__init__(p_game_state)
roles_to_consider = [Role.FIRS... | # Under MIT license, see LICENSE.txt
from ai.STA.Tactic.stay_away_from_ball import StayAwayFromBall
from ai.STA.Strategy.Strategy import Strategy
from ai.Util.role import Role
class StayAway(Strategy):
def __init__(self, p_game_state):
super().__init__(p_game_state)
for r in Role:
p =... | Fix StayAway strat for pull request | Fix StayAway strat for pull request
| Python | mit | RoboCupULaval/StrategyIA,RoboCupULaval/StrategyIA | ---
+++
@@ -8,10 +8,7 @@
def __init__(self, p_game_state):
super().__init__(p_game_state)
- roles_to_consider = [Role.FIRST_ATTACK, Role.SECOND_ATTACK, Role.MIDDLE,
- Role.FIRST_DEFENCE, Role.SECOND_DEFENCE, Role.GOALKEEPER]
- role_by_robots = [(i, self.game_s... |
af56c549a8eae5ebb0d124e2bb397241f11e47af | indico/__init__.py | indico/__init__.py | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico 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 of the
# License, or (a... | # This file is part of Indico.
# Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
#
# Indico 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 of the
# License, or (a... | Fix pip install failing due to wtforms monkeypatch | Fix pip install failing due to wtforms monkeypatch
| Python | mit | OmeGak/indico,mvidalgarcia/indico,mvidalgarcia/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,OmeGak/indico,pferreir/indico,pferreir/indico,OmeGak/indico,mvidalgarcia/indico,DirkHoffmann/indico,ThiefMaster/indico,indico/indico,ThiefMaster/indico,DirkHoffmann/indico,mic4ael/indico,mic4ael/indico,mvidalgarci... | ---
+++
@@ -34,5 +34,10 @@
fields.get_pk_from_identity = get_pk_from_identity
-_patch_wtforms_sqlalchemy()
-del _patch_wtforms_sqlalchemy
+try:
+ _patch_wtforms_sqlalchemy()
+except ImportError as exc:
+ # pip seems to run this sometimes while uninstalling an old sqlalchemy version
+ print 'Could no... |
275301d7a2c2e8c44ff1cfb3d49d9388f9531b56 | invalidate_data.py | invalidate_data.py | #!/usr/bin/env python3
# Copyright (c) 2017, John Skinner
import sys
import logging
import logging.config
import config.global_configuration as global_conf
import database.client
import batch_analysis.invalidate
def main():
"""
Run a particular task.
:args: Only argument is the id of the task to run
... | #!/usr/bin/env python3
# Copyright (c) 2017, John Skinner
import sys
import logging
import logging.config
import config.global_configuration as global_conf
import database.client
import batch_analysis.invalidate
def main():
"""
Run a particular task.
:args: Only argument is the id of the task to run
... | Update invalidate to remove failed trials. | Update invalidate to remove failed trials.
| Python | bsd-2-clause | jskinn/robot-vision-experiment-framework,jskinn/robot-vision-experiment-framework | ---
+++
@@ -26,6 +26,11 @@
logging.getLogger(__name__).info("Invalidating system {0}".format(system_id['_id']))
batch_analysis.invalidate.invalidate_system(db_client, system_id['_id'])
+ failed_trials = db_client.trials_collection.find({'success': False}, {'_id': True})
+ for trial_id in fai... |
ec28eadeab215533cec1b14b627e2793aa7f4f31 | tt_dailyemailblast/send_backends/sync.py | tt_dailyemailblast/send_backends/sync.py | from . import email
def sync_daily_email_blasts(blast):
for l in blast.recipients_lists.all():
l.send(blast)
def sync_recipients_list(recipients_list, blast):
for r in recipients_list.recipientss.all():
r.send(recipients_list, blast)
def sync_recipient(recipient, recipients_list, blast):
... | from .. import email
def sync_daily_email_blasts(blast):
for l in blast.recipients_lists.all():
l.send(blast)
def sync_recipients_list(recipients_list, blast):
for r in recipients_list.recipientss.all():
r.send(recipients_list, blast)
def sync_recipient(recipient, recipients_list, blast):
... | Fix email module could not be imported | Fix email module could not be imported
This helpful message alerted me to this problem:
ImproperlyConfigured: <django.utils.functional.__proxy__ object at
0x10b023990>
| Python | apache-2.0 | texastribune/tt_dailyemailblast,texastribune/tt_dailyemailblast | ---
+++
@@ -1,4 +1,4 @@
-from . import email
+from .. import email
def sync_daily_email_blasts(blast): |
4946adddd889db89d65764f3a680ccc6853ea949 | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP objects.
The implenter has to:
- Pass 'res_mod... | # -*- coding: utf-8 -*-
{
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
'category': 'Hidden/Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP objects.
The implenter has to:
- Pass '... | Update category and website on module description | Update category and website on module description
| Python | agpl-3.0 | xcgd/document_attachment | ---
+++
@@ -3,7 +3,7 @@
'name': 'Document Attachment',
'version': '1.2',
'author': 'XCG Consulting',
- 'category': 'Dependency',
+ 'category': 'Hidden/Dependency',
'description': """Enchancements to the ir.attachment module
to manage kinds of attachments that can be linked with OpenERP obje... |
9ee00a148763c7caac1ae0d7dcb3efa496121ee7 | lamana/__init__.py | lamana/__init__.py | # -----------------------------------------------------------------------------
__title__ = 'lamana'
__version__ = '0.4.11-dev'
__author__ = 'P. Robinson II'
__license__ = 'BSD'
__copyright__ = 'Copyright 2015, P. Robinson II'
import lamana.input_
import lamana.distributions
import lamana.constructs
import lamana.the... | # -----------------------------------------------------------------------------
__title__ = 'lamana'
__version__ = '0.4.11.dev0' # PEP 440 style
##__version__ = '0.4.11-dev'
__author__ = 'P. Robinson II'
__license__ = 'BSD'
__copyright__ = 'Copyright 2015, P. Robinson II'
import lamana.... | Modify dev versioning; see PEP 440 | Modify dev versioning; see PEP 440
| Python | bsd-3-clause | par2/lamana | ---
+++
@@ -1,7 +1,8 @@
# -----------------------------------------------------------------------------
__title__ = 'lamana'
-__version__ = '0.4.11-dev'
+__version__ = '0.4.11.dev0' # PEP 440 style
+##__version__ = '0.4.11-dev'
__author__ = 'P. Robinson II'
__license__ = 'BSD'
__... |
e6e40df6e23f6623c4672b9ec3aab982f5588c8c | downstream-farmer/client.py | downstream-farmer/client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import random
import hashlib
import requests
from heartbeat import Challenge, Heartbeat
from .utils import urlify
from .exc import DownstreamError
class DownstreamClient(object):
def __init__(self, server_url):
self.server = server_url.... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import random
import hashlib
import requests
from heartbeat import Challenge, Heartbeat
from .utils import urlify
from .exc import DownstreamError
class DownstreamClient(object):
def __init__(self, server_url):
self.server = server_url.... | Set heartbeat attrib in init | Set heartbeat attrib in init
| Python | mit | Storj/downstream-farmer | ---
+++
@@ -16,6 +16,7 @@
def __init__(self, server_url):
self.server = server_url.strip('/')
self.challenges = []
+ self.heartbeat = None
def connect(self, url):
raise NotImplementedError |
fa9577f875c999ea876c99e30614051f7ceba129 | authentication_app/models.py | authentication_app/models.py | from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : Account
@desc : Account model. This model is generic to represent a user that has an
account in the ShopIT application. This user can be the store manager or the
mobile app user.
'''
class ... | from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
'''
@name : AccountManager
@desc : AccountManager model. The AccountManager is responsible to manage
the creation of users and superusers.
'''
class AccountManager(BaseUserManager):
def create_user(sel... | Add the account manager that support the creation of accounts. | Add the account manager that support the creation of accounts.
| Python | mit | mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app | ---
+++
@@ -1,5 +1,31 @@
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
+
+'''
+ @name : AccountManager
+ @desc : AccountManager model. The AccountManager is responsible to manage
+ the creation of users and superusers.
+'''
+class AccountManager(BaseU... |
332ea322d55b2d0410db172616fe51ccd0de050d | create_coverage_database.py | create_coverage_database.py | #!/usr/bin/env python
import argparse
import getpass
from cassandra import query
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.management import create_keyspace_simple
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextA... | #!/usr/bin/env python
import argparse
import getpass
from cassandra import query
from cassandra.cqlengine.management import sync_table
from cassandra.cqlengine.management import create_keyspace_simple
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.auth import PlainTextA... | Move setting of row factory to after session object is created | Move setting of row factory to after session object is created
| Python | mit | GastonLab/ddb-datastore,dgaston/ddb-variantstore,dgaston/ddb-datastore,dgaston/ddbio-variantstore | ---
+++
@@ -22,11 +22,13 @@
password = getpass.getpass()
auth_provider = PlainTextAuthProvider(username=args.username, password=password)
cluster = Cluster([args.address], auth_provider=auth_provider)
- session = cluster.connect(row_factory=query.dict_factory)
+ session = clus... |
1fe4a129ba96f14dc91832754de00271a29f48ca | tests/tools/test_foodcritic.py | tests/tools/test_foodcritic.py | from lintreview.review import Comment
from lintreview.review import Problems
from lintreview.tools.foodcritic import Foodcritic
from unittest import TestCase
from nose.tools import eq_
class TestFoodcritic(TestCase):
fixtures = [
'tests/fixtures/foodcritic/noerrors',
'tests/fixtures/foodcritic/er... | from lintreview.review import Comment
from lintreview.review import Problems
from lintreview.tools.foodcritic import Foodcritic
from lintreview.utils import in_path
from unittest import TestCase, skipIf
from nose.tools import eq_
critic_missing = not(in_path('foodcritic'))
class TestFoodcritic(TestCase):
needs_... | Fix tests failing when foodcritic is not installed. | Fix tests failing when foodcritic is not installed.
Tool tests should skip, not fail.
| Python | mit | markstory/lint-review,adrianmoisey/lint-review,zoidbergwill/lint-review,zoidbergwill/lint-review,markstory/lint-review,zoidbergwill/lint-review,adrianmoisey/lint-review,markstory/lint-review | ---
+++
@@ -1,11 +1,16 @@
from lintreview.review import Comment
from lintreview.review import Problems
from lintreview.tools.foodcritic import Foodcritic
-from unittest import TestCase
+from lintreview.utils import in_path
+from unittest import TestCase, skipIf
from nose.tools import eq_
+critic_missing = not... |
7f2df3979458df73e4e3f0a9fdcb16905960de81 | _config.py | _config.py | # Amazon S3 Settings
AWS_KEY = 'REQUIRED'
AWS_SECRET_KEY = 'REQUIRED'
AWS_BUCKET = 'REQUIRED'
AWS_DIRECTORY = '' # Leave blank *not false* unless project not at base URL
# i.e. example.com/apps/ instead of example.com/
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRE... | # Frozen Flask
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = ''
AWS_DIRECTORY = '' # Use if S3 bucket is not root
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Upload Setti... | Update settings for new configuration | Update settings for new configuration
| Python | apache-2.0 | vprnet/EOTS-iframe-widget,vprnet/app-template,vprnet/live-from-the-fort,vprnet/timeline-dcf-systemic-failure,vprnet/app-template,vprnet/old-app-template,vprnet/app-template,vprnet/interactive-transcript-gov-peter-shumlins-third-inaugural-address,vprnet/soundcloud-podcast,vprnet/interactive-transcript-gov-peter-shumlins... | ---
+++
@@ -1,9 +1,12 @@
+# Frozen Flask
+FREEZER_DEFAULT_MIMETYPE = 'text/html'
+FREEZER_IGNORE_MIMETYPE_WARNINGS = True
+
# Amazon S3 Settings
-AWS_KEY = 'REQUIRED'
-AWS_SECRET_KEY = 'REQUIRED'
-AWS_BUCKET = 'REQUIRED'
-AWS_DIRECTORY = '' # Leave blank *not false* unless project not at base URL
- ... |
6c1a285d58825942e51689e7370316151345ab1f | examples/tornado/auth_demo.py | examples/tornado/auth_demo.py | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... | Add the settings to the authdemo. | Add the settings to the authdemo. | Python | bsd-3-clause | ged/mongrel2,ged/mongrel2,ged/mongrel2,ged/mongrel2 | ---
+++
@@ -16,6 +16,6 @@
]
)
-commit([main])
+commit([main], settings={'limits.buffer_size': 4 * 1024})
|
0e8d4e6649b6a48ac7bd87746574119a5ce5fd1a | qiime_studio/api/v1.py | qiime_studio/api/v1.py | from flask import Blueprint, jsonify
from .security import validate_request_authentication
from qiime.sdk import PluginManager
v1 = Blueprint('v1', __name__)
v1.before_request(validate_request_authentication)
@v1.route('/', methods=['GET', 'POST'])
def root():
return jsonify(content="!")
@v1.route('/plugins', ... | from flask import Blueprint, jsonify
from .security import validate_request_authentication
from qiime.sdk import PluginManager
PLUGIN_MANAGER = PluginManager()
v1 = Blueprint('v1', __name__)
v1.before_request(validate_request_authentication)
@v1.route('/', methods=['GET', 'POST'])
def root():
return jsonify(con... | Add plugin workflow fetching to API | Add plugin workflow fetching to API
| Python | bsd-3-clause | jakereps/qiime-studio,qiime2/qiime-studio,qiime2/qiime-studio-frontend,jakereps/qiime-studio,jakereps/qiime-studio,qiime2/qiime-studio-frontend,jakereps/qiime-studio-frontend,qiime2/qiime-studio,jakereps/qiime-studio-frontend,qiime2/qiime-studio | ---
+++
@@ -3,6 +3,7 @@
from .security import validate_request_authentication
from qiime.sdk import PluginManager
+PLUGIN_MANAGER = PluginManager()
v1 = Blueprint('v1', __name__)
v1.before_request(validate_request_authentication)
@@ -11,7 +12,18 @@
def root():
return jsonify(content="!")
+
@v1.route(... |
ccdb064c0523e9293dca13adefa13d155d372505 | spotifyconnect/sink.py | spotifyconnect/sink.py | from __future__ import unicode_literals
import spotifyconnect
class Sink(object):
def on(self):
"""Turn on the alsa_sink sink.
This is done automatically when the sink is instantiated, so you'll
only need to call this method if you ever call :meth:`off` and want to
turn the sink... | from __future__ import unicode_literals
import spotifyconnect
__all__ = [
'Sink'
]
class Sink(object):
def on(self):
"""Turn on the alsa_sink sink.
This is done automatically when the sink is instantiated, so you'll
only need to call this method if you ever call :meth:`off` and want... | Add Sink class to initial spotify-connect import | Add Sink class to initial spotify-connect import
| Python | apache-2.0 | chukysoria/pyspotify-connect,chukysoria/pyspotify-connect | ---
+++
@@ -2,6 +2,9 @@
import spotifyconnect
+__all__ = [
+ 'Sink'
+]
class Sink(object):
|
0a1d7a76407f834a40d8cb96312cf6a5d322c65c | datastage/web/user/models.py | datastage/web/user/models.py | import pam
from django.contrib.auth import models as auth_models
class User(auth_models.User):
class Meta:
proxy = True
def check_password(self, raw_password):
return pam.authenticate(self.username, raw_password)
# Monkey-patch User model
auth_models.User = User | import dpam.pam
from django.contrib.auth import models as auth_models
class User(auth_models.User):
class Meta:
proxy = True
def check_password(self, raw_password):
return dpam.pam.authenticate(self.username, raw_password)
# Monkey-patch User model
auth_models.User = User
| Use django_pams pam.authenticate, instead of some other pam module. | Use django_pams pam.authenticate, instead of some other pam module.
| Python | mit | dataflow/DataStage,dataflow/DataStage,dataflow/DataStage | ---
+++
@@ -1,4 +1,4 @@
-import pam
+import dpam.pam
from django.contrib.auth import models as auth_models
@@ -6,7 +6,7 @@
class Meta:
proxy = True
def check_password(self, raw_password):
- return pam.authenticate(self.username, raw_password)
+ return dpam.pam.authenticate(self.u... |
1d73536020b577b8847f5ce3be1c8686ee324fe9 | murano/tests/unit/api/middleware/test_version_negotiation.py | murano/tests/unit/api/middleware/test_version_negotiation.py | # Copyright 2016 AT&T Corp
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | # Copyright 2016 AT&T Corp
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | Change assertTrue(isinstance()) by optimal assert | Change assertTrue(isinstance()) by optimal assert
Some of tests use different method of assertTrue(isinstance(A, B))
or assertEqual(type(A), B). The correct way is to use assertIsInstance(A, B)
provided by testtools
Change-Id: Id6ff634d7af3ee3b2eb4add770b0ba589bb08d1d
| Python | apache-2.0 | openstack/murano,openstack/murano | ---
+++
@@ -28,4 +28,4 @@
middleware_vn = version_negotiation.VersionNegotiationFilter(None)
request = webob.Request.blank('/environments')
result = middleware_vn.process_request(request)
- self.assertTrue(isinstance(result, versions.Controller))
+ self.assertIsInstance(result... |
8ab5345f5c0c62606a28c608e45e08a89a96dddb | tests/install_tests.py | tests/install_tests.py | import sys
import logging
import subprocess
sys.path.insert(0, '..')
from unittest2 import TestCase
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwa... | import sys
import logging
import subprocess
sys.path.insert(0, '..')
from unittest2 import TestCase
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwa... | Fix test to work with python 2.6 | Fix test to work with python 2.6
| Python | bsd-3-clause | elbaschid/virtual-node | ---
+++
@@ -30,5 +30,6 @@
class TestNode(TestCase):
def test_is_installed(self):
- output = subprocess.check_output(['node', '--version'])
+ proc = subprocess.Popen(['node', '--version'], stdout=subprocess.PIPE)
+ output = proc.stdout.read()
self.assertEquals(output.strip(), 'v0.... |
9888a03368ad7b440cc43384024c71147aa647a3 | fireplace/cards/tgt/shaman.py | fireplace/cards/tgt/shaman.py | from ..utils import *
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
| from ..utils import *
##
# Hero Powers
# Lightning Jolt
class AT_050t:
play = Hit(TARGET, 2)
##
# Minions
# Tuskarr Totemic
class AT_046:
play = Summon(CONTROLLER, RandomTotem())
# Draenei Totemcarver
class AT_047:
play = Buff(SELF, "AT_047e") * Count(FRIENDLY_MINIONS + TOTEM)
# Thunder Bluff Valiant
class... | Implement Shaman cards for The Grand Tournament | Implement Shaman cards for The Grand Tournament
| Python | agpl-3.0 | oftc-ftw/fireplace,smallnamespace/fireplace,amw2104/fireplace,jleclanche/fireplace,Ragowit/fireplace,beheh/fireplace,smallnamespace/fireplace,NightKev/fireplace,liujimj/fireplace,Meerkov/fireplace,liujimj/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,amw2104/fireplace,Meerkov/fireplace | ---
+++
@@ -1,4 +1,12 @@
from ..utils import *
+
+
+##
+# Hero Powers
+
+# Lightning Jolt
+class AT_050t:
+ play = Hit(TARGET, 2)
##
@@ -17,3 +25,24 @@
# Thunder Bluff Valiant
class AT_049:
inspire = Buff(FRIENDLY_MINIONS + TOTEM, "AT_049e")
+
+
+##
+# Spells
+
+# Elemental Destruction
+class AT_051:
+ play... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.