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 |
|---|---|---|---|---|---|---|---|---|---|---|
184b64da2a4fa0d8827d839501e12317f9adfa46 | simple-cipher/simple_cipher.py | simple-cipher/simple_cipher.py | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = Cipher._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.ke... | import math
import secrets
from string import ascii_lowercase
class Cipher(object):
def __init__(self, key=None):
if not key:
key = self._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
self.key ... | Use super() and self within the Cipher and Caesar classes | Use super() and self within the Cipher and Caesar classes
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -6,7 +6,7 @@
class Cipher(object):
def __init__(self, key=None):
if not key:
- key = Cipher._random_key()
+ key = self._random_key()
if not key.isalpha() or not key.islower():
raise ValueError("Key must consist only of lowercase letters")
... |
b0011541a21927c4f9ee378b77b11fd4b0dfbcff | tests/test_cookiecutter_substitution.py | tests/test_cookiecutter_substitution.py | import re
import sh
from .base import DjangoCookieTestCase
class TestCookiecutterSubstitution(DjangoCookieTestCase):
"""Test that all cookiecutter instances are substituted"""
def test_all_cookiecutter_instances_are_substituted(self):
# Build a list containing absolute paths to the generated files
... | import re
import sh
from .base import DjangoCookieTestCase
class TestCookiecutterSubstitution(DjangoCookieTestCase):
"""Test that all cookiecutter instances are substituted"""
def test_all_cookiecutter_instances_are_substituted(self):
# Build a list containing absolute paths to the generated files
... | Fix tests for python 3 | Fix tests for python 3
| Python | bsd-3-clause | wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials | ---
+++
@@ -18,7 +18,7 @@
# Assert that no match is found in any of the files
for path in paths:
- for line in open(path, 'r'):
+ for line in open(path, 'r', encoding='utf-8', errors='ignore'):
match = re_obj.search(line)
self.assertIsNone(
... |
35fa85aa850dbdf6c81e0952911a40755aca5774 | dags/main_summary.py | dags/main_summary.py | from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': 'mreid@mozilla.com',
'depends_on_past': False,
'start_date': datetime(2016, 6, 27),
'email': ['telemetry-alerts... | from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator
default_args = {
'owner': 'mreid@mozilla.com',
'depends_on_past': False,
'start_date': datetime(2016, 6, 27),
'email': ['telemetry-alerts... | Increase timeout to 10 hours (temporarily). | Increase timeout to 10 hours (temporarily).
The job is expected to take 3-4 hours, but was intermittently
timing out at 6 hours. Increase to 10 hours while profiling and
debugging the job.
| Python | mpl-2.0 | opentrials/opentrials-airflow,opentrials/opentrials-airflow | ---
+++
@@ -23,7 +23,7 @@
t1 = EMRSparkOperator(task_id="main_summary",
job_name="Main Summary View",
- execution_timeout=timedelta(hours=6),
+ execution_timeout=timedelta(hours=10),
instance_count=10,
en... |
055966bb3cf16d3d0ef5e03c5da85f6479ae6a0e | examples/annotation.py | examples/annotation.py | import os
from os.path import join as pjoin
from surfer import io
from surfer import viz
subj_dir = os.environ["SUBJECTS_DIR"]
subject_id = 'fsaverage'
sub = 'fsaverage'
hemi = 'lh'
surf = 'inflated'
data_path = pjoin(subj_dir, subject_id)
annot_path = pjoin(data_path, "label", "%s.aparc.annot" % "lh")
brain = viz.... | import os
from os.path import join as pjoin
from surfer import io
from surfer import viz
subj_dir = os.environ["SUBJECTS_DIR"]
subject_id = 'fsaverage'
sub = 'fsaverage'
hemi = 'lh'
surf = 'inflated'
data_path = pjoin(subj_dir, subject_id)
annot_path = pjoin(data_path, "label", "%s.aparc.annot" % "lh")
brain = viz.... | FIX : kwarg pb with annot contour in example | FIX : kwarg pb with annot contour in example
| Python | bsd-3-clause | effigies/PySurfer,nipy/PySurfer,mwaskom/PySurfer,haribharadwaj/PySurfer,diego0020/PySurfer,Eric89GXL/PySurfer,bpinsard/PySurfer | ---
+++
@@ -14,7 +14,7 @@
annot_path = pjoin(data_path, "label", "%s.aparc.annot" % "lh")
brain = viz.Brain(sub, hemi, surf)
-brain.add_annotation(annot_path, contour=True)
+brain.add_annotation(annot_path, borders=True)
# show all views
brain.show_view('lateral')
|
29aa5847feba9d5efceec2014d3524867b4284e1 | go/testsettings.py | go/testsettings.py | import os
from settings import *
# This needs to point at the test riak buckets.
VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'}
VUMI_API_CONFIG['redis_manager'] = {
'key_prefix': 'test',
'FAKE_REDIS': 'sure',
}
if os.environ.get('VUMIGO_FAST_TESTS'):
DATABASES = {
'default': {
... | import os
from settings import *
SECRET_KEY = "test_secret"
# This needs to point at the test riak buckets.
VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'}
VUMI_API_CONFIG['redis_manager'] = {
'key_prefix': 'test',
'FAKE_REDIS': 'sure',
}
if os.environ.get('VUMIGO_FAST_TESTS'):
DATABASES = ... | Add SECRET_KEY which is required by Django 1.5. | Add SECRET_KEY which is required by Django 1.5.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -1,5 +1,7 @@
import os
from settings import *
+
+SECRET_KEY = "test_secret"
# This needs to point at the test riak buckets.
VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'} |
a6b14d2f80355e556c466b52b518dc808c90c54a | polling_stations/settings/static_files.py | polling_stations/settings/static_files.py | from dc_theme.settings import get_pipeline_settings
from dc_theme.settings import STATICFILES_FINDERS
STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
PIPELINE = get_pipeline_settings(
extra_css=[
'custom_css/style.scss',
'font-awesome/css/font-awesome.min.css',
],
extra_js=[],
)
PI... | from dc_theme.settings import get_pipeline_settings
from dc_theme.settings import STATICFILES_FINDERS, STATICFILES_STORAGE
PIPELINE = get_pipeline_settings(
extra_css=[
'custom_css/style.scss',
'font-awesome/css/font-awesome.min.css',
],
extra_js=[],
)
PIPELINE['STYLESHEETS']['map'] = {
... | Remove old pipeline and compressor settings | Remove old pipeline and compressor settings
libsass has a compresssion mode that's enabled by default in the 0.3
dc base theme. This removes the need for uglifyjs
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | ---
+++
@@ -1,6 +1,5 @@
from dc_theme.settings import get_pipeline_settings
-from dc_theme.settings import STATICFILES_FINDERS
-STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
+from dc_theme.settings import STATICFILES_FINDERS, STATICFILES_STORAGE
PIPELINE = get_pipeline_settings(
extra_css=[
@@ -9,... |
63e5bd0e7c771e4a2efe2ff203b75e4a56024af5 | app.py | app.py | """
Main entry point of the logup-factory
"""
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask import request
from flask import render_template
app = Flask(__name__)
app.config.from_pyfile('flask-conf.cfg')
db = MongoEngine(app)
@app.route('/')
def index():
return render_templat... | """
Main entry point of the logup-factory
"""
from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask import request
from flask import render_template
app = Flask(__name__, static_url_path='', static_folder='frontend/dist')
app.config.from_pyfile('flask-conf.cfg')
# db = MongoEngine(app)
@... | Change static directory, commented mongo dev stuff | Change static directory, commented mongo dev stuff
| Python | mit | cogniteev/logup-factory,cogniteev/logup-factory | ---
+++
@@ -8,10 +8,10 @@
from flask import request
from flask import render_template
-app = Flask(__name__)
+app = Flask(__name__, static_url_path='', static_folder='frontend/dist')
app.config.from_pyfile('flask-conf.cfg')
-db = MongoEngine(app)
+# db = MongoEngine(app)
@app.route('/')
def index(): |
58823e20e3891cea7198be15b7c85395521086e1 | extension_course/tests/conftest.py | extension_course/tests/conftest.py | import pytest
from django.conf import settings
from django.core.management import call_command
from events.tests.conftest import (administrative_division, administrative_division_type, data_source, event, # noqa
location_id, minimal_event_dict, municipality, organization, place, use... | import pytest
from events.tests.conftest import (administrative_division, administrative_division_type, data_source, event, # noqa
location_id, minimal_event_dict, municipality, organization, place, user,
user_api_client, django_db_modify_db_setting... | Remove some needless code from course extension tests | Remove some needless code from course extension tests
| Python | mit | City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents | ---
+++
@@ -1,26 +1,7 @@
import pytest
-from django.conf import settings
-from django.core.management import call_command
-
from events.tests.conftest import (administrative_division, administrative_division_type, data_source, event, # noqa
location_id, minimal_event_dict, munic... |
f999b821fc00216d13759eb028f0fbd57352fa35 | flocker/docs/version_code_block.py | flocker/docs/version_code_block.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Sphinx extension to add a ``version-code-block`` directive
This directive allows Flocker's release version to be inserted into code
blocks.
.. version-code-block:: rest
$ brew install flocker-|RELEASE|
"""
from sphinx.directives.code import CodeBl... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Sphinx extension to add a ``version-code-block`` directive
This directive allows Flocker's release version to be inserted into code
blocks.
.. version-code-block:: console
$ brew install flocker-|RELEASE|
"""
from sphinx.directives.code import Cod... | Use console highlighting in example | Use console highlighting in example
| Python | apache-2.0 | jml/flocker,Azulinho/flocker,jml/flocker,w4ngyi/flocker,jml/flocker,AndyHuu/flocker,mbrukman/flocker,LaynePeng/flocker,AndyHuu/flocker,runcom/flocker,runcom/flocker,agonzalezro/flocker,adamtheturtle/flocker,agonzalezro/flocker,1d4Nf6/flocker,LaynePeng/flocker,mbrukman/flocker,w4ngyi/flocker,moypray/flocker,lukemarsden/... | ---
+++
@@ -6,7 +6,7 @@
This directive allows Flocker's release version to be inserted into code
blocks.
-.. version-code-block:: rest
+.. version-code-block:: console
$ brew install flocker-|RELEASE|
""" |
65ed7106126effc922df2bf7252a3c840d9bc768 | hasjob/__init__.py | hasjob/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import environ
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.assets import Environment, Bundle
from coaster import configureapp
# First, make an app and config it
app = Flask(__name__, instance_relative_config=True)
configureapp(app, 'HAS... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import environ
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.assets import Environment, Bundle
from coaster import configureapp
# First, make an app and config it
app = Flask(__name__, instance_relative_config=True)
configureapp(app, 'HAS... | Remove duplicate code, leave comment about circular imports | Remove duplicate code, leave comment about circular imports
| Python | agpl-3.0 | hasgeek/hasjob,ashwin01/hasjob,nhannv/hasjob,qitianchan/hasjob,ashwin01/hasjob,hasgeek/hasjob,qitianchan/hasjob,sindhus/hasjob,sindhus/hasjob,hasgeek/hasjob,sindhus/hasjob,ashwin01/hasjob,ashwin01/hasjob,sindhus/hasjob,qitianchan/hasjob,nhannv/hasjob,qitianchan/hasjob,sindhus/hasjob,qitianchan/hasjob,nhannv/hasjob,hasg... | ---
+++
@@ -14,6 +14,7 @@
mail = Mail()
mail.init_app(app)
assets = Environment(app)
+# Imported here to prevent circular imports
from uploads import configure
from search import configure
uploads.configure()
@@ -35,9 +36,5 @@
import hasjob.models
import hasjob.views
-from uploads import configure
-from sea... |
d6a8b995f2a1b069729f07ef43b966b2f15fd3b3 | linter.py | linter.py | from SublimeLinter.lint import NodeLinter
class XO(NodeLinter):
npm_name = 'xo'
cmd = ('xo', '--stdin', '--reporter', 'compact', '--filename', '@')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
defaults = {
'selector': 'sourc... | from SublimeLinter.lint import NodeLinter
class XO(NodeLinter):
npm_name = 'xo'
cmd = ('xo', '--stdin', '--reporter', 'compact', '--filename', '${file}')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
r' \((?P<code>.+)\)$'
)
def... | Support the new SublimeLinter `code` property | Support the new SublimeLinter `code` property
| Python | mit | sindresorhus/SublimeLinter-contrib-xo,sindresorhus/SublimeLinter-contrib-xo | ---
+++
@@ -2,11 +2,12 @@
class XO(NodeLinter):
npm_name = 'xo'
- cmd = ('xo', '--stdin', '--reporter', 'compact', '--filename', '@')
+ cmd = ('xo', '--stdin', '--reporter', 'compact', '--filename', '${file}')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>War... |
c5b2cb667a59cf6fa16c860744fd5978cd3c01a2 | src/lexington/util/paths.py | src/lexington/util/paths.py | from urllib import parse
from werkzeug.wrappers import Request
from lexington.util.di import depends_on
@depends_on(['environ'])
def get_request(environ):
return Request(environ)
# TODO: clean up all of these...
@depends_on(['environ'])
def get_method(environ):
return environ['REQUEST_METHOD']
@depends_on([... | from werkzeug.wrappers import Request
from lexington.util.di import depends_on
@depends_on(['environ'])
def get_request(environ):
return Request(environ)
@depends_on(['request'])
def get_method(request):
return request.method
@depends_on(['request'])
def get_path(request):
return request.path
@depends_... | Reduce direct dependencies on environ | Reduce direct dependencies on environ
| Python | mit | jmikkola/Lexington | ---
+++
@@ -1,4 +1,3 @@
-from urllib import parse
from werkzeug.wrappers import Request
from lexington.util.di import depends_on
@@ -7,22 +6,21 @@
def get_request(environ):
return Request(environ)
-# TODO: clean up all of these...
-@depends_on(['environ'])
-def get_method(environ):
- return environ['RE... |
2dc34a9952fda8a46a89aa43ea833c36998d891a | shop/models/fields.py | shop/models/fields.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from distutils.version import LooseVersion
import re
from django.db import connection
POSTGRES_FLAG = False
if str(connection.vendor) == 'postgresql':
POSTGRES_FLAG = True
try:
import psycopg2
version = re.search('([0-9.]+)', psycopg2.__vers... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from distutils.version import LooseVersion
import re
from django.db import connection
POSTGRES_FLAG = False
if str(connection.vendor) == 'postgresql':
POSTGRES_FLAG = True
try:
import psycopg2
version = re.search('([0-9.]+)', psycopg2.__vers... | Add psycopg2's version to the comment | Add psycopg2's version to the comment
| Python | bsd-3-clause | nimbis/django-shop,jrief/django-shop,khchine5/django-shop,divio/django-shop,divio/django-shop,divio/django-shop,khchine5/django-shop,awesto/django-shop,nimbis/django-shop,awesto/django-shop,nimbis/django-shop,jrief/django-shop,awesto/django-shop,jrief/django-shop,khchine5/django-shop,nimbis/django-shop,khchine5/django-... | ---
+++
@@ -12,8 +12,8 @@
import psycopg2
version = re.search('([0-9.]+)', psycopg2.__version__ or "0").group(0)
- # To be able to use the Django version of JSONField, it requires to have PostgreSQL ≥ 9.4 , otherwise some issues
- # could be faced.
+ # To be able to use the Django version of JSO... |
a928039c32e1991ec0892ec202d22c43d0add0c2 | config/urls.py | config/urls.py | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from jobs_backend.views import APIRoot
api_urlpatterns = [
# All api endpoints should be included here
url(r'^users/', include('jobs_backend.users.urls.users'... | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from jobs_backend.views import APIRoot
api_urlpatterns = [
# All api endpoints should be included here
url(r'^users/', include('jobs_backend.users.urls.users'... | Fix browsable API index regexp | jobs-041: Fix browsable API index regexp
| Python | mit | pyshopml/jobs-backend,pyshopml/jobs-backend | ---
+++
@@ -20,7 +20,7 @@
]
urlpatterns += [
- url(r'^$', APIRoot.as_view(urlpatterns=urlpatterns, app_namespace='api_v1'), name='api_root')
+ url(r'^api/$', APIRoot.as_view(urlpatterns=urlpatterns, app_namespace='api_v1'), name='api_root')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
... |
cdac109151b3ed804ae889155c140a485653aa40 | wex/__init__.py | wex/__init__.py | """
Wextracto is a library for extracting data from web resources.
:copyright: (c) 2012-2016
"""
__version__ = '0.9.0' # pragma: no cover
| """
Wextracto is a library for extracting data from web resources.
:copyright: (c) 2012-2016
"""
__version__ = '0.9.1' # pragma: no cover
| Bump version for nested cache fix | Bump version for nested cache fix
| Python | bsd-3-clause | gilessbrown/wextracto,eBay/wextracto,eBay/wextracto,gilessbrown/wextracto | ---
+++
@@ -5,4 +5,4 @@
"""
-__version__ = '0.9.0' # pragma: no cover
+__version__ = '0.9.1' # pragma: no cover |
a0e0e70f2ae37bfb3c460324b4aea961f2ea0afb | dallinger/heroku/worker.py | dallinger/heroku/worker.py | """Heroku web worker."""
import os
import redis
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__': # pragma: nocover
# These imports are inside the __main__ block
# to make sure that we only import fr... | """Heroku web worker."""
import os
import redis
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__': # pragma: nocover
# These imports are inside the __main__ block
# to make sure that we only import fr... | Make sure bot jobs can be deserialized | Make sure bot jobs can be deserialized
| Python | mit | Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger | ---
+++
@@ -24,6 +24,9 @@
except ImportError:
from rq import Worker
+ from dallinger.config import initialize_experiment_package
+ initialize_experiment_package(os.getcwd())
+
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
|
b812843f03fd0da920872c109132aee7fae82b3a | tests/instancing_tests/NonterminalsTest.py | tests/instancing_tests/NonterminalsTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 31.08.2017 11:55
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import *
from grammpy.exceptions import TreeDeletedException
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class From(Rul... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 31.08.2017 11:55
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import *
from grammpy.exceptions import TreeDeletedException
class A(Nonterminal): pass
class B(Nonterminal): pass
class C(Nonterminal): pass
class From(Rul... | Add test of deleteing child for nonterminal | Add test of deleteing child for nonterminal
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -41,6 +41,13 @@
with self.assertRaises(TreeDeletedException):
a.from_rule
+ def test_shouldNotDeleteChild(self):
+ a = A()
+ t = To()
+ a._set_to_rule(t)
+ del t
+ a.to_rule
+
if __name__ == '__main__': |
1d321bb0bd6b8e5b6fc14704a6d1b29a365855d8 | goatctf/core/models.py | goatctf/core/models.py | from django.contrib.auth.models import User
from django.db import models
import markdown
from core.settings import CHALLENGE_NAME_LENGTH, FLAG_LENGTH, TEAM_NAME_LENGTH
class Challenge(models.Model):
"""A challenge represents an individual problem to be solved."""
name = models.CharField(max_length=CHALLENGE_... | from django.contrib.auth.models import User
from django.db import models
import markdown
from core.settings import CHALLENGE_NAME_LENGTH, FLAG_LENGTH, TEAM_NAME_LENGTH
class Challenge(models.Model):
"""A challenge represents an individual problem to be solved."""
CATEGORY_CHOICES = (
('be', 'Beer'),... | Add choices for challenge category | Add choices for challenge category
| Python | mit | Without-Proper-Instructions/GoatCTF | ---
+++
@@ -7,9 +7,21 @@
class Challenge(models.Model):
"""A challenge represents an individual problem to be solved."""
+
+ CATEGORY_CHOICES = (
+ ('be', 'Beer'),
+ ('cr', 'Crypto'),
+ ('ex', 'Exploitation'),
+ ('fo', 'Forensics'),
+ ('rn', 'Recon'),
+ ('re', 'Rev... |
6cbfee67047ac43d00bd1ff8fabb11dc33314aff | ledctl/ledctl.py | ledctl/ledctl.py | from flask import Flask, request
import pigpio
app = Flask(__name__)
#rgb 22, 27, 17
#base teal 40 97 15
GPIO_RED = 22
GPIO_GREEN = 27
GPIO_BLUE = 17
def to_PWM_dutycycle(string):
try:
i = int(string)
if i < 0:
i = 0
elif i > 255:
i = 255
return i
excep... | from flask import Flask, request
import pigpio
app = Flask(__name__)
#rgb 22, 27, 17
#base teal 40 97 15
GPIO_RED = 22
GPIO_GREEN = 27
GPIO_BLUE = 17
pi = pigpio.pi()
def to_PWM_dutycycle(string):
try:
i = int(string)
if i < 0:
i = 0
elif i > 255:
i = 255
r... | Create only one instance of pigpio | Create only one instance of pigpio
| Python | mit | ayoy/ledctl | ---
+++
@@ -8,6 +8,7 @@
GPIO_RED = 22
GPIO_GREEN = 27
GPIO_BLUE = 17
+pi = pigpio.pi()
def to_PWM_dutycycle(string):
try:
@@ -30,7 +31,6 @@
r = to_PWM_dutycycle(args['r'])
g = to_PWM_dutycycle(args['g'])
b = to_PWM_dutycycle(args['b'])
- pi = pigpio.pi()
pi.set_PWM_dutycycle(GPIO_RED... |
8b8fea0a212fb93118debc26306ed783196d96a0 | models.py | models.py | from google.appengine.ext import db
from google.appengine.api.users import User
class Cfp(db.Model):
name = db.StringProperty()
fullname = db.StringProperty()
website = db.LinkProperty()
begin_conf_date = db.DateProperty()
end_conf_date = db.DateProperty()
submission_deadline = db.DateProperty(... | from google.appengine.ext import db
from google.appengine.api.users import User
class Cfp(db.Model):
name = db.StringProperty()
fullname = db.StringProperty()
website = db.LinkProperty()
begin_conf_date = db.DateProperty()
end_conf_date = db.DateProperty()
submission_deadline = db.DateProperty(... | Correct bug introduced in the previous commit (last update in feed entries). | Correct bug introduced in the previous commit (last update in feed entries).
| Python | mit | CaptainPatate/ascfpmfsrt | ---
+++
@@ -23,5 +23,5 @@
def setAcceptanceRate(self, rate):
self.rate = db.Rating(rate)
- def rfc3339_update():
- return last_update.strftime('%Y-%m-%dT%H:%M:%SZ')
+ def rfc3339_update(self):
+ return self.last_update.strftime('%Y-%m-%dT%H:%M:%SZ') |
d30358485b78a1257535f8d61611cac168584625 | models.py | models.py | from scipy.io import loadmat
import numpy as np
import keras
from keras.preprocessing.image import load_img, img_to_array
from keras.models import Sequential
from keras.layers import Activation
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
num_classes = 10
# input ima... | Add load image and create array data | Add load image and create array data
| Python | mit | shioyang/model-comparator,shioyang/model-comparator,shioyang/model-comparator,shioyang/model-comparator | ---
+++
@@ -0,0 +1,82 @@
+from scipy.io import loadmat
+import numpy as np
+import keras
+from keras.preprocessing.image import load_img, img_to_array
+from keras.models import Sequential
+from keras.layers import Activation
+from keras.layers import Dense, Dropout, Flatten
+from keras.layers import Conv2D, MaxPoolin... | |
068675a641dc412416624c907fe7b1744d007a99 | lib/js/Loader.py | lib/js/Loader.py | #
# JavaScript Tools
# Copyright 2010 Sebastian Werner
#
from js.core.Profiler import *
import logging
class Loader():
def __init__(self, classList):
self.__classList = classList
def generate(self, fileName=None, bootCode=None):
result = ["$LAB"]
pstart()
log... | #
# JavaScript Tools
# Copyright 2010 Sebastian Werner
#
from js.core.Profiler import *
import logging
class Loader():
def __init__(self, classList):
self.__classList = classList
def generate(self, fileName=None, bootCode=None):
result = ["$LAB"]
pstart()
log... | Make use of array support in script() of LABjs to fix recursion errors | Make use of array support in script() of LABjs to fix recursion errors
| Python | mit | zynga/jasy,sebastian-software/jasy,zynga/jasy,sebastian-software/jasy | ---
+++
@@ -17,12 +17,14 @@
pstart()
logging.info("Generating loader...")
+ scripts = []
for classObj in self.__classList:
if classObj == "WAIT":
- result.append("wait()")
+ result.append('script(["%s"]).wait()' % '","'.join(script... |
f8b35e2a0cf092441efe1350871814fd347d3627 | tests/classifier/LinearSVC/LinearSVCJavaTest.py | tests/classifier/LinearSVC/LinearSVCJavaTest.py | # -*- coding: utf-8 -*-
from unittest import TestCase
from sklearn.svm.classes import LinearSVC
from ..Classifier import Classifier
from ...language.Java import Java
class LinearSVCJavaTest(Java, Classifier, TestCase):
def setUp(self):
super(LinearSVCJavaTest, self).setUp()
self.mdl = LinearSV... | # -*- coding: utf-8 -*-
from unittest import TestCase
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA, NMF
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
... | Add test for using optimizers | Add test for using optimizers
| Python | bsd-3-clause | nok/sklearn-porter | ---
+++
@@ -2,8 +2,15 @@
from unittest import TestCase
+from sklearn.datasets import load_digits
+from sklearn.decomposition import PCA, NMF
+from sklearn.feature_selection import SelectKBest
+from sklearn.feature_selection import chi2
+from sklearn.model_selection import GridSearchCV
+from sklearn.pipeline impo... |
237a66191295cce2cd52d78bcdb7cbe57e399e56 | awx/main/management/commands/remove_instance.py | awx/main/management/commands/remove_instance.py | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved
from django.core.management.base import CommandError
from awx.main.management.commands._base_instance import BaseCommandInstance
from awx.main.models import Instance
instance_str = BaseCommandInstance.instance_str
class Command(BaseCommandInstance):
"""In... | # Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved
from django.core.management.base import CommandError
from awx.main.management.commands._base_instance import BaseCommandInstance
from awx.main.models import Instance
instance_str = BaseCommandInstance.instance_str
class Command(BaseCommandInstance):
"""In... | Fix verbage around why we are disallowing removing a primary | Fix verbage around why we are disallowing removing a primary
| Python | apache-2.0 | wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx | ---
+++
@@ -33,7 +33,7 @@
# Sanity check: Do not remove the primary instance.
if instance.primary:
- raise CommandError('I cowardly refuse to remove the primary instance %s.' % instance_str(instance))
+ raise CommandError('Can not remove primary instance %s. A... |
726f4d016a6e0e3c4d6c053afc98bfcae445620c | test_setup.py | test_setup.py | """Test setup.py."""
import os
import subprocess
import sys
def test_setup():
"""Run setup.py check."""
command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict']
assert subprocess.run(command).returncode == 0
def test_console_scripts():
"""Ensure console scripts were installed corr... | """Test setup.py."""
import os
import subprocess
import sys
def test_setup():
"""Run setup.py check."""
command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict']
assert subprocess.run(command).returncode == 0
def test_console_scripts():
"""Ensure console scripts were installed corr... | Use os.environ['PATH'] instead of sys.path | Use os.environ['PATH'] instead of sys.path
| Python | bsd-3-clause | dmtucker/keysmith | ---
+++
@@ -16,5 +16,5 @@
"""Ensure console scripts were installed correctly."""
assert any(
os.path.isfile(os.path.join(directory, 'keysmith'))
- for directory in sys.path
+ for directory in os.environ['PATH'].split(':')
) |
22f52f97db77e0127172721eacc98196d32a77d7 | Lib/importlib/test/import_/util.py | Lib/importlib/test/import_/util.py | import functools
import importlib._bootstrap
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib._bootstrap.__import__(*args, **kwa... | import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib._... | Move a test-skipping decorator over to unittest.skipIf. | Move a test-skipping decorator over to unittest.skipIf.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,5 +1,7 @@
import functools
+import importlib
import importlib._bootstrap
+import unittest
using___import__ = False
@@ -13,16 +15,7 @@
return importlib._bootstrap.__import__(*args, **kwargs)
-def importlib_only(fxn):
- """Decorator to mark which tests are not supported by the curre... |
0869ee91df9e379ac538300cabd6ef2c9e771c7b | plugins/admin.py | plugins/admin.py | import binascii
import git
import sys
import os
import logging
logger = logging.getLogger('root')
__match__ = r"!update|!reload"
def on_message(bot, channel, user, message):
requires_reload = message == '!reload'
if message == '!update':
local = git.Repo(os.getcwd())
origin = git.remote.Remo... | import binascii
import git
import sys
import os
import logging
logger = logging.getLogger('root')
__match__ = r"!update|!reload"
def on_message(bot, channel, user, message):
requires_reload = message == '!reload'
if message == '!update':
local = git.Repo(os.getcwd())
origin = git.remote.Remo... | Use previous commit as reference point for updates | Use previous commit as reference point for updates
| Python | mit | kvchen/keffbot-py,kvchen/keffbot | ---
+++
@@ -14,11 +14,11 @@
if message == '!update':
local = git.Repo(os.getcwd())
origin = git.remote.Remote(local, 'origin')
- head = local.heads[0]
+ prev_commit = local.heads[0].commit
logger.info("Updating from origin repository")
for pull_info in origin.p... |
f641be2a8b841eea71f9a0fb5709972debb99df3 | stingray/bispectrum.py | stingray/bispectrum.py | from __future__ import division
import numpy as np
from stingray import lightcurve
class Bispectrum(object):
def __init__(self, lc, maxlag, scale=None):
self.lc = lc
# change to fs = 1/lc.dt
self.maxlag = maxlag
self.scale = scale
self.fs = None
# Outputs
... | from __future__ import division
import numpy as np
from stingray import lightcurve
class Bispectrum(object):
def __init__(self, lc, maxlag, scale=None):
def __init__(self, lc, maxlag, scale=None):
self._make_bispetrum(lc, maxlag, scale)
def _make_bispetrum(self, lc, maxlag, scale):
... | Make Bispectrum object assign values to attributes | Make Bispectrum object assign values to attributes
| Python | mit | pabell/stingray,StingraySoftware/stingray,evandromr/stingray,abigailStev/stingray | ---
+++
@@ -5,14 +5,42 @@
class Bispectrum(object):
def __init__(self, lc, maxlag, scale=None):
- self.lc = lc
- # change to fs = 1/lc.dt
- self.maxlag = maxlag
- self.scale = scale
- self.fs = None
-
- # Outputs
+ def __init__(self, lc, maxlag, scale=Non... |
04de16d7287bad5023b34efc072e104d8b35c29a | test/test.py | test/test.py | from RPi import GPIO
GPIO.setmode(GPIO.BCM)
num_pins = 28
pins = range(num_pins)
for pin in pins:
GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP)
pin_states = {pin: GPIO.input(pin) for pin in pins}
print()
for pin, state in pin_states.items():
print("%2d: %s" % (pin, state))
active = sum(pin_states.values())
inact... | from RPi import GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
num_pins = 28
pins = range(num_pins)
for pin in pins:
GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP)
pin_states = {pin: GPIO.input(pin) for pin in pins}
print()
for pin, state in pin_states.items():
print("%2d: %s" % (pin, state))
active = [pin f... | Add printing of active/inactive pins | Add printing of active/inactive pins
| Python | bsd-3-clause | raspberrypilearning/dots,RPi-Distro/python-rpi-dots | ---
+++
@@ -1,6 +1,7 @@
from RPi import GPIO
GPIO.setmode(GPIO.BCM)
+GPIO.setwarnings(False)
num_pins = 28
@@ -15,9 +16,13 @@
for pin, state in pin_states.items():
print("%2d: %s" % (pin, state))
-active = sum(pin_states.values())
-inactive = num_pins - active
+active = [pin for pin, state in pin_sta... |
5b00010451f9ea58936f98b72737a646d77e1bd9 | server/tests/forms/test_RegistrationForm.py | server/tests/forms/test_RegistrationForm.py | import wtforms_json
import pytest
from forms.RegistrationForm import RegistrationForm
wtforms_json.init()
class TestRegistrationForm:
def test_valid(self):
json = {
'username': 'someusername',
'password': 'password',
'confirm': 'confirm',
'email': 'someem... | import pytest
from forms.RegistrationForm import RegistrationForm
class TestRegistrationForm:
def test_valid(self):
json = {
'username': 'someusername',
'password': 'password',
'confirm': 'password',
'email': 'someemail@email.com'
}
form =... | Add tests for failing registration forms | Add tests for failing registration forms
| Python | mit | ganemone/ontheside,ganemone/ontheside,ganemone/ontheside | ---
+++
@@ -1,9 +1,6 @@
-import wtforms_json
import pytest
from forms.RegistrationForm import RegistrationForm
-
-wtforms_json.init()
class TestRegistrationForm:
@@ -12,9 +9,55 @@
json = {
'username': 'someusername',
'password': 'password',
- 'confirm': 'confirm'... |
c31bc6f1b0782a7d9c409e233a363be651594006 | exporters/decompressors.py | exporters/decompressors.py | from exporters.pipeline.base_pipeline_item import BasePipelineItem
import logging
import zlib
__all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor']
class BaseDecompressor(BasePipelineItem):
def decompress(self):
raise NotImplementedError()
def create_decompressor():
# create zlib dec... | from exporters.pipeline.base_pipeline_item import BasePipelineItem
import sys
import zlib
import six
__all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor']
class BaseDecompressor(BasePipelineItem):
def decompress(self):
raise NotImplementedError()
def create_decompressor():
# create z... | Append information to the zlib error | Append information to the zlib error
| Python | bsd-3-clause | scrapinghub/exporters | ---
+++
@@ -1,6 +1,7 @@
from exporters.pipeline.base_pipeline_item import BasePipelineItem
-import logging
+import sys
import zlib
+import six
__all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor']
@@ -29,10 +30,10 @@
stream.unshift(dec.unused_data)
dec =... |
761aff647d3e20fc25f1911efa5d2235fe4b21d8 | modoboa/extensions/admin/forms/forward.py | modoboa/extensions/admin/forms/forward.py | from django import forms
from django.utils.translation import ugettext as _, ugettext_lazy
from modoboa.lib.exceptions import BadRequest, PermDeniedException
from modoboa.lib.emailutils import split_mailbox
from modoboa.extensions.admin.models import (
Domain
)
class ForwardForm(forms.Form):
dest = forms.Char... | from django import forms
from django.utils.translation import ugettext as _, ugettext_lazy
from modoboa.lib.exceptions import BadRequest, PermDeniedException
from modoboa.lib.emailutils import split_mailbox
from modoboa.extensions.admin.models import (
Domain
)
class ForwardForm(forms.Form):
dest = forms.Char... | Add "form-control" attribute to some textareas | Add "form-control" attribute to some textareas
| Python | isc | modoboa/modoboa,RavenB/modoboa,mehulsbhatt/modoboa,bearstech/modoboa,modoboa/modoboa,RavenB/modoboa,tonioo/modoboa,bearstech/modoboa,mehulsbhatt/modoboa,bearstech/modoboa,carragom/modoboa,modoboa/modoboa,tonioo/modoboa,carragom/modoboa,modoboa/modoboa,bearstech/modoboa,RavenB/modoboa,carragom/modoboa,tonioo/modoboa,meh... | ---
+++
@@ -10,7 +10,7 @@
class ForwardForm(forms.Form):
dest = forms.CharField(
label=ugettext_lazy("Recipient(s)"),
- widget=forms.Textarea,
+ widget=forms.Textarea(attrs={"class": "form-control"}),
required=False,
help_text=ugettext_lazy("Indicate one or more recipien... |
a4163d9c1d1b2ce196b582eadc7befd545f804f1 | corehq/ex-submodules/pillowtop/dao/interface.py | corehq/ex-submodules/pillowtop/dao/interface.py | from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
class DocumentStore(object):
"""
Very basic implementation of a document store.
"""
__metaclass__ = ABCMeta
@abstractmethod
def get_document(self, doc_id):
pass
@abstractmethod
def save_document(s... | from __future__ import unicode_literals
from abc import ABCMeta, abstractmethod
class DocumentStore(object):
"""
Very basic implementation of a document store.
"""
__metaclass__ = ABCMeta
@abstractmethod
def get_document(self, doc_id):
pass
@abstractmethod
def save_document(s... | Modify abstract parameter to match its children | Modify abstract parameter to match its children
All instances of this already accept the parameter, so we should codify
it as part of the spec.
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -20,7 +20,7 @@
def delete_document(self, doc_id):
pass
- def iter_document_ids(self):
+ def iter_document_ids(self, last_id=None):
# todo: can convert to @abstractmethod once subclasses handle it
raise NotImplementedError('this function not yet implemented')
|
8cfdda81d12845ad0e76f7a087995080a5420bfb | test/TestLineNumber.py | test/TestLineNumber.py | # Copyright (c) 2020 Albin Vass <albin.vass@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, m... | # Copyright (c) 2020 Albin Vass <albin.vass@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, m... | Add a docstring for `test_rule_linenumber` | Add a docstring for `test_rule_linenumber` | Python | mit | willthames/ansible-lint | ---
+++
@@ -31,7 +31,7 @@
def test_rule_linenumber(monkeypatch):
-
+ """Check that SudoRule offense contains a line number."""
rule = SudoRule()
matches = rule.matchyaml(dict(path="", type='tasklist'), TEST_TASKLIST)
assert matches[0].linenumber == 5 |
3e0e6971923bd6d753eca8bbb66c1f3c9efc2afb | piper/process.py | piper/process.py | import subprocess as sub
import logbook
from piper.logging import SEPARATOR
class Process(object):
"""
Helper class for running processes
"""
def __init__(self, ns, cmd, parent_key):
self.ns = ns
self.cmd = cmd
self.popen = None
self.success = None
self.log... | import subprocess as sub
import logbook
from piper.logging import SEPARATOR
class Process(object):
"""
Helper class for running processes
"""
def __init__(self, ns, cmd, parent_key):
self.ns = ns
self.cmd = cmd
self.popen = None
self.success = None
self.log... | Fix decode bug in Process() failures | Fix decode bug in Process() failures
| Python | mit | thiderman/piper | ---
+++
@@ -55,4 +55,4 @@
self.success = exit == 0
if not self.success:
- self.log.error(self.popen.stderr.read())
+ self.log.error(self.popen.stderr.read().decode('utf-8')) |
695304372ebe4ad76c5d6ce7dea7f39c28ffba07 | libexec/wlint/punctuation-style.py | libexec/wlint/punctuation-style.py | #!/usr/bin/python3
import re
import wlint.common
import wlint.punctuation
class PunctuationStyle(wlint.common.Tool):
def __init__(self, description):
super().__init__(description)
self.checks = wlint.punctuation.PunctuationRules().rules
def setup(self, arguments):
self.result = 0
... | #!/usr/bin/python3
import operator
import wlint.common
import wlint.punctuation
class PunctuationStyle(wlint.common.Tool):
def __init__(self, description):
super().__init__(description)
self.checks = wlint.punctuation.PunctuationRules().rules
def setup(self, arguments):
self.result... | Sort punctuation hits so output is based on line and column, not the order rules are checked | Sort punctuation hits so output is based on line and column, not the order rules are checked
| Python | bsd-2-clause | snewell/wlint,snewell/wlint,snewell/writing-tools,snewell/writing-tools | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/python3
-import re
+import operator
import wlint.common
import wlint.punctuation
@@ -17,13 +17,16 @@
def process(self, fileHandle):
lineNumber = 0
+ hits = []
for text in fileHandle:
lineNumber += 1
for message, fn in ... |
8d85bfd34c291f01235eb630f458972cc11c58ad | embed_tweet.py | embed_tweet.py | """
Embedded tweet plugin for Pelican
=================================
This plugin allows you to embed Twitter tweets into your articles.
And also provides a link for Twitter username.
i.e.
@username
will be replaced by a link to Twitter username page.
@username/status/tweetid
... | """
Embedded tweet plugin for Pelican
=================================
This plugin allows you to embed Twitter tweets into your articles.
And also provides a link for Twitter username.
i.e.
@username
will be replaced by a link to Twitter username page.
@username/status/tweetid
... | Check content._content before using it to prevent errors | Check content._content before using it to prevent errors
| Python | mit | lqez/pelican-embed-tweet | ---
+++
@@ -24,6 +24,9 @@
def embed_tweet(content):
+ if not content._content:
+ return
+
content._content = re.sub(
r'(^|[^@\w])@(\w{1,15})\b',
'\\1<a href="https://twitter.com/\\2">@\\2</a>', |
531c9e943748c576c963b809a7f1052d611346b9 | hearthstone/stringsfile.py | hearthstone/stringsfile.py | """
Hearthstone Strings file
File format: TSV. Lines starting with `#` are ignored.
Key is always `TAG`
"""
import csv
from typing import Dict
import hearthstone_data
StringsRow = Dict[str, str]
StringsDict = Dict[str, StringsRow]
_cache: Dict[str, StringsDict] = {}
def load(fp) -> StringsDict:
reader = csv.Dic... | """
Hearthstone Strings file
File format: TSV. Lines starting with `#` are ignored.
Key is always `TAG`
"""
import csv
from typing import Dict
import hearthstone_data
StringsRow = Dict[str, str]
StringsDict = Dict[str, StringsRow]
_cache: Dict[str, StringsDict] = {}
def load(fp) -> StringsDict:
reader = csv.Dic... | Fix BOM issue with latest strings | Fix BOM issue with latest strings
| Python | mit | HearthSim/python-hearthstone | ---
+++
@@ -28,7 +28,7 @@
def load_globalstrings(locale="enUS") -> StringsDict:
path: str = hearthstone_data.get_strings_file(locale, filename="GLOBAL.txt")
if path not in _cache:
- with open(path, "r") as f:
+ with open(path, "r", encoding="utf-8-sig") as f:
_cache[path] = load(f)
return _cache[path] |
c85ff679ef7a4c88dc4c625f69faed76ef195111 | frappe/website/page_renderers/not_found_page.py | frappe/website/page_renderers/not_found_page.py | import os
from urllib.parse import urlparse
import frappe
from frappe.website.page_renderers.template_page import TemplatePage
from frappe.website.utils import can_cache
HOMEPAGE_PATHS = ('/', '/index', 'index')
class NotFoundPage(TemplatePage):
def __init__(self, path, http_status_code):
self.request_path = path... | import os
from urllib.parse import urlparse
import frappe
from frappe.website.page_renderers.template_page import TemplatePage
from frappe.website.utils import can_cache
HOMEPAGE_PATHS = ('/', '/index', 'index')
class NotFoundPage(TemplatePage):
def __init__(self, path, http_status_code=None):
self.request_path =... | Set default value for http_status_code | fix(NotFoundPage): Set default value for http_status_code
| Python | mit | mhbu50/frappe,yashodhank/frappe,mhbu50/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,mhbu50/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,frappe/frappe,frappe/frappe,yashodhank/frappe,yashodhank/frappe,almeidapaulopt/frappe,frappe/frappe,StrellaGroup/frappe,mhbu50/frappe | ---
+++
@@ -8,11 +8,11 @@
HOMEPAGE_PATHS = ('/', '/index', 'index')
class NotFoundPage(TemplatePage):
- def __init__(self, path, http_status_code):
+ def __init__(self, path, http_status_code=None):
self.request_path = path
self.request_url = frappe.local.request.url if hasattr(frappe.local, 'request') else... |
74800bf43f9b0f130a7b096afd20db373e7dad1e | web/blueprints/helpers/exception.py | web/blueprints/helpers/exception.py | import traceback
from flask import flash
from sqlalchemy.exc import InternalError
from pycroft.helpers import AutoNumber
from pycroft.model import session
from pycroft.lib.net import MacExistsException, SubnetFullException
from pycroft.model.host import MulticastFlagException
from pycroft.model.types import InvalidM... | import traceback
from flask import flash
from pycroft.lib.net import MacExistsException, SubnetFullException
from pycroft.model import session
from pycroft.model.host import MulticastFlagException
from pycroft.model.types import InvalidMACAddressException
def web_execute(function, success_message, *args, **kwargs):... | Remove “username taken in abe” handling | Remove “username taken in abe” handling
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft | ---
+++
@@ -1,12 +1,9 @@
import traceback
from flask import flash
-from sqlalchemy.exc import InternalError
-
-from pycroft.helpers import AutoNumber
-from pycroft.model import session
from pycroft.lib.net import MacExistsException, SubnetFullException
+from pycroft.model import session
from pycroft.model.hos... |
06a70ae323f0eb1fe50c1f01a31ef9548a24b00c | tests/test_favicons.py | tests/test_favicons.py | from django.test import TestCase
from mock import patch
from feedhq.feeds.models import Favicon, Feed
from .factories import FeedFactory
from . import responses
class FaviconTests(TestCase):
@patch("requests.get")
def test_existing_favicon_new_feed(self, get):
get.return_value = responses(304)
... | from mock import patch
from feedhq.feeds.models import Favicon, Feed
from .factories import FeedFactory
from . import responses, TestCase
class FaviconTests(TestCase):
@patch("requests.get")
def test_existing_favicon_new_feed(self, get):
get.return_value = responses(304)
FeedFactory.create(u... | Use base TestCase to properly cleanup indices | Use base TestCase to properly cleanup indices
| Python | bsd-3-clause | rmoorman/feedhq,feedhq/feedhq,rmoorman/feedhq,feedhq/feedhq,rmoorman/feedhq,rmoorman/feedhq,rmoorman/feedhq,vincentbernat/feedhq,feedhq/feedhq,vincentbernat/feedhq,feedhq/feedhq,vincentbernat/feedhq,feedhq/feedhq,vincentbernat/feedhq,vincentbernat/feedhq | ---
+++
@@ -1,10 +1,9 @@
-from django.test import TestCase
from mock import patch
from feedhq.feeds.models import Favicon, Feed
from .factories import FeedFactory
-from . import responses
+from . import responses, TestCase
class FaviconTests(TestCase): |
f089a7828ac2eb42b437166880eef6fea102a8e1 | speech/google/cloud/speech/__init__.py | speech/google/cloud/speech/__init__.py | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Make Encoding accessible from speech.Encoding. | Make Encoding accessible from speech.Encoding.
| Python | apache-2.0 | jonparrott/google-cloud-python,dhermes/gcloud-python,tswast/google-cloud-python,tseaver/google-cloud-python,googleapis/google-cloud-python,daspecster/google-cloud-python,Fkawala/gcloud-python,Fkawala/gcloud-python,dhermes/google-cloud-python,dhermes/gcloud-python,GoogleCloudPlatform/gcloud-python,dhermes/google-cloud-p... | ---
+++
@@ -16,3 +16,4 @@
from google.cloud.speech.client import Client
from google.cloud.speech.connection import Connection
+from google.cloud.speech.encoding import Encoding |
b59f09f02c3f22ba53f08790babd75348153d64b | tests/hashes_test.py | tests/hashes_test.py | from nose.tools import istest, assert_equal
from whack.hashes import Hasher
@istest
def hashing_the_same_single_value_gives_the_same_hash():
def create_hash():
hasher = Hasher()
hasher.update("one")
return hasher.hexdigest()
assert_equal(create_hash(), create_hash())
| from nose.tools import istest, assert_equal
from whack.hashes import Hasher
@istest
def hashing_the_same_single_value_gives_the_same_hash():
def create_hash():
hasher = Hasher()
hasher.update("one")
return hasher.hexdigest()
assert_equal(create_hash(), create_hash())
@istest
def ... | Add test for hashing multiple values | Add test for hashing multiple values
| Python | bsd-2-clause | mwilliamson/whack | ---
+++
@@ -10,3 +10,13 @@
return hasher.hexdigest()
assert_equal(create_hash(), create_hash())
+
+@istest
+def hashing_multiple_values_in_the_same_order_gives_the_same_hash():
+ def create_hash():
+ hasher = Hasher()
+ hasher.update("one")
+ hasher.update("two")
+ r... |
39c5decd98e8d4feb6c1bbfa487faf35396c8b12 | logdna/__init__.py | logdna/__init__.py | from .logdna import LogDNAHandler
__all__ = ['LogDNAHandler']
| from .logdna import LogDNAHandler
__all__ = ['LogDNAHandler']
# Publish this class to the "logging.handlers" module so that it can be use
# from a logging config file via logging.config.fileConfig().
import logging.handlers
logging.handlers.LogDNAHandler = LogDNAHandler
| Make available via config file | feat(handlers): Make available via config file
- Add to `logging.handlers` such that LogDNAHandler can be configured
via a logging config file
| Python | mit | logdna/python | ---
+++
@@ -1,3 +1,8 @@
from .logdna import LogDNAHandler
__all__ = ['LogDNAHandler']
+# Publish this class to the "logging.handlers" module so that it can be use
+# from a logging config file via logging.config.fileConfig().
+import logging.handlers
+
+logging.handlers.LogDNAHandler = LogDNAHandler |
2096f7f2a840d4b506c2493179408903dd045d21 | golang/main.py | golang/main.py | from evolution_master.runners import pkg, download
# Install for Arch
with pkg.pacman() as pkg_man:
pkg_man.install('go')
# Install for Debian & Ubuntu
with pkg.apt() as pkg_man:
pkg_man.install('golang')
# Install for OSX
with pkg.brew() as pkg_man:
pkg_man.install('go')
# Install for Windows
with dow... | from evolution_master.runners import pkg, download
# Install for Arch
with pkg.pacman() as pkg_man:
pkg_man.install('go')
# Install for Debian & Ubuntu
with pkg.apt() as pkg_man:
pkg_man.install('golang')
# TODO: make this a runner and require a switch to enable this
pkg_man.install('golang-go-darwin-... | Add cross compile for debian | Add cross compile for debian | Python | mit | hatchery/genepool,hatchery/Genepool2 | ---
+++
@@ -7,6 +7,11 @@
# Install for Debian & Ubuntu
with pkg.apt() as pkg_man:
pkg_man.install('golang')
+ # TODO: make this a runner and require a switch to enable this
+ pkg_man.install('golang-go-darwin-amd64',
+ 'golang-go-freebsd-amd64',
+ 'golang-go-netbsd-a... |
0fad98f84a6d02d4507ff9acb59d4764d4e4fabc | rdmo/__init__.py | rdmo/__init__.py | __title__ = 'rdmo'
__version__ = '1.0.5'
__author__ = 'Jochen Klar'
__email__ = 'jklar@aip.de'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright 2015-2018 Leibniz Institute for Astrophysics Potsdam (AIP)'
VERSION = __version__
| __title__ = 'rdmo'
__version__ = '1.0.6'
__author__ = 'Jochen Klar'
__email__ = 'jklar@aip.de'
__license__ = 'Apache-2.0'
__copyright__ = 'Copyright 2015-2018 Leibniz Institute for Astrophysics Potsdam (AIP)'
VERSION = __version__
| Bump version number to 1.0.6 | Bump version number to 1.0.6
| Python | apache-2.0 | rdmorganiser/rdmo,DMPwerkzeug/DMPwerkzeug,DMPwerkzeug/DMPwerkzeug,rdmorganiser/rdmo,rdmorganiser/rdmo,DMPwerkzeug/DMPwerkzeug | ---
+++
@@ -1,5 +1,5 @@
__title__ = 'rdmo'
-__version__ = '1.0.5'
+__version__ = '1.0.6'
__author__ = 'Jochen Klar'
__email__ = 'jklar@aip.de'
__license__ = 'Apache-2.0' |
aafa37c83c1464c16c2c6b69cc1546a537ec99a3 | main/forms.py | main/forms.py | from django import forms
from main.fields import RegexField
class IndexForm(forms.Form):
id_list = forms.CharField(
widget=forms.Textarea, label='ID List',
help_text='List of students IDs to query, one per line.')
student_id_regex = RegexField(
label='Student ID regex',
help_t... | from django import forms
from main.fields import RegexField
class IndexForm(forms.Form):
id_list = forms.CharField(
help_text='List of students IDs to query, one per line.',
label='ID List',
widget=forms.Textarea(attrs={
'placeholder': 'Random text\n1234567\n7654321'}))
st... | Add placeholder to ID list field | Add placeholder to ID list field
| Python | mit | m4tx/usos-id-mapper,m4tx/usos-id-mapper | ---
+++
@@ -5,8 +5,10 @@
class IndexForm(forms.Form):
id_list = forms.CharField(
- widget=forms.Textarea, label='ID List',
- help_text='List of students IDs to query, one per line.')
+ help_text='List of students IDs to query, one per line.',
+ label='ID List',
+ widget=form... |
3331ddc41446c1b40cdd6cc7ff3a85af60e7bd5b | registry/urls.py | registry/urls.py | from django.conf.urls import patterns, include, url
from api.views import PackagesListView, PackagesFindView, PackagesSearchView
urlpatterns = patterns('',
url(r'^packages/?$', PackagesListView.as_view(), name='list'),
url(r'^packages/(?P<name>[-\w]+)/?$', PackagesFindView.as_view(), name='find'),
url(r'^... | from django.conf.urls import patterns, include, url
from api.views import PackagesListView, PackagesFindView, PackagesSearchView
urlpatterns = patterns('',
url(r'^packages/?$', PackagesListView.as_view(), name='list'),
url(r'^packages/(?P<name>[-\w]+)/?$', PackagesFindView.as_view(), name='find'),
url(r'^... | Allow dots in package names. | Allow dots in package names.
Packages such as `backbone.wreqr` and `backbone.babysitter` where 404ing fixes #9 | Python | mit | toranb/django-bower-registry | ---
+++
@@ -5,5 +5,5 @@
urlpatterns = patterns('',
url(r'^packages/?$', PackagesListView.as_view(), name='list'),
url(r'^packages/(?P<name>[-\w]+)/?$', PackagesFindView.as_view(), name='find'),
- url(r'^packages/search/(?P<name>[-\w]+)/?$', PackagesSearchView.as_view(), name='search')
+ url(r'^packag... |
20801daf2d774f2c976265edc72e436094930589 | saleor/urls.py | saleor/urls.py | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib.staticfiles.views import serve
from django.views.decorators.csrf import csrf_exempt
from .graphql.api import schema
from .graphql.views import GraphQLView
from .plugins.views import... | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib.staticfiles.views import serve
from django.views.decorators.csrf import csrf_exempt
from .graphql.api import schema
from .graphql.views import GraphQLView
from .plugins.views import... | Update url patterns - accept only exact patterns | Update url patterns - accept only exact patterns
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -10,7 +10,7 @@
from .product.views import digital_product
urlpatterns = [
- url(r"^graphql/", csrf_exempt(GraphQLView.as_view(schema=schema)), name="api"),
+ url(r"^graphql/$", csrf_exempt(GraphQLView.as_view(schema=schema)), name="api"),
url(
r"^digital-download/(?P<token>[0-9A-Za-... |
b8938849ce9239836d2b601dd43324284f1b5604 | whatinstalled.py | whatinstalled.py | import os
history_file = os.path.expanduser("~")+"/.bash_history"
f = open(history_file,"r")
keywords = ["pip", "tar", "brew", "apt-get", "install", "luarocks", "easy_install", "gem", "npm"]
for line in f:
for item in keywords:
if item in line:
print(line[:-1])
break | import os
history_file = os.path.expanduser("~")+"/.bash_history"
f = open(history_file,"r")
keywords = ["pip", "tar", "brew", "apt-get", "aptitude", "apt", "install", "luarocks", "easy_install", "gem", "npm", "bower"]
for line in f:
for item in keywords:
if item in line:
print(line[:-1])
break
| Add aptitude and apt + bower | Add aptitude and apt + bower | Python | mit | AlexMili/WhatInstalled | ---
+++
@@ -3,7 +3,7 @@
history_file = os.path.expanduser("~")+"/.bash_history"
f = open(history_file,"r")
-keywords = ["pip", "tar", "brew", "apt-get", "install", "luarocks", "easy_install", "gem", "npm"]
+keywords = ["pip", "tar", "brew", "apt-get", "aptitude", "apt", "install", "luarocks", "easy_install", "gem... |
ef281c765f46ead27105f78fe634ace64fca776b | yowsup/layers/protocol_iq/layer.py | yowsup/layers/protocol_iq/layer.py | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
... | from yowsup.layers import YowProtocolLayer
from yowsup.common import YowConstants
from .protocolentities import *
class YowIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq)
}
super(YowIqProtocolLayer, self).__init__(handleMap)
... | Handle Ping result in ResultIqProtocolEntity | Handle Ping result in ResultIqProtocolEntity
refs #402
| Python | mit | ongair/yowsup,biji/yowsup | ---
+++
@@ -21,3 +21,6 @@
self.toLower(entity.toProtocolTreeNode())
elif node["type"] == "error":
self.toUpper(ErrorIqProtocolEntity.fromProtocolTreeNode(node))
+ elif node["type"] == "result" and not len(node.getAllChildren()):
+ #allowing only unidentifiable resu... |
dbeaefca7643edd67ea9990c1f665f0ecc5b34d0 | pebble/PblCommand.py | pebble/PblCommand.py | import os
class PblCommand:
name = ''
help = ''
def run(args):
pass
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
parser.add_argument('--debug', action='store_true',
help = 'Ena... | import os
import logging
class PblCommand:
name = ''
help = ''
def run(args):
pass
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
parser.add_argument('--debug', action='store_true',
... | Allow SDK location to be overridden by environment variable. | Allow SDK location to be overridden by environment variable.
| Python | mit | pebble/libpebble,pebble/libpebble,pebble/libpebble,pebble/libpebble | ---
+++
@@ -1,4 +1,5 @@
import os
+import logging
class PblCommand:
name = ''
@@ -9,15 +10,20 @@
def configure_subparser(self, parser):
parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)')
- parser.add_argument('--debug', action='store_true',
+ ... |
c3e27aee3aa27a81dff2e8aaa5ab9be13725f329 | mesos/compute_cluster_url.py | mesos/compute_cluster_url.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
# Get the Mesos cluster URL, assuming the EC2 script environment variables
# are all available.
active_master = os.getenv("MESOS_MASTERS").split("\n")[0]
zoo_list = os.getenv("MESOS_ZOO_LIST")
if zoo_list.strip() == "NONE":
print active_master + "... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
# Get the Mesos cluster URL, assuming the EC2 script environment variables
# are all available.
active_master = os.getenv("MESOS_MASTERS").split("\n")[0]
zoo_list = os.getenv("MESOS_ZOO_LIST")
if zoo_list.strip() == "NONE":
print "mesos://" + acti... | Include URI scheme in Mesos cluster_url | Include URI scheme in Mesos cluster_url
| Python | apache-2.0 | serialx/spark-ec2,madhavhugar/spark-ec2,SiGe/spark-ec2,romanini/spark-ec2,madhavhugar/spark-ec2,uronce-cc/spark-ec2,serialx/spark-ec2,inreachventures/spark-ec2,BrandwatchLtd/spark-ec2,tomerk/spark-ec2,jyt109/spark-ec2,GordonWang/spark-ec2,romanini/spark-ec2,Wealthport/spark-ec2,pluribus-labs/spark-ec2,paulomagalhaes/sp... | ---
+++
@@ -11,7 +11,7 @@
zoo_list = os.getenv("MESOS_ZOO_LIST")
if zoo_list.strip() == "NONE":
- print active_master + ":5050"
+ print "mesos://" + active_master + ":5050"
else:
zoo_nodes = zoo_list.trim().split("\n")
print "zoo://" + ",".join(["%s:2181/mesos" % node for node in zoo_nodes]) |
5a47ca87858bb08fcaac4a38322dc04eaf74cac2 | src/foremast/utils/get_sns_topic_arn.py | src/foremast/utils/get_sns_topic_arn.py | """SNS Topic functions."""
import logging
import boto3
from ..exceptions import SNSTopicNotFound
LOG = logging.getLogger(__name__)
def get_sns_topic_arn(topic_name, account, region):
"""Get SNS topic ARN.
Args:
topic_name (str): Name of the topic to lookup.
account (str): Environment, e.g.... | """SNS Topic functions."""
import logging
import boto3
from ..exceptions import SNSTopicNotFound
LOG = logging.getLogger(__name__)
def get_sns_topic_arn(topic_name, account, region):
"""Get SNS topic ARN.
Args:
topic_name (str): Name of the topic to lookup.
account (str): Environment, e.g.... | Return ARN directly if topic name appears to be an ARN | Return ARN directly if topic name appears to be an ARN
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -20,6 +20,8 @@
str: ARN for requested topic name
"""
+ if topic_name.count(':') == 5:
+ return topic_name
session = boto3.Session(profile_name=account, region_name=region)
sns_client = session.client('sns')
|
e2d80effa425bc12544f3bbf1ad5546b5af40572 | insert_sort.py | insert_sort.py | def insert_sort(my_list):
for i in range(1, len(my_list)):
j = i - 1
key = my_list[i]
while (j >= 0) and (my_list[j] > key):
my_list[j + 1] = my_list[j]
j -= 1
my_list[j + 1] = key
if __name__ == '__main__':
| def insert_sort(my_list):
for i in range(1, len(my_list)):
j = i - 1
key = my_list[i]
while (j >= 0) and (my_list[j] > key):
my_list[j + 1] = my_list[j]
j -= 1
my_list[j + 1] = key
if __name__ == '__main__':
import timeit
best_list = [i for i in rang... | Add timing to __name__ block | Add timing to __name__ block
| Python | mit | nbeck90/data_structures_2 | ---
+++
@@ -8,3 +8,22 @@
my_list[j + 1] = key
if __name__ == '__main__':
+ import timeit
+
+ best_list = [i for i in range(5000)]
+ worst_list = [i for i in range(5000)][::-1]
+
+ def best_case():
+ return insert_sort(best_list)
+
+ def worst_case():
+ return insert_sort(worst... |
7506e93942333a28f1e66c95016071760382a071 | packages/Python/lldbsuite/test/repl/pounwrapping/TestPOUnwrapping.py | packages/Python/lldbsuite/test/repl/pounwrapping/TestPOUnwrapping.py | # TestPOUnwrapping.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIB... | # TestPOUnwrapping.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIB... | Revert "Disable test that fails on bot" | Revert "Disable test that fails on bot"
This reverts commit e214e46e748881e6418ffac374a87d6ad30fcfea.
I have reverted the swift commit that was causing this failure.
rdar://35264910
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb | ---
+++
@@ -18,11 +18,7 @@
class REPLBasicTestCase(lldbrepl.REPLTest):
mydir = lldbrepl.REPLTest.compute_mydir(__file__)
- @decorators.expectedFailureAll(
- oslist=[
- "macosx",
- "linux"],
- bugnumber="rdar://35264910")
+
def doTest(self):
self.command(
... |
dfa72ed557b0206e4f19584d317d202f6e4b84c9 | tests/read/test_read_api.py | tests/read/test_read_api.py | import unittest
import urllib
import datetime
from hamcrest import *
from mock import patch
import pytz
from backdrop.read import api
class ReadApiTestCase(unittest.TestCase):
def setUp(self):
self.app = api.app.test_client()
# @patch('backdrop.core.storage.Bucket.query')
# def test_period_query_... | Test api queries result in correct storage queries | Test api queries result in correct storage queries
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -0,0 +1,50 @@
+import unittest
+import urllib
+import datetime
+from hamcrest import *
+from mock import patch
+import pytz
+from backdrop.read import api
+
+
+class ReadApiTestCase(unittest.TestCase):
+ def setUp(self):
+ self.app = api.app.test_client()
+
+ # @patch('backdrop.core.storage.Bu... | |
04bccd678ba7a67373b94695d7d87d0cf95dffd6 | tests/unit/app_unit_test.py | tests/unit/app_unit_test.py | # -*- coding: utf-8 -*-
"""
Unit Test: orchard.app
"""
import unittest
import orchard
class AppUnitTest(unittest.TestCase):
def setUp(self):
app = orchard.create_app('Testing')
self.app_context = app.app_context()
self.app_context.push()
self.client = app.test_client(use_co... | # -*- coding: utf-8 -*-
"""
Unit Test: orchard.app
"""
import unittest
import orchard
class AppUnitTest(unittest.TestCase):
def setUp(self):
app = orchard.create_app('Testing')
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
self.app_context = app.app_context()
self.app_context.p... | Set default locale in test to avoid test failures when different default is used than expected. | Set default locale in test to avoid test failures when different default is used than expected.
| Python | mit | BMeu/Orchard,BMeu/Orchard | ---
+++
@@ -13,6 +13,7 @@
def setUp(self):
app = orchard.create_app('Testing')
+ app.config['BABEL_DEFAULT_LOCALE'] = 'en'
self.app_context = app.app_context()
self.app_context.push()
self.client = app.test_client(use_cookies = True) |
874477151ba07dd976dd53f604682f018a3c223f | yolk/__init__.py | yolk/__init__.py | """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.1'
| """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.8.2'
| Increment patch version to 0.8.2 | Increment patch version to 0.8.2
| Python | bsd-3-clause | myint/yolk,myint/yolk | ---
+++
@@ -6,4 +6,4 @@
"""
-__version__ = '0.8.1'
+__version__ = '0.8.2' |
2bc249dc4996c0cccfe61a3d8bf1658fa987e7cf | costcocr/writers/csv.py | costcocr/writers/csv.py |
def csv():
def Receipt(meta, body, variables):
output = []
def add(s) : output.append(s)
if "store" in meta:
add("# Store: {}".format(meta["store"]))
if "date" in meta:
add("# Date: {}".format(meta["date"]))
if "location" in meta:
add("... | def Receipt(meta, body, variables):
output = []
def add(s) : output.append(s)
if "store" in meta:
add("# Store: {}".format(meta["store"]))
if "date" in meta:
add("# Date: {}".format(meta["date"]))
if "location" in meta:
add("# Location: {}".format(meta["location"]))
ad... | Convert CSV writer to a module definition. | Convert CSV writer to a module definition.
Use __import__ to import it as a dictionary.
| Python | bsd-3-clause | rdodesigns/costcocr | ---
+++
@@ -1,33 +1,22 @@
+def Receipt(meta, body, variables):
+ output = []
-def csv():
+ def add(s) : output.append(s)
- def Receipt(meta, body, variables):
- output = []
+ if "store" in meta:
+ add("# Store: {}".format(meta["store"]))
+ if "date" in meta:
+ add("# Date: {}".... |
7fa8ba8cffcf3e6dd4748389e1a43776f095a559 | postatus/settings.py | postatus/settings.py | import os
def truthy(item):
return item.lower().startswith('t')
DEBUG = truthy(os.environ.get('DEBUG', 'True'))
PROJECTS = {
'SUMO': {
'name': 'SUMO',
'url': 'https://support.mozilla.org/',
'postatus_url': 'https://support.mozilla.org/media/postatus.txt',
'verbatim_url': 'ht... | import os
def truthy(item):
return item.lower().startswith('t')
DEBUG = truthy(os.environ.get('DEBUG', 'True'))
PROJECTS = {
'SUMO': {
'name': 'SUMO',
'url': 'https://support.mozilla.org/',
'postatus_url': 'https://support.mozilla.org/media/postatus.txt',
'verbatim_url': 'ht... | Update fjord l10n_completion file location | Update fjord l10n_completion file location
| Python | bsd-3-clause | willkg/postatus,willkg/postatus,willkg/postatus | ---
+++
@@ -22,6 +22,6 @@
'postatus_url': 'https://input.mozilla.org/media/postatus.txt',
'verbatim_url': 'https://localize.mozilla.org/projects/input/',
'verbatim_locale_url': 'https://localize.mozilla.org/%s/input/',
- 'l10n_completion_url': 'https://input.mozilla.org/static/l10n_c... |
e276753b458ef7c4c05469324173a455c0e2db46 | tests/basics/subclass-native3.py | tests/basics/subclass-native3.py | class MyExc(Exception):
pass
e = MyExc(100, "Some error")
print(e)
print(repr(e))
print(e.args)
| class MyExc(Exception):
pass
e = MyExc(100, "Some error")
print(e)
print(repr(e))
print(e.args)
try:
raise MyExc("Some error")
except MyExc as e:
print("Caught exception:", repr(e))
try:
raise MyExc("Some error2")
except Exception as e:
print("Caught exception:", repr(e))
try:
raise MyExc("S... | Add testcases for catching user Exception subclasses. | tests: Add testcases for catching user Exception subclasses.
| Python | mit | SungEun-Steve-Kim/test-mp,kerneltask/micropython,oopy/micropython,vitiral/micropython,martinribelotta/micropython,xyb/micropython,omtinez/micropython,HenrikSolver/micropython,ChuckM/micropython,utopiaprince/micropython,ericsnowcurrently/micropython,feilongfl/micropython,ericsnowcurrently/micropython,dxxb/micropython,sk... | ---
+++
@@ -5,3 +5,18 @@
print(e)
print(repr(e))
print(e.args)
+
+try:
+ raise MyExc("Some error")
+except MyExc as e:
+ print("Caught exception:", repr(e))
+
+try:
+ raise MyExc("Some error2")
+except Exception as e:
+ print("Caught exception:", repr(e))
+
+try:
+ raise MyExc("Some error2")
+except... |
4d161278963252d8502f1be2bfb857bcb379f540 | test/python/topology/test_utilities.py | test/python/topology/test_utilities.py | # Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import sys
import streamsx.topology.context
def standalone(test, topo):
rc = streamsx.topology.context.submit("STANDALONE", topo)
test.assertEqual(0, rc)
| # Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import sys
import streamsx.topology.context
def standalone(test, topo):
rc = streamsx.topology.context.submit("STANDALONE", topo)
test.assertEqual(0, rc['return_code'])
| Return value of submit is now a json dict | Return value of submit is now a json dict
| Python | apache-2.0 | ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topology,wmarshall484/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topol... | ---
+++
@@ -5,5 +5,5 @@
def standalone(test, topo):
rc = streamsx.topology.context.submit("STANDALONE", topo)
- test.assertEqual(0, rc)
+ test.assertEqual(0, rc['return_code'])
|
024597e8f32b49844c333fa551862563f2c508ca | pymatgen/__init__.py | pymatgen/__init__.py | from __future__ import unicode_literals
__author__ = "Pymatgen Development Team"
__email__ ="pymatgen@googlegroups.com"
__maintainer__ = "Shyue Ping Ong"
__maintainer_email__ ="shyuep@gmail.com"
__date__ = "Jul 8 2016"
__version__ = "4.0.2"
# Useful aliases for commonly used objects and modules.
# Allows from pymatg... | from __future__ import unicode_literals
__author__ = "Pymatgen Development Team"
__email__ ="pymatgen@googlegroups.com"
__maintainer__ = "Shyue Ping Ong"
__maintainer_email__ ="shyuep@gmail.com"
__date__ = "Jul 8 2016"
__version__ = "4.0.2"
# Order of imports is important on some systems to avoid
# failures when lo... | Fix for DLL load failures when importing top-level package | Fix for DLL load failures when importing top-level package
The order of import affects the success of import pymatgen on certain 64-bit Windows setups and therefore a workaround has been added.
Former-commit-id: 0ff590e053d5e0be2959720a861d06d7ba74d132 [formerly 0da252fe086eaa98942c4eaa39750739964be96f]
Former-commit... | Python | mit | gpetretto/pymatgen,dongsenfo/pymatgen,czhengsci/pymatgen,blondegeek/pymatgen,davidwaroquiers/pymatgen,johnson1228/pymatgen,fraricci/pymatgen,dongsenfo/pymatgen,czhengsci/pymatgen,Bismarrck/pymatgen,setten/pymatgen,vorwerkc/pymatgen,tallakahath/pymatgen,tschaume/pymatgen,johnson1228/pymatgen,nisse3000/pymatgen,richardtr... | ---
+++
@@ -8,6 +8,12 @@
__version__ = "4.0.2"
+# Order of imports is important on some systems to avoid
+# failures when loading shared libraries.
+import spglib
+from . import optimization, util
+del(spglib, optimization, util)
+
# Useful aliases for commonly used objects and modules.
# Allows from pymatgen... |
7fb30506b9de18d39e47d13a2e85c06484cfdecd | tests/modules/test_enumerable.py | tests/modules/test_enumerable.py | class TestKernel(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |sum, n... | class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n|
prod * n
end
""")
assert ec.space.int_w(w_res) == 15120
w_res = ec.space.execute(ec, """
return (1..10).inject 0 do |s... | Fix name of test object for enumerables | Fix name of test object for enumerables
| Python | bsd-3-clause | babelsberg/babelsberg-r,babelsberg/babelsberg-r,topazproject/topaz,topazproject/topaz,babelsberg/babelsberg-r,kachick/topaz,topazproject/topaz,babelsberg/babelsberg-r,topazproject/topaz,kachick/topaz,babelsberg/babelsberg-r,kachick/topaz | ---
+++
@@ -1,4 +1,4 @@
-class TestKernel(object):
+class TestEnumberable(object):
def test_inject(self, ec):
w_res = ec.space.execute(ec, """
return (5..10).inject(1) do |prod, n| |
875451aa1639b6342fa53340edc59c6c521a1e37 | python/microphone.py | python/microphone.py | import time
import numpy as np
import pyaudio
import config
def start_stream(callback):
p = pyaudio.PyAudio()
frames_per_buffer = int(config.MIC_RATE / config.FPS)
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=config.MIC_RATE,
input=Tr... | import time
import numpy as np
import pyaudio
import config
def start_stream(callback):
p = pyaudio.PyAudio()
frames_per_buffer = int(config.MIC_RATE / config.FPS)
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=config.MIC_RATE,
input=Tr... | Fix syntax bug on stream emptying | Fix syntax bug on stream emptying | Python | mit | scottlawsonbc/audio-reactive-led-strip,joeybab3/audio-reactive-led-strip,joeybab3/audio-reactive-led-strip,scottlawsonbc/audio-reactive-led-strip | ---
+++
@@ -18,7 +18,7 @@
try:
y = np.fromstring(stream.read(frames_per_buffer, exception_on_overflow=False), dtype=np.int16)
y = y.astype(np.float32)
- stream.read(get_read_available(), exception_on_overflow=False)
+ stream.read(stream.get_read_available(), ex... |
26ccc283dfe6ac4c3505cef78d27e9a27221b8b6 | readthedocs/core/subdomain_urls.py | readthedocs/core/subdomain_urls.py | from django.conf.urls.defaults import url, patterns
from urls import urlpatterns as main_patterns
urlpatterns = patterns('',
url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.subproject_serve_docs',
name='subproject_docs_detail... | from django.conf.urls.defaults import url, patterns
from urls import urlpatterns as main_patterns
urlpatterns = patterns('',
url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.subproject_serve_docs',
name='subproject_docs_detail... | Fix regex on subdomain urls so empty string will match. | Fix regex on subdomain urls so empty string will match.
| Python | mit | kdkeyser/readthedocs.org,fujita-shintaro/readthedocs.org,GovReady/readthedocs.org,sunnyzwh/readthedocs.org,fujita-shintaro/readthedocs.org,titiushko/readthedocs.org,asampat3090/readthedocs.org,takluyver/readthedocs.org,SteveViss/readthedocs.org,ojii/readthedocs.org,mrshoki/readthedocs.org,ojii/readthedocs.org,CedarLogi... | ---
+++
@@ -7,7 +7,7 @@
'core.views.subproject_serve_docs',
name='subproject_docs_detail'
),
- url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.+)$',
+ url(r'^(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$',
'core.views.serve_docs',
n... |
594923a44d80a2879eb1ed5b9b0a6be11e13c88f | tests/Epsilon_tests/ImportTest.py | tests/Epsilon_tests/ImportTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import EPS
from grammpy import EPSILON
class ImportTest(TestCase):
def test_idSame(self):
self.assertEqual(id(EPS),id(EPSILON)... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import TestCase, main
from grammpy import EPS
from grammpy import EPSILON
class ImportTest(TestCase):
def test_idSame(self):
self.assertEqual(id(EPS), id(EPSILON))... | Revert "Revert "Add tests to compare epsilon with another objects"" | Revert "Revert "Add tests to compare epsilon with another objects""
This reverts commit d13b3d89124d03f563c2ee2143ae16eec7d0b191.
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -13,12 +13,24 @@
class ImportTest(TestCase):
-
def test_idSame(self):
- self.assertEqual(id(EPS),id(EPSILON))
+ self.assertEqual(id(EPS), id(EPSILON))
def test_equal(self):
self.assertEqual(EPS, EPSILON)
+ def test_equalToSelf(self):
+ self.assertEqual(EP... |
957047b0ba6be692b2b8385ffb41ae9d626bfe7b | tests/basics/OverflowFunctions.py | tests/basics/OverflowFunctions.py | # Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | # Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | Make the test robust against usage for comparisons between minor Python versions. | Make the test robust against usage for comparisons between minor Python versions.
Typically, for Wine, I have an older version installed, than my Debian has, and
this then fails the test without strict need.
| Python | apache-2.0 | tempbottle/Nuitka,kayhayen/Nuitka,wfxiang08/Nuitka,tempbottle/Nuitka,wfxiang08/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,tempbottle/Nuitka,wfxiang08/Nuitka,kayhayen/Nuitka,wfxiang08/Nuitka,tempbottle/Nuitka | ---
+++
@@ -19,7 +19,7 @@
def starImporterFunction():
from sys import *
- print "Version", version.split()[0]
+ print "Version", version.split()[0].split( "." )[:-1]
starImporterFunction()
|
34fda0b20a87b94d7413054bfcfc81dad0ecde19 | utils/get_message.py | utils/get_message.py | import amqp
from contextlib import closing
def get_message(queue):
""" Get the first message from a queue.
The first message from a queue is retrieved. If there is no such message, the function exits quietly.
:param queue: The name of the queue from which to get the message.
Usage::
>>> from ... | import amqp
from contextlib import closing
def __get_channel(connection):
return connection.channel()
def __get_message_from_queue(channel, queue):
return channel.basic_get(queue=queue)
def get_message(queue):
""" Get the first message from a queue.
The first message from a queue is retrieved. If t... | Revert "Remove redundant functions (one too many levels of abstraction)@" | Revert "Remove redundant functions (one too many levels of abstraction)@"
This reverts commit 9c5bf06d1427db9839b1531aa08e66574c7b4582.
| Python | mit | jdgillespie91/trackerSpend,jdgillespie91/trackerSpend | ---
+++
@@ -1,6 +1,12 @@
import amqp
from contextlib import closing
+
+def __get_channel(connection):
+ return connection.channel()
+
+def __get_message_from_queue(channel, queue):
+ return channel.basic_get(queue=queue)
def get_message(queue):
""" Get the first message from a queue.
@@ -16,5 +22,5 ... |
7eb8da13a873604f12dd9a4b9e890be7447115c4 | tests/services/authorization/test_service.py | tests/services/authorization/test_service.py | """
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.authorization import service as authorization_service
from tests.base import AbstractAppTestCase
class AuthorizationServiceTestCase(AbstractAppTestCase):
def test_get_permission_ids_for_user... | """
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.authorization import service as authorization_service
from tests.base import AbstractAppTestCase
from tests.helpers import assign_permissions_to_user
class AuthorizationServiceTestCase(AbstractAp... | Use existing test helper to create and assign permissions and roles | Use existing test helper to create and assign permissions and roles
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps | ---
+++
@@ -6,25 +6,24 @@
from byceps.services.authorization import service as authorization_service
from tests.base import AbstractAppTestCase
+from tests.helpers import assign_permissions_to_user
class AuthorizationServiceTestCase(AbstractAppTestCase):
def test_get_permission_ids_for_user(self):
- ... |
2b6f3687c5203364ce3d935e10a05fbcc1b16ed5 | tests/messenger/messaging_test.py | tests/messenger/messaging_test.py | import os
import vcr_unittest
from app.messenger import messaging
class MessagingTestCase(vcr_unittest.VCRTestCase):
def setUp(self):
self.access_token = os.environ['ACCESS_TOKEN']
self.user_id = '100011269503253'
def test_send_main_menu(self):
response = messaging.send_main_me... | import os
import vcr_unittest
from app.messenger import messaging
class MessagingTestCase(vcr_unittest.VCRTestCase):
def setUp(self):
self.access_token = os.environ['ACCESS_TOKEN']
self.user_id = '474276666029691'
def test_send_main_menu(self):
response = messaging.send_main_me... | Replace test user_id with a correct one | Replace test user_id with a correct one
| Python | mit | Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot | ---
+++
@@ -9,7 +9,7 @@
def setUp(self):
self.access_token = os.environ['ACCESS_TOKEN']
- self.user_id = '100011269503253'
+ self.user_id = '474276666029691'
def test_send_main_menu(self):
response = messaging.send_main_menu(self.access_token, self.user_id) |
bfed3c6b45810d2dacfbf71e499e450a0c762ad7 | django_rq/decorators.py | django_rq/decorators.py | from rq.decorators import job
from .queues import get_queue
class job(job):
"""
The same as RQ's job decorator, but it works automatically works out
the ``connection`` argument from RQ_QUEUES.
"""
def __init__(self, queue, connection=None, *args, **kwargs):
if isinstance(queue, b... | from rq.decorators import job as _rq_job
from .queues import get_queue
def job(func_or_queue, connection=None, *args, **kwargs):
"""
The same as RQ's job decorator, but it works automatically works out
the ``connection`` argument from RQ_QUEUES.
And also, it allows simplified ``@job`` syntax to put ... | Allow simple syntax for `job` decorator. | Allow simple syntax for `job` decorator.
It is nice to use simple syntax:
@job
def some_func():
pass
in cases, when you have only 'default' queue.
| Python | mit | mjec/django-rq,ui/django-rq,sbussetti/django-rq,meteozond/django-rq,viaregio/django-rq,1024inc/django-rq,lechup/django-rq,ryanisnan/django-rq,sbussetti/django-rq,lechup/django-rq,ryanisnan/django-rq,1024inc/django-rq,meteozond/django-rq,ui/django-rq,mjec/django-rq,viaregio/django-rq | ---
+++
@@ -1,20 +1,33 @@
-from rq.decorators import job
+from rq.decorators import job as _rq_job
from .queues import get_queue
-class job(job):
+def job(func_or_queue, connection=None, *args, **kwargs):
"""
The same as RQ's job decorator, but it works automatically works out
the ``connection``... |
748a9ebf425f7ff4b28c34bc371735d2a892ec58 | snoop/ipython.py | snoop/ipython.py | import ast
from snoop import snoop
from IPython import get_ipython
from IPython.core.magic import Magics, cell_magic, magics_class
@magics_class
class SnoopMagics(Magics):
@cell_magic
def snoop(self, _line, cell):
shell = get_ipython()
filename = shell.compile.cache(cell)
code = shell... | import ast
from snoop import snoop
from IPython.core.magic import Magics, cell_magic, magics_class
@magics_class
class SnoopMagics(Magics):
@cell_magic
def snoop(self, _line, cell):
filename = self.shell.compile.cache(cell)
code = self.shell.compile(cell, filename, 'exec')
tracer = sn... | Use shell attribute of magics class | Use shell attribute of magics class
| Python | mit | alexmojaki/snoop,alexmojaki/snoop | ---
+++
@@ -1,7 +1,6 @@
import ast
from snoop import snoop
-from IPython import get_ipython
from IPython.core.magic import Magics, cell_magic, magics_class
@@ -9,9 +8,8 @@
class SnoopMagics(Magics):
@cell_magic
def snoop(self, _line, cell):
- shell = get_ipython()
- filename = shell.... |
e5876287aacda81bac2d9937e285d132c7133094 | test/tests/python-imports/container.py | test/tests/python-imports/container.py | import platform
isWindows = platform.system() == 'Windows'
isNotPypy = platform.python_implementation() != 'PyPy'
isCaveman = platform.python_version_tuple()[0] == '2'
if not isWindows:
import curses
import readline
if isCaveman:
import gdbm
else:
import dbm.gnu
if isNotPypy:... | import platform
isWindows = platform.system() == 'Windows'
isNotPypy = platform.python_implementation() != 'PyPy'
isCaveman = platform.python_version_tuple()[0] == '2'
if not isWindows:
import curses
import readline
if isCaveman:
import gdbm
else:
import dbm.gnu
if isNotPypy:... | Add "lzma" to "python-imports" test | Add "lzma" to "python-imports" test
| Python | apache-2.0 | docker-library/official-images,infosiftr/stackbrew,31z4/official-images,dinogun/official-images,docker-library/official-images,docker-solr/official-images,docker-library/official-images,docker-library/official-images,neo-technology/docker-official-images,neo-technology/docker-official-images,thresheek/official-images,3... | ---
+++
@@ -23,3 +23,7 @@
import zlib
assert(zlib.decompress(zlib.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
+
+if not isCaveman:
+ import lzma
+ assert(lzma.decompress(lzma.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS') |
a5791ea2a229b13eb84cc92bd20d87df93687d5e | cactus/skeleton/plugins/sprites.disabled.py | cactus/skeleton/plugins/sprites.disabled.py | import os
import sys
import pipes
import shutil
import subprocess
"""
This plugin uses glue to sprite images:
http://glue.readthedocs.org/en/latest/quickstart.html
Install:
(Only if you want to sprite jpg too)
brew install libjpeg
(Only if you want to optimize pngs with optipng)
brew install optipng
sudo easy_inst... | import os
import sys
import pipes
import shutil
import subprocess
"""
This plugin uses glue to sprite images:
http://glue.readthedocs.org/en/latest/quickstart.html
Install:
(Only if you want to sprite jpg too)
brew install libjpeg
sudo easy_install pip
sudo pip uninstall pil
sudo pip install pil
sudo pip install gl... | Remove deprecated --optipng from glue options | Remove deprecated --optipng from glue options
Optipng is now deprecated in glue, so including that option in
Cactus doesn't really make sense.
https://github.com/jorgebastida/glue/blob/master/docs/changelog.rst#09
| Python | bsd-3-clause | dreadatour/Cactus,fjxhkj/Cactus,juvham/Cactus,andyzsf/Cactus-,Knownly/Cactus,danielmorosan/Cactus,ibarria0/Cactus,danielmorosan/Cactus,page-io/Cactus,koobs/Cactus,andyzsf/Cactus-,PegasusWang/Cactus,chaudum/Cactus,danielmorosan/Cactus,dreadatour/Cactus,juvham/Cactus,eudicots/Cactus,page-io/Cactus,koobs/Cactus,dreadatour... | ---
+++
@@ -12,9 +12,6 @@
(Only if you want to sprite jpg too)
brew install libjpeg
-
-(Only if you want to optimize pngs with optipng)
-brew install optipng
sudo easy_install pip
sudo pip uninstall pil
@@ -50,6 +47,6 @@
shutil.rmtree(CSS_PATH)
os.mkdir(CSS_PATH)
- os.system('glue --cachebuster --crop... |
1da0f795cdedd1de3bdcc03d6171f9a143ee8e5b | backdrop/admin/config/development.py | backdrop/admin/config/development.py | LOG_LEVEL = "DEBUG"
SINGLE_SIGN_ON = True
BACKDROP_ADMIN_UI_HOST = "http://backdrop-admin.dev.gov.uk"
ALLOW_TEST_SIGNIN=True
SECRET_KEY = "something unique and secret"
DATABASE_NAME = "backdrop"
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
try:
from development_environment import *
except ImportError:
from dev... | LOG_LEVEL = "DEBUG"
BACKDROP_ADMIN_UI_HOST = "http://backdrop-admin.dev.gov.uk"
ALLOW_TEST_SIGNIN=True
SECRET_KEY = "something unique and secret"
DATABASE_NAME = "backdrop"
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
try:
from development_environment import *
except ImportError:
from development_environment_s... | Remove flag to enable single sign on | Remove flag to enable single sign on
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -1,5 +1,4 @@
LOG_LEVEL = "DEBUG"
-SINGLE_SIGN_ON = True
BACKDROP_ADMIN_UI_HOST = "http://backdrop-admin.dev.gov.uk"
ALLOW_TEST_SIGNIN=True
SECRET_KEY = "something unique and secret" |
52bbd54503cbf3fe3e4db2e8033967351bb638b0 | pi/web/temperature_client.py | pi/web/temperature_client.py | import requests
"""Client to retrieve the current temperature reading"""
class TemperatureClient:
def __init__(self, host, port):
self.host = host
self.port = port
def get(self):
"""Retrieve the reading from the temperature server"""
location = "http://{0}:{1}/".format(self.hos... | import requests
"""Client to retrieve the current temperature reading"""
class TemperatureClient:
def __init__(self, host, port):
self.host = host
self.port = port
def get(self):
"""Retrieve the reading from the temperature server"""
location = "http://{0}:{1}/".format(self.hos... | Fix incorrect variable from TemperatureClient | Fix incorrect variable from TemperatureClient
| Python | mit | drewtempelmeyer/harbor-roasts | ---
+++
@@ -10,5 +10,5 @@
"""Retrieve the reading from the temperature server"""
location = "http://{0}:{1}/".format(self.host, self.port)
response = requests.get(location)
- return r.json()
+ return response.json()
|
e2f2fbc0df695102c4d51bdf0e633798c3ae8417 | yawf/messages/submessage.py | yawf/messages/submessage.py | from . import Message
class Submessage(object):
need_lock_object = True
def __init__(self, obj, message_id, sender, raw_params, need_lock_object=True):
self.obj = obj
self.sender = sender
self.message_id = message_id
self.raw_params = raw_params
self.need_lock_object =... | from . import Message
class Submessage(object):
need_lock_object = True
def __init__(self, obj, message_id, sender, raw_params=None, need_lock_object=True):
self.obj = obj
self.sender = sender
self.message_id = message_id
self.raw_params = raw_params
self.need_lock_obj... | Make raw_params an optional argument in Submessage | Make raw_params an optional argument in Submessage
| Python | mit | freevoid/yawf | ---
+++
@@ -4,7 +4,7 @@
need_lock_object = True
- def __init__(self, obj, message_id, sender, raw_params, need_lock_object=True):
+ def __init__(self, obj, message_id, sender, raw_params=None, need_lock_object=True):
self.obj = obj
self.sender = sender
self.message_id = messa... |
7406e2fdcc19566e4a577c8dd4a3484f401580c7 | pinry/settings/docker.py | pinry/settings/docker.py | import logging
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
if 'SECRET_KEY' not in os.environ:
logging.warning(
"No SECRET_KEY given in environ, please have a check"
)
SECRET_KEY = os.environ.get('SECRET_KEY', "PLEASE_REPLACE_ME")
# SECURITY WARNING: don't r... | import logging
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
if 'SECRET_KEY' not in os.environ:
logging.warning(
"No SECRET_KEY given in environ, please have a check"
)
SECRET_KEY = os.environ.get('SECRET_KEY', "PLEASE_REPLACE_ME")
# SECURITY WARNING: don't r... | Allow JsonRender only in production mode | Feature: Allow JsonRender only in production mode
| Python | bsd-2-clause | lapo-luchini/pinry,pinry/pinry,pinry/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,lapo-luchini/pinry | ---
+++
@@ -31,6 +31,10 @@
USE_X_FORWARDED_HOST = True
+REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] = [
+ 'rest_framework.renderers.JSONRenderer',
+]
+
try:
from .local_settings import *
except ImportError: |
d0139d460b1f4710e8f870700ecf51336538d430 | examples/basic_flask.py | examples/basic_flask.py | import flask
import mmstats
application = app = flask.Flask(__name__)
app.config['DEBUG'] = True
class Stats(mmstats.MmStats):
ok = mmstats.CounterField(label="mmstats.example.ok")
bad = mmstats.CounterField(label="mmstats.example.bad")
working = mmstats.BoolField(label="mmstats.example.working")
stat... | import flask
import mmstats
application = app = flask.Flask(__name__)
app.config['DEBUG'] = True
class Stats(mmstats.MmStats):
ok = mmstats.CounterField(label="mmstats.example.ok")
bad = mmstats.CounterField(label="mmstats.example.bad")
working = mmstats.BoolField(label="mmstats.example.working")
stat... | Make the default OK page in the flask example obvious to find | Make the default OK page in the flask example obvious to find
| Python | bsd-3-clause | schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats | ---
+++
@@ -31,9 +31,9 @@
flask.request_finished.connect(inc_response, app)
-@app.route('/200')
+@app.route('/')
def ok():
- return 'OK'
+ return "OK or see /status for a single process's status"
@app.route('/500') |
49ea86d93d75afb1c3a3f95dd72a78b6d78f04cc | sitecustomize.py | sitecustomize.py |
import sys
import os
from combinator.branchmgr import theBranchManager
theBranchManager.addPaths()
for key in sys.modules.keys():
# Unload all Combinator modules that had to be loaded in order to call
# addPaths(). Although the very very beginning of this script needs to
# load the trunk combinator (or ... |
import sys
import os
from combinator.branchmgr import theBranchManager
theBranchManager.addPaths()
for key in sys.modules.keys():
# Unload all Combinator modules that had to be loaded in order to call
# addPaths(). Although the very very beginning of this script needs to
# load the trunk combinator (or ... | Remove distutils-mangling code from Combinator which breaks setuptools. | Remove distutils-mangling code from Combinator which breaks setuptools.
After this change, Combinator will no longer attempt to force 'python setup.py install' to put things into your home directory. Use `setup.py --prefix ~/.local`, or, if your package is trying to use setuptools, `python setup.py --site-dirs ~/.loc... | Python | mit | habnabit/Combinator,habnabit/Combinator | ---
+++
@@ -18,25 +18,3 @@
if key == 'combinator' or key.startswith('combinator'):
del sys.modules[key]
-# Install stuff as a user, by default.
-
-if sys.platform != 'darwin':
- # For use with setup.py...
-
- if sys.platform.startswith('win'):
- execprefix = os.path.abspath(os.path.expand... |
7525ddcd1a0c668045f37e87cbafa4a598b10148 | apps/__init__.py | apps/__init__.py | ## module loader, goes to see which submodules have 'html' directories
## and declares them at the toplevel
import os,importlib
def find_module_dirs():
curdir = os.path.dirname(os.path.abspath(__file__))
subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))]
... | ## module loader, goes to see which submodules have 'html' directories
## and declares them at the toplevel
import os,importlib
def find_module_dirs():
curdir = os.path.dirname(os.path.abspath(__file__))
subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))]
... | Handle application erroring to not break the server | Handle application erroring to not break the server
| Python | agpl-3.0 | indx/indx-core,indx/indx-core,indx/indx-core,indx/indx-core,indx/indx-core | ---
+++
@@ -13,7 +13,13 @@
subdirs = [(o,os.path.sep.join([curdir,o,'html'])) for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'html']))]
return dict(subdirs)
+def import_app(app):
+ try:
+ importlib.import_module(app)
+ except Exception as e:
+ logging.error("C... |
72fb6ca12b685809bd5de0c5df9f051eef1163c4 | test/TestBaseUtils.py | test/TestBaseUtils.py | import unittest
import sys
sys.path.append('../src')
import BaseUtils
class TestBaseUtils(unittest.TestCase):
def test_word_segmenter(self):
segments = BaseUtils.get_words('this is a random sentence')
self.assertEqual(segments, ['this', 'is', 'a', 'random', 'sentence'])
def test_word_segmente... | ''' Tests for BaseUtils
'''
import unittest
import sys
sys.path.append('../src')
import BaseUtils
class TestBaseUtils(unittest.TestCase):
''' Main test class for the BaseUtils '''
def test_word_segmenter_with_empty(self):
''' For an empty string, the segmenter returns
just an empty list '''
... | Add test for empty string; cleanup | Add test for empty string; cleanup
| Python | bsd-2-clause | ambidextrousTx/RNLTK | ---
+++
@@ -1,3 +1,5 @@
+''' Tests for BaseUtils
+'''
import unittest
import sys
sys.path.append('../src')
@@ -5,15 +7,28 @@
class TestBaseUtils(unittest.TestCase):
+ ''' Main test class for the BaseUtils '''
+ def test_word_segmenter_with_empty(self):
+ ''' For an empty string, the segmenter ret... |
73c9173f801048cba0a9a72e78073c454a1ba0c4 | rinse/client.py | rinse/client.py | """SOAP client."""
from __future__ import print_function
import requests
from rinse import ENVELOPE_XSD
from rinse.util import SCHEMA
from rinse.response import RinseResponse
class SoapClient(object):
"""Rinse SOAP client."""
__session = None
def __init__(self, url, debug=False, **kwargs):
"""S... | """SOAP client."""
from __future__ import print_function
import requests
from rinse import ENVELOPE_XSD
from rinse.util import SCHEMA
from rinse.response import RinseResponse
class SoapClient(object):
"""Rinse SOAP client."""
__session = None
def __init__(self, url, debug=False, **kwargs):
"""S... | Fix line continuation indent level. | Fix line continuation indent level.
| Python | mit | MarkusH/rinse,MarkusH/rinse,simudream/rinse,tysonclugg/rinse,simudream/rinse,tysonclugg/rinse | ---
+++
@@ -33,7 +33,7 @@
self.__session = session
def __call__(self, msg, action="", build_response=RinseResponse,
- debug=False):
+ debug=False):
"""Post 'msg' to remote service."""
# generate HTTP request from msg
request = msg.request(self.url,... |
2b8208e2f6ba8554aefc8e984132a0d4084c26ec | open_folder.py | open_folder.py | import os, platform
# I intend to hide the Operating Specific details of opening a folder
# here in this module.
#
# On Mac OS X you do this with "open"
# e.g. "open '\Users\golliher\Documents\Tickler File'"
# On Windows you do this with "explorer"
# e.g. "explorer c:\Documents and Settings\Tickler File"
# On Lin... | import os, platform, subprocess
# I intend to hide the Operating Specific details of opening a folder
# here in this module.
#
# On Mac OS X you do this with "open"
# e.g. "open '\Users\golliher\Documents\Tickler File'"
# On Windows you do this with "explorer"
# e.g. "explorer c:\Documents and Settings\Tickler Fi... | Raise exception if path not found, os not found, or command execution fails. | Raise exception if path not found, os not found, or command execution fails.
| Python | mit | golliher/dg-tickler-file | ---
+++
@@ -1,4 +1,4 @@
-import os, platform
+import os, platform, subprocess
# I intend to hide the Operating Specific details of opening a folder
# here in this module.
#
@@ -13,14 +13,19 @@
path = os.path.normpath(path)
+ if not os.path.isdir(path):
+ raise Exception("Folder does not exist.... |
6ed5d899d8c2fbef8c4b40180c497421b9f8e6c4 | map_service/serializers.py | map_service/serializers.py | from map_service.models import LkState
from map_service.models import SpatialObjects
from rest_framework_mongoengine import serializers
class LkStateSerializer(serializers.DocumentSerializer):
class Meta:
model = LkState
class SpatialObjectsSerializer(serializers.DocumentSerializer):
class Meta:
... | from map_service.models import LkState
from map_service.models import SpatialObjects
from rest_framework_mongoengine import serializers
class LkStateSerializer(serializers.DocumentSerializer):
class Meta:
model = LkState
fields = '__all__'
class SpatialObjectsSerializer(serializers.DocumentSerial... | Fix Compatibility issue with django 1.8+ | Fix Compatibility issue with django 1.8+
| Python | apache-2.0 | tmkasun/Knnect,tmkasun/Knnect,tmkasun/Knnect,tmkasun/Knnect | ---
+++
@@ -6,7 +6,7 @@
class LkStateSerializer(serializers.DocumentSerializer):
class Meta:
model = LkState
-
+ fields = '__all__'
class SpatialObjectsSerializer(serializers.DocumentSerializer):
class Meta: |
b69e7f094514e0027f5fabda9d4c127c5cc1d512 | sir/__main__.py | sir/__main__.py | # Copyright (c) 2014 Wieland Hoffmann
# License: MIT, see LICENSE for details
import argparse
import logging
from . import config
from .indexing import reindex
logger = logging.getLogger("sir")
def watch(args):
raise NotImplementedError
def main():
loghandler = logging.StreamHandler()
formatter = lo... | # Copyright (c) 2014 Wieland Hoffmann
# License: MIT, see LICENSE for details
import argparse
import logging
from . import config
from .indexing import reindex
logger = logging.getLogger("sir")
def watch(args):
raise NotImplementedError
def main():
loghandler = logging.StreamHandler()
formatter = lo... | Change the logging format to begin with the threadname | Change the logging format to begin with the threadname
| Python | mit | jeffweeksio/sir | ---
+++
@@ -17,7 +17,7 @@
def main():
loghandler = logging.StreamHandler()
- formatter = logging.Formatter(fmt="%(asctime)s %(threadName)s %(levelname)s: %(message)s")
+ formatter = logging.Formatter(fmt="%(threadName)s %(asctime)s %(levelname)s: %(message)s")
loghandler.setFormatter(formatter)
... |
5ffb645e36fdbb3feae52ac6dfedb1b492f45b8f | examples/list.py | examples/list.py | # Copyright (c) 2013 Jordan Halterman <jordan.halterman@gmail.com>
# See LICENSE for details.
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from active_redis import ActiveRedis
redis = ActiveRedis()
# Create an unnamed list.
mylist = redis.list()
# Append items to the list.
mylist.app... | # Copyright (c) 2013 Jordan Halterman <jordan.halterman@gmail.com>
# See LICENSE for details.
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from active_redis import ActiveRedis
redis = ActiveRedis()
# Create an unnamed list.
mylist = redis.list()
# Append items to the list.
mylist.app... | Update dict and set examples. | Update dict and set examples.
| Python | mit | kuujo/active-redis | ---
+++
@@ -20,6 +20,7 @@
# will capture changes and re-serialize the list.
mylist.append(['foo', 'bar'])
mylist[2].append('baz')
+mylist.delete()
# We can also create a named list by passing a key to the constructor.
mylist = redis.list('mylist') |
ce4bb4b0868e45459771531b9008f492f920c406 | project/commands/main.py | project/commands/main.py | """The ``main`` function chooses and runs a subcommand."""
from __future__ import absolute_import, print_function
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import project.commands.launch as launch
import project.commands.prepare as prepare
import project.commands.activate as activate
def _run... | """The ``main`` function chooses and runs a subcommand."""
from __future__ import absolute_import, print_function
import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import project.commands.launch as launch
import project.commands.prepare as prepare
import project.commands.activate as activate... | Revert "remove unecessary sys.exit call" | Revert "remove unecessary sys.exit call"
This reverts commit 50b79fec1e96c1e5e5cc17f58f2c4ccfba16d6d6.
| Python | bsd-3-clause | conda/kapsel,conda/kapsel | ---
+++
@@ -1,6 +1,7 @@
"""The ``main`` function chooses and runs a subcommand."""
from __future__ import absolute_import, print_function
+import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter
import project.commands.launch as launch
@@ -35,3 +36,6 @@
def main(argv):
"""Start the l... |
f808dbbd28e750a7be440394865e708c78938c6c | test/test_compiled.py | test/test_compiled.py | """
Test compiled module
"""
import os
import platform
import sys
import jedi
from .helpers import cwd_at
@cwd_at('extensions')
def test_compiled():
if platform.architecture()[0] == '64bit':
package_name = "compiled%s%s" % sys.version_info[:2]
if os.path.exists(package_name):
s = jedi... | """
Test compiled module
"""
import os
import platform
import sys
import jedi
from .helpers import cwd_at
@cwd_at('extensions')
def test_compiled():
if platform.architecture()[0] == '64bit':
package_name = "compiled%s%s" % sys.version_info[:2]
sys.path.insert(0, os.getcwd())
if os.path.ex... | Change sys.path for the test to succeed. | Change sys.path for the test to succeed.
Tested locally with a python3 extension module (in
/extensions/compiled33).
Also tested that reverting a75773cf9f7a9fde2a7b2c77b9846b4f0dd5b711 make
the test fail.
| Python | mit | flurischt/jedi,tjwei/jedi,jonashaag/jedi,dwillmer/jedi,tjwei/jedi,WoLpH/jedi,flurischt/jedi,dwillmer/jedi,mfussenegger/jedi,jonashaag/jedi,WoLpH/jedi,mfussenegger/jedi | ---
+++
@@ -13,6 +13,7 @@
def test_compiled():
if platform.architecture()[0] == '64bit':
package_name = "compiled%s%s" % sys.version_info[:2]
+ sys.path.insert(0, os.getcwd())
if os.path.exists(package_name):
s = jedi.Script("from %s import compiled; compiled." % package_na... |
00df7af980d0e469173ad4f3d82cb7c68b51ea21 | fancyflags/_metadata.py | fancyflags/_metadata.py | # Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | # Copyright 2021 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | Update fancyflags version to 1.0 | Update fancyflags version to 1.0
PiperOrigin-RevId: 354582100
Change-Id: Ib4ce53fd0fc197c0f92cd8d46348dec8849c51df
| Python | apache-2.0 | deepmind/fancyflags | ---
+++
@@ -18,4 +18,4 @@
a time when the package dependencies may not have been installed yet.
"""
-__version__ = 'a0.1' # https://www.python.org/dev/peps/pep-0440/
+__version__ = '1.0' # https://www.python.org/dev/peps/pep-0440/ |
7c4f3f8b4d3ac92290af45bba4995ba266b78704 | osuapi/__init__.py | osuapi/__init__.py | __title__ = "osssss"
__author__ = "khazhyk"
__license__ = "MIT"
__copyright__ = "Copyright khazhyk"
__version__ = "0.0.8"
from .osu import OsuApi
from .connectors import *
from .model import OsuMode, OsuMod, BeatmapStatus, BeatmapGenre, BeatmapLanguage
| __title__ = "osuapi"
__author__ = "khazhyk"
__license__ = "MIT"
__copyright__ = "Copyright khazhyk"
__version__ = "0.0.8"
from .osu import OsuApi
from .connectors import *
from .model import OsuMode, OsuMod, BeatmapStatus, BeatmapGenre, BeatmapLanguage
| Rename to osuapi to match module. | Rename to osuapi to match module.
| Python | mit | Phxntxm/osuapi,khazhyk/osuapi | ---
+++
@@ -1,4 +1,4 @@
-__title__ = "osssss"
+__title__ = "osuapi"
__author__ = "khazhyk"
__license__ = "MIT"
__copyright__ = "Copyright khazhyk" |
5a2d8a580795be37312a6ccfd2e3d0ffca28dc1c | bot/config.py | bot/config.py | import logging
import pytz
BOT_URL = ""
LAST_UPDATE_ID_FILE = "last_update"
TAGS_FILE = "tags"
POLL_PERIOD = 1
MAX_TAGS = 5
LOGGING_LEVEL = logging.DEBUG
LOCAL_TIMEZONE = pytz.timezone('America/Mexico_City')
| import os
import logging
import pytz
BOT_URL = os.getenv("BOT_URL", "")
LAST_UPDATE_ID_FILE = "last_update"
TAGS_FILE = "tags"
POLL_PERIOD = 1
MAX_TAGS = 5
LOGGING_LEVEL = logging.DEBUG
LOCAL_TIMEZONE = pytz.timezone('America/Mexico_City')
| Enable BOT_URL from env variable | Enable BOT_URL from env variable
| Python | mit | cesar0094/telegram-tldrbot | ---
+++
@@ -1,7 +1,8 @@
+import os
import logging
import pytz
-BOT_URL = ""
+BOT_URL = os.getenv("BOT_URL", "")
LAST_UPDATE_ID_FILE = "last_update"
TAGS_FILE = "tags"
POLL_PERIOD = 1 |
df227a375c1cf5fdd0ad23505799e7c6f7177b9c | InvenTree/InvenTree/validators.py | InvenTree/InvenTree/validators.py | """
Custom field validators for InvenTree
"""
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_part_name(value):
# Prevent some illegal characters in part names
for c in ['/', '\\', '|', '#', '$']:
if c in str(value):
r... | """
Custom field validators for InvenTree
"""
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_part_name(value):
# Prevent some illegal characters in part names
for c in ['|', '#', '$']:
if c in str(value):
raise Valida... | Allow some more chars in part names | Allow some more chars in part names
| Python | mit | inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree | ---
+++
@@ -8,7 +8,7 @@
def validate_part_name(value):
# Prevent some illegal characters in part names
- for c in ['/', '\\', '|', '#', '$']:
+ for c in ['|', '#', '$']:
if c in str(value):
raise ValidationError(
_('Invalid character in part name') |
33496a58852bcdb2ef9f3cbe1881b06efd48b624 | script/sample/submitshell.py | script/sample/submitshell.py | #!/usr/bin/env python
import multyvac
multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/api')
jid = multyvac.shell_submit(cmd='for i in {1..10}; do echo $i && sleep 10; done')
print("Submitted job [{}].".format(jid))
job = multyvac.get(jid)
result = job.get_result()
print(... | #!/usr/bin/env python
from __future__ import print_function
import multyvac
import sys
multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/api')
jobs = {
"stdout result": {
"cmd": 'echo "success"',
},
"file result": {
"cmd": 'echo "success" > /tmp... | Test different mechanisms for job submission. | Test different mechanisms for job submission.
| Python | bsd-3-clause | cloudpipe/cloudpipe,cloudpipe/cloudpipe,cloudpipe/cloudpipe | ---
+++
@@ -1,12 +1,44 @@
#!/usr/bin/env python
+from __future__ import print_function
+
import multyvac
+import sys
multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/api')
-jid = multyvac.shell_submit(cmd='for i in {1..10}; do echo $i && sleep 10; done')
-print("Su... |
ca138dac13d032ac8f55ca0a5ebf4e1ffe2cab72 | fuckit_commit.py | fuckit_commit.py | '''
This module will send SMS reminders periodically, using Twilio.
The aim is to encourage user to code, commit and push to GitHub everyday
'''
import requests
from twilio.rest import TwilioRestClient
from datetime import datetime, date
def send_sms():
'''
Send SMS reminder
'''
config = {'account_sid... | '''
This module will send SMS reminders periodically, using Twilio.
The aim is to encourage user to code, commit and push to GitHub everyday
'''
import requests
from twilio.rest import TwilioRestClient
from datetime import datetime, date
def send_sms():
'''
Send SMS reminder
'''
config = {'account_sid... | Add condition to check for latest commit activity | Add condition to check for latest commit activity
| Python | mit | ueg1990/fuckit_commit | ---
+++
@@ -17,18 +17,17 @@
body="Hello there!")
def check_commit_activity():
'''
- Check if there was any change in the commit history of the user
+ Check if there was any change in the commit history of the user. If date of
+ latest event is the same as current ... |
fd9f9bb2f471a8c14e7d34276060be953795538f | nightreads/emails/admin.py | nightreads/emails/admin.py | from django.contrib import admin
from django.conf.urls import url
from .models import Email, Tag
from .views import SendEmailAdminView, UpdateTargetCountView
from .forms import EmailAdminForm
class EmailAdmin(admin.ModelAdmin):
form = EmailAdminForm
readonly_fields = ('targetted_users', 'is_sent',)
add_f... | from django.contrib import admin
from django.conf.urls import url
from .models import Email, Tag
from .views import SendEmailAdminView, UpdateTargetCountView
from .forms import EmailAdminForm
class EmailAdmin(admin.ModelAdmin):
list_display = ['__str__', 'is_sent']
list_filter = ['is_sent']
form = EmailA... | Add filters to Email Admin List View | Add filters to Email Admin List View
| Python | mit | avinassh/nightreads,avinassh/nightreads | ---
+++
@@ -7,6 +7,8 @@
class EmailAdmin(admin.ModelAdmin):
+ list_display = ['__str__', 'is_sent']
+ list_filter = ['is_sent']
form = EmailAdminForm
readonly_fields = ('targetted_users', 'is_sent',)
add_fieldsets = ( |
7ba23ab480df92025c3d76c4afa6d56987088899 | serialenum.py | serialenum.py | import os
import os.path
import sys
def enumerate():
ports = []
if sys.platform == 'win32':
# Iterate through registry because WMI does not show virtual serial ports
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'HARDWARE\DEVICEMAP\SERIALCOMM')
i = 0
... | import os
import os.path
import sys
def enumerate():
ports = []
if sys.platform == 'win32':
# Iterate through registry because WMI does not show virtual serial ports
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'HARDWARE\DEVICEMAP\SERIALCOMM')
i = 0
... | Return None for unsupported platforms | Return None for unsupported platforms
| Python | bsd-2-clause | djs/serialenum | ---
+++
@@ -25,5 +25,7 @@
for x in entries]
ports.extend([os.path.normpath(os.path.join('/dev/serial/by-id', x))
for x in dirs])
+ else:
+ return None
return ports |
8fa895189696e83e6120875886bc8888e0509195 | bin/confluent-server.py | bin/confluent-server.py | import sys
import os
path = os.path.dirname(os.path.realpath(__file__))
path = os.path.realpath(os.path.join(path, '..'))
sys.path.append(path)
from confluent import main
main.run()
| import sys
import os
path = os.path.dirname(os.path.realpath(__file__))
path = os.path.realpath(os.path.join(path, '..'))
sys.path.append(path)
from confluent import main
#import cProfile
#import time
#p = cProfile.Profile(time.clock)
#p.enable()
#try:
main.run()
#except:
# pass
#p.disable()
#p.print_stats(sort='cum... | Put comments in to hint a decent strategy to profile runtime performance | Put comments in to hint a decent strategy to profile runtime performance
To do performance optimization in this sort of application, this is
about as well as I have been able to manage in python. I will say perl with
NYTProf seems to be significantly better for data, but this is servicable.
I tried yappi, but it goe... | Python | apache-2.0 | chenglch/confluent,whowutwut/confluent,jufm/confluent,jufm/confluent,michaelfardu/thinkconfluent,xcat2/confluent,jjohnson42/confluent,jjohnson42/confluent,whowutwut/confluent,chenglch/confluent,michaelfardu/thinkconfluent,jufm/confluent,michaelfardu/thinkconfluent,xcat2/confluent,xcat2/confluent,xcat2/confluent,jjohnso... | ---
+++
@@ -5,4 +5,14 @@
sys.path.append(path)
from confluent import main
+#import cProfile
+#import time
+#p = cProfile.Profile(time.clock)
+#p.enable()
+#try:
main.run()
+#except:
+# pass
+#p.disable()
+#p.print_stats(sort='cumulative')
+#p.print_stats(sort='time') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.