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
a179b2afff8af8dce5ae816d6f97a002a9151cf4
booger_test.py
booger_test.py
#!/usr/bin/python ################################################################################ # "THE BEER-WARE LICENSE" (Revision 42): # <thenoviceoof> wrote this file. As long as you retain this notice # you can do whatever you want with this stuff. If we meet some day, # and you think this stuff is worth it, you...
#!/usr/bin/python ################################################################################ # "THE BEER-WARE LICENSE" (Revision 42): # <thenoviceoof> wrote this file. As long as you retain this notice # you can do whatever you want with this stuff. If we meet some day, # and you think this stuff is worth it, you...
Write some more tests for the short nosetests parser
Write some more tests for the short nosetests parser
Python
mit
thenoviceoof/booger,thenoviceoof/booger
--- +++ @@ -6,7 +6,6 @@ # and you think this stuff is worth it, you can buy me a beer in # return # Nathan Hwang <thenoviceoof> -# ---------------------------------------------------------------------------- ################################################################################ from unittest import T...
65731a34e152d085f55893c65607b8fa25dcfd63
pathvalidate/_interface.py
pathvalidate/_interface.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass @add_metaclass(abc.ABCMeta) class NameSanitizer(object): @abc.abstractproperty...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import abc from ._common import validate_null_string from ._six import add_metaclass from .error import ValidationError @add_metaclass(abc.ABCMeta) class NameSanitizer...
Add is_valid method for file sanitizer classes
Add is_valid method for file sanitizer classes
Python
mit
thombashi/pathvalidate
--- +++ @@ -10,6 +10,7 @@ from ._common import validate_null_string from ._six import add_metaclass +from .error import ValidationError @add_metaclass(abc.ABCMeta) @@ -22,6 +23,14 @@ def validate(self, value): # pragma: no cover pass + def is_valid(self, value): + try: + ...
95d498009eca0a9e179a14eec05e7e3738a72bfb
twitter/stream_example.py
twitter/stream_example.py
""" Example program for the Stream API. This prints public status messages from the "sample" stream as fast as possible. USAGE twitter-stream-example <username> <password> """ from __future__ import print_function import sys from .stream import TwitterStream from .auth import UserPassAuth from .util import prin...
""" Example program for the Stream API. This prints public status messages from the "sample" stream as fast as possible. USAGE stream-example -t <token> -ts <token_secret> -ck <consumer_key> -cs <consumer_secret> """ from __future__ import print_function import argparse from twitter.stream import TwitterStream ...
Update to use OAuth, take in command line arguments and modify the imports to function from within the module.
Update to use OAuth, take in command line arguments and modify the imports to function from within the module.
Python
mit
Adai0808/twitter,tytek2012/twitter,adonoho/twitter,miragshin/twitter,hugovk/twitter,sixohsix/twitter,jessamynsmith/twitter
--- +++ @@ -4,25 +4,39 @@ USAGE - twitter-stream-example <username> <password> + stream-example -t <token> -ts <token_secret> -ck <consumer_key> -cs <consumer_secret> """ from __future__ import print_function -import sys +import argparse -from .stream import TwitterStream -from .auth import UserPassA...
70c98a42326471d3ed615def61954905673c5972
typhon/nonlte/__init__.py
typhon/nonlte/__init__.py
# -*- coding: utf-8 -*- from .version import __version__ try: __ATRASU_SETUP__ except: __ATRASU_SETUP__ = False if not __ATRASU_SETUP__: from . import spectra from . import setup_atmosphere from . import const from . import nonltecalc from . import mathmatics from . import rtc
# -*- coding: utf-8 -*- try: __ATRASU_SETUP__ except: __ATRASU_SETUP__ = False if not __ATRASU_SETUP__: from . import spectra from . import setup_atmosphere from . import const from . import nonltecalc from . import mathmatics from . import rtc
Remove import of removed version module.
Remove import of removed version module.
Python
mit
atmtools/typhon,atmtools/typhon
--- +++ @@ -1,7 +1,5 @@ # -*- coding: utf-8 -*- - -from .version import __version__ try: __ATRASU_SETUP__
9ccdbcc01d1bf6323256b8b8f19fa1446bb57d59
tests/unit/test_authenticate.py
tests/unit/test_authenticate.py
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, ...
"""Test the DigitalOcean backed ACME DNS Authentication Class.""" from acmednsauth.authenticate import Authenticate from mock import call def test_valid_data_calls_digital_ocean_record_creation( mocker, api_key, hostname, domain, fqdn, auth_token): create_environment = { 'DO_API_KEY': api_key, ...
Fix Bug in Test Assertion
Fix Bug in Test Assertion Need to train myself better on red-green-refactor. The previous assert always passed, because I wasn't triggering an actual Mock method. I had to change to verifying that the call is in the list of calls. I've verified that it fails when the call isn't made from the code under test and that i...
Python
apache-2.0
Jitsusama/lets-do-dns
--- +++ @@ -18,4 +18,4 @@ Authenticate(environment=create_environment) record.assert_called_once_with(api_key, domain, hostname) - record.has_calls([call().create(auth_token)]) + assert call().create(auth_token) in record.mock_calls
e1291e88e8d5cf1f50e9547fa78a4a53032cc89a
reproject/overlap.py
reproject/overlap.py
from ._overlap_wrapper import _computeOverlap def compute_overlap(ilon, ilat, olon, olat, energy_mode=True, reference_area=1.): """ Compute the overlap between two 'pixels' in spherical coordinates Parameters ---------- ilon : np.ndarray The longitudes defining the four corners of the ...
from ._overlap_wrapper import _computeOverlap def compute_overlap(ilon, ilat, olon, olat): """ Compute the overlap between two 'pixels' in spherical coordinates Parameters ---------- ilon : np.ndarray The longitudes defining the four corners of the input pixel ilat : np.ndarray ...
Remove options until we actually need and understand them
Remove options until we actually need and understand them
Python
bsd-3-clause
barentsen/reproject,astrofrog/reproject,barentsen/reproject,mwcraig/reproject,astrofrog/reproject,astrofrog/reproject,mwcraig/reproject,barentsen/reproject,bsipocz/reproject,bsipocz/reproject
--- +++ @@ -1,6 +1,6 @@ from ._overlap_wrapper import _computeOverlap -def compute_overlap(ilon, ilat, olon, olat, energy_mode=True, reference_area=1.): +def compute_overlap(ilon, ilat, olon, olat): """ Compute the overlap between two 'pixels' in spherical coordinates @@ -14,11 +14,7 @@ Th...
2c1673930a40fc94c3d7c7d4f764ea423b638d26
mccurse/cli.py
mccurse/cli.py
"""Package command line interface.""" import click from .curse import Game, Mod # Static data MINECRAFT = {'id': 432, 'name': 'Minecraft'} @click.group() def cli(): """Minecraft Curse CLI client.""" @cli.command() @click.option( '--refresh', is_flag=True, default=False, help='Force refreshing of sea...
"""Package command line interface.""" import click from .curse import Game, Mod # Static data MINECRAFT = {'id': 432, 'name': 'Minecraft'} @click.group() def cli(): """Minecraft Curse CLI client.""" @cli.command() @click.option( '--refresh', is_flag=True, default=False, help='Force refreshing of sea...
Raise error when there is no term to search for
Raise error when there is no term to search for
Python
agpl-3.0
khardix/mccurse
--- +++ @@ -23,6 +23,9 @@ def search(refresh, text): """Search for TEXT in mods on CurseForge.""" + if not text: + raise SystemExit('No text to search for!') + mc = Game(**MINECRAFT) text = ' '.join(text)
6bdcda14c8bd5b66bc6fcb4bb6a520e326211f74
poll/models.py
poll/models.py
from django.db import models class QuestionGroup(models.Model): heading = models.TextField() text = models.TextField(blank=True) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) class Question(models.Model): text = models.TextField() qu...
from django.db import models class QuestionGroup(models.Model): heading = models.TextField() text = models.TextField(blank=True) date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + ". " + self.he...
Implement __str__ for proper printing in admin
Implement __str__ for proper printing in admin
Python
mit
gabriel-v/psi,gabriel-v/psi,gabriel-v/psi
--- +++ @@ -7,6 +7,9 @@ date_added = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now_add=True) + def __str__(self): + return str(self.id) + ". " + self.heading + class Question(models.Model): text = models.TextField() @@ -14,12 +17,18 @@ date_added ...
0989089aa4e9766739359b57b2bd56e5b70fa53b
update_ip/ip_getters/__init__.py
update_ip/ip_getters/__init__.py
import base import getters ALL_CLASSES= base.BaseIpGetter.__subclasses__() ALL= [x() for x in ALL_CLASSES] def get_ip(): import random remaining= ALL[:] while remaining: getter= random.choice(remaining) try: return getter.get_ip() except base.GetIpFailed: re...
import base import getters import logging log= logging.getLogger('update_ip.ip_getters') ALL_CLASSES= base.BaseIpGetter.__subclasses__() ALL= [x() for x in ALL_CLASSES] def get_ip(): import random getters= ALL[:] random.shuffle( getters ) #for load balancing purposes for getter in getters: log...
Add basic logging to ip_getters
Add basic logging to ip_getters
Python
bsd-3-clause
bkonkle/update-ip
--- +++ @@ -1,16 +1,19 @@ import base import getters +import logging +log= logging.getLogger('update_ip.ip_getters') ALL_CLASSES= base.BaseIpGetter.__subclasses__() ALL= [x() for x in ALL_CLASSES] def get_ip(): import random - remaining= ALL[:] - while remaining: - getter= random.choice(rem...
35d5dc83d8abc4e33988ebf26a6fafadf9b815d4
fontGenerator/util.py
fontGenerator/util.py
import base64, os def get_content(texts): if isinstance(texts, str) or isinstance(texts, unicode): file_path = texts with open(file_path, 'r') as f: return list(f.read().decode("utf-8")) f.close() else: return texts def write_file( path, data ): with open( pa...
import base64, os def get_content(texts): if isinstance(texts, str) or isinstance(texts, unicode): file_path = texts with open(file_path, 'r') as f: return list(f.read().decode("utf-8")) f.close() else: return texts def write_file( path, data ): with open( pa...
Use `with` syntax to open file
Use `with` syntax to open file
Python
mit
eHanlin/font-generator,eHanlin/font-generator
--- +++ @@ -16,9 +16,9 @@ f.close() def read_by_base64(path): - f = open(path, "r") - data = f.read() - f.close() + with open(path, "r") as f: + data = f.read() + f.close() return base64.b64encode(data)
c43e6a69fa1391b5fd00a43628111f8d52ec8792
pct_vs_time.py
pct_vs_time.py
from deuces.deuces import Card, Deck from convenience import who_wins p1 = [Card.new('As'), Card.new('Ac')] p2 = [Card.new('Ad'), Card.new('Kd')] win_record = [] for i in range(100000): deck = Deck() b = [] while len(b) < 5: c = deck.draw() if c in p1 or c in p2: continue ...
from deuces.deuces import Card, Deck from convenience import who_wins, pr from copy import deepcopy p1 = [Card.new('As'), Card.new('Ac')] p2 = [Card.new('Ad'), Card.new('Kd')] def find_pcts(p1, p2, start_b = [], iter = 10000): win_record = [] for i in range(iter): deck = Deck() b = deepcopy(st...
Make find_pcts() function that can repetitively run.
Make find_pcts() function that can repetitively run.
Python
mit
zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments
--- +++ @@ -1,21 +1,25 @@ from deuces.deuces import Card, Deck -from convenience import who_wins +from convenience import who_wins, pr +from copy import deepcopy p1 = [Card.new('As'), Card.new('Ac')] p2 = [Card.new('Ad'), Card.new('Kd')] -win_record = [] -for i in range(100000): - deck = Deck() - b = [] ...
89a9d812f68fee1bda300be853cdf9536da6ba6b
pelicanconf.py
pelicanconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # AUTHOR = 'Glowstone Organization' SITENAME = 'Glowstone' SITEURL = '' PATH = 'content' TIMEZONE = 'UTC' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEE...
#!/usr/bin/env python # -*- coding: utf-8 -*- # AUTHOR = 'Glowstone Organization' SITENAME = 'Glowstone' SITEURL = '' PATH = 'content' PAGE_PATHS = [''] PAGE_URL = '{slug}/' PAGE_SAVE_AS = '{slug}/index.html' TIMEZONE = 'UTC' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_AT...
Move pages to root URL
Move pages to root URL Fixes #1
Python
artistic-2.0
GlowstoneMC/glowstonemc.github.io,GlowstoneMC/glowstonemc.github.io,GlowstoneMC/glowstonemc.github.io
--- +++ @@ -6,6 +6,10 @@ SITEURL = '' PATH = 'content' + +PAGE_PATHS = [''] +PAGE_URL = '{slug}/' +PAGE_SAVE_AS = '{slug}/index.html' TIMEZONE = 'UTC'
0292bf82de87483ec0391ecd580e93f42bf6a95b
more/jinja2/main.py
more/jinja2/main.py
import os import morepath import jinja2 class Jinja2App(morepath.App): pass @Jinja2App.setting_section(section='jinja2') def get_setting_section(): return { 'auto_reload': False, 'autoescape': True, 'extensions': ['jinja2.ext.autoescape'] } @Jinja2App.template_engine(extension=...
import os import morepath import jinja2 class Jinja2App(morepath.App): pass @Jinja2App.setting_section(section='jinja2') def get_setting_section(): return { 'auto_reload': False, 'autoescape': True, 'extensions': ['jinja2.ext.autoescape'] } @Jinja2App.template_engine(extension=...
Add another note about caching.
Add another note about caching.
Python
bsd-3-clause
morepath/more.jinja2
--- +++ @@ -21,6 +21,8 @@ config = settings.jinja2.__dict__ # XXX creates a new environment and loader each time, # which could slow startup somewhat + # XXX and probably breaks caching if you have one template inherit + # from another dirpath, filename = os.path.split(path) environment...
82b517426804e9e6984317f4b3aa5bbda5e3dc5e
tests/qctests/test_density_inversion.py
tests/qctests/test_density_inversion.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Check density inversion QC test """ from numpy import ma from cotede.qctests import density_inversion def test(): dummy_data = { 'PRES': ma.masked_array([0.0, 100, 5000]), 'TEMP': ma.masked_array([25.18, 19.73, 2.13]), 'PSAL': ma.masked_...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Check density inversion QC test """ from numpy import ma from cotede.qctests import density_inversion def test(): try: import gsw except: print('GSW package not available. Can\'t run density_inversion test.') return dummy_data =...
Exit density inversion test if gsw is not available.
Exit density inversion test if gsw is not available.
Python
bsd-3-clause
castelao/CoTeDe
--- +++ @@ -10,6 +10,12 @@ def test(): + try: + import gsw + except: + print('GSW package not available. Can\'t run density_inversion test.') + return + dummy_data = { 'PRES': ma.masked_array([0.0, 100, 5000]), 'TEMP': ma.masked_array([25.18, 19.73, 2.13]),
053239698dcb0842a8c8fcc019092c65b7f436e7
spec_cleaner/rpmbuild.py
spec_cleaner/rpmbuild.py
# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmBuild(Section): """ Replace various troublemakers in build phase """ def add(self, line): line = self._complete_cleanup(line) # smp_mflags for jobs if not self.reg.re_comment.match(line): ...
# vim: set ts=4 sw=4 et: coding=UTF-8 from rpmsection import Section class RpmBuild(Section): """ Replace various troublemakers in build phase """ def add(self, line): line = self._complete_cleanup(line) # smp_mflags for jobs if not self.reg.re_comment.match(line): ...
Fix parsing make with || on line.
Fix parsing make with || on line.
Python
bsd-3-clause
pombredanne/spec-cleaner,pombredanne/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner
--- +++ @@ -23,7 +23,7 @@ if line.find('%{?_smp_mflags}') == -1 and line.find('-j') == -1: # Don't append %_smp_mflags if the line ends with a backslash, # it would break the formatting - if not line.endswith('\\'): + if not line.endswith('\...
a6491e62201e070665020e8e123d1cd65fc2cca6
Examples/THINGS/submit_all_THINGS.py
Examples/THINGS/submit_all_THINGS.py
import os ''' Submits a job for every sample defined in the info dict ''' script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load in the info dict for the names execfile(os.path.join(script_path, "info_THINGS.py")) datapath = "/lust...
import os from datetime import datetime ''' Submits a job for every sample defined in the info dict ''' def timestring(): return datetime.now().strftime("%Y%m%d%H%M%S%f") script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" submit_file = os.path.join(script_path, "submit_THINGS.pbs") # Load ...
Write the error and output files with the galaxy name and in the right folder
Write the error and output files with the galaxy name and in the right folder
Python
mit
e-koch/BaSiCs
--- +++ @@ -1,9 +1,14 @@ import os +from datetime import datetime ''' Submits a job for every sample defined in the info dict ''' + + +def timestring(): + return datetime.now().strftime("%Y%m%d%H%M%S%f") script_path = "/lustre/home/ekoch/code_repos/BaSiCs/Examples/THINGS/" @@ -16,5 +21,13 @@ for na...
ad68b5f75bc58f467ba92be6b8835bad60bcbcd5
common/http.py
common/http.py
# -*- coding: utf-8 -*- from django.template import RequestContext, loader from django.conf import settings from django.core.exceptions import PermissionDenied from django.http import HttpResponseForbidden # A custom Http403 exception # from http://theglenbot.com/creating-a-custom-http403-exception-in-django/ clas...
# -*- coding: utf-8 -*- from django.template import RequestContext, loader from django.conf import settings from django.core.exceptions import PermissionDenied from django.http import HttpResponseForbidden # A custom Http403 exception # from http://theglenbot.com/creating-a-custom-http403-exception-in-django/ clas...
Update mimetype to content_type here, too.
common: Update mimetype to content_type here, too.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
--- +++ @@ -16,7 +16,7 @@ args = [] args.append('403.html') - httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)} + httpresponse_kwargs = {'content_type': kwargs.pop('content_type', None)} response = HttpResponseForbidden(loader.re...
8db9ab08725ebbdb3a9b5a70b1f8071433b01a04
data/models.py
data/models.py
""" The data models """ class Repository(object): def __init__(self, base_url, identifier): self.base_url = base_url self.identifier = identifier class GitObject(object): def __init__(self, sha1): self.sha1 = sha1 class Blog(Object): @property def commits(self): pass ...
""" The data models """ class Repository(object): def __init__(self, base_url, identifier): self.base_url = base_url self.identifier = identifier class GitObject(object): def __init__(self, sha1): self.sha1 = sha1 class Blog(GitObject): @property def commits(self): pas...
Replace Object everywhere, not just the class definition.
Replace Object everywhere, not just the class definition.
Python
mit
ebroder/anygit,ebroder/anygit
--- +++ @@ -11,17 +11,17 @@ def __init__(self, sha1): self.sha1 = sha1 -class Blog(Object): +class Blog(GitObject): @property def commits(self): pass -class Tree(Object): +class Tree(GitObject): @property def commits(self): pass -class Commit(Object): +class C...
443cc0114d7669471e39661c97e2bad91c8eabb8
tests/basics/set_difference.py
tests/basics/set_difference.py
l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.differen...
l = [1, 2, 3, 4] s = set(l) outs = [s.difference(), s.difference({1}), s.difference({1}, [1, 2]), s.difference({1}, {1, 2}, {2, 3})] for out in outs: print(sorted(out)) s = set(l) print(s.difference_update()) print(sorted(s)) print(s.difference_update({1})) print(sorted(s)) print(s.differen...
Add test for set.difference_update with arg being itself.
tests/basics: Add test for set.difference_update with arg being itself.
Python
mit
blazewicz/micropython,tobbad/micropython,tuc-osg/micropython,henriknelson/micropython,SHA2017-badge/micropython-esp32,cwyark/micropython,ryannathans/micropython,Timmenem/micropython,alex-robbins/micropython,PappaPeppar/micropython,dxxb/micropython,Peetz0r/micropython-esp32,jmarcelino/pycom-micropython,hiway/micropython...
--- +++ @@ -14,3 +14,6 @@ print(sorted(s)) print(s.difference_update({1}, [2])) print(sorted(s)) + +s.difference_update(s) +print(s)
9a4afbab2aded6e6e0ad1088f8cc2d92cfd7684a
26-lazy-rivers/tf-26.py
26-lazy-rivers/tf-26.py
#!/usr/bin/env python import sys, operator, string def characters(filename): for line in open(filename): for c in line: yield c def all_words(filename): start_char = True for c in characters(filename): if start_char == True: word = "" if c.isalnum(): ...
#!/usr/bin/env python import sys, operator, string def characters(filename): for line in open(filename): for c in line: yield c def all_words(filename): start_char = True for c in characters(filename): if start_char == True: word = "" if c.isalnum(): ...
Make the last function also a generator, so that the explanation flows better
Make the last function also a generator, so that the explanation flows better
Python
mit
alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style,alex-quiterio/exercises-in-programming-style
--- +++ @@ -31,15 +31,18 @@ yield w def count_and_sort(filename): - freqs = {} + freqs, i = {}, 1 for w in non_stop_words(filename): freqs[w] = 1 if w not in freqs else freqs[w]+1 - return sorted(freqs.iteritems(), key=operator.itemgetter(1), reverse=True) - + if i % 5000...
6c2354a1e56477eb983b0adbcc2d15223c158184
foodsaving/subscriptions/consumers.py
foodsaving/subscriptions/consumers.py
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = m...
from channels.auth import channel_session_user_from_http, channel_session_user from django.utils import timezone from foodsaving.subscriptions.models import ChannelSubscription @channel_session_user_from_http def ws_connect(message): """The user has connected! Register their channel subscription.""" user = m...
Remove redundant ws accept replies
Remove redundant ws accept replies It's only relevent on connection
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
--- +++ @@ -20,7 +20,6 @@ if not user.is_anonymous(): reply_channel = message.reply_channel.name ChannelSubscription.objects.filter(user=user, reply_channel=reply_channel).update(lastseen_at=timezone.now()) - message.reply_channel.send({"accept": True}) @channel_session_user @@ -29,4 +2...
9f76a0a673b83b2de6a5f8a37b0628796da4a88c
tests/hello/hello/__init__.py
tests/hello/hello/__init__.py
import pkg_resources version = pkg_resources.require(__name__)[0].version def greet(name='World'): print "Hi, %s! -- from version %s of %s" % (name, version, __name__)
import pkg_resources try: version = pkg_resources.require(__name__)[0].version except: version = 'unknown' def greet(name='World'): print "Hi, %s! -- from version %s of %s" % (name, version, __name__)
Allow 'hello' test package to be used unpackaged
Allow 'hello' test package to be used unpackaged
Python
apache-2.0
comoyo/python-transmute
--- +++ @@ -1,6 +1,7 @@ import pkg_resources -version = pkg_resources.require(__name__)[0].version +try: version = pkg_resources.require(__name__)[0].version +except: version = 'unknown' def greet(name='World'): print "Hi, %s! -- from version %s of %s" % (name, version, __name__)
8d5ac7efd98426394040fb01f0096f35a804b1b7
tests/plugins/test_generic.py
tests/plugins/test_generic.py
import pytest from detectem.core import MATCHERS from detectem.plugin import load_plugins, GenericPlugin from .utils import create_har_entry class TestGenericPlugin(object): @pytest.fixture def plugins(self): return load_plugins() def test_generic_plugin(self): class MyGenericPlugin(Gene...
import pytest from detectem.core import MATCHERS from detectem.plugin import load_plugins, GenericPlugin from tests import create_pm from .utils import create_har_entry class TestGenericPlugin: @pytest.fixture def plugins(self): return load_plugins() def test_generic_plugin(self): class ...
Fix test for generic plugins
Fix test for generic plugins
Python
mit
spectresearch/detectem
--- +++ @@ -2,10 +2,11 @@ from detectem.core import MATCHERS from detectem.plugin import load_plugins, GenericPlugin +from tests import create_pm from .utils import create_har_entry -class TestGenericPlugin(object): +class TestGenericPlugin: @pytest.fixture def plugins(self): return load_p...
a33ccab017bd6dfab03e12242c7e1306b47b2bed
seed_stage_based_messaging/testsettings.py
seed_stage_based_messaging/testsettings.py
from seed_stage_based_messaging.settings import * # flake8: noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'TESTSEKRET' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True CELERY_ALWAYS_...
from seed_stage_based_messaging.settings import * # flake8: noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'TESTSEKRET' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True CELERY_ALWAYS_...
Change password hasher for tests for faster tests
Change password hasher for tests for faster tests
Python
bsd-3-clause
praekelt/seed-stage-based-messaging,praekelt/seed-stage-based-messaging,praekelt/seed-staged-based-messaging
--- +++ @@ -24,3 +24,5 @@ METRICS_URL = "http://metrics-url" METRICS_AUTH_TOKEN = "REPLACEME" + +PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
ade69178edac1d4d73dedee0ad933d4106e22c82
knox/crypto.py
knox/crypto.py
import binascii from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from OpenSSL.rand import bytes as generate_bytes from knox.settings import knox_settings, CONSTANTS sha = knox_settings.SECURE_HASH_ALGORITHM def create_token_string(): return binascii.hex...
import binascii from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from os import urandom as generate_bytes from knox.settings import knox_settings, CONSTANTS sha = knox_settings.SECURE_HASH_ALGORITHM def create_token_string(): return binascii.hexlify( ...
Use os.urandom instead of OpenSSL.rand.bytes
Use os.urandom instead of OpenSSL.rand.bytes Follows suggestion in pyOpenSSL changelog https://github.com/pyca/pyopenssl/blob/1eac0e8f9b3829c5401151fabb3f78453ad772a4/CHANGELOG.rst#backward-incompatible-changes-1
Python
mit
James1345/django-rest-knox,James1345/django-rest-knox
--- +++ @@ -2,7 +2,7 @@ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes -from OpenSSL.rand import bytes as generate_bytes +from os import urandom as generate_bytes from knox.settings import knox_settings, CONSTANTS
d0ca3952a34a74f0167b76bbedfa3cf8875a399c
var/spack/repos/builtin/packages/py-scikit-learn/package.py
var/spack/repos/builtin/packages/py-scikit-learn/package.py
from spack import * class PyScikitLearn(Package): """""" homepage = "https://pypi.python.org/pypi/scikit-learn" url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz" version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b617...
from spack import * class PyScikitLearn(Package): """""" homepage = "https://pypi.python.org/pypi/scikit-learn" url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz" version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b617...
Add version 0.17.1 of scikit-learn.
Add version 0.17.1 of scikit-learn.
Python
lgpl-2.1
matthiasdiener/spack,mfherbst/spack,EmreAtes/spack,TheTimmy/spack,iulian787/spack,iulian787/spack,iulian787/spack,mfherbst/spack,tmerrick1/spack,mfherbst/spack,LLNL/spack,LLNL/spack,tmerrick1/spack,skosukhin/spack,TheTimmy/spack,skosukhin/spack,TheTimmy/spack,skosukhin/spack,matthiasdiener/spack,mfherbst/spack,mfherbst...
--- +++ @@ -7,6 +7,7 @@ version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') + version('0.17.1', 'a2f8b877e6d99b1ed737144f5a478dfc') extends('python')
1d017e9e07e48a8a1960de4c16fd49b4b40abbc2
ldap-helper.py
ldap-helper.py
# Handles queries to the LDAP backend # Reads the LDAP server configuration from a JSON file import json import ldap first_connect = True # The default config filename config_file = 'config.json' def load_config(): with open(config_file, 'r') as f: config = json.load(f) ldap_server = config['ldap_ser...
# Handles queries to the LDAP backend # Reads the LDAP server configuration from a JSON file import json import ldap first_connect = True # The default config filename config_file = 'config.json' def load_config(): with open(config_file, 'r') as f: config = json.load(f) ldap_server = config['ldap_ser...
Add LDAP version to depend on config instead
Add LDAP version to depend on config instead
Python
mit
motorolja/ldap-updater
--- +++ @@ -22,7 +22,7 @@ first_connect = False l = ldap.initialize('ldap://' + ldap_server) try: - l.protocol_version = ldap.VERSION3 # parse this from config instead + l.protocol_version = ldap_version l.simple_bind_s(ldap_user, ldap_password) valid = True exc...
2a241bd07a4abd66656e3fb505310798f398db7f
respawn/cli.py
respawn/cli.py
""" CLI Entry point for respawn """ from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> respawn --...
""" CLI Entry point for respawn """ from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn import os def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> ...
Remove test print and use better practice to get path of gen.py
Remove test print and use better practice to get path of gen.py
Python
isc
dowjones/respawn,dowjones/respawn
--- +++ @@ -7,6 +7,7 @@ from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn +import os def generate(): @@ -32,11 +33,13 @@ }) args = scheme.validate(args) - gen_location = "/".join(respawn.__file__.split("/")[:-1]) + "/gen.py" - print gen_lo...
6795e8f5c97ba2f10d05725faf4999cfba785fdd
molecule/default/tests/test_default.py
molecule/default/tests/test_default.py
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host)...
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_service_elasticsearch_running(host): assert host.service("elasticsearch").is_running is True def test_service_mongodb_running(host): ...
Fix test in Ubuntu 20.04.
Fix test in Ubuntu 20.04.
Python
apache-2.0
Graylog2/graylog-ansible-role
--- +++ @@ -2,14 +2,18 @@ import testinfra.utils.ansible_runner -testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( - os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') +testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') ...
4d406f3e0caf19c8cc935e4ebec4d2df3e41df19
l10n_ch_payment_slip/__manifest__.py
l10n_ch_payment_slip/__manifest__.py
# -*- coding: utf-8 -*- # © 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - Payment Slip (BVR/ESR)', 'summary': 'Print ESR/BVR payment slip with your invoices', 'version': '10.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category...
# -*- coding: utf-8 -*- # © 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - Payment Slip (BVR/ESR)', 'summary': 'Print ESR/BVR payment slip with your invoices', 'version': '11.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category...
Change l10n_ch_payment_slip version to v 11.0
Change l10n_ch_payment_slip version to v 11.0
Python
agpl-3.0
brain-tec/l10n-switzerland,brain-tec/l10n-switzerland,brain-tec/l10n-switzerland
--- +++ @@ -3,7 +3,7 @@ # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - Payment Slip (BVR/ESR)', 'summary': 'Print ESR/BVR payment slip with your invoices', - 'version': '10.0.1.1.1', + 'version': '11.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'c...
c830d67e6b640791e1a8d9117c75ca146ea5d6c8
spyral/core.py
spyral/core.py
import spyral import pygame def init(): spyral.event.init() pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = []
import spyral import pygame _inited = False def init(): global _inited if _inited: return _inited = True spyral.event.init() pygame.init() pygame.font.init() def quit(): pygame.quit() spyral.director._stack = []
Remove poor way of doing default styles
Remove poor way of doing default styles Signed-off-by: Robert Deaton <eb00a885478926d5d594195591fb94a03acb1062@udel.edu>
Python
lgpl-2.1
platipy/spyral
--- +++ @@ -1,12 +1,17 @@ import spyral import pygame +_inited = False + def init(): + global _inited + if _inited: + return + _inited = True spyral.event.init() pygame.init() pygame.font.init() - def quit(): pygame.quit() spyral.director._stack = []
6bfe3ee375847d9a71181d618732d747614aede4
electro/api.py
electro/api.py
# -*- coding: utf-8 -*- from electro.errors import ResourceDuplicatedDefinedError class API(object): def __init__(self, app=None, decorators=None, catch_all_404s=None): self.app = app self.endpoints = set() self.decorators = decorators or [] self.catch_all_404s = catch...
# -*- coding: utf-8 -*- from electro.errors import ResourceDuplicatedDefinedError class API(object): def __init__(self, app=None, decorators=None, catch_all_404s=None): self.app = app self.endpoints = set() self.decorators = decorators or [] self.catch_all_404s = catch...
Raise with endpoint when duplicated.
Raise with endpoint when duplicated.
Python
mit
soasme/electro
--- +++ @@ -18,7 +18,7 @@ if endpoint in self.app.view_functions: previous_view_class = self.app.view_functions[endpoint].__dict__['view_class'] if previous_view_class != resource: - raise ResourceDuplicatedDefinedError, "already set" + raise ResourceDu...
9938f0b70e4714fb6e74deb14a751368edd5d48f
pyhn/__init__.py
pyhn/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __title__ = 'pyhn' __version__ = '0.2.7' __author__ = 'Geoffrey Lehée' __license__ = 'AGPL3' __copyright__ = 'Copyright 2014 Geoffrey Lehée'
#!/usr/bin/env python # -*- coding: utf-8 -*- __title__ = 'pyhn' __version__ = '0.2.8' __author__ = 'Geoffrey Lehée' __license__ = 'MIT' __copyright__ = 'Copyright 2015 Geoffrey Lehée'
Update license and bump to 0.2.8
Update license and bump to 0.2.8
Python
mit
toxinu/pyhn,socketubs/pyhn
--- +++ @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- __title__ = 'pyhn' -__version__ = '0.2.7' +__version__ = '0.2.8' __author__ = 'Geoffrey Lehée' -__license__ = 'AGPL3' -__copyright__ = 'Copyright 2014 Geoffrey Lehée' +__license__ = 'MIT' +__copyright__ = 'Copyright 2015 Geoffrey Lehée'
91853432d2e57bd7c01403c943fff4c2dad1cf5a
openquake/__init__.py
openquake/__init__.py
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2010-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
Make the openquake namespace compatible with old setuptools
Make the openquake namespace compatible with old setuptools Former-commit-id: b1323f4831645a19d5e927fc342abe4b319a76bb [formerly 529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc] [formerly 529c98ec0a7c5a3fefa4da6cdf2f6a58b5487ebc [formerly e5f4dc01e94694bf9bfcae3ecd6eca34a33a24eb]] Former-commit-id: e01df405c03f37a89cdf889c4...
Python
agpl-3.0
gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine,gem/oq-engine
--- +++ @@ -16,4 +16,9 @@ # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. -__import__('pkg_resources').declare_namespace(__name__) +# Make the namespace compatible with old setuptools, like the one +# provided by QGIS 2...
4443f6d2493ce6ff9d49cf4049c6a89d2a61eddf
cmt/printers/nc/tests/test_ugrid_read.py
cmt/printers/nc/tests/test_ugrid_read.py
import unittest import os from cmt.printers.nc.read import field_fromfile class DataTestFileMixIn(object): def data_file(self, name): return os.path.join(self.data_dir(), name) def data_dir(self): return os.path.join(os.path.dirname(__file__), 'data') class TestNetcdfRead(unittest.TestCase...
import unittest import os import urllib2 from cmt.printers.nc.read import field_fromfile def fetch_data_file(filename): url = ('http://csdms.colorado.edu/thredds/fileServer/benchmark/ugrid/' + filename) remote_file = urllib2.urlopen(url) with open(filename, 'w') as netcdf_file: netcdf_...
Read test data files from a remote URL.
Read test data files from a remote URL. Changed ------- * Instead of reading test netcdf files from a data directory in the repository, fetch them from a URL.
Python
mit
csdms/coupling,csdms/coupling,csdms/pymt
--- +++ @@ -1,7 +1,18 @@ import unittest import os +import urllib2 from cmt.printers.nc.read import field_fromfile + + +def fetch_data_file(filename): + url = ('http://csdms.colorado.edu/thredds/fileServer/benchmark/ugrid/' + + filename) + remote_file = urllib2.urlopen(url) + with open(filenam...
62d3f84155291bf020870b618cf139d8333a04cd
example-flask-python3.6-index/app/main.py
example-flask-python3.6-index/app/main.py
import os from flask import Flask, send_file app = Flask(__name__) @app.route("/hello") def hello(): return "Hello World from Flask in a uWSGI Nginx Docker container with \ Python 3.6 (from the example template)" @app.route("/") def main(): return send_file('./static/index.html') # Everything not de...
import os from flask import Flask, send_file app = Flask(__name__) @app.route("/hello") def hello(): return "Hello World from Flask in a uWSGI Nginx Docker container with \ Python 3.6 (from the example template)" @app.route("/") def main(): index_path = os.path.join(app.static_folder, 'index.html') ...
Update view function to keep working even when moved to a package project structure
Update view function to keep working even when moved to a package project structure
Python
apache-2.0
tiangolo/uwsgi-nginx-flask-docker,tiangolo/uwsgi-nginx-flask-docker,tiangolo/uwsgi-nginx-flask-docker
--- +++ @@ -12,7 +12,8 @@ @app.route("/") def main(): - return send_file('./static/index.html') + index_path = os.path.join(app.static_folder, 'index.html') + return send_file(index_path) # Everything not declared before (not a Flask route / API endpoint)... @@ -20,12 +21,13 @@ def route_frontend(p...
06e96684b589def7b7adce122005ffebbf0ed7f3
python/tests/test_ambassador.py
python/tests/test_ambassador.py
from kat.harness import Runner from abstract_tests import AmbassadorTest # Import all the real tests from other files, to make it easier to pick and choose during development. import t_basics import t_cors import t_extauth import t_grpc import t_grpc_bridge import t_grpc_web import t_gzip import t_headerrouting impo...
from kat.harness import Runner from abstract_tests import AmbassadorTest # Import all the real tests from other files, to make it easier to pick and choose during development. import t_basics import t_cors import t_extauth import t_grpc import t_grpc_bridge import t_grpc_web import t_gzip import t_headerrouting impo...
Comment out t_shadow, t_stats, and t_circuitbreaker, at Flynn's behest
Comment out t_shadow, t_stats, and t_circuitbreaker, at Flynn's behest
Python
apache-2.0
datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador,datawire/ambassador
--- +++ @@ -19,14 +19,14 @@ import t_plain import t_ratelimit import t_redirect -import t_shadow -import t_stats +#import t_shadow +#import t_stats import t_tcpmapping import t_tls import t_tracing import t_retrypolicy import t_consul -import t_circuitbreaker +#import t_circuitbreaker import t_knative impor...
70458f45f3419927271f51872252834f08ef13f2
workshopvenues/venues/tests.py
workshopvenues/venues/tests.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 a...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase from .models import Address class ModelsTest(TestCase): def test_create_address(self): a ...
Add Address model creation test case
Add Address model creation test case
Python
bsd-3-clause
andreagrandi/workshopvenues
--- +++ @@ -6,11 +6,15 @@ """ from django.test import TestCase +from .models import Address -class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.assertEqual(1 + 1, 2) +class ModelsTest(TestCase): + def test_creat...
f267b56b46a824fa5b519a22b3026d2b3c6ee106
source/hostel_huptainer/system.py
source/hostel_huptainer/system.py
"""Write data out to console.""" from __future__ import print_function import sys def abnormal_exit(): """Exits program under abnormal conditions.""" sys.exit(1) def error_message(message): """Write message to STDERR, when message is valid.""" if message: print('{}'.format(message), file=sy...
"""Write data out to console.""" from __future__ import print_function import sys def abnormal_exit(): """Exit program under abnormal conditions.""" sys.exit(1) def error_message(message): """Write message to STDERR, when message is valid.""" if message: print('{}'.format(message), file=sys...
Make abnormal_exit docstring be in the imperative mood - pydocstyle
Make abnormal_exit docstring be in the imperative mood - pydocstyle
Python
apache-2.0
Jitsusama/hostel-huptainer
--- +++ @@ -5,7 +5,7 @@ def abnormal_exit(): - """Exits program under abnormal conditions.""" + """Exit program under abnormal conditions.""" sys.exit(1)
8dc6e5632ecbab6143e25f403022ae068fbb24a2
backend/unpp_api/settings/staging.py
backend/unpp_api/settings/staging.py
from __future__ import absolute_import from .base import * # noqa: ignore=F403 # dev overrides DEBUG = False IS_STAGING = True MEDIA_ROOT = os.path.join(BASE_DIR, '%s' % UPLOADS_DIR_NAME) STATIC_ROOT = '%s/staticserve' % BASE_DIR COMPRESS_ENABLED = True COMPRESS_OFFLINE = True
from __future__ import absolute_import from .base import * # noqa: ignore=F403 # dev overrides DEBUG = False IS_STAGING = True
Revert "trying to fix statics issue" - id didnt work
Revert "trying to fix statics issue" - id didnt work This reverts commit c1a0d920491358716315a8c6aeaa6ec475b37709.
Python
apache-2.0
unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal,unicef/un-partner-portal
--- +++ @@ -5,9 +5,3 @@ # dev overrides DEBUG = False IS_STAGING = True - -MEDIA_ROOT = os.path.join(BASE_DIR, '%s' % UPLOADS_DIR_NAME) -STATIC_ROOT = '%s/staticserve' % BASE_DIR - -COMPRESS_ENABLED = True -COMPRESS_OFFLINE = True
0d2525de51edd99b821f32b3bfd962f3d673a6e1
Instanssi/admin_store/forms.py
Instanssi/admin_store/forms.py
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreItemForm, s...
# -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StoreItemForm, se...
Remove deprecated fields from form
admin_store: Remove deprecated fields from form
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
--- +++ @@ -4,7 +4,6 @@ from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.store.models import StoreItem - class StoreItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): @@ -21,7 +20,6 @@ 'max', ...
00fc915c09e0052289fa28d7da174e44f838c15b
quickstart/python/voice/example-1-make-call/outgoing_call.6.x.py
quickstart/python/voice/example-1-make-call/outgoing_call.6.x.py
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token can be found at https://www.twilio.com/console account_sid = "AC6062f793ce5918fef56b1681e6446e87" auth_token = "your_auth_token" client = Client(account_sid, auth_token) call = cli...
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token can be found at https://www.twilio.com/console account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) call = cli...
Use placeholder for account sid :facepalm:
Use placeholder for account sid :facepalm:
Python
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
--- +++ @@ -2,7 +2,7 @@ from twilio.rest import Client # Your Account Sid and Auth Token can be found at https://www.twilio.com/console -account_sid = "AC6062f793ce5918fef56b1681e6446e87" +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) ...
2307942c6e29ae24d6d4fdc42a646e4f6843fca8
echo_client.py
echo_client.py
import socket import sys def client(msg): client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect(('127.0.0.1', 50000)) # sends command line message to server, closes socket to writing client_socket.sendall(msg) client_so...
import socket import sys def client(msg): client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect(('127.0.0.1', 50000)) buffer = 16 # sends command line message to server, closes socket to writing client_socket.sendall(ms...
Update client to receive packets larger than buffer
Update client to receive packets larger than buffer
Python
mit
jwarren116/network-tools,jwarren116/network-tools
--- +++ @@ -8,13 +8,16 @@ socket.SOCK_STREAM, socket.IPPROTO_IP) client_socket.connect(('127.0.0.1', 50000)) + buffer = 16 # sends command line message to server, closes socket to writing client_socket.sendall(msg) client_socket.shutdown(socket.SHUT_WR) - # receives and...
ce963503cea617cb552739b49caeba450e5fb55e
backslash/api_object.py
backslash/api_object.py
class APIObject(object): def __init__(self, client, json_data): super(APIObject, self).__init__() self.client = client self._data = json_data def __eq__(self, other): if not isinstance(other, APIObject): return NotImplemented return self.client is other.cli...
class APIObject(object): def __init__(self, client, json_data): super(APIObject, self).__init__() self.client = client self._data = json_data def __eq__(self, other): if not isinstance(other, APIObject): return NotImplemented return self.client is other.cli...
Add without_fields method to API objects
Add without_fields method to API objects Helps with unit-testing Backslash - allowing more percise comparisons
Python
bsd-3-clause
slash-testing/backslash-python,vmalloc/backslash-python
--- +++ @@ -31,3 +31,9 @@ def __repr__(self): return '<API:{data[type]}:{data[id]}>'.format(data=self._data) + + def without_fields(self, field_names): + new_data = dict((field_name, field_value) + for field_name, field_value in self._data.items() + ...
7bc736b9a31d532930e9824842f7adb84436a7b8
django_filters/rest_framework/filters.py
django_filters/rest_framework/filters.py
from ..filters import * from ..widgets import BooleanWidget class BooleanFilter(BooleanFilter): def __init__(self, *args, **kwargs): kwargs.setdefault('widget', BooleanWidget) super().__init__(*args, **kwargs)
from ..filters import BooleanFilter as _BooleanFilter from ..filters import * from ..widgets import BooleanWidget class BooleanFilter(_BooleanFilter): def __init__(self, *args, **kwargs): kwargs.setdefault('widget', BooleanWidget) super().__init__(*args, **kwargs)
Fix mypy error: circular inheritance
Fix mypy error: circular inheritance Closes #832, #833
Python
bsd-3-clause
alex/django-filter,alex/django-filter
--- +++ @@ -1,9 +1,10 @@ +from ..filters import BooleanFilter as _BooleanFilter from ..filters import * from ..widgets import BooleanWidget -class BooleanFilter(BooleanFilter): +class BooleanFilter(_BooleanFilter): def __init__(self, *args, **kwargs): kwargs.setdefault('widget', BooleanWidget)
8d789a822a34f59d79f0e1129ab7ce5fa945a746
OctaHomeAppInterface/models.py
OctaHomeAppInterface/models.py
from django.contrib.auth.models import * from django.contrib.auth.backends import ModelBackend from django.utils.translation import ugettext_lazy as _ from OctaHomeCore.basemodels import * from OctaHomeCore.authmodels import * import string import random import hashlib import time from authy.api import AuthyApiClient...
from django.contrib.auth.models import * from django.contrib.auth.backends import ModelBackend from django.utils.translation import ugettext_lazy as _ from OctaHomeCore.basemodels import * from OctaHomeCore.authmodels import * import datetime import string import random import hashlib import time from authy.api impor...
Update to make sure the auth date is on utc for time zone support on devices
Update to make sure the auth date is on utc for time zone support on devices
Python
mit
Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation
--- +++ @@ -4,6 +4,7 @@ from OctaHomeCore.basemodels import * from OctaHomeCore.authmodels import * +import datetime import string import random import hashlib @@ -24,7 +25,7 @@ return {"host":host, "user":self.id, "password":self.Secret } def checkToken(self, token): - salt = time.strftime("%H:%M-%d/...
6e4daa3745cf51443550d559493a0cf8c2dbd8f1
grid_map_demos/scripts/image_publisher.py
grid_map_demos/scripts/image_publisher.py
#!/usr/bin/env python # simple script to publish a image from a file. import rospy import cv2 import sensor_msgs.msg #change these to fit the expected topic names IMAGE_MESSAGE_TOPIC = 'grid_map_image' IMAGE_PATH = 'test2.png' def callback(self): """ Convert a image to a ROS compatible message (sensor_msg...
#!/usr/bin/env python # simple script to publish a image from a file. import rospy import cv2 import sensor_msgs.msg #change these to fit the expected topic names IMAGE_MESSAGE_TOPIC = 'grid_map_image' IMAGE_PATH = 'test2.png' def callback(self): """ Convert a image to a ROS compatible message (sensor_msg...
Read gray scale image with alpha channel
Read gray scale image with alpha channel
Python
bsd-3-clause
uzh-rpg/grid_map,chen0510566/grid_map,ANYbotics/grid_map,ysonggit/grid_map,ANYbotics/grid_map,ysonggit/grid_map,ethz-asl/grid_map,ethz-asl/grid_map,uzh-rpg/grid_map,chen0510566/grid_map
--- +++ @@ -12,8 +12,8 @@ """ Convert a image to a ROS compatible message (sensor_msgs.Image). """ - img = cv2.imread(IMAGE_PATH) - + img = cv2.imread(IMAGE_PATH, -1) + rosimage = sensor_msgs.msg.Image() rosimage.encoding = 'mono16' rosimage.width = img.shape[1] @@ -21,7 +21,7...
3c87312aa5605e2705257052d38a4c8fae705da3
rnacentral/sequence_search/settings.py
rnacentral/sequence_search/settings.py
""" Copyright [2009-2019] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
""" Copyright [2009-2019] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
Use search.rnacentral.org as the sequence search endpoint
Use search.rnacentral.org as the sequence search endpoint
Python
apache-2.0
RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode
--- +++ @@ -12,10 +12,10 @@ """ # SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy -SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy +# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy # SEQUENCE_SEA...
a8070975c31aef61d722de93b7104b09f853e02d
robotars/templatetags/robotars_tags.py
robotars/templatetags/robotars_tags.py
# http://robohash.org/ from django import template from md5 import md5 register = template.Library() @register.inclusion_tag("robotars/robotar.html") def robotar(user, size=None, gravatar_fallback=False, hashed=False): url = "http://robohash.org/" if gravatar_fallback: if hashed: url +=...
# http://robohash.org/ from django import template from md5 import md5 register = template.Library() @register.inclusion_tag("robotars/robotar.html") def robotar(user, size=None, gravatar_fallback=False, hashed=False): url = "//robohash.org/" if gravatar_fallback: if hashed: url += "%s?...
Use agnostic protocol urls to support both http/https.
Use agnostic protocol urls to support both http/https.
Python
bsd-3-clause
eldarion/robotars
--- +++ @@ -9,7 +9,7 @@ @register.inclusion_tag("robotars/robotar.html") def robotar(user, size=None, gravatar_fallback=False, hashed=False): - url = "http://robohash.org/" + url = "//robohash.org/" if gravatar_fallback: if hashed: url += "%s?gravatar=hashed&" % md5(user.email).he...
4d4b412bf67b782fc35d12531a9263c38230a96b
cloud_browser_project/urls.py
cloud_browser_project/urls.py
# pylint: disable=no-value-for-parameter from django.conf import settings from django.conf.urls import patterns, url, include from django.contrib import admin from django.views.generic import RedirectView # Enable admin. admin.autodiscover() ADMIN_URLS = False urlpatterns = patterns('') # pylint: disable=C0103 if ...
# pylint: disable=no-value-for-parameter from django.conf import settings from django.conf.urls import patterns, url, include from django.contrib import admin from django.views.generic import RedirectView # Enable admin. admin.autodiscover() ADMIN_URLS = False urlpatterns = patterns('') # pylint: disable=C0103 if ...
Update URL patterns for Django >= 1.8
Update URL patterns for Django >= 1.8
Python
mit
ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser,ryan-roemer/django-cloud-browser
--- +++ @@ -12,35 +12,31 @@ urlpatterns = patterns('') # pylint: disable=C0103 if ADMIN_URLS: - urlpatterns += patterns( - '', + urlpatterns += [ # Admin URLs. Note: Include ``urls_admin`` **before** admin. url(r'^$', RedirectView.as_view(url='/admin/'), name='index'), url...
455b77877e2a3ee7f795ab969ed70ddc3dd8c531
hello.py
hello.py
import json import requests import subprocess from flask import Flask from flask import render_template app = Flask(__name__) config = {} def shell_handler(command, **kwargs): return_code = subprocess.call(command, shell=True) return json.dumps(return_code == 0) def http_handler(address, **kwargs): tr...
import json import requests import subprocess from flask import Flask from flask import render_template app = Flask(__name__) with open('config.json') as f: config = json.loads(f.read()) def shell_handler(command, **kwargs): return_code = subprocess.call(command, shell=True) return json.dumps(return_cod...
Fix an error in production.
Fix an error in production.
Python
mit
xhacker/miracle-board,huangtao728/miracle-board,matthewbaggett/miracle-board,xhacker/miracle-board,matthewbaggett/miracle-board,huangtao728/miracle-board,forblackking/miracle-board,forblackking/miracle-board
--- +++ @@ -6,7 +6,8 @@ from flask import render_template app = Flask(__name__) -config = {} +with open('config.json') as f: + config = json.loads(f.read()) def shell_handler(command, **kwargs): @@ -47,6 +48,4 @@ if __name__ == '__main__': - with open('config.json') as f: - config = json.lo...
1ccf85b257d0774f6383a5e9dc6fdb43a20400ea
guild/commands/download_impl.py
guild/commands/download_impl.py
# Copyright 2017-2018 TensorHub, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
# Copyright 2017-2018 TensorHub, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
Handle error on download command
Handle error on download command
Python
apache-2.0
guildai/guild,guildai/guild,guildai/guild,guildai/guild
--- +++ @@ -15,16 +15,30 @@ from __future__ import absolute_import from __future__ import division +import logging + +from guild import cli from guild import pip_util from guild import resolver from guild import resourcedef from guild import util + +log = logging.getLogger("guild") def main(args): res...
0a1056bd1629cc5c2423b83cf1d667ba46274fc9
scikits/image/io/__init__.py
scikits/image/io/__init__.py
"""Utilities to read and write images in various formats.""" from _plugins import load as load_plugin from _plugins import use as use_plugin from _plugins import available as plugins # Add this plugin so that we can read images by default load_plugin('pil') from sift import * from collection import * from io import...
__doc__ = """Utilities to read and write images in various formats. The following plug-ins are available: """ from _plugins import load as load_plugin from _plugins import use as use_plugin from _plugins import available as plugins from _plugins import info as plugin_info # Add this plugin so that we can read image...
Add table of available plugins to module docstring.
io: Add table of available plugins to module docstring.
Python
bsd-3-clause
oew1v07/scikit-image,oew1v07/scikit-image,WarrenWeckesser/scikits-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,GaZ3ll3/scikit-image,almarklein/scikit-image,robintw/scikit-image,GaelVaroquaux/scikits.image,keflavich/scikit-image,SamHames/scikit-image,almarklein/scikit-image,Warre...
--- +++ @@ -1,8 +1,13 @@ -"""Utilities to read and write images in various formats.""" +__doc__ = """Utilities to read and write images in various formats. + +The following plug-ins are available: + +""" from _plugins import load as load_plugin from _plugins import use as use_plugin from _plugins import availabl...
fd5742bf48691897640d117330d3c1f89276e907
fft/convert.py
fft/convert.py
from scikits.audiolab import Sndfile import matplotlib.pyplot as plt import os dt = 0.05 Fs = int(1.0/dt) current_dir = os.path.dirname(__file__) for (dirpath, dirnames, filenames) in os.walk(current_dir): for filename in filenames: path = os.path.join(current_dir + "/" + filename) print (path) fname, exte...
from scikits.audiolab import Sndfile import matplotlib.pyplot as plt import os dt = 0.05 Fs = int(1.0/dt) print 'started...' current_dir = os.path.dirname(__file__) print current_dir for (dirpath, dirnames, filenames) in os.walk(current_dir): for filename in filenames: path = os.path.join(current_dir + "/" + fi...
Update spectrogram plot file size
Update spectrogram plot file size
Python
mit
ritazh/EchoML,ritazh/EchoML,ritazh/EchoML
--- +++ @@ -5,8 +5,9 @@ dt = 0.05 Fs = int(1.0/dt) +print 'started...' current_dir = os.path.dirname(__file__) - +print current_dir for (dirpath, dirnames, filenames) in os.walk(current_dir): for filename in filenames: path = os.path.join(current_dir + "/" + filename) @@ -20,4 +21,12 @@ outputf...
d7ce69c7b07782902970a9b21713295f6b1f59ad
audiorename/__init__.py
audiorename/__init__.py
"""Rename audio files from metadata tags.""" import sys from .args import fields, parse_args from .batch import Batch from .job import Job from .message import job_info, stats fields __version__: str = '0.0.0' def execute(*argv: str): """Main function :param list argv: The command line arguments specifie...
"""Rename audio files from metadata tags.""" import sys from importlib import metadata from .args import fields, parse_args from .batch import Batch from .job import Job from .message import job_info, stats fields __version__: str = metadata.version('audiorename') def execute(*argv: str): """Main function ...
Use the version number in pyproject.toml as the single source of truth
Use the version number in pyproject.toml as the single source of truth From Python 3.8 on we can use importlib.metadata.version('package_name') to get the current version.
Python
mit
Josef-Friedrich/audiorename
--- +++ @@ -1,6 +1,7 @@ """Rename audio files from metadata tags.""" import sys +from importlib import metadata from .args import fields, parse_args from .batch import Batch @@ -9,7 +10,7 @@ fields -__version__: str = '0.0.0' +__version__: str = metadata.version('audiorename') def execute(*argv: str...
dd27eea0ea43447dad321b4b9ec88f24e5ada268
asv/__init__.py
asv/__init__.py
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import os import sys if sys.version_info >= (3, 3): # OS X framework builds of Python 3.3 can not call other 3.3 ...
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import os import sys if sys.version_info >= (3, 3): # OS X framework builds of Python 3.3 can not call other 3.3 ...
Add version check for incompatible Python 3.x/virtualenv 1.11 combination
Add version check for incompatible Python 3.x/virtualenv 1.11 combination
Python
bsd-3-clause
pv/asv,mdboom/asv,airspeed-velocity/asv,waylonflinn/asv,airspeed-velocity/asv,giltis/asv,cpcloud/asv,spacetelescope/asv,mdboom/asv,giltis/asv,edisongustavo/asv,qwhelan/asv,airspeed-velocity/asv,pv/asv,cpcloud/asv,airspeed-velocity/asv,spacetelescope/asv,mdboom/asv,ericdill/asv,ericdill/asv,pv/asv,cpcloud/asv,mdboom/asv...
--- +++ @@ -13,3 +13,19 @@ # inherited. if os.environ.get('__PYVENV_LAUNCHER__'): os.unsetenv('__PYVENV_LAUNCHER__') + + +def check_version_compatibility(): + """ + Performs a number of compatibility checks with third-party + libraries. + """ + from distutils.version import LooseVers...
16c567f27e1e4979321d319ddb334c263b43443f
gitcv/gitcv.py
gitcv/gitcv.py
import os import yaml from git import Repo class GitCv: def __init__(self, cv_path, repo_path): self._cv = self._load_cv(cv_path) self._repo_path = os.path.join(repo_path, 'cv') def _load_cv(self, cv_path): with open(cv_path, "r") as f: cv = yaml.load(f) return cv...
import os import yaml from git import Repo class GitCv: def __init__(self, cv_path, repo_path): self._repo_path = os.path.join(repo_path, 'cv') self._cv_path = cv_path self._load_cv() def _load_cv(self): with open(self._cv_path, "r") as f: self._cv = yaml.load(f) ...
Make cv path class attribute
Make cv path class attribute
Python
mit
jangroth/git-cv,jangroth/git-cv
--- +++ @@ -6,13 +6,13 @@ class GitCv: def __init__(self, cv_path, repo_path): - self._cv = self._load_cv(cv_path) self._repo_path = os.path.join(repo_path, 'cv') + self._cv_path = cv_path + self._load_cv() - def _load_cv(self, cv_path): - with open(cv_path, "r") as f...
0f42038436fae01e248bbf86c5d52f7cdfe97fdc
ironicclient/tests/functional/utils.py
ironicclient/tests/functional/utils.py
# Copyright (c) 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
# Copyright (c) 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
Fix quotation mark in docstring
Fix quotation mark in docstring Change-Id: Ie9501a0bce8c43e0316d1b8bda7296e859b0c8fb
Python
apache-2.0
openstack/python-ironicclient,NaohiroTamura/python-ironicclient,NaohiroTamura/python-ironicclient,openstack/python-ironicclient
--- +++ @@ -27,7 +27,7 @@ def get_object(object_list, object_value): - """"Get Ironic object by value from list of Ironic objects. + """Get Ironic object by value from list of Ironic objects. :param object_list: the output of the cmd :param object_value: value to get
ff4c49b9d89d4f92804ce1d827015072b6b60b7b
addons/sale_margin/__init__.py
addons/sale_margin/__init__.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from functools import partial import openerp from openerp import api, SUPERUSER_ID from . import models # noqa from . import report # noqa def uninstall_hook(cr, registry): def recreate_view(dbname): ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from functools import partial import odoo from odoo import api, SUPERUSER_ID from . import models # noqa from . import report # noqa def uninstall_hook(cr, registry): def recreate_view(dbname): d...
Use odoo instead of openerp
[IMP] sale_margin: Use odoo instead of openerp Closes #23451
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
--- +++ @@ -2,8 +2,8 @@ # Part of Odoo. See LICENSE file for full copyright and licensing details. from functools import partial -import openerp -from openerp import api, SUPERUSER_ID +import odoo +from odoo import api, SUPERUSER_ID from . import models # noqa from . import report # noqa @@ -11,7 +1...
84e9995668d8c34993b9fdf1a95f187897328750
ex6.py
ex6.py
# left out assignment for types_of_people mentioned in intro types_of_people = 10 # change variable from 10 to types_of_people x = f"There are {types_of_people} types of people." binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}." print(x) print(y) # left out f in front of strin...
types_of_people = 10 x = f"There are {types_of_people} types of people." binary = "binary" do_not = "don't" y = f"Those who know {binary} and those who {do_not}." print(x) print(y) print(f"I said: {x}") print(f"I also said: '{y}'") hilarious = False joke_evaluation = "Isn't that joke so funny?! {}" print(joke_eval...
Remove unnesessary comments for learners
Remove unnesessary comments for learners
Python
mit
zedshaw/learn-python3-thw-code,zedshaw/learn-python3-thw-code,zedshaw/learn-python3-thw-code
--- +++ @@ -1,6 +1,4 @@ -# left out assignment for types_of_people mentioned in intro types_of_people = 10 -# change variable from 10 to types_of_people x = f"There are {types_of_people} types of people." binary = "binary" @@ -10,9 +8,7 @@ print(x) print(y) -# left out f in front of string and omit extra per...
ed10111f92b1f75d852647fe55e260974fab5eb4
apps/approval/api/serializers.py
apps/approval/api/serializers.py
from rest_framework import serializers from apps.approval.models import CommitteeApplication, CommitteePriority class CommitteeSerializer(serializers.ModelSerializer): group_name = serializers.SerializerMethodField(source='group') class Meta(object): model = CommitteePriority fields = ('grou...
from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework import serializers from apps.approval.models import CommitteeApplication, CommitteePriority class CommitteeSerializer(serializers.ModelSerializer): group_name = serializers.SerializerMethodField(source='group') c...
Raise DRF ValidationError to get APIException base
Raise DRF ValidationError to get APIException base
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
--- +++ @@ -1,3 +1,4 @@ +from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework import serializers from apps.approval.models import CommitteeApplication, CommitteePriority @@ -23,7 +24,12 @@ def create(self, validated_data): committees = validated_data.pop(...
e081c1944506330a3c01cfe90dcf8deb242bd63b
bin/migrate-tips.py
bin/migrate-tips.py
from gratipay.wireup import db, env from gratipay.models.team import migrate_all_tips db = db(env()) if __name__ == '__main__': migrate_all_tips(db)
from gratipay.wireup import db, env from gratipay.models.team.mixins.tip_migration import migrate_all_tips db = db(env()) if __name__ == '__main__': migrate_all_tips(db)
Fix imports in tip migration script
Fix imports in tip migration script
Python
mit
gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com
--- +++ @@ -1,5 +1,5 @@ from gratipay.wireup import db, env -from gratipay.models.team import migrate_all_tips +from gratipay.models.team.mixins.tip_migration import migrate_all_tips db = db(env())
a2d90e92a0686578cc354b5979af1945233f03f6
sitetools/venv_hook/sitecustomize.py
sitetools/venv_hook/sitecustomize.py
""" This file serves as a hook into virtualenvs that do NOT have sitetools installed. It is added to the $PYTHONPATH by the `dev` command so that new virtualenvs can refer to the sitetools from the old virtualenv. It tries to play nice by looking for the next sitecustomize module. """ import imp import os import sy...
""" This file serves as a hook into virtualenvs that do NOT have sitetools installed. It is added to the $PYTHONPATH by the `dev` command so that new virtualenvs can refer to the sitetools from the old virtualenv. It tries to play nice by looking for the next sitecustomize module. """ import imp import os import sy...
Fix formatting of error in venv_hook
Fix formatting of error in venv_hook
Python
bsd-3-clause
mikeboers/sitetools,westernx/sitetools,westernx/sitetools
--- +++ @@ -28,7 +28,7 @@ import sitetools._startup except Exception as e: - warnings.warn("Error while importing sitetools._startup: %e" % e) + warnings.warn("Error while importing sitetools._startup: %s" % e) # Be a good citizen and find the next sitecustomize module.
c2da36340d372deb3ebfc16f395bb32a60a9da12
rps.py
rps.py
from random import choice class RPSGame: shapes = ['rock', 'paper', 'scissors'] draws = [('rock', 'rock'), ('paper', 'paper'), ('scissors', 'scissors')] first_wins = [('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')] def _evaluate(self, player_move, computer_move): if (player...
from random import choice import unittest class RPSGame: shapes = ['rock', 'paper', 'scissors'] draws = [('rock', 'rock'), ('paper', 'paper'), ('scissors', 'scissors')] first_wins = [('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')] def _evaluate(self, player_move, computer_move): ...
Add simple unittest to test computer's strategy.
Add simple unittest to test computer's strategy.
Python
mit
kubkon/ee106-additional-material
--- +++ @@ -1,4 +1,5 @@ from random import choice +import unittest class RPSGame: shapes = ['rock', 'paper', 'scissors'] @@ -13,10 +14,13 @@ else: return "Computer wins!" + def _computer_move(self): + return choice(RPSGame.shapes) + def play(self, rounds=1): fo...
7c05eb09dc5ff83ef45f3f84b9603ec6e43f58c7
run.py
run.py
import argparse from app import app parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False) parser.add_argument('-p', '--port', action='store', dest='port', default=5000, type=int) params = parser.parse_args() app.run(debug=params.debug, port=params.p...
import argparse import os from app import app if os.geteuid() != 0: raise OSError("Must be run as root") parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False) parser.add_argument('-p', '--port', action='store', dest='port', default=5000, type=i...
Add error if missing root
Add error if missing root
Python
mit
njbbaer/unicorn-remote,njbbaer/unicorn-remote,njbbaer/unicorn-remote
--- +++ @@ -1,6 +1,11 @@ import argparse +import os from app import app + + +if os.geteuid() != 0: + raise OSError("Must be run as root") parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug', action='store_true', dest='debug', default=False)
858a68a66e40ecc5d1a592503166e7096544b8c3
leetcode/ds_hash_contains_duplicate.py
leetcode/ds_hash_contains_duplicate.py
# @file Contains Duplicate # @brief Given array of integers, find if array contains duplicates # https://leetcode.com/problems/contains-duplicate/ ''' Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it shoul...
# @file Contains Duplicate # @brief Given array of integers, find if array contains duplicates # https://leetcode.com/problems/contains-duplicate/ ''' Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it shoul...
Change keyword val to num
Change keyword val to num
Python
mit
ngovindaraj/Python
--- +++ @@ -13,8 +13,8 @@ #Time Complexity = O(n) since we have a single for-loop to look at all numbers def containsDuplicate(self, nums): dict = {} - for val in nums: - if val not in dict: dict[val] = 1 - elif val in dict: return True + for num in nums: + if num not in dict: dict[num] = 1 + ...
c3f5212dbb7452db48420d717c1815ad4e536c40
cgen_wrapper.py
cgen_wrapper.py
from cgen import * from codeprinter import ccode import ctypes class Ternary(Generable): def __init__(self, condition, true_statement, false_statement): self.condition = ccode(condition) self.true_statement = ccode(true_statement) self.false_statement = ccode(false_statement) def gene...
from cgen import * import ctypes def convert_dtype_to_ctype(dtype): conversion_dict = {'int64': ctypes.c_int64, 'float64': ctypes.c_float} return conversion_dict[str(dtype)]
Remove the Ternary class from cgen wrapper
Remove the Ternary class from cgen wrapper This is no longer required since we are not using preprocessor macros any more
Python
mit
opesci/devito,opesci/devito
--- +++ @@ -1,16 +1,5 @@ from cgen import * -from codeprinter import ccode import ctypes - - -class Ternary(Generable): - def __init__(self, condition, true_statement, false_statement): - self.condition = ccode(condition) - self.true_statement = ccode(true_statement) - self.false_statement =...
01949a1f5d8278ab1d577e2d56b1c9fd2f79724c
metpy/plots/tests/test_skewt.py
metpy/plots/tests/test_skewt.py
import tempfile import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from metpy.plots.skewt import * # noqa # TODO: Need at some point to do image-based comparison, but that's a lot to # bite off right now class TestSkewT(object): def test_api(self):...
import tempfile import numpy as np from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg from metpy.plots.skewt import * # noqa # TODO: Need at some point to do image-based comparison, but that's a lot to # bite off right now class TestSkewT(object): def test_api(self):...
Remove test for not passing figure.
Remove test for not passing figure. This will trigger matplotlib's backend detection, which won't work well for us on Travis.
Python
bsd-3-clause
dopplershift/MetPy,ahaberlie/MetPy,Unidata/MetPy,ShawnMurd/MetPy,Unidata/MetPy,jrleeman/MetPy,ahaberlie/MetPy,ahill818/MetPy,deeplycloudy/MetPy,jrleeman/MetPy,dopplershift/MetPy
--- +++ @@ -28,9 +28,3 @@ with tempfile.NamedTemporaryFile() as f: FigureCanvasAgg(fig).print_png(f.name) - - def test_no_figure(self): - 'Test the SkewT api' - skew = SkewT() - with tempfile.NamedTemporaryFile() as f: - FigureCanvasAgg(skew.ax.figure).print_...
f3f7cc59cfc79420a2f1fa00e3e8631250f4e9cf
cloaca/stack.py
cloaca/stack.py
class Stack(object): def __init__(self, stack=None): self.stack = stack if stack else [] def push_frame(self, function_name, *args): self.stack.append(Frame(function_name, *args)) def remove(self, item): self.stack.remove(item) def __str__(self): return str(self.stack)...
class Stack(object): def __init__(self, stack=None): self.stack = stack if stack else [] def push_frame(self, function_name, *args): self.stack.append(Frame(function_name, *args)) def remove(self, item): self.stack.remove(item) def __str__(self): return str(self.stack)...
Fix repr to include args as kwargs.
Fix repr to include args as kwargs. It's a weird signature.
Python
mit
mhmurray/cloaca,mhmurray/cloaca,mhmurray/cloaca,mhmurray/cloaca
--- +++ @@ -25,4 +25,4 @@ return 'Frame({0})'.format(self.function_name) def __repr__(self): - return 'Frame({0}, {1})'.format(self.function_name, self.args) + return 'Frame({0}, args={1})'.format(self.function_name, self.args)
5a67bff672e0a74419cadbdcaf9f6bd7b9336499
config/fuzzer_params.py
config/fuzzer_params.py
switch_failure_rate = 0.0 switch_recovery_rate = 0.0 dataplane_drop_rate = 0.3 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 ofp_message_send_rate = 1.0 ofp_cmd_passthrough_rate = 0.0 link_failure_rate = 0.0 link_recovery_rate = 1.0 controller_crash_rate = 0.0 controller_r...
switch_failure_rate = 0.02 switch_recovery_rate = 0.0 dataplane_drop_rate = 0.005 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 ofp_message_send_rate = 1.0 ofp_cmd_passthrough_rate = 0.0 link_failure_rate = 0.0 link_recovery_rate = 1.0 controller_crash_rate = 0.0 controlle...
Make fuzzer params somewhat more realistic (not so high)
Make fuzzer params somewhat more realistic (not so high)
Python
apache-2.0
jmiserez/sts,ucb-sts/sts,jmiserez/sts,ucb-sts/sts
--- +++ @@ -1,6 +1,6 @@ -switch_failure_rate = 0.0 +switch_failure_rate = 0.02 switch_recovery_rate = 0.0 -dataplane_drop_rate = 0.3 +dataplane_drop_rate = 0.005 controlplane_block_rate = 0.0 controlplane_unblock_rate = 1.0 ofp_message_receipt_rate = 1.0 @@ -10,7 +10,7 @@ link_recovery_rate = 1.0 controller_cra...
a9da17d7edb443bbdee7406875717d30dc4e4bf5
src/scripts/write_hosts.py
src/scripts/write_hosts.py
#!/usr/bin/python import os hostnames = eval(os.environ['hostnames']) addresses = eval(os.environ['addresses']) def write_hosts(hostnames, addresses, file): f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n') f.write('127.0.0.1 localhost\n\n') for idx, hostname in enumerate(hostnames): f.write(addres...
#!/usr/bin/python import os hostnames = eval(os.environ['hostnames']) addresses = eval(os.environ['addresses']) def write_hosts(hostnames, addresses, file): f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n') f.write('127.0.0.1 localhost ' + os.uname()[1] + '\n\n') for idx, hostname in enumerate(hostname...
Add own hostname to /etc/hosts
Add own hostname to /etc/hosts
Python
mit
evoila/heat-common,evoila/heat-common
--- +++ @@ -6,7 +6,7 @@ def write_hosts(hostnames, addresses, file): f.write('DO NOT EDIT! THIS FILE IS MANAGED VIA HEAT\n\n') - f.write('127.0.0.1 localhost\n\n') + f.write('127.0.0.1 localhost ' + os.uname()[1] + '\n\n') for idx, hostname in enumerate(hostnames): f.write(addresses[idx] + ' ' + hos...
fe3db3aca1d6166c3c3d739971346205591d8d9e
roamer/python_edit.py
roamer/python_edit.py
""" argh """ import tempfile import os from subprocess import call EDITOR = os.environ.get('EDITOR', 'vim') if EDITOR in ['vim', 'nvim']: EXTRA_EDITOR_COMMAND = '+set backupcopy=yes' else: EXTRA_EDITOR_COMMAND = None def file_editor(content): with tempfile.NamedTemporaryFile(suffix=".tmp") as temp: ...
""" argh """ import tempfile import os from subprocess import call EDITOR = os.environ.get('EDITOR', 'vim') if EDITOR in ['vim', 'nvim']: EXTRA_EDITOR_COMMAND = '+set backupcopy=yes' else: EXTRA_EDITOR_COMMAND = None def file_editor(content): with tempfile.NamedTemporaryFile(suffix=".roamer") as temp: ...
Change file type to .roamer
Change file type to .roamer
Python
mit
abaldwin88/roamer
--- +++ @@ -15,7 +15,7 @@ def file_editor(content): - with tempfile.NamedTemporaryFile(suffix=".tmp") as temp: + with tempfile.NamedTemporaryFile(suffix=".roamer") as temp: temp.write(content) temp.flush() if EXTRA_EDITOR_COMMAND:
367be3298ac72f6d3e369a592e7a3f1d37b042e1
bin/ext_service/reset_all_habitica_users.py
bin/ext_service/reset_all_habitica_users.py
import argparse import sys import logging import emission.core.get_database as edb import emission.net.ext_service.habitica.proxy as proxy def reset_user(reset_em_uuid): del_result = proxy.habiticaProxy(reset_em_uuid, "POST", "/api/v3/user/reset", {}) logging.debug("reset ...
import argparse import sys import logging import emission.core.get_database as edb import emission.net.ext_service.habitica.proxy as proxy import emission.net.ext_service.habitica.sync_habitica as autocheck def reset_user(reset_em_uuid): del_result = proxy.habiticaProxy(reset_em_uuid, "POST", ...
Enhance the habitica reset pipeline to reset all users
Enhance the habitica reset pipeline to reset all users Also reset the last timestamp since we have deleted all points so we need to restore all points. Also restore their points with an optional argument. This is useful when the trips/sections are correct but the habitica set is screwed up.
Python
bsd-3-clause
shankari/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server
--- +++ @@ -4,17 +4,29 @@ import emission.core.get_database as edb import emission.net.ext_service.habitica.proxy as proxy +import emission.net.ext_service.habitica.sync_habitica as autocheck def reset_user(reset_em_uuid): del_result = proxy.habiticaProxy(reset_em_uuid, "POST", ...
d20f04d65437138559445bf557be52a87690c7f2
test/checker/test_checker_ipaddress.py
test/checker/test_checker_ipaddress.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import unicode_literals from ipaddress import ip_address import itertools import pytest import six from typepy import ( Typecode, StrictLevel, ) from typepy.type import IpAddress nan = float("nan") i...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import unicode_literals from ipaddress import ip_address import itertools import pytest import six from typepy import ( Typecode, StrictLevel, ) from typepy.type import IpAddress nan = float("nan") i...
Change class definitions from old style to new style
Change class definitions from old style to new style
Python
mit
thombashi/typepy
--- +++ @@ -23,7 +23,7 @@ inf = float("inf") -class Test_IpAddress_is_type: +class Test_IpAddress_is_type(object): @pytest.mark.parametrize( ["value", "strict_level", "expected"],
3e374aa6714b677bd9d9225b155adc5b1ffd680d
stubilous/builder.py
stubilous/builder.py
from functools import partial def response(callback, method, url, body, status=200): from stubilous.config import Route callback(Route(method=method, path=url, body=body, status=status, desc="")) class Builder(object): def __init__(self): self.host = None self.port = None self.r...
from functools import partial from stubilous.config import Route def response(callback, method, url, body, status=200, headers=None, cookies=None): callback(Route(method=method, path=url, body=body...
Allow cookies and headers in response
Allow cookies and headers in response
Python
mit
CodersOfTheNight/stubilous
--- +++ @@ -1,9 +1,22 @@ from functools import partial +from stubilous.config import Route -def response(callback, method, url, body, status=200): - from stubilous.config import Route - callback(Route(method=method, path=url, body=body, status=status, desc="")) +def response(callback, + method,...
9728d59217e2fd8bcaaf7586a9a3b99c61764630
tests/changes/api/test_plan_details.py
tests/changes/api/test_plan_details.py
from changes.testutils import APITestCase class PlanIndexTest(APITestCase): def test_simple(self): project1 = self.create_project() project2 = self.create_project() plan1 = self.create_plan(label='Foo') plan1.projects.append(project1) plan1.projects.append(project2) ...
from changes.testutils import APITestCase class PlanDetailsTest(APITestCase): def test_simple(self): project1 = self.create_project() project2 = self.create_project() plan1 = self.create_plan(label='Foo') plan1.projects.append(project1) plan1.projects.append(project2) ...
Fix plan details test name
Fix plan details test name
Python
apache-2.0
dropbox/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes
--- +++ @@ -1,7 +1,7 @@ from changes.testutils import APITestCase -class PlanIndexTest(APITestCase): +class PlanDetailsTest(APITestCase): def test_simple(self): project1 = self.create_project() project2 = self.create_project()
5a3ed191cb29d328976b33a3bc4a2fa68b0be2e4
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
from openerp import models, fields class Course(models.Model): _name = 'openacademy.course' name = fields.Char(string='Title', required=True) description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', ...
from openerp import api, models, fields class Course(models.Model): _name = 'openacademy.course' name = fields.Char(string='Title', required=True) description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', ...
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
arogel/openacademy-project
--- +++ @@ -1,4 +1,4 @@ -from openerp import models, fields +from openerp import api, models, fields class Course(models.Model): @@ -20,3 +20,17 @@ 'UNIQUE(name)', "The course title must be unique"), ] + + @api.one # api.one send default params: cr, uid, id context + def copy(self,...
fed8d1d85b929dc21cd49cd2cd0ac660f19e7a36
comics/crawlers/bizarro.py
comics/crawlers/bizarro.py
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Bizarro' language = 'no' url = 'http://www.start.no/tegneserier/bizarro/' start_date = '1985-01-01' end_date = '2009-06-24' # No longer hosted at start.no histo...
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Bizarro' language = 'no' url = 'http://underholdning.no.msn.com/tegneserier/bizarro/' start_date = '1985-01-01' history_capable_days = 12 schedule = 'Mo,Tu,We,T...
Update 'Bizarro' crawler to use msn.no instead of start.no
Update 'Bizarro' crawler to use msn.no instead of start.no
Python
agpl-3.0
klette/comics,datagutten/comics,datagutten/comics,datagutten/comics,klette/comics,klette/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,jodal/comics
--- +++ @@ -4,16 +4,18 @@ class ComicMeta(BaseComicMeta): name = 'Bizarro' language = 'no' - url = 'http://www.start.no/tegneserier/bizarro/' + url = 'http://underholdning.no.msn.com/tegneserier/bizarro/' start_date = '1985-01-01' - end_date = '2009-06-24' # No longer hosted at start.no - ...
51aca89cfcac99ffb0fa9304e55fad34a911bdc9
sconsole/manager.py
sconsole/manager.py
# Import third party libs import urwid # Import sconsole libs import sconsole.cmdbar import sconsole.static import sconsole.jidtree FOOTER = [ ('title', 'Salt Console'), ' ', ('key', 'UP'), ' ', ('key', 'DOWN'), ' '] class Manager(object): def __init__(self, opts): self.opts =...
# Import third party libs import urwid # Import sconsole libs import sconsole.cmdbar import sconsole.static import sconsole.jidtree FOOTER = [ ('title', 'Salt Console'), ' ', ('key', 'UP'), ' ', ('key', 'DOWN'), ' '] class Manager(object): def __init__(self, opts): self.opts =...
Call an update method to manage incoming jobs
Call an update method to manage incoming jobs
Python
apache-2.0
saltstack/salt-console
--- +++ @@ -40,4 +40,5 @@ self.view, palette=palette, unhandled_input=self.unhandled_input) + loop.set_alarm_in(1, self.jidtree.update) loop.run()
8cc66b50f3b4b7708ccf46e263cffba8e69dc1a2
climlab/__init__.py
climlab/__init__.py
__version__ = '0.2.3' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation...
__version__ = '0.2.4' # This list defines all the modules that will be loaded if a user invokes # from climLab import * # totally out of date! #__all__ = ["constants", "thermo", "orbital_table", # "long_orbital_table", "insolation", "ebm", # "column", "convadj"] #from climlab import radiation...
Increment version number to 0.2.4 with performance improvements in transmissivity code.
Increment version number to 0.2.4 with performance improvements in transmissivity code.
Python
mit
cjcardinale/climlab,brian-rose/climlab,cjcardinale/climlab,cjcardinale/climlab,brian-rose/climlab
--- +++ @@ -1,4 +1,4 @@ -__version__ = '0.2.3' +__version__ = '0.2.4' # This list defines all the modules that will be loaded if a user invokes # from climLab import *
2510e85a0b09c3b8a8909d74a25b444072c740a8
test/test_integration.py
test/test_integration.py
import unittest import http.client import time class TestStringMethods(unittest.TestCase): def test_404NoConfig(self): connRouter = http.client.HTTPConnection("localhost", 8666) connConfig = http.client.HTTPConnection("localhost", 8888) connRouter.request("GET", "/google") response...
import unittest import http.client import time class TestStringMethods(unittest.TestCase): def test_404NoConfig(self): connRouter = http.client.HTTPConnection("localhost", 8666) connConfig = http.client.HTTPConnection("localhost", 8888) connRouter.request("GET", "/httpbin") respons...
Fix tests to use httpbin.org, return always 200
Fix tests to use httpbin.org, return always 200
Python
apache-2.0
dhiaayachi/dynx,dhiaayachi/dynx
--- +++ @@ -7,28 +7,29 @@ def test_404NoConfig(self): connRouter = http.client.HTTPConnection("localhost", 8666) connConfig = http.client.HTTPConnection("localhost", 8888) - connRouter.request("GET", "/google") + connRouter.request("GET", "/httpbin") response = connRouter...
765dd18fb05c0cef21b9dce7cbddda3c079f0b7d
logtoday/tests.py
logtoday/tests.py
from django.test import TestCase from django.urls import resolve class HomePageTest(TestCase): fixtures = ['tests/functional/auth_dump.json'] def test_root_url_resolves_to_index_page_view(self): found = resolve("/") self.assertEqual(found.view_name, "index") def test_uses_login_template(...
from django.test import TestCase from django.urls import resolve class HomePageTest(TestCase): fixtures = ['tests/functional/auth_dump.json'] def test_root_url_resolves_to_index_page_view(self): found = resolve("/") self.assertEqual(found.view_name, "index") def test_uses_login_template(...
Add unittest for dashboard redirection and template
Add unittest for dashboard redirection and template Test that checks template rendered by /dashboard endpoint.
Python
mit
sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily,sundeep-co-in/makegoalsdaily
--- +++ @@ -22,3 +22,10 @@ response = self.client.get('/logout/') self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/') + + def test_uses_dashboard_landing_page(self): + # login is required to access /dashboard url. + self.client.post('/login/', {'...
2c95054842db106883a400e5d040aafc31b123dd
comics/meta/base.py
comics/meta/base.py
import datetime as dt from comics.core.models import Comic class MetaBase(object): # Required values name = None language = None url = None # Default values start_date = None end_date = None rights = '' @property def slug(self): return self.__module__.split('.')[-1] ...
import datetime as dt from comics.core.models import Comic class MetaBase(object): # Required values name = None language = None url = None # Default values active = True start_date = None end_date = None rights = '' @property def slug(self): return self.__module_...
Add new boolean field MetaBase.active
Add new boolean field MetaBase.active
Python
agpl-3.0
jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,datagutten/comics,klette/comics,klette/comics,jodal/comics,datagutten/comics
--- +++ @@ -9,6 +9,7 @@ url = None # Default values + active = True start_date = None end_date = None rights = '' @@ -29,6 +30,7 @@ slug=self.slug, language=self.language, url=self.url) + comic.active = self.active comic....
7c9b93106d741568e64917ddb4c989a9fecdea17
typesetter/typesetter.py
typesetter/typesetter.py
from flask import Flask, render_template, jsonify app = Flask(__name__) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().split('\n') @app.route('/') def index(): return render_tem...
from functools import lru_cache from flask import Flask, render_template, jsonify app = Flask(__name__) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().split('\n') @app.route('/') d...
Use LRU cache to further improve search response times
Use LRU cache to further improve search response times
Python
mit
rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter
--- +++ @@ -1,3 +1,5 @@ +from functools import lru_cache + from flask import Flask, render_template, jsonify @@ -16,6 +18,13 @@ @app.route('/api/search/<fragment>') def search(fragment): + results = find_matches(fragment) + + return jsonify(results) + + +@lru_cache() +def find_matches(fragment): r...
ec30ac35feb0708414cfa70e8c42425fa25f74c2
components/utilities.py
components/utilities.py
"""Utilities for general operations.""" def IsNumeric(num_str): try: val = int(num_str) except ValueError: return False else: return True def GuaranteeUnicode(obj): if type(obj) == unicode: return obj elif type(obj) == str: return unicode(obj, "utf-8") ...
"""Utilities for general operations.""" def IsNumeric(num_str): try: val = int(num_str) except ValueError: return False else: return True def GuaranteeUnicode(obj): if type(obj) == unicode: return obj elif type(obj) == str: return unicode(obj, "utf-8") ...
Add EscapeHtml function (need to change it to a class)
Add EscapeHtml function (need to change it to a class)
Python
mit
lnishan/SQLGitHub
--- +++ @@ -40,3 +40,11 @@ return "\\%" elif ch == "_": return "\\_" + +def EscapeHtml(ch): + mapping = {u"&": u"&amp;", + u"<": u"&lt;", + u">": u"&gt;", + u"\"": u"&quot;", + u"\'": u"&#39;"} + return mapping[ch] if mapping.has_key...
a1acbcfc41a3f55e58e0f240eedcdf6568de4850
test/contrib/test_securetransport.py
test/contrib/test_securetransport.py
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import ( WrappedSocket, inject_into_urllib3, extract_from_urllib3 ) except ImportError as e: pytestmark = pytest.mark.skip('Could not import SecureTransport: %r' % e) from .....
# -*- coding: utf-8 -*- import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() exce...
Fix skip logic in SecureTransport tests
Fix skip logic in SecureTransport tests
Python
mit
urllib3/urllib3,urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3
--- +++ @@ -6,11 +6,26 @@ import pytest try: - from urllib3.contrib.securetransport import ( - WrappedSocket, inject_into_urllib3, extract_from_urllib3 - ) -except ImportError as e: - pytestmark = pytest.mark.skip('Could not import SecureTransport: %r' % e) + from urllib3.contrib.securetranspor...
e2234d41831d513b4da17d1031e2856785d23089
ui/__init__.py
ui/__init__.py
import multiprocessing as mp class UI: def __init__(self, game): parent_conn, child_conn = mp.Pipe(duplex=False) self.ui_event_pipe = parent_conn self.game = game def get_move(self): raise Exception("Method 'get_move' not implemented.") def update(self): raise Ex...
class UI: def __init__(self, game): self.game = game def get_move(self): raise Exception("Method 'get_move' not implemented.") def update(self): raise Exception("Method 'update' not implemented.") def run(self, mainloop): return mainloop()
Remove unused UI event pipe
Remove unused UI event pipe
Python
mit
ethanal/othello,ethanal/othello
--- +++ @@ -1,11 +1,6 @@ -import multiprocessing as mp - - class UI: def __init__(self, game): - parent_conn, child_conn = mp.Pipe(duplex=False) - self.ui_event_pipe = parent_conn self.game = game def get_move(self):
f61ba51f92ff47716128bb9d607b4cb46e7bfa4b
gblinks/cli.py
gblinks/cli.py
# -*- coding: utf-8 -*- import click import json import sys from gblinks import Gblinks def check_broken_links(gblinks): broken_links = gblinks.check_broken_links() if broken_links: print_links(broken_links) click.echo( click.style( '%d broken links found in the ...
# -*- coding: utf-8 -*- import click import json import sys from gblinks import Gblinks def check_broken_links(gblinks): broken_links = gblinks.check_broken_links() if broken_links: print_links(broken_links) click.echo( click.style( '%d broken links found in the ...
Add code to handle exception
Add code to handle exception
Python
mit
davidmogar/gblinks
--- +++ @@ -19,7 +19,7 @@ ) ) - sys.exit(-1) + sys.exit(-2) else: click.echo('No broken links found in the given path') @@ -37,13 +37,17 @@ @click.option('--check/--no-check', default=False) @click.option('--list/--no-list', default=False) def main(path, check,...
c24f497bb3595e3034a8c641a88527092e27c450
testdoc/tests/test_formatter.py
testdoc/tests/test_formatter.py
import StringIO import unittest from testdoc.formatter import WikiFormatter class WikiFormatterTest(unittest.TestCase): def setUp(self): self.stream = StringIO.StringIO() self.formatter = WikiFormatter(self.stream) def test_title(self): self.formatter.title('foo') self.assert...
import StringIO import unittest from testdoc.formatter import WikiFormatter class WikiFormatterTest(unittest.TestCase): def setUp(self): self.stream = StringIO.StringIO() self.formatter = WikiFormatter(self.stream) def test_title(self): self.formatter.title('foo') self.assert...
Fix a bug in the tests.
Fix a bug in the tests.
Python
mit
testing-cabal/testdoc
--- +++ @@ -15,7 +15,7 @@ def test_section(self): self.formatter.section('foo') - self.assertEqual(self.stream.getvalue(), '== foo ==\n\n') + self.assertEqual(self.stream.getvalue(), '\n== foo ==\n\n') def test_subsection(self): self.formatter.subsection('foo')
045192dd0a69dfe581075e76bbb7ca4676d321b8
test_project/urls.py
test_project/urls.py
from django.conf.urls import url from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^$', lambda request, *args, **kwargs: HttpResponse()), url(r'^admin/', admin.site.urls), ]
from django.urls import re_path from django.contrib import admin from django.http import HttpResponse urlpatterns = [ re_path(r'^$', lambda request, *args, **kwargs: HttpResponse()), re_path(r'^admin/', admin.site.urls), ]
Replace url() with re_path() available in newer Django
Replace url() with re_path() available in newer Django
Python
bsd-3-clause
ecometrica/django-vinaigrette
--- +++ @@ -1,9 +1,9 @@ -from django.conf.urls import url +from django.urls import re_path from django.contrib import admin from django.http import HttpResponse urlpatterns = [ - url(r'^$', lambda request, *args, **kwargs: HttpResponse()), - url(r'^admin/', admin.site.urls), + re_path(r'^$', lambda re...
c30347f34967ee7634676e0e4e27164910f9e52b
regparser/tree/xml_parser/note_processor.py
regparser/tree/xml_parser/note_processor.py
from regparser.tree.depth import markers as mtypes, optional_rules from regparser.tree.struct import Node from regparser.tree.xml_parser import ( paragraph_processor, simple_hierarchy_processor) class IgnoreNotesHeader(paragraph_processor.BaseMatcher): """We don't want to include "Note:" and "Notes:" headers"...
import re from regparser.tree.depth import markers as mtypes, optional_rules from regparser.tree.struct import Node from regparser.tree.xml_parser import ( paragraph_processor, simple_hierarchy_processor) class IgnoreNotesHeader(paragraph_processor.BaseMatcher): """We don't want to include "Note:" and "Notes...
Use regex rather than string match for Note:
Use regex rather than string match for Note: Per suggestion from @tadhg-ohiggins
Python
cc0-1.0
eregs/regulations-parser,tadhg-ohiggins/regulations-parser,tadhg-ohiggins/regulations-parser,cmc333333/regulations-parser,cmc333333/regulations-parser,eregs/regulations-parser
--- +++ @@ -1,3 +1,5 @@ +import re + from regparser.tree.depth import markers as mtypes, optional_rules from regparser.tree.struct import Node from regparser.tree.xml_parser import ( @@ -6,8 +8,10 @@ class IgnoreNotesHeader(paragraph_processor.BaseMatcher): """We don't want to include "Note:" and "Notes:" ...
49d67984d318d64528244ff525062210f94bd033
tests/helpers.py
tests/helpers.py
import numpy as np import glfw def step_env(env, max_path_length=100, iterations=1): """Step env helper.""" for _ in range(iterations): env.reset() for _ in range(max_path_length): _, _, done, _ = env.step(env.action_space.sample()) env.render() if done: ...
import numpy as np import glfw def step_env(env, max_path_length=100, iterations=1): """Step env helper.""" for _ in range(iterations): env.reset() for _ in range(max_path_length): _, _, done, _ = env.step(env.action_space.sample()) env.render() if done: ...
Fix indentation to pass the tests
Fix indentation to pass the tests
Python
mit
rlworkgroup/metaworld,rlworkgroup/metaworld
--- +++ @@ -13,6 +13,6 @@ def close_env(env): """Close env helper.""" - if env.viewer is not None: - glfw.destroy_window(env.viewer.window) - env.viewer = None + if env.viewer is not None: + glfw.destroy_window(env.viewer.window) + env.viewer = None
e159465d4495ed2ebcbd1515d82f4f85fc28c8f7
corral/views/private.py
corral/views/private.py
# -*- coding: utf-8 -*- """These JSON-formatted views require authentication.""" from flask import Blueprint, jsonify, request, current_app, g from werkzeug.exceptions import NotFound from os.path import join from ..dl import download from ..error import handle_errors from ..util import enforce_auth private = Bluepri...
# -*- coding: utf-8 -*- """These JSON-formatted views require authentication.""" from flask import Blueprint, jsonify, request, current_app, g from werkzeug.exceptions import NotFound from os.path import join from ..dl import download from ..error import handle_errors from ..util import enforce_auth private = Bluepri...
Use a better example error message
Use a better example error message
Python
mit
nickfrostatx/corral,nickfrostatx/corral,nickfrostatx/corral
--- +++ @@ -14,7 +14,7 @@ @handle_errors(private) def json_error(e): - """Return an error response like {"msg":"Method not allowed"}.""" + """Return an error response like {"msg":"Not Found"}.""" return jsonify({'msg': e.name}), e.code
592be8dc73b4da45c948eac133ceb018c60c3be7
src/pysme/matrix_form.py
src/pysme/matrix_form.py
"""Code for manipulating expressions in matrix form .. module:: matrix_form.py :synopsis:Code for manipulating expressions in matrix form .. moduleauthor:: Jonathan Gross <jarthurgross@gmail.com> """ import numpy as np def comm(A, B): '''Calculate the commutator of two matrices ''' retur...
"""Code for manipulating expressions in matrix form .. module:: matrix_form.py :synopsis:Code for manipulating expressions in matrix form .. moduleauthor:: Jonathan Gross <jarthurgross@gmail.com> """ import numpy as np def comm(A, B): '''Calculate the commutator of two matrices ''' retur...
Change euler integrator to return list, not array
Change euler integrator to return list, not array The state of the system is a heterogeneous data type for some applications, so the array isn't appropriate.
Python
mit
CQuIC/pysme
--- +++ @@ -27,4 +27,4 @@ for dt, t in zip(dts, times[:-1]): rho_dot = rho_dot_fn(rhos[-1], t) rhos.append(rhos[-1] + dt * rho_dot) - return np.array(rhos) + return rhos
763077f355386b8a5fdb4bda44f5d2856563f674
sklearn_porter/estimator/EstimatorApiABC.py
sklearn_porter/estimator/EstimatorApiABC.py
# -*- coding: utf-8 -*- from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Method, Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter....
# -*- coding: utf-8 -*- from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimato...
Remove unused imports and `pass` keywords
feature/oop-api-refactoring: Remove unused imports and `pass` keywords
Python
bsd-3-clause
nok/sklearn-porter
--- +++ @@ -4,7 +4,7 @@ from pathlib import Path from abc import ABC, abstractmethod -from sklearn_porter.enums import Method, Language, Template +from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): @@ -27,19 +27,18 @@ Parameters ---------- - method : Me...
605202c7be63f2676b24b5f2202bfa0aa09c9e08
javelin/ase.py
javelin/ase.py
"""Theses functions read the legacy DISCUS stru file format in ASE Atoms.""" from __future__ import absolute_import from ase.atoms import Atoms from javelin.utils import unit_cell_to_vectors def read_stru(filename): f = open(filename) lines = f.readlines() f.close() a = b = c = alpha = beta = gamma ...
"""Theses functions read the legacy DISCUS stru file format in ASE Atoms.""" from __future__ import absolute_import from ase.atoms import Atoms from javelin.utils import unit_cell_to_vectors def read_stru(filename): with open(filename) as f: lines = f.readlines() a = b = c = alpha = beta = gamma = 0...
Use with to open file in read_stru
Use with to open file in read_stru
Python
mit
rosswhitfield/javelin
--- +++ @@ -6,9 +6,8 @@ def read_stru(filename): - f = open(filename) - lines = f.readlines() - f.close() + with open(filename) as f: + lines = f.readlines() a = b = c = alpha = beta = gamma = 0
503d3efd882466be4c846f74bd8eac9b90807dc2
services/myspace.py
services/myspace.py
import foauth.providers class MySpace(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.myspace.com/' docs_url = 'http://developerwiki.myspace.com/index.php?title=RESTful_API_Overview' category = 'Social' # URLs to interact with the API request_token_url =...
import foauth.providers class MySpace(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.myspace.com/' docs_url = 'http://developerwiki.myspace.com/index.php?title=RESTful_API_Overview' category = 'Social' # URLs to interact with the API request_token_url =...
Remove an unnecessary blank line
Remove an unnecessary blank line
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
--- +++ @@ -16,4 +16,3 @@ available_permissions = [ (None, 'read and write your social information'), ] -
8c5dba68915bb1cdba3c56eff15fdf67c5feed00
tests/test_global.py
tests/test_global.py
import unittest import cbs class MySettings(cbs.GlobalSettings): PROJECT_NAME = 'tests' @property def TEMPLATE_LOADERS(self): return super(MySettings, self).TEMPLATE_LOADERS + ('test',) class GlobalSettingsTest(unittest.TestCase): def test_precedence(self): g = {} cbs.appl...
import unittest import cbs class MySettings(cbs.GlobalSettings): PROJECT_NAME = 'tests' @property def INSTALLED_APPS(self): return super(MySettings, self).INSTALLED_APPS + ('test',) class GlobalSettingsTest(unittest.TestCase): def test_precedence(self): g = {} cbs.apply(My...
Update tests for new default globals
Update tests for new default globals
Python
bsd-2-clause
funkybob/django-classy-settings
--- +++ @@ -7,8 +7,8 @@ PROJECT_NAME = 'tests' @property - def TEMPLATE_LOADERS(self): - return super(MySettings, self).TEMPLATE_LOADERS + ('test',) + def INSTALLED_APPS(self): + return super(MySettings, self).INSTALLED_APPS + ('test',) class GlobalSettingsTest(unittest.TestCase):...
8fb574900a6680f8342487e32979829efa33a11a
spacy/about.py
spacy/about.py
# fmt: off __title__ = "spacy" __version__ = "3.0.0.dev14" __release__ = True __download_url__ = "https://github.com/explosion/spacy-models/releases/download" __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" __shortcuts__ = "https://raw.githubusercontent.com/explo...
# fmt: off __title__ = "spacy_nightly" __version__ = "3.0.0a0" __release__ = True __download_url__ = "https://github.com/explosion/spacy-models/releases/download" __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" __shortcuts__ = "https://raw.githubusercontent.com/e...
Update parent package and version
Update parent package and version
Python
mit
explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy
--- +++ @@ -1,6 +1,6 @@ # fmt: off -__title__ = "spacy" -__version__ = "3.0.0.dev14" +__title__ = "spacy_nightly" +__version__ = "3.0.0a0" __release__ = True __download_url__ = "https://github.com/explosion/spacy-models/releases/download" __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-mode...
5fe4351ea52c8cb11af1cb61d65cb5f765638fd1
tap/tests/test_runner.py
tap/tests/test_runner.py
# Copyright (c) 2014, Matt Layman import tempfile import unittest from tap import TAPTestRunner from tap.runner import TAPTestResult class TestTAPTestRunner(unittest.TestCase): def test_has_tap_test_result(self): runner = TAPTestRunner() self.assertEqual(runner.resultclass, TAPTestResult) ...
# Copyright (c) 2014, Matt Layman import tempfile import unittest from tap import TAPTestRunner from tap.runner import TAPTestResult class TestTAPTestRunner(unittest.TestCase): def test_has_tap_test_result(self): runner = TAPTestRunner() self.assertEqual(runner.resultclass, TAPTestResult) ...
Fix the runner test where it wasn't setting outdir.
Fix the runner test where it wasn't setting outdir.
Python
bsd-2-clause
blakev/tappy,python-tap/tappy,Mark-E-Hamilton/tappy,mblayman/tappy
--- +++ @@ -21,7 +21,7 @@ the unittest classes aren't very extensible. """ # Save the previous outdir in case **this** execution was using it. - previous_outdir = TAPTestResult + previous_outdir = TAPTestResult.OUTDIR outdir = tempfile.mkdtemp() TAPTestRunn...