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
021c21207cab0cf3f7cca3cb31ffa4c62d49e58c
python/chigger/base/KeyPressInteractorStyle.py
python/chigger/base/KeyPressInteractorStyle.py
#pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/...
#pylint: disable=missing-docstring #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/...
Make camera interaction more sensitive
Make camera interaction more sensitive (refs #12095)
Python
lgpl-2.1
lindsayad/moose,dschwen/moose,andrsd/moose,milljm/moose,milljm/moose,sapitts/moose,SudiptaBiswas/moose,bwspenc/moose,sapitts/moose,jessecarterMOOSE/moose,dschwen/moose,harterj/moose,sapitts/moose,permcody/moose,andrsd/moose,idaholab/moose,YaqiWang/moose,jessecarterMOOSE/moose,laagesen/moose,SudiptaBiswas/moose,permcody...
--- +++ @@ -19,6 +19,8 @@ self.AddObserver("KeyPressEvent", self.keyPress) super(KeyPressInteractorStyle, self).__init__(parent, **kwargs) + self.SetMotionFactor(0.1*self.GetMotionFactor()) + def keyPress(self, obj, event): #pylint: disable=unused-argument """ Execute...
2fba1c04c8083211df8664d87080480a1f63ed2a
csunplugged/utils/group_lessons_by_age.py
csunplugged/utils/group_lessons_by_age.py
"""Return ordered groups of lessons.""" from collections import OrderedDict from topics.models import ( AgeGroup, LessonNumber, ) def group_lessons_by_age(lessons): """Return ordered groups of lessons. Lessons are grouped by the lesson minimum age and maximum ages, and then order by number. ...
"""Return ordered groups of lessons.""" from collections import OrderedDict from topics.models import ( AgeGroup, LessonNumber, ) def group_lessons_by_age(lessons): """Return ordered groups of lessons. Lessons are grouped by the lesson minimum age and maximum ages, and then order by number. ...
Fix bug where lessons are duplicated across age groups.
Fix bug where lessons are duplicated across age groups.
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
--- +++ @@ -27,7 +27,7 @@ for lesson in age_group.lessons.filter(id__in=lessons).order_by("lessonnumber"): lesson.number = LessonNumber.objects.get(lesson=lesson, age_group=age_group).number if age_group in grouped_lessons.keys(): - grouped_lessons[age_group].append(l...
7882f838241ce92c15d49bf17ed7b307342386b6
pyrax/identity/keystone_identity.py
pyrax/identity/keystone_identity.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pyrax from pyrax.base_identity import BaseAuth import pyrax.exceptions as exc class KeystoneIdentity(BaseAuth): """ Implements the Keystone-specific behaviors for Identity. In most cases you will want to create specific subclasses to implement the ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pyrax from pyrax.base_identity import BaseAuth import pyrax.exceptions as exc class KeystoneIdentity(BaseAuth): """ Implements the Keystone-specific behaviors for Identity. In most cases you will want to create specific subclasses to implement the ...
Fix a minor typo in the EndpointNotDefined exception
Fix a minor typo in the EndpointNotDefined exception
Python
apache-2.0
roelvv/pyrax,0dataloss/pyrax,briancurtin/pyrax,naemono/pyrax,rackerlabs/heat-pyrax,vikomall/pyrax,sivel/pyrax,ddaeschler/pyrax,pratikmallya/pyrax,rackspace/pyrax,opsdisk/pyrax,EdLeafe/pyrax,mandx/pyrax
--- +++ @@ -19,5 +19,5 @@ def _get_auth_endpoint(self): ep = pyrax.get_setting("auth_endpoint") if ep is None: - raise exc.EndpointNotDefined("No auth enpoint has been specified.") + raise exc.EndpointNotDefined("No auth endpoint has been specified.") return ep
5d663ae690f0c488f7a38f4556c30b169389c441
flaskiwsapp/projects/models/target.py
flaskiwsapp/projects/models/target.py
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM from sqlalchemy_utils.types.url import URLType from flask_validator.constraints.internet import ValidateURL AREAS = ('Poli...
''' Created on Sep 24, 2016 @author: rtorres ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM AREAS = ('Policies', 'Billing', 'Claims', 'Reports') class Target(SurrogatePK, Model): """A user of the app.""" ...
Remove import from testing packages
Remove import from testing packages
Python
mit
rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel
--- +++ @@ -5,8 +5,6 @@ ''' from flaskiwsapp.database import SurrogatePK, Model, db, reference_col, relationship, Column from sqlalchemy.dialects.postgresql.base import ENUM -from sqlalchemy_utils.types.url import URLType -from flask_validator.constraints.internet import ValidateURL AREAS = ('Policies', 'Bill...
7171b8bba0cd7b595abcdea7b819fc26e27252bc
docker-images/training-webapp/app.py
docker-images/training-webapp/app.py
import os import pgdb from flask import Flask app = Flask(__name__) @app.route('/') def hello(): conn = pgdb.connect( host='pg', user='postgres', password='testnet', database='testnet' ) cur = conn.cursor() cur.execute( "SELECT value FROM kv WHERE key='provider'" ) provider = cur.fetchone()[0] co...
import os import pgdb import logging from flask import Flask app = Flask(__name__) @app.route('/') def hello(): conn = pgdb.connect( host='pg', user='postgres', password='testnet', database='testnet' ) cur = conn.cursor() cur.execute( "SELECT value FROM kv WHERE key='provider'" ) provider = cur.fetch...
Add logging to python webserver
Add logging to python webserver
Python
apache-2.0
bolcom/docker-for-testers,bolcom/docker-for-testers,bolcom/docker-for-testers
--- +++ @@ -1,5 +1,6 @@ import os import pgdb +import logging from flask import Flask @@ -15,6 +16,7 @@ return 'Hello '+provider+'!' if __name__ == '__main__': + logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) # Bind to PORT if defined, otherwise default to 5000. ...
730a32f90d618e99a55084cf1442a86eaf4ebdf9
core/configs/base_config.py
core/configs/base_config.py
"""Kraken - base config module. Classes: BaseConfig -- Base config object used to configure builders. """ class BaseConfig(object): """Base Configuration for Kraken builders.""" def __init__(self): super(BaseConfig, self).__init__() self.nameTemplate = { "locat...
"""Kraken - base config module. Classes: BaseConfig -- Base config object used to configure builders. """ class BaseConfig(object): """Base Configuration for Kraken builders.""" def __init__(self): super(BaseConfig, self).__init__() self.nameTemplate = { "locat...
Change suffix for locator to 'loc'
Change suffix for locator to 'loc'
Python
bsd-3-clause
goshow-jp/Kraken,goshow-jp/Kraken,oculusstorystudio/kraken,oculusstorystudio/kraken,goshow-jp/Kraken
--- +++ @@ -26,7 +26,7 @@ "HierarchyGroup": "hrc", "Joint": "def", "Layer": "", - "Locator": "null", + "Locator": "loc", ...
3c0db422301955430ecd572103097fc68fec254d
tests/testapp/admin.py
tests/testapp/admin.py
from django import forms from django.contrib import admin from django.db import models from content_editor.admin import ContentEditor, ContentEditorInline from .models import Article, Download, RichText, Thing class RichTextarea(forms.Textarea): def __init__(self, attrs=None): default_attrs = {"class": ...
from django import forms from django.contrib import admin from django.db import models from content_editor.admin import ContentEditor, ContentEditorInline from .models import Article, Download, RichText, Thing class RichTextarea(forms.Textarea): def __init__(self, attrs=None): default_attrs = {"class": ...
Use sets to define allowed regions for plugins
Use sets to define allowed regions for plugins
Python
bsd-3-clause
matthiask/django-content-editor,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/feincms2-content
--- +++ @@ -19,7 +19,7 @@ model = RichText formfield_overrides = {models.TextField: {"widget": RichTextarea}} fieldsets = [(None, {"fields": ("text", "region", "ordering")})] - regions = ("main",) + regions = {"main"} class Media: js = ("//cdn.ckeditor.com/4.5.6/standard/ckeditor....
6e0654386c7a5d7e0a399ac363af4f2d59770d16
coffeestats/caffeine_oauth2/tests/test_models.py
coffeestats/caffeine_oauth2/tests/test_models.py
from __future__ import unicode_literals from django.test import TestCase from caffeine_oauth2.models import CoffeestatsApplication class CoffeestatsApplicationTest(TestCase): def test___str__(self): application = CoffeestatsApplication(name='test', client_id='client') self.assertEquals(str(appli...
from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from django.test import TestCase from caffeine_oauth2.models import CoffeestatsApplication User = get_user_model() class CoffeestatsApplicationTest(TestCase): def test___str__(sel...
Add tests for new caffeine_oauth2.models code
Add tests for new caffeine_oauth2.models code
Python
mit
coffeestats/coffeestats-django,coffeestats/coffeestats-django,coffeestats/coffeestats-django,coffeestats/coffeestats-django
--- +++ @@ -1,11 +1,52 @@ from __future__ import unicode_literals +from django.contrib.auth import get_user_model +from django.core.urlresolvers import reverse from django.test import TestCase from caffeine_oauth2.models import CoffeestatsApplication + +User = get_user_model() class CoffeestatsApplication...
249293336d2bfcc018c44d9279b89b31522c37da
u2fserver/jsobjects.py
u2fserver/jsobjects.py
from u2flib_server.jsapi import (JSONDict, RegisterRequest, RegisterResponse, SignRequest, SignResponse) __all__ = [ 'RegisterRequestData', 'RegisterResponseData', 'AuthenticateRequestData', 'AuthenticateResponseData' ] class RegisterRequestData(JSONDict): @prope...
# Copyright (C) 2014 Yubico AB # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is ...
Use a mixin for get-/setProps
Use a mixin for get-/setProps
Python
bsd-2-clause
moreati/u2fval,Yubico/u2fval
--- +++ @@ -1,3 +1,18 @@ +# Copyright (C) 2014 Yubico AB +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later...
b48bc4c1fff91173327f10a29e140fc781619edb
src/adhocracy/lib/helpers/staticpage_helper.py
src/adhocracy/lib/helpers/staticpage_helper.py
import babel.core from adhocracy.lib import cache from adhocracy.lib.helpers import url as _url @cache.memoize('staticpage_url') def url(staticpage, **kwargs): pid = staticpage.key + '_' + staticpage.lang return _url.build(None, 'static', pid, **kwargs) def get_lang_info(lang): locale = babel.core.Local...
import babel.core from adhocracy.lib import cache, staticpage from adhocracy.lib.helpers import url as _url @cache.memoize('staticpage_url') def url(staticpage, **kwargs): pid = staticpage.key + '_' + staticpage.lang return _url.build(None, 'static', pid, **kwargs) def get_lang_info(lang): locale = babe...
Make can_edit available in the helper
Make can_edit available in the helper
Python
agpl-3.0
alkadis/vcv,liqd/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,SysTheron/adhocracy,phihag/adhocracy,alkadis/vcv,SysTheron/adhocracy,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,liqd/adhocracy,phihag/adhocracy,alkadis/vcv,DanielNeuge...
--- +++ @@ -1,6 +1,6 @@ import babel.core -from adhocracy.lib import cache +from adhocracy.lib import cache, staticpage from adhocracy.lib.helpers import url as _url @@ -12,3 +12,7 @@ def get_lang_info(lang): locale = babel.core.Locale(lang) return {'id': lang, 'name': locale.display_name} + +def c...
bbfc0357c9a37599776584c40f6a3b4f462ad110
run_notebooks.py
run_notebooks.py
#!/usr/bin/env python import subprocess NOTEBOOKS_DIR = 'notebooks' SKIP_NOTEBOOKS = ['Bonus/What to do when things go wrong.ipynb'] def run_notebook(notebook): args = ['jupyter', 'nbconvert', '--execute', '--ExecutePreprocessor.timeout=900', '--ExecutePreprocessor.kernel_name=workshop',...
#!/usr/bin/env python import subprocess import os.path NOTEBOOKS_DIR = 'notebooks' SKIP_NOTEBOOKS = [os.path.join('Bonus','What to do when things go wrong.ipynb')] def run_notebook(notebook): args = ['jupyter', 'nbconvert', '--execute', '--ExecutePreprocessor.timeout=900', '--ExecutePrep...
Use os.join for testing on multiple platforms.
Use os.join for testing on multiple platforms.
Python
mit
Unidata/unidata-python-workshop,julienchastang/unidata-python-workshop,julienchastang/unidata-python-workshop
--- +++ @@ -1,9 +1,10 @@ #!/usr/bin/env python import subprocess +import os.path NOTEBOOKS_DIR = 'notebooks' -SKIP_NOTEBOOKS = ['Bonus/What to do when things go wrong.ipynb'] +SKIP_NOTEBOOKS = [os.path.join('Bonus','What to do when things go wrong.ipynb')] def run_notebook(notebook): @@ -20,11 +21,10 @@ ...
af52a3967568a3d5af838e695d5fcdd825f585cf
numba2/runtime/tests/test_ffi.py
numba2/runtime/tests/test_ffi.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): def ...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import math import unittest from numba2 import jit, types, int32, float64, Type, cast from numba2.runtime import ffi # ______________________________________________________________________ class TestFFI(unittest.TestCase): ...
Insert explicit cast to malloc implementation
Insert explicit cast to malloc implementation
Python
bsd-2-clause
flypy/flypy,flypy/flypy
--- +++ @@ -4,7 +4,7 @@ import math import unittest -from numba2 import jit, types, int32, float64, Type +from numba2 import jit, types, int32, float64, Type, cast from numba2.runtime import ffi # ______________________________________________________________________ @@ -12,11 +12,9 @@ class TestFFI(unittest...
c0374d50f1265bdbce566cb712ab848375f6794e
schwag/schwag/urls.py
schwag/schwag/urls.py
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'schwag.views.home', name='home'), url(r'^...
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'schwag.views.home', name='home'), url(r'^...
Configure debug_toolbar to not fail.
Configure debug_toolbar to not fail.
Python
mit
endthestart/schwag,endthestart/schwag,endthestart/schwag
--- +++ @@ -23,11 +23,14 @@ # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: - import debug_toolbar + try: + import debug_toolbar - urlpatterns += patterns('', - url(r'^__debug__/', include(debug_toolbar.urls)), - ) +...
c7461cfe456b0aaf2f6ab4c9625cf7afc8a02eff
scripts/lib/logger.py
scripts/lib/logger.py
# logger module from datetime import datetime import os logfile = None logbuf = [] def init(analysis_path): global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) use_log_dir = False if use_log_dir: logdir = os.path.join(analysis_path,...
# logger module from datetime import datetime import os import socket # gethostname() logfile = None logbuf = [] def init(analysis_path): global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) logfile = os.path.join(analysis_path...
Append hostname to messages file. This supports a use-case where portions of the processing could happen on various hosts.
Append hostname to messages file. This supports a use-case where portions of the processing could happen on various hosts.
Python
mit
UASLab/ImageAnalysis
--- +++ @@ -2,6 +2,7 @@ from datetime import datetime import os +import socket # gethostname() logfile = None logbuf = [] @@ -10,15 +11,7 @@ global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) - use_log_dir = False - ...
484233e1c3140e7cca9cd1874c1cf984280e2c92
zeus/tasks/send_build_notifications.py
zeus/tasks/send_build_notifications.py
from uuid import UUID from zeus import auth from zeus.config import celery from zeus.constants import Result, Status from zeus.models import Build from zeus.notifications import email @celery.task(name='zeus.tasks.send_build_notifications', max_retries=None) def send_build_notifications(build_id: UUID): build = ...
from uuid import UUID from zeus import auth from zeus.config import celery from zeus.constants import Result, Status from zeus.models import Build from zeus.notifications import email @celery.task(name='zeus.tasks.send_build_notifications', max_retries=None) def send_build_notifications(build_id: UUID): build = ...
Remove tenant req from task query
Remove tenant req from task query
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
--- +++ @@ -9,7 +9,7 @@ @celery.task(name='zeus.tasks.send_build_notifications', max_retries=None) def send_build_notifications(build_id: UUID): - build = Build.query.get(build_id) + build = Build.query.unrestricted_unsafe().get(build_id) if not build: raise ValueError('Unable to find build wi...
97bcf652a18808d89c8de2235e2b32ae933036b6
tests/options_tests.py
tests/options_tests.py
from nose.tools import istest, assert_equal from mammoth import style_reader from mammoth.options import read_options, _default_style_map @istest def default_style_map_is_used_if_style_map_is_not_set(): assert_equal(_default_style_map, read_options({})["style_map"]) @istest def custom_style_mappings_are_prepen...
from nose.tools import istest, assert_equal from mammoth import style_reader from mammoth.options import read_options, _default_style_map @istest def default_style_map_is_used_if_style_map_is_not_set(): assert_equal(_default_style_map, read_options({})["style_map"]) @istest def custom_style_mappings_are_prepen...
Add test to ensure that style map lines beginning with hash are ignored
Add test to ensure that style map lines beginning with hash are ignored
Python
bsd-2-clause
mwilliamson/python-mammoth
--- +++ @@ -25,3 +25,12 @@ "include_default_style_map": False })["style_map"] assert_equal([style_reader.read_style("p.SectionTitle => h2")], style_map) + + +@istest +def lines_starting_with_hash_in_custom_style_map_are_ignored(): + style_map = read_options({ + "style_map": "#p.SectionTit...
398a3f8856b1390c2ad8a0fda2dd14eda4efbd2d
test_input/test70.py
test_input/test70.py
'test checking constant conditions' # __pychecker__ = '' def func1(x): 'should not produce a warning' if 1: pass while 1: print x break assert x, 'test' return 0 def func2(x): 'should produce a warning' __pychecker__ = 'constant1' if 1: pass while 1...
'test checking constant conditions' # __pychecker__ = '' def func1(x): 'should not produce a warning' if 1: pass while 1: print x break assert x, 'test' return 0 def func2(x): 'should produce a warning' __pychecker__ = 'constant1' if 1: pass while 1...
Fix a problem reported by Greg Ward and pointed out by John Machin when doing:
Fix a problem reported by Greg Ward and pointed out by John Machin when doing: return (need_quotes) and ('"%s"' % text) or (text) The following warning was generated: Using a conditional statement with a constant value ("%s") This was because even the stack wasn't modified after a BINARY_MODULO to s...
Python
bsd-3-clause
thomasvs/pychecker,thomasvs/pychecker,akaihola/PyChecker,akaihola/PyChecker
--- +++ @@ -47,3 +47,8 @@ print x break return 0 + +def func5(need_quotes, text): + 'should not produce a warning' + return (need_quotes) and ('"%s"' % text) or (text) +
e229c797a507932d7992f44d3ab93517096c2e94
tests/test_autotime.py
tests/test_autotime.py
from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): ip.run_cell("%load_ext autotime") ...
from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): ip.run_cell('%load_ext autotime') ...
Make unload test assertion explicit
Make unload test assertion explicit
Python
apache-2.0
cpcloud/ipython-autotime
--- +++ @@ -8,10 +8,10 @@ ip = get_ipython() with tt.AssertPrints('time: '): - ip.run_cell("%load_ext autotime") + ip.run_cell('%load_ext autotime') with tt.AssertPrints('time: '): - ip.run_cell("x = 1") + ip.run_cell('x = 1') - with tt.AssertPrints(''): - ip...
daed28559cc16374f85830ef9d939ccddece64a1
tests/test_parser.py
tests/test_parser.py
# -*- coding: utf-8 -*- import codecs import pytest from poyo import parse_string @pytest.fixture def string_data(): with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile: return ymlfile.read() def test_parse_string(string_data): expected = { u'default_context': { u...
# -*- coding: utf-8 -*- import codecs import pytest from poyo import parse_string @pytest.fixture def string_data(): with codecs.open('tests/foobar.yml', encoding='utf-8') as ymlfile: return ymlfile.read() def test_parse_string(string_data): expected = { u'default_context': { u...
Add list to expectation in test
Add list to expectation in test
Python
mit
hackebrot/poyo
--- +++ @@ -23,6 +23,7 @@ u'someint': 1000000, u'foo': u'hallo #welt', u'trueish': u'Falseeeeeee', + u'doc_tools': [u'mkdocs', u'sphinx', None], }, u'zZz': True, u'NullValue': None,
3a5cbdbe4a79efd59114ca11f86e282aee0eac5c
tests/trunk_aware.py
tests/trunk_aware.py
import functools import sys import nose from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk __author__ = 'moskupols' _multiprocess_shared_ = True _all_trunks = set(trunks_registered()) _trunk_filter = _all_trunks def trunk_parametrized(trunks=set(trunks_registered()))...
import functools import sys import nose from preparation.resources.Resource import trunks_registered, applied_modifiers, resource_by_trunk __author__ = 'moskupols' _multiprocess_shared_ = True _all_trunks = set(trunks_registered()) _trunk_filter = _all_trunks def trunk_parametrized(trunks=set(trunks_registered()))...
Add ability to exclude trunks by passing % before it
Add ability to exclude trunks by passing % before it For example, ./run_nose -v %FilmTitles %BookTitles
Python
mit
hatbot-team/hatbot_resources
--- +++ @@ -33,9 +33,13 @@ if args is None: args = sys.argv - _trunk_filter = _all_trunks & set(args) - if len(_trunk_filter) == 0: - _trunk_filter = _all_trunks + include = _all_trunks & set(args) + exclude_percented = set('%' + t for t in _all_trunks) & set(args) + exclude = se...
acba9a027eafb1877f0b6208613206674ba5d55d
tmc/models/employee.py
tmc/models/employee.py
# -*- coding: utf-8 -*- from odoo import fields, models class Employee(models.Model): _name = 'tmc.hr.employee' _order = 'name' name = fields.Char() internal_number = fields.Char( size=3, required=True ) docket_number = fields.Integer( required=True ) bank...
# -*- coding: utf-8 -*- from odoo import fields, models class Employee(models.Model): _name = 'tmc.hr.employee' _order = 'name' name = fields.Char() internal_number = fields.Char( size=3 ) docket_number = fields.Integer() bank_account_number = fields.Char() bank_branch =...
Remove required property on some fields
[DEL] Remove required property on some fields
Python
agpl-3.0
tmcrosario/odoo-tmc
--- +++ @@ -11,13 +11,10 @@ name = fields.Char() internal_number = fields.Char( - size=3, - required=True + size=3 ) - docket_number = fields.Integer( - required=True - ) + docket_number = fields.Integer() bank_account_number = fields.Char()
5f7137b8167704e3a9893ce0b9e72c0f6a64ac4e
warehouse/__init__.py
warehouse/__init__.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import importlib import logging import os from flask import Flask from flask.ext.script import Manager from flask.ext.sqlalchemy import SQLAlchemy __all__ = ["create_app", "db", "script"] MODULES = [ ...
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import importlib import logging import os from flask import Flask from flask.ext.script import Manager from flask.ext.sqlalchemy import SQLAlchemy __all__ = ["create_app", "db", "script"] MODULES = [ ...
Enable registering commands in a module
Enable registering commands in a module * Looks for a key "commands" with a value of True to import the module named warehouse.MODULE.commands to trigger command registration
Python
bsd-2-clause
davidfischer/warehouse
--- +++ @@ -56,3 +56,9 @@ script = Manager(create_app) script.add_option("-c", "--config", dest="config", required=False) + +for module in MODULES: + # Load commands + if module.get("commands"): + logger.debug("Loading commands for %s", module["name"]) + importlib.import_module("warehouse.%(na...
3c9b49ef968c7e59028eb0bda78b1474a49339f3
numscons/tools/intel_common/common.py
numscons/tools/intel_common/common.py
# INPUTS: # ICC_ABI: x86, amd64 _ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} def get_abi(env): try: abi = env['ICC_ABI'] except KeyError: abi = 'default' try: return _ARG2ABI[abi] except KeyError: ValueError("Unknown abi %s" % abi)
# INPUTS: # ICC_ABI: x86, amd64 _ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} def get_abi(env, lang='C'): if lang == 'C' or lang == 'CXX': try: abi = env['ICC_ABI'] except KeyError: abi = 'default' elif lang == 'FORTRAN': try: abi...
Add a language argument to get abi for intel tools.
Add a language argument to get abi for intel tools.
Python
bsd-3-clause
cournape/numscons,cournape/numscons,cournape/numscons
--- +++ @@ -3,11 +3,17 @@ _ARG2ABI = {'x86': 'ia32', 'amd64': 'em64t', 'default': 'ia32'} -def get_abi(env): - try: - abi = env['ICC_ABI'] - except KeyError: - abi = 'default' +def get_abi(env, lang='C'): + if lang == 'C' or lang == 'CXX': + try: + abi = env['ICC_ABI'] + ...
ecbb3ffdf063bc53eae0f8bd180e62ae61f99fee
opencontrail_netns/vrouter_control.py
opencontrail_netns/vrouter_control.py
from contrail_vrouter_api.vrouter_api import ContrailVRouterApi def interface_register(vm, vmi, iface_name): api = ContrailVRouterApi() mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0] api.add_port(vm.uuid, vmi.uuid, iface_name, mac) def interface_unregister(vmi_uuid): api = Contrail...
from contrail_vrouter_api.vrouter_api import ContrailVRouterApi def interface_register(vm, vmi, iface_name): api = ContrailVRouterApi() mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0] api.add_port(vm.uuid, vmi.uuid, iface_name, mac, port_type='NovaVMPort') def interface_unregister(vmi_u...
Use NovaVMPort type; otherwise the agent will believe it is a Use NovaVMPort as type; otherwise the agent will believe it is dealing with a service-instance and will not send a VM registration.
Use NovaVMPort type; otherwise the agent will believe it is a Use NovaVMPort as type; otherwise the agent will believe it is dealing with a service-instance and will not send a VM registration.
Python
apache-2.0
pedro-r-marques/opencontrail-netns,DreamLab/opencontrail-netns
--- +++ @@ -4,7 +4,7 @@ def interface_register(vm, vmi, iface_name): api = ContrailVRouterApi() mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0] - api.add_port(vm.uuid, vmi.uuid, iface_name, mac) + api.add_port(vm.uuid, vmi.uuid, iface_name, mac, port_type='NovaVMPort') def inter...
ac4eb3cbbd8e08092ddfb8f55e0ce838a803aa43
__init__.py
__init__.py
# Apparently South has some problems with upgrading permissions. The # following piece of code hooks into the migrations and recreates the # permissions. See also # http://stackoverflow.com/questions/1742021/adding-new-custom-permissions-in-django/11914435#11914435 from south.signals import post_migrate def update_pe...
Add a hack to work around a problem with South and permissions
Add a hack to work around a problem with South and permissions
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
--- +++ @@ -0,0 +1,20 @@ +# Apparently South has some problems with upgrading permissions. The +# following piece of code hooks into the migrations and recreates the +# permissions. See also +# http://stackoverflow.com/questions/1742021/adding-new-custom-permissions-in-django/11914435#11914435 + +from south.signals i...
8a080a94300403487dce023eec8467832af8ae79
tests/core/migrations/0004_bookwithchapters.py
tests/core/migrations/0004_bookwithchapters.py
from __future__ import unicode_literals from django import VERSION from django.db import migrations, models if VERSION >= (1, 8): from django.contrib.postgres.fields import ArrayField chapters_field = ArrayField(base_field=models.CharField(max_length=100), default=list, size=None) else: chapters_field = mo...
from __future__ import unicode_literals from django import VERSION from django.db import migrations, models can_use_arrayfield = False chapters_field = models.Field() # Dummy field if VERSION >= (1, 8): try: from django.contrib.postgres.fields import ArrayField chapters_field = ArrayField(base_fi...
Refactor migration script to handle case where Postgres is being used but psycopg2 isn't installed
Refactor migration script to handle case where Postgres is being used but psycopg2 isn't installed
Python
bsd-2-clause
brillgen/django-import-export,copperleaftech/django-import-export,bmihelac/django-import-export,jnns/django-import-export,copperleaftech/django-import-export,jnns/django-import-export,brillgen/django-import-export,PetrDlouhy/django-import-export,jnns/django-import-export,PetrDlouhy/django-import-export,brillgen/django-...
--- +++ @@ -2,21 +2,17 @@ from django import VERSION from django.db import migrations, models + +can_use_arrayfield = False +chapters_field = models.Field() # Dummy field if VERSION >= (1, 8): - from django.contrib.postgres.fields import ArrayField - chapters_field = ArrayField(base_field=models.CharField...
c53725ef0c30875e8727001b05f50c6eb02abe00
nn/models/font2char2word2sent2doc.py
nn/models/font2char2word2sent2doc.py
import tensorflow as tf from ..font import font2char from ..util import static_rank, funcname_scope from .ar2word2sent2doc import ar2word2sent2doc @funcname_scope def font2char2word2sent2doc(document, *, words, fonts, ...
import tensorflow as tf from ..font import font2char from ..util import static_rank, funcname_scope from .ar2word2sent2doc import ar2word2sent2doc @funcname_scope def font2char2word2sent2doc(document, *, words, fonts, ...
Delete an extra blank line
Delete an extra blank line
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
--- +++ @@ -18,7 +18,6 @@ assert static_rank(words) == 2 assert static_rank(fonts) == 3 - return ar2word2sent2doc( document, words=words,
7a77b42691e051269a146fd218dd619ccefecc54
src/ansible/models.py
src/ansible/models.py
from django.db import models class Project(models.Model): project_name = models.CharField(max_length=200) playbook_path = models.CharField(max_length=200, default="~/") ansible_config_path = models.CharField(max_length=200, default="~/") default_inventory = models.CharField(max_length=200, default="hos...
from django.db import models class Project(models.Model): project_name = models.CharField(max_length=200) playbook_path = models.CharField(max_length=200, default="~/") ansible_config_path = models.CharField(max_length=200, default="~/") default_inventory = models.CharField(max_length=200, default="hos...
Fix plural form of Registry
Fix plural form of Registry TIL how to use meta class
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
--- +++ @@ -9,6 +9,10 @@ class Registry(models.Model): + class Meta: + verbose_name_plural = "registries" + + project = models.OneToOneField( Project, on_delete=models.CASCADE,
4a4abb215684a169be4ba7e0a670000f25870cd7
nodeconductor/logging/serializers.py
nodeconductor/logging/serializers.py
from rest_framework import serializers from nodeconductor.core.serializers import GenericRelatedField from nodeconductor.core.fields import MappedChoiceField, JsonField from nodeconductor.logging import models, utils, log class AlertSerializer(serializers.HyperlinkedModelSerializer): scope = GenericRelatedField(...
from rest_framework import serializers from nodeconductor.core.serializers import GenericRelatedField from nodeconductor.core.fields import MappedChoiceField, JsonField from nodeconductor.logging import models, utils, log class AlertSerializer(serializers.HyperlinkedModelSerializer): scope = GenericRelatedField(...
Remove wrong serializer field (nc-553)
Remove wrong serializer field (nc-553)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
--- +++ @@ -12,13 +12,11 @@ choice_mappings={v: k for k, v in models.Alert.SeverityChoices.CHOICES}, ) context = JsonField(read_only=True) - status = serializers.ChoiceField( - choices=(('PROBLEM', 'Problem'), ('OK', 'OK')), default='PROBLEM', write_only=True) class Meta(object): ...
6528a426ffb7a9a55c9f84f3c134a195a5e17046
problems/examples/cryptography/ecb-1/challenge.py
problems/examples/cryptography/ecb-1/challenge.py
import string from hacksport.problem import ProtectedFile, Remote class Problem(Remote): program_name = "ecb.py" files = [ProtectedFile("flag"), ProtectedFile("key")] def initialize(self): # generate random 32 hexadecimal characters self.enc_key = "".join( self.random.choice(...
import secrets import string from hacksport.problem import ProtectedFile, Remote from hacksport.deploy import flag_fmt class Problem(Remote): program_name = "ecb.py" files = [ProtectedFile("flag"), ProtectedFile("key")] def initialize(self): # generate random 32 hexadecimal characters se...
Fix ecb-1 to assert flag length
Fix ecb-1 to assert flag length
Python
mit
picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF
--- +++ @@ -1,6 +1,8 @@ +import secrets import string from hacksport.problem import ProtectedFile, Remote +from hacksport.deploy import flag_fmt class Problem(Remote): @@ -16,3 +18,11 @@ self.welcome_message = "Welcome to Secure Encryption Service version 1.{}".format( self.random.randi...
35303ce7654e14a88fcb9db0690f72c07410dade
python/pythagorean-triplet/pythagorean_triplet.py
python/pythagorean-triplet/pythagorean_triplet.py
def triplets_with_sum(n): pass
from math import ceil, gcd, sqrt def triplets_in_range(range_start, range_end): for limit in range(range_start, range_end, 4): for x, y, z in primitive_triplets(limit): a, b, c = (x, y, z) # yield multiples of primitive triplet while a < range_start: a,...
Solve pythagorean_triple - reference solution
Solve pythagorean_triple - reference solution
Python
mit
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
--- +++ @@ -1,2 +1,44 @@ -def triplets_with_sum(n): - pass +from math import ceil, gcd, sqrt + + +def triplets_in_range(range_start, range_end): + for limit in range(range_start, range_end, 4): + for x, y, z in primitive_triplets(limit): + a, b, c = (x, y, z) + + # yield multiples o...
af184be16c4bd0ea45f7e8c6dc59388c4d8893c5
main.py
main.py
import tweepy import app_config # Twitter API configuration consumer_key = app_config.twitter["consumer_key"] consumer_secret = app_config.twitter["consumer_secret"] access_token = app_config.twitter["access_token"] access_token_secret = app_config.twitter["access_token_secret"] # Start auth = tweepy.OAuthHandler(co...
import tweepy import json import unicodedata import sqlite3 import app_config import definitions API_launch() followers_list(followers_name[1]) create_db() create_table() tweet_info(followers_name[1],tweets_number=100)
Update Main.py to work with definitions.py
Update Main.py to work with definitions.py functions are loaded from definitions.py and the database can be created without modifying functions
Python
mit
franckbrignoli/twitter-bot-detection
--- +++ @@ -1,19 +1,17 @@ import tweepy +import json +import unicodedata +import sqlite3 + import app_config +import definitions -# Twitter API configuration -consumer_key = app_config.twitter["consumer_key"] -consumer_secret = app_config.twitter["consumer_secret"] +API_launch() -access_token = app_config.twitt...
47593fae71deb378bd60a14d1b6f4a3a2bb98bf6
pitz.py
pitz.py
#!/usr/bin/python import sys import subprocess cmd = sys.argv[1] new_args = sys.argv[2:] or [] subprocess.call(["pitz-%s" % cmd] + new_args)
#!/usr/bin/python import sys import subprocess def _help(): subprocess.call(['pitz-help']) sys.exit(1) if len(sys.argv) < 2: _help() cmd = sys.argv[1] new_args = sys.argv[2:] or [] try: subprocess.call(["pitz-%s" % cmd] + new_args) except OSError as exc: _help()
Add at least a minimal exception handling (missing subcommand).
Add at least a minimal exception handling (missing subcommand).
Python
bsd-3-clause
mw44118/pitz,mw44118/pitz,mw44118/pitz
--- +++ @@ -3,6 +3,16 @@ import sys import subprocess +def _help(): + subprocess.call(['pitz-help']) + sys.exit(1) + +if len(sys.argv) < 2: + _help() + cmd = sys.argv[1] new_args = sys.argv[2:] or [] -subprocess.call(["pitz-%s" % cmd] + new_args) +try: + subprocess.call(["pitz-%s" % cmd] + new_args)...
1c2ea508bd0c4e687d6a46c438a476609b43d264
databroker/tests/test_document.py
databroker/tests/test_document.py
import copy import pytest from ..core import Document, NotMutable def test_immutable(): d = Document({'a': 1}) with pytest.raises(NotMutable): # Update existing key d['a'] = 2 with pytest.raises(NotMutable): # Add new key d['b'] = 2 with pytest.raises(NotMutable): ...
import copy import pytest from ..core import Document, NotMutable def test_immutable(): d = Document({'a': 1}) with pytest.raises(NotMutable): # Update existing key d['a'] = 2 with pytest.raises(NotMutable): # Add new key d['b'] = 2 with pytest.raises(NotMutable): ...
Make test stricter to be safe.
Make test stricter to be safe.
Python
bsd-3-clause
ericdill/databroker,ericdill/databroker
--- +++ @@ -44,8 +44,7 @@ def test_to_dict(): a = Document({'x': {'y': {'z': 1}}}) b = a.to_dict() - assert not isinstance(b, Document) - assert isinstance(b, dict) + assert type(b) is dict # i.e. not Document b['x']['y']['z'] = 2 # Verify original is not modified. assert a['x']['y...
869db9b392356912beebfc4ed1db97baa82e87e3
resin/models/config.py
resin/models/config.py
import sys from ..base_request import BaseRequest from ..settings import Settings class Config(object): """ This class implements configuration model for Resin Python SDK. Attributes: _config (dict): caching configuration. """ def __init__(self): self.base_request = BaseRequest...
import sys from ..base_request import BaseRequest from ..settings import Settings def _normalize_device_type(dev_type): if dev_type['state'] == 'PREVIEW': dev_type['state'] = 'ALPHA' dev_type['name'] = dev_type['name'].replace('(PREVIEW)', '(ALPHA)') if dev_type['state'] == 'EXPERIMENTAL': ...
Patch device types to be marked as ALPHA and BETA
Patch device types to be marked as ALPHA and BETA
Python
apache-2.0
resin-io/resin-sdk-python,resin-io/resin-sdk-python,nghiant2710/resin-sdk-python,nghiant2710/resin-sdk-python
--- +++ @@ -2,6 +2,18 @@ from ..base_request import BaseRequest from ..settings import Settings + + +def _normalize_device_type(dev_type): + if dev_type['state'] == 'PREVIEW': + dev_type['state'] = 'ALPHA' + dev_type['name'] = dev_type['name'].replace('(PREVIEW)', '(ALPHA)') + if dev_type['sta...
732430fcfa1cfc6e7303ae1fb6d0f2eea43bdd00
deps/pyextensibletype/extensibletype/test/test_interning.py
deps/pyextensibletype/extensibletype/test/test_interning.py
from .. import intern def test_global_interning(): try: intern.global_intern("hello") except AssertionError as e: pass else: raise Exception("Expects complaint about uninitialized table") intern.global_intern_initialize() id1 = intern.global_intern("hello") id2 = intern...
from .. import intern def test_global_interning(): try: intern.global_intern("hello") except AssertionError as e: pass else: raise Exception("Expects complaint about uninitialized table") intern.global_intern_initialize() id1 = intern.global_intern("hello") id2 = intern...
Add more thorough intern test
Add more thorough intern test
Python
bsd-2-clause
stefanseefeld/numba,GaZ3ll3/numba,sklam/numba,stonebig/numba,stefanseefeld/numba,pitrou/numba,GaZ3ll3/numba,seibert/numba,ssarangi/numba,seibert/numba,pombredanne/numba,GaZ3ll3/numba,shiquanwang/numba,IntelLabs/numba,IntelLabs/numba,GaZ3ll3/numba,stonebig/numba,ssarangi/numba,IntelLabs/numba,gdementen/numba,numba/numba...
--- +++ @@ -23,3 +23,11 @@ id3 = intern.global_intern("hallo") assert id1 == id2 assert id1 != id3 + +def test_intern_many(): + table = intern.InternTable() + + for i in range(1000000): + table.global_intern("my randrom string %d" % i) + table.global_intern("my randrom string %d" % ...
832f30022e29ac882f6dcaf3af50dfd0a935d73c
picoCTF-web/api/setup.py
picoCTF-web/api/setup.py
""" Setup for the API """ import api log = api.logger.use(__name__) def index_mongo(): """ Ensure the mongo collections are indexed. """ db = api.common.get_conn() log.debug("Ensuring mongo is indexed.") db.users.ensure_index("uid", unique=True, name="unique uid") db.users.ensure_inde...
""" Setup for the API """ import api log = api.logger.use(__name__) def index_mongo(): """ Ensure the mongo collections are indexed. """ db = api.common.get_conn() log.debug("Ensuring mongo is indexed.") db.users.ensure_index("uid", unique=True, name="unique uid") db.users.ensure_inde...
Add more 2 indexes to cache to improve invalidation speed
Add more 2 indexes to cache to improve invalidation speed
Python
mit
royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF
--- +++ @@ -31,6 +31,8 @@ db.cache.ensure_index("expireAt", expireAfterSeconds=0) db.cache.ensure_index("kwargs", name="kwargs") + db.cache.ensure_index("kwargs.uid", name="kwargs.uid") + db.cache.ensure_index("kwargs.tid", name="kwargs.tid") db.cache.ensure_index("args", name="args") db...
fd4ddd1a4978191fdb0d19960960c703569c6348
examples/rmg/minimal/input.py
examples/rmg/minimal/input.py
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], kineticsEstimator = 'rate rules', ) # List of species species( label='et...
# Data sources database( thermoLibraries = ['primaryThermoLibrary'], reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], kineticsFamilies = 'default', kineticsEstimator = 'rate rules', ) # List of species species( label='ethane', reactive=True, structur...
Set minimal example to 'default' kineticsFamilies.
Set minimal example to 'default' kineticsFamilies.
Python
mit
pierrelb/RMG-Py,faribas/RMG-Py,nickvandewiele/RMG-Py,enochd/RMG-Py,nickvandewiele/RMG-Py,KEHANG/RMG-Py,nyee/RMG-Py,comocheng/RMG-Py,enochd/RMG-Py,pierrelb/RMG-Py,KEHANG/RMG-Py,faribas/RMG-Py,comocheng/RMG-Py,chatelak/RMG-Py,chatelak/RMG-Py,nyee/RMG-Py
--- +++ @@ -4,7 +4,7 @@ reactionLibraries = [], seedMechanisms = [], kineticsDepositories = ['training'], - kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'], + kineticsFamilies = 'default', kineticsEstimator = 'rate rules', )
98389db2ae73147aeab9b56a0ea588843649a5ce
plugin/import-js-sublime/import-js.py
plugin/import-js-sublime/import-js.py
import sublime, sublime_plugin, subprocess, os importjs_path = os.path.expanduser('~/.rbenv/shims/import-js') class ImportJsCommand(sublime_plugin.TextCommand): def run(self, edit): entire_file_region = sublime.Region(0, self.view.size()) current_file_contents = self.view.substr(entire_file_region) env...
import sublime, sublime_plugin, subprocess, os importjs_path = os.path.expanduser('~/.rbenv/shims/import-js') class ImportJsCommand(sublime_plugin.TextCommand): def run(self, edit): entire_file_region = sublime.Region(0, self.view.size()) current_file_contents = self.view.substr(entire_file_region) env...
Check for exit code > 0 instead of existence of stderr
Check for exit code > 0 instead of existence of stderr I'm about to make messages appear in the Sublime plugin. In order to do that, I need a channel to post them that won't mess up the end results being posted to stdout.
Python
mit
lencioni/import-js,trotzig/import-js,trotzig/import-js,trotzig/import-js,lencioni/import-js,Galooshi/import-js,lencioni/import-js
--- +++ @@ -21,7 +21,7 @@ result = proc.communicate(input=current_file_contents.encode('utf-8')) stderr = result[1].decode() - if(len(stderr) > 0): + if(proc.returncode > 0): sublime.error_message('Error when executing import-js: ' + stderr) return
ea60a04280533c00bcefdf3e0fa6d0bcd8692be0
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '9006e277b20109de165d4a17827c9b2029bf3831' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[...
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[...
Upgrade libchromiumcontent to fix chromiumviews.
Upgrade libchromiumcontent to fix chromiumviews.
Python
mit
egoist/electron,yalexx/electron,gerhardberger/electron,arturts/electron,tonyganch/electron,tincan24/electron,adamjgray/electron,fomojola/electron,jsutcodes/electron,minggo/electron,matiasinsaurralde/electron,adamjgray/electron,mattotodd/electron,shennushi/electron,seanchas116/electron,deepak1556/atom-shell,thompsonemer...
--- +++ @@ -5,7 +5,7 @@ NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' -LIBCHROMIUMCONTENT_COMMIT = '9006e277b20109de165d4a17827c9b2029bf3831' +LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d' ARCH = { 'cygwin': '32bit',
e9a849f311f54e92c86f149670a318b1e5f5f5e6
update_cloudflare.py
update_cloudflare.py
import pathlib import socket import pyflare import yaml s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 53)) myip = s.getsockname()[0] s.close() with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r: update_list = yaml.load(r) for account in update_list: r...
import pathlib import socket import pyflare from yaml import load s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 53)) myip = s.getsockname()[0] s.close() with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r: update_list = load(r) for account in update_list: ...
Change import statement for external library yaml
Change import statement for external library yaml
Python
mit
tkiapril/cloudflare-updater
--- +++ @@ -2,7 +2,7 @@ import socket import pyflare -import yaml +from yaml import load s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) @@ -11,7 +11,7 @@ s.close() with (pathlib.Path(__file__).resolve().parent / 'config.yaml').open('r') as r: - update_list = yaml.load(r) + update_list = load(...
d1324e8d29d01be3d9f7a83bed21737652a7bf71
feder/letters/utils.py
feder/letters/utils.py
from textwrap import TextWrapper BODY_FOOTER_SEPERATOR = "\n\n--\n" def email_wrapper(text): wrapper = TextWrapper() wrapper.subsequent_indent = '> ' wrapper.initial_indent = '> ' return "\n".join(wrapper.wrap(text)) def normalize_msg_id(msg_id): if msg_id[0] == '<': msg_id = msg_id[1:] ...
from textwrap import TextWrapper from django.utils import six BODY_FOOTER_SEPERATOR = "\n\n--\n" def email_wrapper(text): wrapper = TextWrapper() wrapper.subsequent_indent = '> ' wrapper.initial_indent = '> ' return "\n".join(wrapper.wrap(text)) def normalize_msg_id(msg_id): if msg_id[0] == '<'...
Fix encoding in reply footer
Fix encoding in reply footer
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
--- +++ @@ -1,6 +1,8 @@ from textwrap import TextWrapper +from django.utils import six BODY_FOOTER_SEPERATOR = "\n\n--\n" + def email_wrapper(text): wrapper = TextWrapper() @@ -16,10 +18,12 @@ msg_id = msg_id[:-1] return msg_id + def is_spam_check(email_object): return email_object['...
69ffc92471536d557de4ea4ddb38d7fdfe3ee120
salt/utils/pycrypto.py
salt/utils/pycrypto.py
# -*- coding: utf-8 -*- ''' Use pycrypto to generate random passwords on the fly. ''' # Import python libraries import Crypto.Random import crypt import re def secure_password(length=20): ''' Generate a secure password. ''' pw = '' while len(pw) < length: pw += re.sub('\W', '', Crypto.Ra...
# -*- coding: utf-8 -*- ''' Use pycrypto to generate random passwords on the fly. ''' # Import python libraries import Crypto.Random import crypt import re def secure_password(length=20): ''' Generate a secure password. ''' pw = '' while len(pw) < length: pw += re.sub(r'\W', '', Crypto.R...
Use raw string for secure_password
Use raw string for secure_password
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -16,7 +16,7 @@ ''' pw = '' while len(pw) < length: - pw += re.sub('\W', '', Crypto.Random.get_random_bytes(1)) + pw += re.sub(r'\W', '', Crypto.Random.get_random_bytes(1)) return pw
95686933911fb2720b0fad816056c9008ef1097d
kafka_influxdb/reader/kafka_reader.py
kafka_influxdb/reader/kafka_reader.py
# -*- coding: utf-8 -*- import logging import time from kafka.client import KafkaClient from kafka.consumer import SimpleConsumer class KafkaReader(object): def __init__(self, host, port, group, topic, connection_wait_time=2): """ Initialize Kafka reader """ self.host = host self.port = p...
# -*- coding: utf-8 -*- import logging import time from kafka.client import KafkaClient from kafka.consumer import SimpleConsumer class KafkaReader(object): def __init__(self, host, port, group, topic, connection_wait_time=2): """ Initialize Kafka reader """ self.host = host self.port = p...
Make kafka client a field in Reader
Make kafka client a field in Reader
Python
apache-2.0
mre/kafka-influxdb,mre/kafka-influxdb
--- +++ @@ -18,8 +18,8 @@ def connect(self): connection = "{0}:{1}".format(self.host, self.port) logging.info("Connecting to Kafka at {}...", connection) - kafka_client = KafkaClient(connection) - self.consumer = SimpleConsumer(kafka_client, + self.kafka_client = KafkaClien...
0fec8460ae0d03aed6956137ec06757812f3f689
lc0199_binary_tree_right_side_view.py
lc0199_binary_tree_right_side_view.py
"""Leetcode 199. Binary Tree Right Side View Medium URL: https://leetcode.com/problems/binary-tree-right-side-view/ Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Ex...
"""Leetcode 199. Binary Tree Right Side View Medium URL: https://leetcode.com/problems/binary-tree-right-side-view/ Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Ex...
Complete level traversal last sol
Complete level traversal last sol
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -25,17 +25,56 @@ self.right = None -class Solution(object): +class SolutionLevelTraversalLast(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] + + Time complexity: O(n). + Space complexity: O(n). """ - ...
9b110b93ab8b2c7e58bb5447b3801138fedc4f51
src/config/vnc_openstack/vnc_openstack/context.py
src/config/vnc_openstack/vnc_openstack/context.py
import gevent import bottle import uuid class NeutronApiContext(object): def __init__(self, request=None, user_token=None): self.request = request self.user_token = user_token self.request_id = str(uuid.uuid4()) # end __init__ # end class NeutronApiContext def get_context(): return...
import gevent import bottle import uuid class NeutronApiContext(object): def __init__(self, request=None, user_token=None): self.request = request self.user_token = user_token self.request_id = request.json['context'].get('request_id', str(uuid.uuid4())) # end __init__ # end class Neutr...
Use request_id forwarded by neutron plugin
Use request_id forwarded by neutron plugin Change-Id: Id395e1bd225c99aafad57eaa48ae3ae3897e249d Closes-Bug: #1723193
Python
apache-2.0
eonpatapon/contrail-controller,eonpatapon/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller...
--- +++ @@ -6,7 +6,7 @@ def __init__(self, request=None, user_token=None): self.request = request self.user_token = user_token - self.request_id = str(uuid.uuid4()) + self.request_id = request.json['context'].get('request_id', str(uuid.uuid4())) # end __init__ # end class Ne...
39bc635f083f53b7cf34019e4fa642bfc8f1971b
server_app/__main__.py
server_app/__main__.py
import sys import os import logging logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG) from app import app, db, main, socketio db.create_all() app.register_blueprint(main) port = app.config['PORT'] if len(sys.argv) == 2: port = int(sys.argv[1]) logging.info("Chat ser...
import sys import os import logging if not os.path.exists(os.path.expanduser("~/.chatserver")): os.makedirs(os.path.expanduser("~/.chatserver") logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG) from app import app, db, main, socketio db.create_all() app.register_bluep...
Fix logging directory njot existing
Fix logging directory njot existing
Python
bsd-3-clause
jos0003/Chat,jos0003/Chat,jos0003/Chat,jos0003/Chat,jos0003/Chat
--- +++ @@ -2,6 +2,8 @@ import os import logging +if not os.path.exists(os.path.expanduser("~/.chatserver")): + os.makedirs(os.path.expanduser("~/.chatserver") logging.basicConfig(filename=os.path.expanduser("~/.chatserver/chat.log"), level=logging.DEBUG) from app import app, db, main, socketio
bf8ae76e7c73dc49beff7a23f2bc5f6a0dfc3b36
registration/__init__.py
registration/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.cor...
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backe...
Add reminder to myself to to importlib fallback.
Add reminder to myself to to importlib fallback.
Python
bsd-3-clause
gone/django-registration,awakeup/django-registration,dirtycoder/django-registration,liberation/django-registration,artursmet/django-registration,ubernostrum/django-registration,Troyhy/django-registration,artursmet/django-registration,liberation/django-registration,euanlau/django-registration,spurfly/django-registration...
--- +++ @@ -1,5 +1,8 @@ from django.conf import settings from django.core.exceptions import ImproperlyConfigured + +# TODO: When Python 2.7 is released this becomes a try/except falling +# back to Django's implementation. from django.utils.importlib import import_module def get_backend():
c9cd06f9bb2a3b7598a49e97bde93e6845394ec7
gvi/accounts/models.py
gvi/accounts/models.py
from django.db import models class Currency(models.Model): name = models.CharField(max_length=25) contraction = models.CarField(max_length=5) def __str__(self): return self.name class Account(models.Model): DEFAULT_CURRENCY_ID = 1 # pounds ? BANK = 'b' CASH = 'c' TYPE_CHOICES = (...
from django.db import models import datetime class Currency(models.Model): name = models.CharField(max_length=25) contraction = models.CarField(max_length=5) def __str__(self): return self.name class Account(models.Model): DEFAULT_CURRENCY_ID = 1 # pounds ? BANK = 'b' CASH = 'c' ...
Create the transfer model of accounts
Create the transfer model of accounts
Python
mit
m1k3r/gvi-accounts,m1k3r/gvi-accounts,m1k3r/gvi-accounts
--- +++ @@ -1,4 +1,5 @@ from django.db import models +import datetime class Currency(models.Model): @@ -25,7 +26,18 @@ #add the account owner def __str__(self): - if(account_type == 'b') + if account_type == 'b' return self.number else - return self...
8115116fb81fd5a121f9f94e47abbadd2c892b3d
pytablewriter/writer/binary/_interface.py
pytablewriter/writer/binary/_interface.py
# encoding: utf-8 import abc import six from .._table_writer import AbstractTableWriter @six.add_metaclass(abc.ABCMeta) class BinaryWriterInterface(object): @abc.abstractmethod def is_opened(self): # pragma: no cover pass @abc.abstractmethod def open(self, file_path): # pragma: no cover ...
# encoding: utf-8 import abc import six from .._table_writer import AbstractTableWriter @six.add_metaclass(abc.ABCMeta) class BinaryWriterInterface(object): @abc.abstractmethod def is_opened(self): # pragma: no cover pass @abc.abstractmethod def open(self, file_path): # pragma: no cover ...
Add stream verification for binary format writers
Add stream verification for binary format writers
Python
mit
thombashi/pytablewriter
--- +++ @@ -21,3 +21,7 @@ class AbstractBinaryTableWriter(AbstractTableWriter, BinaryWriterInterface): def dumps(self): raise NotImplementedError("binary format writers did not support dumps method") + + def _verify_stream(self): + if self.stream is None: + raise IOError("null outp...
ef2b13ec19d28b56647c0a11044cba6d400f9175
vimiv/image_enhance.py
vimiv/image_enhance.py
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Wrapper functions for the _image_enhance C extension.""" from gi.repository import GdkPixbuf, GLib from vimiv import _image_enhance def enhance_bc(pixbuf, brightness, contrast): """Enhance brightness and contrast of a GdkPixbuf.Pixbuf. Args: pixbu...
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Wrapper functions for the _image_enhance C extension.""" from gi.repository import GdkPixbuf, GLib from vimiv import _image_enhance def enhance_bc(pixbuf, brightness, contrast): """Enhance brightness and contrast of a GdkPixbuf.Pixbuf. Args: pixbu...
Use rowstride directly from GdkPixbuf in enhance
Use rowstride directly from GdkPixbuf in enhance The custom calculation of rowstride failed for images with weird dimensions and completely broke enhance. fixes #51
Python
mit
karlch/vimiv,karlch/vimiv,karlch/vimiv
--- +++ @@ -15,16 +15,18 @@ Return: The enhanced GdkPixbuf.Pixbuf """ - width = pixbuf.get_width() - height = pixbuf.get_height() data = pixbuf.get_pixels() has_alpha = pixbuf.get_has_alpha() c_has_alpha = 1 if has_alpha else 0 # Numbers are easier for C - rowstride = 4 * w...
116c2a875b3d9384ae744c02f3651b481ee23838
app/gunicorn-ws.conf.py
app/gunicorn-ws.conf.py
# gunicorn config file for dermshare-ws.py bind = '0.0.0.0:8025' # Only one worker, since connections need to share state workers = 1 worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker' pidfile = 'gunicorn-ws.pid' proc_name = 'dermshare-ws'
# gunicorn config file for dermshare-ws.py bind = '0.0.0.0:8026' # Only one worker, since connections need to share state workers = 1 worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker' pidfile = 'gunicorn-ws.pid' proc_name = 'dermshare-ws'
Change gunicorn websocket listening port
Change gunicorn websocket listening port
Python
epl-1.0
cmusatyalab/dermshare,spressomonkey/dermshare,spressomonkey/dermshare,spressomonkey/dermshare,spressomonkey/dermshare,cmusatyalab/dermshare,cmusatyalab/dermshare,cmusatyalab/dermshare,spressomonkey/dermshare,spressomonkey/dermshare
--- +++ @@ -1,6 +1,6 @@ # gunicorn config file for dermshare-ws.py -bind = '0.0.0.0:8025' +bind = '0.0.0.0:8026' # Only one worker, since connections need to share state workers = 1 worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker'
1fb6166198d90166881230d9edb1dd4f6fc36963
aws/customise-stack-template.py
aws/customise-stack-template.py
from amazonia.classes.sns import SNS from troposphere import Ref, Join, cloudwatch from troposphere.sns import Topic, Subscription def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) def new_cors_site_request_received_topic(emails): return topic("NewCorsSiteRequestReceived",...
from amazonia.classes.sns import SNS from troposphere import Ref, Join, cloudwatch from troposphere.sns import Topic, Subscription def user_registration_topic(emails): return topic("UserRegistrationReceived", emails) def new_cors_site_request_received_topic(emails): return topic("NewCorsSiteRequestReceived",...
Add site log received SNS topic
Add site log received SNS topic
Python
bsd-3-clause
GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services
--- +++ @@ -8,6 +8,9 @@ def new_cors_site_request_received_topic(emails): return topic("NewCorsSiteRequestReceived", emails) + +def site_log_received_topic(emails): + return topic("SiteLogReceived", emails) def topic(topic_title, emails): topic = Topic(topic_title, @@ -25,4 +28,5 @@ def customise_...
97a58f80014fbecd483c45438397a70c0789efd3
app_metrics/__init__.py
app_metrics/__init__.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals __name__ = 'app_metrics' __author__ = 'Pivotal Energy Solutions' __version_info__ = (1, 0, 0) __version__ = '.'.join(map(str, __version_info__)) __date__ = '2014/07/22 4:47:00 PM' __credits__ = ['Frank Wiles', 'Ross Poulton', 'Flavio Curella', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals __name__ = 'app_metrics' __author__ = 'Pivotal Energy Solutions' __version_info__ = (1, 1, 0) __version__ = '.'.join(map(str, __version_info__)) __date__ = '2014/07/22 4:47:00 PM' __credits__ = ['Frank Wiles', 'Ross Poulton', 'Flavio Curella', ...
Support and rollup a release
Support and rollup a release
Python
bsd-3-clause
pivotal-energy-solutions/django-app-metrics,pivotal-energy-solutions/django-app-metrics
--- +++ @@ -4,7 +4,7 @@ __name__ = 'app_metrics' __author__ = 'Pivotal Energy Solutions' -__version_info__ = (1, 0, 0) +__version_info__ = (1, 1, 0) __version__ = '.'.join(map(str, __version_info__)) __date__ = '2014/07/22 4:47:00 PM' __credits__ = ['Frank Wiles', 'Ross Poulton', 'Flavio Curella',
0cd084550fc5c1315fe33fcb00e57c1c332be6ab
indra/tests/test_mesh.py
indra/tests/test_mesh.py
from indra.databases import mesh_client def test_mesh_id_lookup(): mesh_id = 'D003094' mesh_name = mesh_client.get_mesh_name(mesh_id) assert mesh_name == 'Collagen'
from indra.databases import mesh_client def test_mesh_id_lookup(): mesh_id = 'D003094' mesh_name = mesh_client.get_mesh_name(mesh_id) assert mesh_name == 'Collagen' def test_invalid_id(): mesh_name = mesh_client.get_mesh_name('34jkgfh') assert mesh_name is None
Add test for invalid MESH ID
Add test for invalid MESH ID
Python
bsd-2-clause
pvtodorov/indra,johnbachman/indra,pvtodorov/indra,johnbachman/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy
--- +++ @@ -4,3 +4,8 @@ mesh_id = 'D003094' mesh_name = mesh_client.get_mesh_name(mesh_id) assert mesh_name == 'Collagen' + +def test_invalid_id(): + mesh_name = mesh_client.get_mesh_name('34jkgfh') + assert mesh_name is None +
7aab3ca6cdf3cf8c4c2a1e01ededede5a4bad0f1
tests/test_cardinal/test_context.py
tests/test_cardinal/test_context.py
import pytest from cardinal.context import Context from cardinal.errors import IllegalSessionUse @pytest.fixture def base_ctor(mocker): return mocker.patch('cardinal.context.commands.Context.__init__') @pytest.fixture(params=[ {}, {'asdf': 123} ]) def ctx(base_ctor, request): yield Context(**reques...
import pytest from cardinal.context import Context from cardinal.errors import IllegalSessionUse @pytest.fixture def base_ctor(mocker): return mocker.patch('cardinal.context.commands.Context.__init__') @pytest.fixture def ctx(base_ctor, request): kwargs = getattr(request, 'param', {}) yield Context(**...
Adjust fixture usage in context tests
Adjust fixture usage in context tests
Python
mit
FallenWarrior2k/cardinal.py,FallenWarrior2k/cardinal.py
--- +++ @@ -9,13 +9,13 @@ return mocker.patch('cardinal.context.commands.Context.__init__') -@pytest.fixture(params=[ - {}, - {'asdf': 123} -]) +@pytest.fixture def ctx(base_ctor, request): - yield Context(**request.param) - base_ctor.assert_called_once_with(**request.param) + kwargs = getatt...
920bc2620533cb4c91d7b7dd186ba59fd09edbf9
datadog/api/screenboards.py
datadog/api/screenboards.py
from datadog.api.base import GetableAPIResource, CreateableAPIResource, \ UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource class Screenboard(GetableAPIResource, CreateableAPIResource, UpdatableAPIResource, DeletableAPIResource, ActionAPIResourc...
from datadog.api.base import GetableAPIResource, CreateableAPIResource, \ UpdatableAPIResource, DeletableAPIResource, ActionAPIResource, ListableAPIResource class Screenboard(GetableAPIResource, CreateableAPIResource, UpdatableAPIResource, DeletableAPIResource, ActionAPIResourc...
Add `revoke` method to Screenboard
Add `revoke` method to Screenboard - This method allow to revoke the public access of a shared screenboard
Python
bsd-3-clause
percipient/datadogpy,clokep/datadogpy,KyleJamesWalker/datadogpy,jofusa/datadogpy,rogst/datadogpy,rogst/datadogpy,percipient/datadogpy,jofusa/datadogpy,clokep/datadogpy,KyleJamesWalker/datadogpy
--- +++ @@ -23,3 +23,15 @@ :returns: JSON response from HTTP request """ return super(Screenboard, cls)._trigger_action('GET', 'screen/share', board_id) + + @classmethod + def revoke(cls, board_id): + """ + Revoke a shared screenboard with given id + + :param boar...
70d0e524051442958b5098e7206c5ab745d20eb6
adminator/kea_agent.py
adminator/kea_agent.py
#!/usr/bin/python3 -tt # -*- coding: utf-8 -*- __all__ = ['KeaAgent'] from os import system from twisted.python import log from simplejson import dump, load from adminator.kea import generate_kea_config, DEFAULTS class KeaAgent(object): def __init__(self, db, template=None, output=None, signal=None): se...
#!/usr/bin/python3 -tt # -*- coding: utf-8 -*- __all__ = ['KeaAgent'] from os import system from twisted.python import log from json import dump, load from adminator.kea import generate_kea_config, DEFAULTS class KeaAgent(object): def __init__(self, db, template=None, output=None, signal=None): self.db ...
Use json instead of simplejson
Use json instead of simplejson Signed-off-by: Jan Dvořák <86df5a4870880bf501c926309e3bcfbe57789f3f@mordae.eu>
Python
mit
techlib/adminator,techlib/adminator,techlib/adminator
--- +++ @@ -5,7 +5,7 @@ from os import system from twisted.python import log -from simplejson import dump, load +from json import dump, load from adminator.kea import generate_kea_config, DEFAULTS
f5e67a55535b48afd95272083336d61dd1175765
administrator/admin.py
administrator/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import User # Register your models here. admin.site.register(User)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.contrib import admin from django.contrib.auth.admin import UserAdmin as Admin from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import Group from .models import User class Regist...
Add form for user creation
Add form for user creation
Python
mit
Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python,Social-projects-Rivne/Rv-025.Python
--- +++ @@ -1,8 +1,57 @@ # -*- coding: utf-8 -*- from __future__ import unicode_literals +from django import forms from django.contrib import admin +from django.contrib.auth.admin import UserAdmin as Admin +from django.contrib.auth.forms import UserCreationForm +from django.contrib.auth.models import Group + fr...
5b7a1a40ea43834feb5563f566d07bd5b31c589d
tests/test-recipes/metadata/always_include_files_glob/run_test.py
tests/test-recipes/metadata/always_include_files_glob/run_test.py
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert set...
import os import sys import json def main(): prefix = os.environ['PREFIX'] info_file = os.path.join(prefix, 'conda-meta', 'always_include_files_regex-0.1-0.json') with open(info_file, 'r') as fh: info = json.load(fh) if sys.platform == 'darwin': assert set...
Add error messages to the asserts
Add error messages to the asserts
Python
bsd-3-clause
ilastik/conda-build,shastings517/conda-build,frol/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,ilastik/conda-build,sandhujasmine/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,shastings517/conda-build,rmcgibbo/conda-build,shastings517/conda-build,da...
--- +++ @@ -11,9 +11,9 @@ info = json.load(fh) if sys.platform == 'darwin': - assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'} + assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files']...
f59852e0db6941ce0862545f552a2bc17081086a
schedule/tests/test_templatetags.py
schedule/tests/test_templatetags.py
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assert...
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assert...
Update unit test to use escaped ampersands in comparision.
Update unit test to use escaped ampersands in comparision.
Python
bsd-3-clause
Gustavosdo/django-scheduler,erezlife/django-scheduler,Gustavosdo/django-scheduler,nharsch/django-scheduler,nharsch/django-scheduler,drodger/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,llazzaro/django-scheduler,llazzaro/django-scheduler,rowbot-dev/django-scheduler,nwaxiomatic/django-schedu...
--- +++ @@ -9,5 +9,5 @@ def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) - self.assertEqual("?year=2008&month=1&day=1&hour=0&minute=0&second=0", + self.assertEqual("?year=2008&amp;month=1&amp;day=1&amp;hour=0...
ab7c15b791f42f90fa41dfd0557172ce520933f8
LibCharm/IO/__init__.py
LibCharm/IO/__init__.py
try: from Bio import SeqIO from Bio.Alphabet import IUPAC except ImportError as e: print('ERROR: {}'.format(e.msg)) exit(1) def load_file(filename, file_format="fasta"): """ Load sequence from file in FASTA file_format filename - Path and filename of input sequence file """ content ...
try: from Bio import SeqIO from Bio.Alphabet import IUPAC except ImportError as e: print('ERROR: {}'.format(e.msg)) exit(1) def load_file(filename, file_format="fasta"): """ Load sequence from file and returns sequence as Bio.Seq object filename - String; Path and filename of input seque...
Prepare for tagging release 0.1: Add comments to LibCharm.IO
Prepare for tagging release 0.1: Add comments to LibCharm.IO
Python
mit
Athemis/charm
--- +++ @@ -7,22 +7,28 @@ def load_file(filename, file_format="fasta"): """ - Load sequence from file in FASTA file_format - filename - Path and filename of input sequence file + Load sequence from file and returns sequence as Bio.Seq object + filename - String; Path and filename of input seque...
c581d1aab8df44b3c4e8e809e390517432c67d93
skan/test/test_vendored_correlate.py
skan/test/test_vendored_correlate.py
from contextlib import contextmanager from time import time import numpy as np from skan.vendored import thresholding as th @contextmanager def timer(): result = [0.] t = time() yield result result[0] = time() - t def test_fast_sauvola(): image = np.random.rand(512, 512) w0 = 25 w1 = 251...
from time import time import numpy as np from skan.vendored import thresholding as th class Timer: def __init__(self): self.interval = 0 def __enter__(self): self.t0 = time() return self def __exit__(self, exc_type, exc_val, exc_tb): self.interval = time() - self.t0 def...
Use timer class instead of weird list
Use timer class instead of weird list
Python
bsd-3-clause
jni/skan
--- +++ @@ -1,15 +1,18 @@ -from contextlib import contextmanager from time import time import numpy as np from skan.vendored import thresholding as th -@contextmanager -def timer(): - result = [0.] - t = time() - yield result - result[0] = time() - t +class Timer: + def __init__(self): + ...
923f6127eec0a6a576493f41d0f3b2fb9b6156d1
tests/Settings/TestContainerStack.py
tests/Settings/TestContainerStack.py
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. import UM.Settings def test_container_stack(): stack = UM.Settings.ContainerStack()
# Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. import pytest import uuid # For creating unique ID's for each container stack. import UM.Settings ## Creates a brand new container stack to test with. # # The container stack will get a new, unique ID. @pytest.fixtu...
Test creating container stack with fixture
Test creating container stack with fixture The fixture will automatically generate a unique ID. Contributes to issue CURA-1278.
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
--- +++ @@ -1,7 +1,18 @@ # Copyright (c) 2016 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. +import pytest +import uuid # For creating unique ID's for each container stack. + import UM.Settings -def test_container_stack(): - stack = UM.Settings.ContainerStack() +## Creates a...
f6d7bbffcbd5f1df0bbf122054e3c0930128d26c
src/py/handlers/www.py
src/py/handlers/www.py
"""www URL handlers""" import os import template import webapp2 def redirect(url): """Create a request handler to redirect to the given URL. Args: url: The URL to redirect to. Returns: A class definition of a request handler that will always redirect the user to the given URL. ...
"""www URL handlers""" import os import template import webapp2 def redirect(url): """Create a request handler to redirect to the given URL. Args: url: The URL to redirect to. Returns: A class definition of a request handler that will always redirect the user to the given URL. ...
Use the correct status code in the redirect handler
Use the correct status code in the redirect handler
Python
mpl-2.0
kjiwa/till,kjiwa/till,kjiwa/till,kjiwa/till
--- +++ @@ -19,7 +19,7 @@ def get(self): """GET method handler.""" self.response.location = url - self.response.status = 201 + self.response.status = 301 return RequestHandler
09835326d799cd05200856d6114b2df126d21bfb
wagtail/tests/routablepage/models.py
wagtail/tests/routablepage/models.py
from django.http import HttpResponse from django.conf.urls import url from wagtail.contrib.wagtailroutablepage.models import RoutablePage def routable_page_external_view(request, arg): return HttpResponse("EXTERNAL VIEW: " + arg) class RoutablePageTest(RoutablePage): @property def subpage_urls(self): ...
from django.http import HttpResponse from django.conf.urls import url from wagtail.contrib.wagtailroutablepage.models import RoutablePage def routable_page_external_view(request, arg): return HttpResponse("EXTERNAL VIEW: " + arg) class RoutablePageTest(RoutablePage): subpage_urls = ( url(r'^$', 'mai...
Revert "Make subpage_urls a property on RoutablePageTest"
Revert "Make subpage_urls a property on RoutablePageTest" This reverts commit d80a92cfe45907b9f91fd212a3b06fa0b2321364.
Python
bsd-3-clause
janusnic/wagtail,marctc/wagtail,nrsimha/wagtail,WQuanfeng/wagtail,nrsimha/wagtail,nilnvoid/wagtail,Klaudit/wagtail,WQuanfeng/wagtail,rv816/wagtail,timorieber/wagtail,mikedingjan/wagtail,thenewguy/wagtail,kaedroho/wagtail,bjesus/wagtail,jordij/wagtail,bjesus/wagtail,thenewguy/wagtail,nimasmi/wagtail,darith27/wagtail,ste...
--- +++ @@ -8,14 +8,12 @@ return HttpResponse("EXTERNAL VIEW: " + arg) class RoutablePageTest(RoutablePage): - @property - def subpage_urls(self): - return ( - url(r'^$', self.main, name='main'), - url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'), ...
758621d6b44ea546d96d631417088ef3eaed08a6
tvnamer/unicode_helper.py
tvnamer/unicode_helper.py
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Helpers to deal with strings, unicode objects and terminal output """ import sys def unicodify(obj, encoding = "utf-...
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvnamer #repository:http://github.com/dbr/tvnamer #license:Creative Commons GNU GPL v2 # http://creativecommons.org/licenses/GPL/2.0/ """Helpers to deal with strings, unicode objects and terminal output """ import sys def unicodify(obj, encoding = "utf-...
Support "encoding = None" argument
Support "encoding = None" argument
Python
unlicense
lahwaacz/tvnamer,dbr/tvnamer,m42e/tvnamer
--- +++ @@ -36,8 +36,11 @@ if not isinstance(x, basestring): new_args.append(repr(x)) else: - new_args.append(x) + if kw['encoding'] is not None: + new_args.append(x.encode(kw['encoding'])) + else: + new_args.append(x) - ...
5510f0990712381391dbffc38ae1bc796e2babf0
txircd/modules/umode_i.py
txircd/modules/umode_i.py
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fi...
from txircd.modbase import Mode class InvisibleMode(Mode): def namesListEntry(self, recipient, channel, user, representation): if channel.name not in recipient.channels and "i" in user.mode: return "" return representation def checkWhoVisible(self, user, targetUser, filters, fi...
Make the usermode +i check for WHO slightly neater.
Make the usermode +i check for WHO slightly neater.
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd
--- +++ @@ -7,9 +7,8 @@ return representation def checkWhoVisible(self, user, targetUser, filters, fields, channel, udata): - destination = udata["dest"] - if destination[0] == "#": - if destination not in user.channels and "i" in targetUser.mode: + if channel: + ...
cc006a07a486ec6c88cd2b4deb929a3c723c5a2c
cupyx/fallback_mode/__init__.py
cupyx/fallback_mode/__init__.py
# Attributes and Methods for fallback_mode # Auto-execute numpy method when corresponding cupy method is not found # "NOQA" to suppress flake8 warning from cupyx.fallback_mode.fallback import numpy # NOQA
from cupy import util as _util # Attributes and Methods for fallback_mode # Auto-execute numpy method when corresponding cupy method is not found # "NOQA" to suppress flake8 warning from cupyx.fallback_mode.fallback import numpy # NOQA _util.experimental('cupyx.fallback_mode.numpy')
Support fallback-mode as an experimental feature
Support fallback-mode as an experimental feature
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
--- +++ @@ -1,5 +1,10 @@ +from cupy import util as _util + # Attributes and Methods for fallback_mode # Auto-execute numpy method when corresponding cupy method is not found # "NOQA" to suppress flake8 warning from cupyx.fallback_mode.fallback import numpy # NOQA + + +_util.experimental('cupyx.fallback_mode.nu...
ec410ee0d8d51f2c12b4e8d52369956d6e846662
src/puzzle/problems/anagram_problem.py
src/puzzle/problems/anagram_problem.py
import collections from data import warehouse from puzzle.heuristics import analyze_word from puzzle.problems import problem class AnagramProblem(problem.Problem): @staticmethod def score(lines): # TODO: Support more input. if len(lines) > 1: return 0 return analyze_word.score_anagram(lines[0]...
import collections from data import warehouse from puzzle.heuristics import analyze_word from puzzle.problems import problem class AnagramProblem(problem.Problem): @staticmethod def score(lines): if len(lines) > 1: return 0 return analyze_word.score_anagram(lines[0]) def _solve(self): index...
Delete some TODOs of little value.
TODOs: Delete some TODOs of little value.
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
--- +++ @@ -9,7 +9,6 @@ @staticmethod def score(lines): - # TODO: Support more input. if len(lines) > 1: return 0 return analyze_word.score_anagram(lines[0]) @@ -20,6 +19,5 @@ return {} results = collections.OrderedDict() for index, word in enumerate(index[self.lines[0]]):...
29ef482dc43b2f4927a02b13adf9b24402ddb949
test_project/adam.py
test_project/adam.py
# A set of function which exercise specific mutation operators. This # is paired up with a test suite. The idea is that cosmic-ray should # kill every mutant when that suite is run; if it doesn't, then we've # got a problem. def constant_number(): return 42 def constant_true(): return True def constant_fal...
# A set of function which exercise specific mutation operators. This # is paired up with a test suite. The idea is that cosmic-ray should # kill every mutant when that suite is run; if it doesn't, then we've # got a problem. def constant_number(): return 42 def constant_true(): return True def constant_fal...
Modify the infinite loop function
Modify the infinite loop function Don't use `while True` b/c BooleanReplacer breaks this function's test. This is a bit ugly but until Issue #97 is fixed there is no other way around it.
Python
mit
sixty-north/cosmic-ray
--- +++ @@ -47,5 +47,9 @@ def trigger_infinite_loop(): # When `break` becomes `continue`, this should enter an infinite loop. This # helps us test timeouts. - while True: + # Any object which isn't None passes the truth value testing so here + # we use `while object()` instead of `while True` b/c ...
9145bf291ffbe1ec43345aff53ac17ad5de38e4e
IPython/html/widgets/widget_image.py
IPython/html/widgets/widget_image.py
"""ButtonWidget class. Represents a button in the frontend using a widget. Allows user to listen for click events on the button and trigger backend code when the clicks are fired. """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. #...
"""ButtonWidget class. Represents a button in the frontend using a widget. Allows user to listen for click events on the button and trigger backend code when the clicks are fired. """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. #...
Use CUnicode for width and height in ImageWidget
Use CUnicode for width and height in ImageWidget
Python
bsd-3-clause
jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywi...
--- +++ @@ -17,7 +17,7 @@ import base64 from .widget import DOMWidget -from IPython.utils.traitlets import Unicode, Bytes +from IPython.utils.traitlets import Unicode, CUnicode, Bytes #----------------------------------------------------------------------------- # Classes @@ -27,8 +27,8 @@ # Define...
7c1612d954c38ea86d2dff91537a4103f15cc0cb
statsmodels/tsa/api.py
statsmodels/tsa/api.py
from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp ...
from .ar_model import AR from .arima_model import ARMA, ARIMA import vector_ar as var from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR import filters import tsatools from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp ...
Use import * since __all__ is defined.
REF: Use import * since __all__ is defined.
Python
bsd-3-clause
josef-pkt/statsmodels,bert9bert/statsmodels,ChadFulton/statsmodels,statsmodels/statsmodels,musically-ut/statsmodels,wwf5067/statsmodels,DonBeo/statsmodels,huongttlan/statsmodels,astocko/statsmodels,jstoxrocky/statsmodels,bashtage/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,bashtage/statsmodels,nvoron23/statsmod...
--- +++ @@ -9,6 +9,5 @@ from .tsatools import (add_trend, detrend, lagmat, lagmat2ds, add_lag) import interp import stattools -from .stattools import (adfuller, acovf, q_stat, acf, pacf_yw, pacf_ols, pacf, - ccovf, ccf, periodogram, grangercausalitytests) +from .stattools import * from ...
43b5da74b17e313115e0576dbae2dd0e869b88af
course_discovery/apps/publisher/api/permissions.py
course_discovery/apps/publisher/api/permissions.py
from rest_framework.permissions import BasePermission from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access from course_discovery.apps.publisher.models import OrganizationExtension from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_use...
from rest_framework.permissions import BasePermission from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access from course_discovery.apps.publisher.models import OrganizationExtension from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_use...
Allow staff access to Publisher APIs
Allow staff access to Publisher APIs A few Publisher APIs were marked as only allowing publisher users. We should also let staff in. DISCO-1365
Python
agpl-3.0
edx/course-discovery,edx/course-discovery,edx/course-discovery,edx/course-discovery
--- +++ @@ -22,14 +22,14 @@ """ Permission class to check user is an internal user. """ def has_object_permission(self, request, view, obj): - return is_internal_user(request.user) + return request.user.is_staff or is_internal_user(request.user) class PublisherUserPermission(BasePermiss...
07710f97883452cbe472ae9735700773aa59f492
falmer/content/models/selection_grid.py
falmer/content/models/selection_grid.py
from wagtail.core import blocks from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock from falmer.content.models.core import Page class GridItem(blocks.StructBlock): ...
from wagtail.core import blocks from wagtail.core.blocks import RichTextBlock from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList from falmer.content.blocks import HeroImageBlock, FalmerImageChooserBlock from falmer.content.models.core impor...
Add description to selectiongrid items
Add description to selectiongrid items
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
--- +++ @@ -1,4 +1,5 @@ from wagtail.core import blocks +from wagtail.core.blocks import RichTextBlock from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import TabbedInterface, StreamFieldPanel, ObjectList @@ -10,14 +11,13 @@ title = blocks.CharBlock(required=True) link = blo...
a71ebcb1f2a855be0c5675c38a275a0835887c88
examples/tutorial_pandas.py
examples/tutorial_pandas.py
import argparse import pandas as pd from influxdb import DataFrameClient def main(host='localhost', port=8086): user = 'root' password = 'root' dbname = 'example' client = DataFrameClient(host, port, user, password, dbname) print("Create pandas DataFrame") df = pd.DataFrame(data=list(range(...
import argparse import pandas as pd from influxdb import DataFrameClient def main(host='localhost', port=8086): user = 'root' password = 'root' dbname = 'example' client = DataFrameClient(host, port, user, password, dbname) print("Create pandas DataFrame") df = pd.DataFrame(data=list(range(...
Fix method name in example
Fix method name in example
Python
mit
BenHewins/influxdb-python,influxdata/influxdb-python,influxdb/influxdb-python,influxdb/influxdb-python,omki2005/influxdb-python,omki2005/influxdb-python,BenHewins/influxdb-python,influxdata/influxdb-python,tzonghao/influxdb-python,tzonghao/influxdb-python
--- +++ @@ -29,7 +29,7 @@ client.query("select * from demo") print("Delete database: " + dbname) - client.delete_database(dbname) + client.drop_database(dbname) def parse_args():
04bfb5cf06cf70754e10e4a9a02cdbdf830356cd
registration/__init__.py
registration/__init__.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backend for use on this site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise ``django.cor...
from django.conf import settings from django.core.exceptions import ImproperlyConfigured # TODO: When Python 2.7 is released this becomes a try/except falling # back to Django's implementation. from django.utils.importlib import import_module def get_backend(): """ Return an instance of the registration backe...
Add reminder to myself to to importlib fallback.
Add reminder to myself to to importlib fallback.
Python
bsd-3-clause
remarkablerocket/django-mailinglist-registration,remarkablerocket/django-mailinglist-registration
--- +++ @@ -1,5 +1,8 @@ from django.conf import settings from django.core.exceptions import ImproperlyConfigured + +# TODO: When Python 2.7 is released this becomes a try/except falling +# back to Django's implementation. from django.utils.importlib import import_module def get_backend():
a13dd09a1f205fbd5aa997c2efcd0fee401f91f0
utils/utils_debug.py
utils/utils_debug.py
"""Function for Debuging.""" import inspect def pv(name): # type: (str) -> str """Analysis an expresion 'expresion : evaulation'. Used to help debuging values. """ frame = inspect.currentframe().f_back val = eval(name, frame.f_globals, frame.f_locals) return '{0}: {1}'.format(name, val)
"""Function for Debuging.""" import inspect def pv(name): # type: (str) -> str """Analysis an expresion 'expresion : evaulation'. Used to help debuging values. """ if "__" in name: raise ValueError("Double underscores not allowed for saftey reasons.") frame = inspect.currentframe().f_...
Disable dunder evaluation in debuging tool.
Disable dunder evaluation in debuging tool.
Python
mit
iastro-pt/ObservationTools,DanielAndreasen/ObservationTools
--- +++ @@ -8,6 +8,8 @@ Used to help debuging values. """ + if "__" in name: + raise ValueError("Double underscores not allowed for saftey reasons.") frame = inspect.currentframe().f_back val = eval(name, frame.f_globals, frame.f_locals) return '{0}: {1}'.format(name, val)
f3508aa348aa6f560953cbf48c6671ccf8558410
tests/test_forms.py
tests/test_forms.py
from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { 'field': '{% load sniplates %}{% form_field form.field %}' } def test_field_tag(self): ''' ...
from django import forms from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin class TestForm(forms.Form): char = forms.CharField() class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { 'widgets': '''{% block Char...
Make first field test work
Make first field test work
Python
mit
kezabelle/django-sniplates,funkybob/django-sniplates,funkybob/django-sniplates,sergei-maertens/django-sniplates,wengole/django-sniplates,sergei-maertens/django-sniplates,wengole/django-sniplates,kezabelle/django-sniplates,kezabelle/django-sniplates,sergei-maertens/django-sniplates
--- +++ @@ -1,14 +1,23 @@ +from django import forms from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin +class TestForm(forms.Form): + char = forms.CharField() + + class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLAT...
cebf3fa5cf428659960a547780e53a247a2322e8
lib/custom_data/settings_manager.py
lib/custom_data/settings_manager.py
"""This module provides functions for saving to and loading data from the settings XML file. Attributes: SETTINGS_PATH (String): The file path for the settings file. SETTINGS_SCHEMA_PATH (String): The file path for the settings' XML Schema. """ from lib.custom_data.xml_ops import load_xml_doc_as_object...
"""This module provides functions for saving to and loading data from the settings XML file. Attributes: SETTINGS_PATH (String): The file path for the settings file. SETTINGS_SCHEMA_PATH (String): The file path for the settings' XML Schema. """ from lib.custom_data.settings_data import SettingsData fro...
Use default settings in case of file read errors
Use default settings in case of file read errors
Python
unlicense
MarquisLP/Sidewalk-Champion
--- +++ @@ -6,6 +6,7 @@ SETTINGS_SCHEMA_PATH (String): The file path for the settings' XML Schema. """ +from lib.custom_data.settings_data import SettingsData from lib.custom_data.xml_ops import load_xml_doc_as_object @@ -17,8 +18,11 @@ """Load all Settings data from the settings file and ret...
7015766b70bf56f9338713c4302aa3cba75510c5
app/tests/test_views.py
app/tests/test_views.py
from django.test import TestCase from django.core.urlresolvers import reverse class IndexViewCase(TestCase): """Index view case""" def setUp(self): self.url = reverse('home') def test_get_ok(self): """Test status=200""" response = self.client.get(self.url) self.assertEqua...
import sure from django.test import TestCase from django.core.urlresolvers import reverse class IndexViewCase(TestCase): """Index view case""" def setUp(self): self.url = reverse('home') def test_get_ok(self): """Test status=200""" response = self.client.get(self.url) res...
Use sure in app tests
Use sure in app tests
Python
mit
nvbn/coviolations_web,nvbn/coviolations_web
--- +++ @@ -1,3 +1,4 @@ +import sure from django.test import TestCase from django.core.urlresolvers import reverse @@ -11,4 +12,4 @@ def test_get_ok(self): """Test status=200""" response = self.client.get(self.url) - self.assertEqual(response.status_code, 200) + response.statu...
d8e054df4810ad2c32cd61c41391e0ee1b542a66
ipython_widgets/__init__.py
ipython_widgets/__init__.py
from .widgets import * # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None: ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
from .widgets import * # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None and hasattr(ip, 'kernel') and hasattr(ip.kernel, 'comm_manager'): ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
Make it possible to import ipython_widgets without having a kernel or comm manager
Make it possible to import ipython_widgets without having a kernel or comm manager
Python
bsd-3-clause
ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,...
--- +++ @@ -3,5 +3,5 @@ # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() -if ip is not None: +if ip is not None and hasattr(ip, 'kernel') and hasattr(ip.kernel, 'comm_manager'): ip.kernel.comm_manager.register_target('ipython.widget', Widget.hand...
03491b6c11964f18f7c1867ef9f2612761a006ae
test/config/nsuserdefaults_config.py
test/config/nsuserdefaults_config.py
import unittest if sys.platform.startswith('darwin'): from nativeconfig.config import NSUserDefaultsConfig from test.config import TestConfigMixin class MyNSUserDefaultsConfig(NSUserDefaultsConfig): pass class TestMemoryConfig(unittest.TestCase, TestConfigMixin): CONFIG_TYPE = MyNSU...
import sys import unittest if sys.platform.startswith('darwin'): from nativeconfig.config import NSUserDefaultsConfig from test.config import TestConfigMixin class MyNSUserDefaultsConfig(NSUserDefaultsConfig): pass class TestMemoryConfig(unittest.TestCase, TestConfigMixin): CONFIG_T...
Add missing import of sys.
Add missing import of sys.
Python
mit
GreatFruitOmsk/nativeconfig
--- +++ @@ -1,3 +1,4 @@ +import sys import unittest if sys.platform.startswith('darwin'):
66a7e939fece2e7ddeff7b0ac858459e93a6a3d6
tests/interval_test.py
tests/interval_test.py
from timewreport.interval import TimeWarriorInterval def test_interval_should_be_hashable(): a = TimeWarriorInterval("20180816T100209Z", "20180816T110209Z", [], None) b = TimeWarriorInterval("20180816T090319Z", "20180816T100700Z", [], None) set([a, b])
from timewreport.interval import TimeWarriorInterval def test_interval_should_be_hashable(): a = TimeWarriorInterval("20180816T100209Z", "20180816T110209Z", [], None) b = TimeWarriorInterval("20180816T090319Z", "20180816T100700Z", [], None) assert {a, b}
Replace function call with set literal
Replace function call with set literal - Add assert statement so we do not have a "statement with no effect"
Python
mit
lauft/timew-report
--- +++ @@ -5,4 +5,4 @@ a = TimeWarriorInterval("20180816T100209Z", "20180816T110209Z", [], None) b = TimeWarriorInterval("20180816T090319Z", "20180816T100700Z", [], None) - set([a, b]) + assert {a, b}
3f5a73f39451e73b2f32fe3a05888f118952e591
ppp_datamodel/utils.py
ppp_datamodel/utils.py
"""Utilities for using the PPP datamodel.""" from . import Resource, Triple, Missing, Intersection, List, Union, And, Or, Exists, First, Last, Sort def contains_missing(tree): def predicate(node, childs): if isinstance(node, Missing): return True else: return any(childs.val...
"""Utilities for using the PPP datamodel.""" from . import Resource, Triple, Missing, Intersection, List, Union, And, Or, Exists, First, Last, Sort def contains_missing(tree): def predicate(node, childs): if isinstance(node, Missing): return True else: return any(childs.val...
Fix isincluded for List operators.
Fix isincluded for List operators.
Python
agpl-3.0
ProjetPP/PPP-datamodel-Python,ProjetPP/PPP-datamodel-Python
--- +++ @@ -30,4 +30,10 @@ isincluded(tree1.object,tree2.object) if isinstance(tree1,Sort): return tree1.predicate == tree2.predicate and isincluded(tree1.list,tree2.list) - return isincluded(tree1.list,tree2.list) + if isinstance(tree1,First) or isinstance(tree1,Last) or isinstance(t...
3a61d30972093d72e06d0c6bd760764d473b1dee
pygotham/frontend/speakers.py
pygotham/frontend/speakers.py
"""PyGotha speakers.""" from flask import abort, Blueprint, g, render_template from pygotham.frontend import route from pygotham.models import User __all__ = ('blueprint',) blueprint = Blueprint( 'speakers', __name__, subdomain='<event_slug>', url_prefix='/speakers', ) @route(blueprint, '/profile/...
"""PyGotham speakers.""" from flask import abort, Blueprint, g, render_template from pygotham.frontend import route from pygotham.models import User __all__ = ('blueprint',) blueprint = Blueprint( 'speakers', __name__, subdomain='<event_slug>', url_prefix='/speakers', ) @route(blueprint, '/profile...
Fix a typo in a docstring
Fix a typo in a docstring
Python
bsd-3-clause
pathunstrom/pygotham,PyGotham/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,PyGotham/pygotham,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,PyGotham/pygotham,pathunstrom/pygotham
--- +++ @@ -1,4 +1,4 @@ -"""PyGotha speakers.""" +"""PyGotham speakers.""" from flask import abort, Blueprint, g, render_template
c37cafb9c83e9f9bcc806cdb979f127fe924fa00
tools/get_binary.py
tools/get_binary.py
#!/usr/bin/env python import os import sys import shutil from version import full_version from optparse import OptionParser import pkgutils def main(): usage = "usage: %prog [destination path]" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args) != 1: pars...
#!/usr/bin/env python import os import sys import shutil from version import full_version from optparse import OptionParser import pkgutils def main(): usage = "usage: %prog [destination path]" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args) != 1: pars...
Revert "remove the dest tree and recreate it"
Revert "remove the dest tree and recreate it" This reverts commit becc4657acea505594836e62c49de2b4cb0160a9.
Python
apache-2.0
christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-m...
--- +++ @@ -20,10 +20,6 @@ sys.exit(1) dest = args[0] - - shutil.rmtree(dest, True) - os.mkdir(dest) - build_dir = pkgutils.package_builder_dir() binary_name = pkgutils.package_binary() binary = os.path.join(build_dir, binary_name)
db580bc3a433f15b31c21fbeac39fc2e40e85cdd
km3pipe/io/tests/test_ch.py
km3pipe/io/tests/test_ch.py
# Filename: test_ch.py # pylint: disable=locally-disabled,C0111,R0904,C0301,C0103,W0212 from km3pipe.testing import TestCase, patch, Mock from km3pipe.io.ch import CHPump __author__ = "Tamas Gal" __copyright__ = "Copyright 2018, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer...
# Filename: test_ch.py # pylint: disable=locally-disabled,C0111,R0904,C0301,C0103,W0212 from km3pipe.testing import TestCase, patch, Mock from km3pipe.io.ch import CHPump __author__ = "Tamas Gal" __copyright__ = "Copyright 2018, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer...
Add a test for CHPump
Add a test for CHPump
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
--- +++ @@ -13,5 +13,9 @@ class TestCHPump(TestCase): - def test_init(self): - pass + @patch("km3pipe.io.ch.CHPump._init_controlhost") + @patch("km3pipe.io.ch.CHPump._start_thread") + def test_init(self, init_controlhost_mock, start_thread_mock): + CHPump() + init_controlhost_moc...
072944268a5932875532d53237f9fdfd26406c2d
thrive_refugee/urls.py
thrive_refugee/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'thrive_refugee.views.home', name='home'), # url(r'^thrive_refugee/', include('thrive_refugee.foo.urls')), # Uncomment the admin/doc line below...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'thrive_refugee.views.home', name='home'), # url(r'^thrive_refugee/', include('thrive_refugee.foo.urls')), # Uncomment the admin/doc line below...
Set root route to point to admin
Set root route to point to admin
Python
mit
thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee
--- +++ @@ -12,4 +12,5 @@ # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), + url(r'^$', include(admin.site.urls)), )
411b6548d2ccc49e323b34ce8ace79ba8d330229
patches/sitecustomize.py
patches/sitecustomize.py
import os kaggle_proxy_token = os.getenv("KAGGLE_DATA_PROXY_TOKEN") bq_user_jwt = os.getenv("KAGGLE_BQ_USER_JWT") if kaggle_proxy_token or bq_user_jwt: from google.auth import credentials from google.cloud import bigquery from google.cloud.bigquery._http import Connection from kaggle_gcp import PublicB...
import os kaggle_proxy_token = os.getenv("KAGGLE_DATA_PROXY_TOKEN") bq_user_jwt = os.getenv("KAGGLE_BQ_USER_JWT") if kaggle_proxy_token or bq_user_jwt: from google.auth import credentials from google.cloud import bigquery from google.cloud.bigquery._http import Connection # TODO: Update this to the cor...
Add comment about kaggle_gcp module path.
Add comment about kaggle_gcp module path.
Python
apache-2.0
Kaggle/docker-python,Kaggle/docker-python
--- +++ @@ -6,6 +6,8 @@ from google.auth import credentials from google.cloud import bigquery from google.cloud.bigquery._http import Connection + # TODO: Update this to the correct kaggle.gcp path once we no longer inject modules + # from the worker. from kaggle_gcp import PublicBigqueryCli...
21424e243542a9e548a79bf28fbcfa31cc24b36f
angus/services/dummy.py
angus/services/dummy.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache Licens...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache Licens...
Fix bug, use instance and not classes as storage
Fix bug, use instance and not classes as storage
Python
apache-2.0
angus-ai/angus-service-dummy,angus-ai/angus-service-dummy
--- +++ @@ -43,7 +43,7 @@ 'dummy', 1, PORT, compute, - resource_storage=angus.storage.MemoryStorage, threads=1 + resource_storage=angus.storage.MemoryStorage(), threads=1 ) service.start()
6ff07265feaf40e20fe0fbd23df2747660dd0483
trex/serializers.py
trex/serializers.py
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from rest_framework.serializers import ( HyperlinkedModelSerializer, HyperlinkedIdentityField, ) from trex.models.project import Project, Entry class ProjectSerializer(Hype...
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from rest_framework.serializers import ( HyperlinkedModelSerializer, HyperlinkedIdentityField, ) from trex.models.project import Project, Entry class ProjectSerializer(Hype...
Add url, id and trags to the EntriesSerializer
Add url, id and trags to the EntriesSerializer
Python
mit
bjoernricks/trex,bjoernricks/trex
--- +++ @@ -32,4 +32,5 @@ class Meta: model = Entry - fields = ("date", "duration", "description", "state", "user", "created") + fields = ("url", "id", "date", "duration", "description", "state", + "user_abbr", "user", "created", "tags")
aac11d0d9805559000635b24227a8d13314feaa1
booksforcha/booksforcha.py
booksforcha/booksforcha.py
# -*- coding: utf-8 -*- import schedule from feed import load_feed from twitter import send_queued_tweet import time import os RSS_FEED_LIST = os.environ['RSS_FEED_LIST'] LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS']) SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS']) def parse_feed...
# -*- coding: utf-8 -*- import schedule from feed import load_feed from twitter import send_queued_tweet import time import os RSS_FEED_LIST = os.environ['RSS_FEED_LIST'] LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS']) SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS']) def parse_feed...
Move process scheduling out of main.
Move process scheduling out of main.
Python
mit
ChattanoogaPublicLibrary/booksforcha
--- +++ @@ -20,12 +20,12 @@ else: return parsed +schedule.every(LOAD_FEED_SECONDS).seconds.do( + load_feed, parse_feed_list(RSS_FEED_LIST)) +schedule.every(SEND_QUEUED_TWEET_SECONDS).seconds.do(send_queued_tweet) + def main(): - rsslist = parse_feed_list(RSS_FEED_LIST) - schedule.every(LOA...
017b01a1df6e7095aac78d2c859125bf7107095a
plugins/random/plugin.py
plugins/random/plugin.py
import random import re from cardinal.decorators import command def parse_roll(arg): # some people might separate with commas arg = arg.rstrip(',') if match := re.match(r'^(\d+)?d(\d+)$', arg): num_dice = match.group(1) sides = match.group(2) elif match := re.match(r'^d?(\d+)$', arg)...
import random import re from cardinal.decorators import command, help def parse_roll(arg): # some people might separate with commas arg = arg.rstrip(',') if match := re.match(r'^(\d+)?d(\d+)$', arg): num_dice = match.group(1) sides = match.group(2) elif match := re.match(r'^d?(\d+)$'...
Add help text for roll command
Add help text for roll command
Python
mit
JohnMaguire/Cardinal
--- +++ @@ -1,7 +1,7 @@ import random import re -from cardinal.decorators import command +from cardinal.decorators import command, help def parse_roll(arg): @@ -22,9 +22,13 @@ class RandomPlugin: @command('roll') + @help("Roll dice") + @help("Syntax: .roll #d# (e.g. .roll 2d6)") def roll(s...
948e5b89db6056cd6a5065f8a5411113f6b320a7
zc-list.py
zc-list.py
#!/usr/bin/env python import client_wrap def main(): client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0) key_str = client.GetKeys() keys = key_str.split (';') del keys[-1] if len(keys) == 0: return print keys if __name__ == "__main__": main()
#!/usr/bin/env python import sys import client_wrap def get_keys(client): key_str = client.GetKeys() keys = key_str.split (';') del keys[-1] if len(keys) == 0: sys.exit() return keys def print_keys(client, keys): for key in keys: value = client.ReadLong(key) print "%...
Implement formatted list of keys and values in output
Implement formatted list of keys and values in output
Python
agpl-3.0
ellysh/zero-cache-utils,ellysh/zero-cache-utils
--- +++ @@ -1,18 +1,29 @@ #!/usr/bin/env python +import sys import client_wrap -def main(): - client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0) - +def get_keys(client): key_str = client.GetKeys() keys = key_str.split (';') del keys[-1] if len(keys) == 0: ...
4987275ab868aa98359d6583c7817c4adf09000b
zipeggs.py
zipeggs.py
import logging, os, zc.buildout, sys, shutil class ZipEggs: def __init__(self, buildout, name, options): self.name, self.options = name, options if options['target'] is None: raise zc.buildout.UserError('Invalid Target') if options['source'] is None: raise zc.buildou...
import logging, os, zc.buildout, sys, shutil class ZipEggs: def __init__(self, buildout, name, options): self.name, self.options = name, options if options['target'] is None: raise zc.buildout.UserError('Invalid Target') if options['source'] is None: raise zc.buildou...
Improve variable names for clarity
Improve variable names for clarity
Python
apache-2.0
tamizhgeek/zipeggs
--- +++ @@ -10,19 +10,19 @@ def zipit(self): - target = self.options['target'] - if not os.path.exists(target): - os.mkdir(target) - path = self.options['source'] - for dirs in os.listdir(path): + target_dir = self.options['target'] + if not os.path.exists...
7396b20c3ee1b037580463c9a653e782c197e536
xdocker/run_worker.py
xdocker/run_worker.py
from rq import Connection, Queue, Worker def worker_exc_handler(job, exc_type, exc_value, traceback): job.meta['exc_code'] = exc_type.code job.meta['exc_message'] = exc_type.message return True def main(): with Connection(): q = Queue() worker = Worker([q]) worker.push_exc_ha...
from rq import Connection, Queue, Worker from worker.exceptions import WorkerException def worker_exc_handler(job, exc_type, exc_value, traceback): if isinstance(exc_type, WorkerException): job.meta['exc_code'] = exc_type.code job.meta['exc_message'] = exc_type.message return True def main()...
Fix worker exception handler for non workerexceptions
Fix worker exception handler for non workerexceptions
Python
apache-2.0
XDocker/Engine,XDocker/Engine
--- +++ @@ -1,9 +1,11 @@ from rq import Connection, Queue, Worker +from worker.exceptions import WorkerException def worker_exc_handler(job, exc_type, exc_value, traceback): - job.meta['exc_code'] = exc_type.code - job.meta['exc_message'] = exc_type.message + if isinstance(exc_type, WorkerException): +...
e2a6fe346a8fac07c9c7bd4166ed45fd641faaf6
royalfilms/movies/api.py
royalfilms/movies/api.py
from .serializers import MovieSerializer from .models import Movie from rest_framework import generics from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from rest_framework import permissions class MovieList(generics.ListCreateAPIView): """ ...
from .serializers import MovieSerializer from .models import Movie from rest_framework import generics from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from rest_framework import permissions class MovieList(generics.ListAPIView): """ API ...
Remove admin restictions to movies endpoint
Remove admin restictions to movies endpoint
Python
mit
juliancantillo/royal-films,juliancantillo/royal-films,juliancantillo/royal-films,juliancantillo/royal-films
--- +++ @@ -8,10 +8,10 @@ from rest_framework import permissions -class MovieList(generics.ListCreateAPIView): +class MovieList(generics.ListAPIView): """ API class for list all Movies from a thread, or create a new Movie. """ - permission_classes = (permissions.IsAdminUser,) + # permission_...
260cb862f5324387d796826d76ff224c01ca5036
localore/localore_admin/migrations/0003_auto_20160316_1646.py
localore/localore_admin/migrations/0003_auto_20160316_1646.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('localore_admin', '0002_auto_20160316_1444'), ] operations = [ migrations.RenameField( model_name='localoreimage'...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('localore_admin', '0002_auto_20160316_1444'), ] run_before = [ ('home', '0002_create_homepage'), ] operations = [ ...
Fix migrations dependency issue caused by 990563e.
Fix migrations dependency issue caused by 990563e.
Python
mpl-2.0
ghostwords/localore,ghostwords/localore,ghostwords/localore
--- +++ @@ -10,6 +10,10 @@ ('localore_admin', '0002_auto_20160316_1444'), ] + run_before = [ + ('home', '0002_create_homepage'), + ] + operations = [ migrations.RenameField( model_name='localoreimage',
3d5902b341e15a6d5f8ba1599902b6f9327a021b
typedjsonrpc/errors.py
typedjsonrpc/errors.py
"""This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): super(Error, self).__init__() self.data = data def as_error_object(self): """Turns the...
"""This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): super(Error, self).__init__(self.code, self.message, data) self.data = data def as_error_objec...
Make exception messages more descriptive
Make exception messages more descriptive
Python
apache-2.0
palantir/typedjsonrpc,palantir/typedjsonrpc
--- +++ @@ -8,7 +8,7 @@ data = None def __init__(self, data=None): - super(Error, self).__init__() + super(Error, self).__init__(self.code, self.message, data) self.data = data def as_error_object(self):