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 |
|---|---|---|---|---|---|---|---|---|---|---|
abf91ac218c2386a2366eae243a15b1215f47832 | teuthology/task/tests/test_run.py | teuthology/task/tests/test_run.py | import logging
import pytest
from io import StringIO
from teuthology.exceptions import CommandFailedError
log = logging.getLogger(__name__)
class TestRun(object):
"""
Tests to see if we can make remote procedure calls to the current cluster
"""
def test_command_failed_label(self, ctx, config):
... | import logging
import pytest
from io import StringIO
from teuthology.exceptions import CommandFailedError
log = logging.getLogger(__name__)
class TestRun(object):
"""
Tests to see if we can make remote procedure calls to the current cluster
"""
def test_command_failed_label(self, ctx, config):
... | Fix reference to python binary | task.tests: Fix reference to python binary
It was trying to use `python` as opposed to `python3`.
Signed-off-by: Zack Cerza <d7cdf09fc0f0426e98c9978ee42da5d61fa54986@redhat.com>
| Python | mit | ktdreyer/teuthology,ceph/teuthology,ceph/teuthology,ktdreyer/teuthology | ---
+++
@@ -17,7 +17,7 @@
result = ""
try:
ctx.cluster.run(
- args=["python", "-c", "assert False"],
+ args=["python3", "-c", "assert False"],
label="working as expected, nothing to see here"
)
except CommandFailedErro... |
3d980016ad5fd65bb167d2f44a83c78e52ebb7b5 | applications/plugins/SofaPython/python/SofaPython/PythonAdvancedTimer.py | applications/plugins/SofaPython/python/SofaPython/PythonAdvancedTimer.py | import os
import sys
import Sofa
# ploting
import matplotlib.pyplot as plt
# JSON deconding
from collections import OrderedDict
import json
# argument parser: usage via the command line
import argparse
def measureAnimationTime(node, timerName, timerInterval, timerOutputType, resultFileName, simulationDeltaTime, itera... | import os
import sys
import Sofa
# ploting
import matplotlib.pyplot as plt
# JSON deconding
from collections import OrderedDict
import json
# argument parser: usage via the command line
import argparse
def measureAnimationTime(node, timerName, timerInterval, timerOutputType, resultFileName, simulationDeltaTime, itera... | FIX crash in python script when visualizing advanced timer output | [SofaPython] FIX crash in python script when visualizing advanced timer output
| Python | lgpl-2.1 | FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa | ---
+++
@@ -21,7 +21,7 @@
with open(resultFileName, "w+") as outputFile :
outputFile.write("{")
i = 0
- Sofa.timerSetOutPutType(timerName, timerOutputType)
+ Sofa.timerSetOutputType(timerName, timerOutputType)
while i < iterations:
Sofa.timerBegin(timerName)
... |
ffc1b8c83e32f4c2b5454a0ae71b9c30cc8e7596 | toolz/tests/test_serialization.py | toolz/tests/test_serialization.py | from toolz import *
import pickle
def test_compose():
f = compose(str, sum)
g = pickle.loads(pickle.dumps(f))
assert f((1, 2)) == g((1, 2))
def test_curry():
f = curry(map)(str)
g = pickle.loads(pickle.dumps(f))
assert list(f((1, 2, 3))) == list(g((1, 2, 3)))
def test_juxt():
f = juxt(... | from toolz import *
import pickle
def test_compose():
f = compose(str, sum)
g = pickle.loads(pickle.dumps(f))
assert f((1, 2)) == g((1, 2))
def test_curry():
f = curry(map)(str)
g = pickle.loads(pickle.dumps(f))
assert list(f((1, 2, 3))) == list(g((1, 2, 3)))
def test_juxt():
f = juxt(... | Add serialization test for `complement` | Add serialization test for `complement`
| Python | bsd-3-clause | pombredanne/toolz,simudream/toolz,machinelearningdeveloper/toolz,quantopian/toolz,jdmcbr/toolz,bartvm/toolz,jcrist/toolz,cpcloud/toolz,pombredanne/toolz,quantopian/toolz,simudream/toolz,machinelearningdeveloper/toolz,bartvm/toolz,llllllllll/toolz,jdmcbr/toolz,llllllllll/toolz,cpcloud/toolz,jcrist/toolz | ---
+++
@@ -19,3 +19,12 @@
g = pickle.loads(pickle.dumps(f))
assert f(1) == g(1)
assert f.funcs == g.funcs
+
+
+def test_complement():
+ f = complement(bool)
+ assert f(True) is False
+ assert f(False) is True
+ g = pickle.loads(pickle.dumps(f))
+ assert f(True) == g(True)
+ assert f(... |
7318e3f1a6169ed7b708d6f6f09816f1ff88419a | printer.py | printer.py | #!/usr/bin/env python2
from PrinterApplication import PrinterApplication
app = PrinterApplication.getInstance()
app.run()
| #!/usr/bin/env python3
from src.PrinterApplication import PrinterApplication
app = PrinterApplication.getInstance()
app.run()
| Load the right file for PrinterApplication | Load the right file for PrinterApplication
| Python | agpl-3.0 | markwal/Cura,totalretribution/Cura,quillford/Cura,bq/Ultimaker-Cura,DeskboxBrazil/Cura,totalretribution/Cura,quillford/Cura,ynotstartups/Wanhao,Curahelper/Cura,hmflash/Cura,derekhe/Cura,derekhe/Cura,hmflash/Cura,fxtentacle/Cura,fieldOfView/Cura,fxtentacle/Cura,lo0ol/Ultimaker-Cura,ynotstartups/Wanhao,ad1217/Cura,fieldO... | ---
+++
@@ -1,6 +1,6 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
-from PrinterApplication import PrinterApplication
+from src.PrinterApplication import PrinterApplication
app = PrinterApplication.getInstance()
app.run() |
f04ccb741ea059aed8891f647ff19b26172ba61c | src/tvmaze/parsers/__init__.py | src/tvmaze/parsers/__init__.py | """Parse data from TVMaze."""
import datetime
import typing
def parse_date(
val: typing.Optional[str],
) -> typing.Optional[datetime.date]:
"""
Parse date from TVMaze API.
:param val: A date string
:return: A datetime.date object
"""
fmt = '%Y-%m-%d'
try:
return datetime.... | """Parse data from TVMaze."""
import datetime
import typing
def parse_date(
val: typing.Optional[str],
) -> typing.Optional[datetime.date]:
"""
Parse date from TVMaze API.
:param val: A date string
:return: A datetime.date object
"""
fmt = '%Y-%m-%d'
try:
return datetime.... | Fix parsing duration when duration is None | Fix parsing duration when duration is None
Fixes tvmaze/tvmaze#14
| Python | mit | tvmaze/tvmaze | ---
+++
@@ -22,15 +22,19 @@
def parse_duration(
- val: int,
-) -> datetime.timedelta:
+ val: typing.Optional[int],
+) -> typing.Optional[datetime.timedelta]:
"""
Parse duration from TVMaze API.
:param val: A duration in minutes
:return: A datetime.timedelta object
"""
- ... |
a50cca78f400077d56b328a20661c1a9d1e2aff4 | app/tests/test_generate_profiles.py | app/tests/test_generate_profiles.py | import os
from unittest import TestCase
import re
from app import generate_profiles
class TestGenerateProfiles(TestCase):
gen = generate_profiles.GenerateProfiles
network_environment = "%s/misc/network-environment" % gen.bootcfg_path
@classmethod
def setUpClass(cls):
cls.gen = generate_prof... | import os
import subprocess
from unittest import TestCase
import re
from app import generate_profiles
class TestGenerateProfiles(TestCase):
gen = generate_profiles.GenerateProfiles
network_environment = "%s/misc/network-environment" % gen.bootcfg_path
@classmethod
def setUpClass(cls):
subpr... | Add a requirement for serving the assets in all tests | Add a requirement for serving the assets in all tests
| Python | mit | nyodas/enjoliver,kirek007/enjoliver,nyodas/enjoliver,kirek007/enjoliver,JulienBalestra/enjoliver,nyodas/enjoliver,kirek007/enjoliver,JulienBalestra/enjoliver,JulienBalestra/enjoliver,JulienBalestra/enjoliver,nyodas/enjoliver,kirek007/enjoliver,JulienBalestra/enjoliver,nyodas/enjoliver,kirek007/enjoliver | ---
+++
@@ -1,4 +1,5 @@
import os
+import subprocess
from unittest import TestCase
import re
@@ -12,6 +13,7 @@
@classmethod
def setUpClass(cls):
+ subprocess.check_output(["make", "-C", cls.gen.project_path])
cls.gen = generate_profiles.GenerateProfiles()
if os.path.isfile("%... |
9cc39104b96a197a1f42667964f32f9671b5125f | ch01/sin_graph.py | ch01/sin_graph.py | # coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
# データの作成
x = np.arange(0, 7, 0.1)
y = np.sin(x)
# グラフの描画
plt.plot(x, y)
plt.show() | # coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
# データの作成
x = np.arange(0, 6, 0.1)
y = np.sin(x)
# グラフの描画
plt.plot(x, y)
plt.show()
| Modify np.arange from 7 to 6 | Modify np.arange from 7 to 6 | Python | mit | kgsn1763/deep-learning-from-scratch,oreilly-japan/deep-learning-from-scratch | ---
+++
@@ -3,7 +3,7 @@
import matplotlib.pyplot as plt
# データの作成
-x = np.arange(0, 7, 0.1)
+x = np.arange(0, 6, 0.1)
y = np.sin(x)
# グラフの描画 |
44db9de83aad25a1302ac4c31450a525c0095583 | binobj/__init__.py | binobj/__init__.py | """
binobj
======
A Python library for reading and writing structured binary data.
"""
__version_info__ = (0, 1, 0)
__version__ = '.'.join(str(v) for v in __version_info__)
| """
binobj
======
A Python library for reading and writing structured binary data.
"""
# pylint: disable=wildcard-import,unused-import
from .errors import *
from .fields import *
from .serialization import *
from .structures import *
__version_info__ = (0, 1, 0)
__version__ = '.'.join(str(v) for v in __version_info_... | Add wildcard imports at root. | Add wildcard imports at root.
| Python | bsd-3-clause | dargueta/binobj | ---
+++
@@ -4,6 +4,12 @@
A Python library for reading and writing structured binary data.
"""
+# pylint: disable=wildcard-import,unused-import
+
+from .errors import *
+from .fields import *
+from .serialization import *
+from .structures import *
__version_info__ = (0, 1, 0)
__version__ = '.'.join(str(v) for... |
98190f0e96b2e2880e81b4801ebd5b04c1e9f1d8 | geomdl/__init__.py | geomdl/__init__.py | """ This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces.
Please follow the... | """ This package contains native Python implementations of several `The NURBS Book <http://www.springer.com/gp/book/9783642973857>`_ algorithms for generating B-spline / NURBS curves and surfaces. It also provides a data structure for storing elements required for evaluation these curves and surfaces.
Please follow the... | Fix importing * (star) from package | Fix importing * (star) from package
| Python | mit | orbingol/NURBS-Python,orbingol/NURBS-Python | ---
+++
@@ -16,3 +16,15 @@
"""
__version__ = "3.0.0"
+
+# Fixes "from geomdl import *" but this is not considered as a good practice
+# @see: https://docs.python.org/3/tutorial/modules.html#importing-from-a-package
+__all__ = ["BSpline.Curve",
+ "BSpline.Curve2D",
+ "BSpline.Surface",
+ ... |
44798dff0992d1c4e62bea97d4deaee1eed657e7 | docs/conf.py | docs/conf.py | #!/usr/bin/env python3
templates_path = ["templates"]
source_suffix = ".rst"
master_doc = "index"
project = "dependencies"
copyright = "2016-2018, Artem Malyshev"
author = "Artem Malyshev"
version = "0.14"
release = "0.14"
language = None
exclude_patterns = ["_build"]
pygments_style = "sphinx"
todo_include_tod... | #!/usr/bin/env python3
templates_path = ["templates"]
source_suffix = ".rst"
master_doc = "index"
project = "dependencies"
copyright = "2016-2018, Artem Malyshev"
author = "Artem Malyshev"
version = "0.14"
release = "0.14"
language = None
exclude_patterns = ["_build"]
pygments_style = "sphinx"
todo_include_... | Enable prev/next links in the docs. | Enable prev/next links in the docs.
| Python | bsd-2-clause | proofit404/dependencies,proofit404/dependencies,proofit404/dependencies,proofit404/dependencies | ---
+++
@@ -7,10 +7,13 @@
master_doc = "index"
project = "dependencies"
+
copyright = "2016-2018, Artem Malyshev"
+
author = "Artem Malyshev"
version = "0.14"
+
release = "0.14"
language = None
@@ -25,6 +28,8 @@
html_static_path = ["static"]
-html_sidebars = {"**": ["sidebarlogo.html", "globaltoc.ht... |
01f9649c9a661f1bf7289d3e6ea585b00ed48af3 | docs/conf.py | docs/conf.py | import sys
import os
extensions = [
'sphinx.ext.doctest',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
'sphinx.ext.autodoc',
]
master_doc = 'index'
project = u'openprovider.py'
copyright = u'2014, Antagonist B.V'
version = '0.0.1'
release = '0.0.1'
html_static_path = ['_static']
templates_path = ['_... | import sys
import os
extensions = [
'sphinx.ext.doctest',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
'sphinx.ext.autodoc',
]
master_doc = 'index'
project = u'openprovider.py'
copyright = u'2014, Antagonist B.V'
version = '0.0.1'
release = '0.0.1'
html_static_path = ['_static']
templates_path = ['_... | Enable LaTeX output for docs | Enable LaTeX output for docs
| Python | mit | AntagonistHQ/openprovider.py | ---
+++
@@ -23,3 +23,15 @@
html_theme = 'default'
htmlhelp_basename = 'openproviderpydoc'
+
+latex_elements = {
+ 'papersize': 'a4paper',
+ 'classoptions': ',openany,oneside',
+ 'babel': '\\usepackage[english]{babel}',
+ 'preamble': '\usepackage{microtype}',
+}
+
+latex_documents = [
+ ('index', 'o... |
f1f6848557428e9b2fc39c6b0d476279a0f5dd5c | docs/conf.py | docs/conf.py | import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = "2016-2021, {:s}".format(author)
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
... | import datetime
import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
copyright = f"2016-{datetime.date.today().year}, {author}"
release = version = pymanopt.__version__
# Build settings
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.coverag... | Define date in docs dynamically | Define date in docs dynamically
Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
| Python | bsd-3-clause | pymanopt/pymanopt,pymanopt/pymanopt | ---
+++
@@ -1,10 +1,12 @@
+import datetime
+
import pymanopt
# Package information
project = "Pymanopt"
author = "Jamie Townsend, Niklas Koep, Sebastian Weichwald"
-copyright = "2016-2021, {:s}".format(author)
+copyright = f"2016-{datetime.date.today().year}, {author}"
release = version = pymanopt.__version_... |
7abecbcd949278eec4082b733c5d687ba8bf11d4 | random-object-id.py | random-object-id.py | import binascii
import os
import time
from optparse import OptionParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8))
return timestamp + rest
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l', '--longform',... | import binascii
import os
import time
from optparse import OptionParser
def gen_random_object_id():
timestamp = '{0:x}'.format(int(time.time()))
rest = binascii.b2a_hex(os.urandom(8))
return timestamp + rest
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-l', '--longform',... | Add quotes to long form output | Add quotes to long form output
| Python | mit | mxr/random-object-id | ---
+++
@@ -22,6 +22,6 @@
object_id = gen_random_object_id()
if options.long_form:
- print 'ObjectId({})'.format(object_id)
+ print 'ObjectId("{}")'.format(object_id)
else:
print object_id |
0c01cb42527fdc2a094d3cc3f2f99a75da6992fa | geoportailv3/models.py | geoportailv3/models.py | # -*- coding: utf-8 -*-
import logging
from pyramid.i18n import TranslationStringFactory
from c2cgeoportal.models import * # noqa
_ = TranslationStringFactory('geoportailv3')
log = logging.getLogger(__name__)
| # -*- coding: utf-8 -*-
import logging
from pyramid.i18n import TranslationStringFactory
from c2cgeoportal.models import * # noqa
from pyramid.security import Allow, ALL_PERMISSIONS
from formalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy.types import Integer, Boolean, Unicode
from c2cgeopor... | Create the model for project specific tables | Create the model for project specific tables
| Python | mit | Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr,geoportallux/geoportailv3-gisgr,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr | ---
+++
@@ -5,6 +5,71 @@
from pyramid.i18n import TranslationStringFactory
from c2cgeoportal.models import * # noqa
+from pyramid.security import Allow, ALL_PERMISSIONS
+from formalchemy import Column
+from sqlalchemy import ForeignKey
+from sqlalchemy.types import Integer, Boolean, Unicode
+from c2cgeoportal.mo... |
c3284516e8dc2c7fccfbf7e4bff46a66b4ad2f15 | cref/evaluation/__init__.py | cref/evaluation/__init__.py | import os
import statistics
from cref.structure import rmsd
from cref.app.terminal import download_pdb, download_fasta, predict_fasta
pdbs = ['1zdd', '1gab']
runs = 100
fragment_sizes = range(5, 13, 2)
number_of_clusters = range(4, 20, 1)
for pdb in pdbs:
output_dir = 'predictions/evaluation/{}/'.format(pdb)
... | import os
import statistics
from cref.structure import rmsd
from cref.app.terminal import download_pdb, download_fasta, predict_fasta
pdbs = ['1zdd', '1gab']
runs = 5
fragment_sizes = range(5, 13, 2)
number_of_clusters = range(4, 20, 1)
for pdb in pdbs:
output_dir = 'predictions/evaluation/{}/'.format(pdb)
... | Save output for every run | Save output for every run
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 | ---
+++
@@ -6,7 +6,7 @@
pdbs = ['1zdd', '1gab']
-runs = 100
+runs = 5
fragment_sizes = range(5, 13, 2)
number_of_clusters = range(4, 20, 1)
@@ -30,7 +30,9 @@
}
- output_files = predict_fasta(fasta_file, output_dir, params)
+ prediction_output = output_dir + ... |
76bc5171cbccf9ce171f8891f24b66daa91aef0d | glitter/pages/forms.py | glitter/pages/forms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.conf import settings
from .models import Page
from glitter.integration import glitter_app_pool
class DuplicatePageForm(forms.ModelForm):
class Meta:
model = Page
fields = ['url', 'title', 'parent... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.conf import settings
from glitter.integration import glitter_app_pool
from .models import Page
class DuplicatePageForm(forms.ModelForm):
class Meta:
model = Page
fields = ['url', 'title', 'paren... | Sort the Glitter app choices for page admin | Sort the Glitter app choices for page admin
For #69
| Python | bsd-3-clause | developersociety/django-glitter,developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,blancltd/django-glitter,blancltd/django-glitter | ---
+++
@@ -4,8 +4,9 @@
from django import forms
from django.conf import settings
+from glitter.integration import glitter_app_pool
+
from .models import Page
-from glitter.integration import glitter_app_pool
class DuplicatePageForm(forms.ModelForm):
@@ -27,8 +28,11 @@
def get_glitter_app_choices():
g... |
09462f834d2c61b106cfa44eb45360c10db47f35 | rtwilio/__init__.py | rtwilio/__init__.py | "Twilio backend for the RapidSMS project."
__version__ = '0.3.0'
| "Twilio backend for the RapidSMS project."
__version__ = '1.0.0dev'
| Develop is now v1.0 dev. | Develop is now v1.0 dev.
| Python | bsd-3-clause | caktus/rapidsms-twilio | ---
+++
@@ -1,4 +1,4 @@
"Twilio backend for the RapidSMS project."
-__version__ = '0.3.0'
+__version__ = '1.0.0dev' |
bda36d78984ee8b4701315170f004ed6955072ac | common/widgets.py | common/widgets.py | # This file is part of e-Giełda.
# Copyright (C) 2014 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... | # This file is part of e-Giełda.
# Copyright (C) 2014 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... | Handle "no file uploaded" situation in FileFieldLink | Handle "no file uploaded" situation in FileFieldLink
Fixes ValueErrors when user has no identity card uploaded
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda | ---
+++
@@ -13,6 +13,8 @@
from django.forms.utils import flatatt
from django.utils.html import format_html
+from django.utils.translation import ugettext as _
+
class PhoneNumberInput(TextInput):
input_type = 'tel'
@@ -24,7 +26,15 @@
"""
def render(self, name, value, attrs=None):
- retu... |
41b8cefb881e294b3bcdbb497d21fe1153a25725 | capomastro/urls.py | capomastro/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from capomastro.views import HomeView
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'capomastro... | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from capomastro.views import HomeView
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'capomastro... | Change from ADDITIONAL_URLS to AUTHENTICATION_URLS | Change from ADDITIONAL_URLS to AUTHENTICATION_URLS
| Python | mit | caio1982/capomastro,caio1982/capomastro,timrchavez/capomastro,timrchavez/capomastro,caio1982/capomastro | ---
+++
@@ -22,7 +22,7 @@
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
-if hasattr(settings, 'ADDITIONAL_URLS'):
- urlpatterns += settings.ADDITIONAL_URLS
+if hasattr(settings, 'AUTHENTICATION_URLS'):
+ urlpatterns += settings.AUTHENTICATION_URLS
else:
urlpatterns += url(r'^accounts... |
49f506dce441b3a8fb1e2eb0f06c26661721785e | {{cookiecutter.app_name}}/models.py | {{cookiecutter.app_name}}/models.py | from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.db import models
from django_extensions.db.models import TimeStampedModel
class {{ cookiecutter.model_name }}(TimeStampedModel):
name = models.CharField(
verbose_name=_('name'),
max_length... | from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.db import models
from django_extensions.db.models import TimeStampedModel
class {{ cookiecutter.model_name }}(TimeStampedModel):
name = models.CharField(
verbose_name=_('name'),
max_length... | Use friendly name for admin | Use friendly name for admin
| Python | mit | rickydunlop/cookiecutter-django-app-template-drf-haystack | ---
+++
@@ -13,3 +13,6 @@
blank=True,
null=True,
)
+
+ def __str__(self):
+ return self.name |
b0d24c3aa1bea35afb81ee01fd238c8a263527c9 | scripts/cts-load.py | scripts/cts-load.py | from __future__ import print_function
from re import sub
import sys
from os.path import basename, splitext
from pyspark.sql import SparkSession, Row
def parseCTS(f):
res = dict()
text = ''
locs = []
for line in f[1].split('\n'):
if line != '':
(loc, raw) = line.split('\t', 2)
... | from __future__ import print_function
from re import sub
import sys
from os.path import basename, splitext
from pyspark.sql import SparkSession, Row
def parseCTS(f):
res = dict()
text = ''
locs = []
id = (splitext(basename(f[0])))[0]
for line in f[1].split('\n'):
if line != '':
... | Add series and normalize locs. | Add series and normalize locs.
| Python | apache-2.0 | ViralTexts/vt-passim,ViralTexts/vt-passim,ViralTexts/vt-passim | ---
+++
@@ -8,15 +8,21 @@
res = dict()
text = ''
locs = []
+ id = (splitext(basename(f[0])))[0]
for line in f[1].split('\n'):
if line != '':
(loc, raw) = line.split('\t', 2)
+ parts = loc.split(':')
+ if len(parts) >= 4: id = ':'.join(parts[0:4])
... |
370bc073d56615a5aaa3668ab89d96cdd49ef17d | compare.py | compare.py | """The compare module contains the components you need to
compare values and ensure that your expectations are met.
To make use of this module, you simply import the "expect"
starter into your spec/test file, and specify the expectation
you have about two values.
"""
class Expr(object):
"""Encapsulates a pytho... | Implement Expr class -- the base of it all. | Implement Expr class -- the base of it all.
| Python | bsd-3-clause | rudylattae/compare,rudylattae/compare | ---
+++
@@ -0,0 +1,36 @@
+"""The compare module contains the components you need to
+compare values and ensure that your expectations are met.
+
+To make use of this module, you simply import the "expect"
+starter into your spec/test file, and specify the expectation
+you have about two values.
+"""
+
+class Expr(... | |
c4fa912acc573f5590510c0345d9a9b3bc40f4c8 | espresso/repl.py | espresso/repl.py | # -*- coding: utf-8 -*-
from code import InteractiveConsole
class EspressoConsole(InteractiveConsole, object):
def interact(self):
banner = """███████╗███████╗██████╗ ██████╗ ███████╗███████╗███████╗ ██████╗
██╔════╝██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝██╔════╝██╔═══██╗
█████╗ ███████╗██████╔╝██████╔╝... | # -*- coding: utf-8 -*-
from code import InteractiveConsole
class EspressoConsole(InteractiveConsole, object):
def interact(self, banner = None):
banner = """███████╗███████╗██████╗ ██████╗ ███████╗███████╗███████╗ ██████╗
██╔════╝██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝██╔════╝██╔═══██╗
█████╗ ███████╗█... | Make EspressoConsole.interact conform to InteractiveConsole.interact | Make EspressoConsole.interact conform to InteractiveConsole.interact
| Python | bsd-3-clause | ratchetrobotics/espresso | ---
+++
@@ -2,14 +2,14 @@
from code import InteractiveConsole
class EspressoConsole(InteractiveConsole, object):
- def interact(self):
+ def interact(self, banner = None):
banner = """███████╗███████╗██████╗ ██████╗ ███████╗███████╗███████╗ ██████╗
██╔════╝██╔════╝██╔══██╗██╔══██╗██╔════╝██╔════╝... |
bd181f778e74bbd070fd4f46329ad5c8dc637ea7 | zendesk_tickets_machine/tickets/services.py | zendesk_tickets_machine/tickets/services.py | import datetime
from django.utils.timezone import utc
from .models import Ticket
class TicketServices():
def edit_ticket_once(self, **kwargs):
id_list = kwargs.get('id_list')
edit_tags = kwargs.get('edit_tags')
edit_requester = kwargs.get('edit_requester')
edit_subject = kwargs.g... | import datetime
from django.utils.timezone import utc
from .models import Ticket
class TicketServices():
def edit_ticket_once(self, **kwargs):
id_list = kwargs.get('id_list')
edit_tags = kwargs.get('edit_tags')
edit_requester = kwargs.get('edit_requester')
edit_subject = kwargs.g... | Adjust code style to reduce lines of code :bear: | Adjust code style to reduce lines of code :bear:
| Python | mit | prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine,prontotools/zendesk-tickets-machine | ---
+++
@@ -15,26 +15,20 @@
edit_assignee = kwargs.get('edit_assignee')
if edit_tags:
- Ticket.objects.filter(
- pk__in=id_list
- ).update(tags=edit_tags)
+ Ticket.objects.filter(pk__in=id_list).update(tags=edit_tags)
if edit_subject:
- ... |
69df0f5148b998cc7757405b9965200276ce55b9 | fireplace/cards/league/adventure.py | fireplace/cards/league/adventure.py | from ..utils import *
##
# Spells
# Medivh's Locket
class LOEA16_12:
play = Morph(FRIENDLY_HAND, "GVG_003")
| from ..utils import *
##
# Spells
# Medivh's Locket
class LOEA16_12:
play = Morph(FRIENDLY_HAND, "GVG_003")
##
# Temple Escape events
# Pit of Spikes
class LOEA04_06:
choose = ("LOEA04_06a", "LOEA04_06b")
# Swing Across
class LOEA04_06a:
play = COINFLIP & Hit(FRIENDLY_HERO, 10)
# Walk Across Gingerly
class L... | Implement Temple Escape event choices | Implement Temple Escape event choices
| Python | agpl-3.0 | beheh/fireplace,NightKev/fireplace,jleclanche/fireplace,amw2104/fireplace,amw2104/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,Ragowit/fireplace,Ragowit/fireplace | ---
+++
@@ -7,3 +7,58 @@
# Medivh's Locket
class LOEA16_12:
play = Morph(FRIENDLY_HAND, "GVG_003")
+
+
+##
+# Temple Escape events
+
+# Pit of Spikes
+class LOEA04_06:
+ choose = ("LOEA04_06a", "LOEA04_06b")
+
+# Swing Across
+class LOEA04_06a:
+ play = COINFLIP & Hit(FRIENDLY_HERO, 10)
+
+# Walk Across Gingerly
... |
5c681567c359c76e9e323a82ab9162f5098b6421 | measurator/main.py | measurator/main.py | def run_main():
pass
| import argparse
def run_main():
path = file_path()
def file_path():
parser = argparse.ArgumentParser()
parser.add_argument("path")
args = parser.parse_args()
return args.path
| Add mandatory argument: path to file | Add mandatory argument: path to file
| Python | mit | ahitrin-attic/measurator-proto | ---
+++
@@ -1,2 +1,10 @@
+import argparse
+
def run_main():
- pass
+ path = file_path()
+
+def file_path():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("path")
+ args = parser.parse_args()
+ return args.path |
509669de3b61f7f67c5c3603f696b06ad759a7b3 | mopidy/internal/gi.py | mopidy/internal/gi.py | import sys
import textwrap
try:
import gi
gi.require_version("Gst", "1.0")
from gi.repository import GLib, GObject, Gst
except ImportError:
print(
textwrap.dedent(
"""
ERROR: A GObject based library was not found.
Mopidy requires GStreamer to work. GStreamer is a C... | import sys
import textwrap
try:
import gi
gi.require_version("Gst", "1.0")
from gi.repository import GLib, GObject, Gst
except ImportError:
print(
textwrap.dedent(
"""
ERROR: A GObject based library was not found.
Mopidy requires GStreamer to work. GStreamer is a C... | Use https for docs URL | Use https for docs URL
| Python | apache-2.0 | adamcik/mopidy,mopidy/mopidy,jodal/mopidy,jcass77/mopidy,mopidy/mopidy,jodal/mopidy,mopidy/mopidy,kingosticks/mopidy,adamcik/mopidy,kingosticks/mopidy,kingosticks/mopidy,jodal/mopidy,adamcik/mopidy,jcass77/mopidy,jcass77/mopidy | ---
+++
@@ -16,7 +16,7 @@
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
- Please see http://docs.mopidy.com/en/latest/installation/ for
+ Please see https://docs.mopidy.com/en/latest/installation/ for
instructions on how to in... |
418357ead146a98f2318af6c76323e2705b79cec | cvloop/__init__.py | cvloop/__init__.py | """Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks."""
import sys
OPENCV_FOUND = False
OPENCV_VERSION_COMPATIBLE = False
try:
import cv2
OPENCV_FOUND = True
except Exception as e:
# print ("Error:", e)
print('OpenCV is not found (tried importing cv2).', file=... | """Provides cvloop, a ready to use OpenCV VideoCapture mapper, designed for jupyter notebooks."""
import sys
OPENCV_FOUND = False
OPENCV_VERSION_COMPATIBLE = False
try:
import cv2
OPENCV_FOUND = True
except ModuleNotFoundError:
print('OpenCV is not found (tried importing cv2).', file=sys.stderr)
print... | Revert unnecessary change to original | Revert unnecessary change to original
| Python | mit | shoeffner/cvloop | ---
+++
@@ -7,8 +7,7 @@
try:
import cv2
OPENCV_FOUND = True
-except Exception as e:
- # print ("Error:", e)
+except ModuleNotFoundError:
print('OpenCV is not found (tried importing cv2).', file=sys.stderr)
print('''
Is OpenCV installed and properly added to your path? |
c8152d1ce0c9f83460da3d384a532d6d064d6543 | cross_site_urls/urlresolvers.py | cross_site_urls/urlresolvers.py | # -*- coding:utf-8 -*-
# Standard library imports
from __future__ import unicode_literals
import uuid
import requests
from django.core.exceptions import ImproperlyConfigured
from django.utils import translation
import slumber
from .conf import settings as local_settings
from .encoding import prefix_kwargs
from .uti... | # -*- coding:utf-8 -*-
# Standard library imports
from __future__ import unicode_literals
import uuid
import requests
from django.core.exceptions import ImproperlyConfigured
from django.utils import translation
import slumber
from .conf import settings as local_settings
from .encoding import prefix_kwargs
from .uti... | Add a new settings allowing to set manually the language code of the url resolve when calling the resolver | FEAT(Resolvers): Add a new settings allowing to set manually the language code of the url resolve when calling the resolver
| Python | bsd-3-clause | kapt-labs/django-cross-site-urls,kapt-labs/django-cross-site-urls | ---
+++
@@ -16,14 +16,13 @@
from .constants import RESOLVE_API_VIEW_URL
-def resolve_url(site_id, view_name, args=None, kwargs=None):
+def resolve_url(site_id, view_name, args=None, kwargs=None, language=None):
if site_id not in local_settings.SITES:
raise ImproperlyConfigured("[Cross site] Confi... |
0e4db0303d4a8212a91082ace75df95fd440bbfa | server/app.py | server/app.py | from flask import Flask, request
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
@app.route('/')
def hello_world():
return 'Team FifthEye!'
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
if file:
... | from flask import Flask, request
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
@app.route('/')
def hello_world():
return 'Team FifthEye!'
@app.route('/upload', methods=['POST'])
def upload():
imgData = request.form['file']
if imgData:... | Save data sent from phone | Save data sent from phone
| Python | mit | navinpai/LMTAS,navinpai/LMTAS,navinpai/LMTAS | ---
+++
@@ -12,13 +12,14 @@
@app.route('/upload', methods=['POST'])
def upload():
- file = request.files['file']
- if file:
- filename = secure_filename(file.filename)
- file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
+ imgData = request.form['file']
+ if imgData:
+ ... |
3629e58c47941965406372cb2d3b52a3fdbadfc2 | ckanext/tayside/logic/action/get.py | ckanext/tayside/logic/action/get.py | from ckan.logic.action import get as get_core
from ckan.plugins import toolkit
@toolkit.side_effect_free
def package_show(context, data_dict):
''' This action is overriden so that the extra field "theme" is added.
This is needed because when a dataset is exposed to DCAT it needs this
field.
Themes ar... | from ckan.logic.action import get as get_core
from ckan.plugins import toolkit
@toolkit.side_effect_free
def package_show(context, data_dict):
''' This action is overriden so that the extra field "theme" is added.
This is needed because when a dataset is exposed to DCAT it needs this
field.
Themes ar... | Handle logic for extras for dataset | Handle logic for extras for dataset
| Python | agpl-3.0 | ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside,ViderumGlobal/ckanext-tayside | ---
+++
@@ -28,11 +28,17 @@
result = result.copy()
extras = result.get('extras')
- for extra in extras:
- if extra.get('key') == 'theme':
- extra['value'] = themes
- return result
+ if extras:
+ for extra in extras:
+ if extra.get('key') == 'theme':
+ ... |
e22bf1a54d8b532f0a417221b04e382e71b29186 | LiSE/LiSE/tests/test_examples.py | LiSE/LiSE/tests/test_examples.py | from LiSE.examples import college, kobold, polygons, sickle
def test_college(engy):
college.install(engy)
engy.turn = 10 # wake up the students
engy.next_turn()
def test_kobold(engy):
kobold.inittest(engy, shrubberies=20, kobold_sprint_chance=.9)
for i in range(10):
engy.next_turn()
d... | from LiSE import Engine
from LiSE.examples import college, kobold, polygons, sickle
def test_college(engy):
college.install(engy)
engy.turn = 10 # wake up the students
engy.next_turn()
def test_kobold(engy):
kobold.inittest(engy, shrubberies=20, kobold_sprint_chance=.9)
for i in range(10):
... | Add a test to catch that load error next time | Add a test to catch that load error next time
| Python | agpl-3.0 | LogicalDash/LiSE,LogicalDash/LiSE | ---
+++
@@ -1,3 +1,4 @@
+from LiSE import Engine
from LiSE.examples import college, kobold, polygons, sickle
@@ -19,6 +20,27 @@
engy.next_turn()
+def test_char_stat_startup(tempdir):
+ with Engine(tempdir) as eng:
+ tri = eng.new_character('triangle')
+ sq = eng.new_character('squar... |
11cbeb3d0140e79fc0bedf5039a3c70f626062eb | condor/python/resync_dashboards.py | condor/python/resync_dashboards.py | #!/usr/bin/env python
import argparse
import sys
import logging
import elasticsearch
import elasticsearch.helpers
ES_NODES = 'uct2-es-door.mwt2.org'
VERSION = '0.1'
SOURCE_INDEX = '.kibana'
TARGET_INDEX = 'osg-connect-kibana'
def get_es_client():
""" Instantiate DB client and pass connection back """
retur... | #!/usr/bin/env python
import argparse
import sys
import logging
import elasticsearch
import elasticsearch.helpers
ES_NODES = 'uct2-es-door.mwt2.org'
VERSION = '0.1'
SOURCE_INDEX = '.kibana'
TARGET_INDEX = 'osg-connect-kibana'
def get_es_client():
""" Instantiate DB client and pass connection back """
retur... | Convert results to a string before printing | Convert results to a string before printing
| Python | apache-2.0 | DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs | ---
+++
@@ -30,6 +30,6 @@
SOURCE_INDEX,
TARGET_INDEX,
scroll='30m')
- sys.stdout.write(results)
+ sys.stdout.write(str(results))
|
73d0225b64ec82c7a8142dbac023be499b41fe0f | figures.py | figures.py | #! /usr/bin/env python
import sys
import re
import yaml
FILE = sys.argv[1]
YAML = sys.argv[2]
TYPE = sys.argv[3]
header = open(YAML, "r")
text = open(FILE, "r")
copy = open(FILE+"_NEW", "wt")
docs = yaml.load_all(header)
for doc in docs:
if not doc == None:
if 'figure' in doc.keys():
for li... | #! /usr/bin/env python
import sys
import re
import yaml
FILE = sys.argv[1]
YAML = sys.argv[2]
TYPE = sys.argv[3]
header = open(YAML, "r")
text = open(FILE, "r")
copy = open(FILE+"_NEW", "wt")
docs = yaml.load_all(header)
for doc in docs:
if not doc == None:
if 'figure' in doc.keys():
for li... | Make the python script silent | Make the python script silent
| Python | mit | PoisotLab/PLMT | ---
+++
@@ -23,7 +23,6 @@
my_regex = r"^!\{" + re.escape(f['id']) + r"\}$"
if re.search(my_regex, line, re.IGNORECASE):
mfig = True
- print line
if TYPE == 'preprint':
ftype ... |
b597956cd427a3b830a498c69602753ce6117119 | chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py | chrome/test/chromeos/autotest/files/client/site_tests/desktopui_SyncIntegrationTests/desktopui_SyncIntegrationTests.py | # Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from autotest_lib.client.cros import chrome_test
class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase):
version = 1
def run_once(sel... | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from autotest_lib.client.cros import chrome_test
class desktopui_SyncIntegrationTests(chrome_test.ChromeTestBase):
version = 1
binary_to_run = ... | Make the sync integration tests self-contained on autotest | Make the sync integration tests self-contained on autotest
In the past, the sync integration tests used to require a password file
stored on every test device in order to do a gaia sign in using
production gaia servers. This caused the tests to be brittle.
As of today, the sync integration tests no longer rely on a p... | Python | bsd-3-clause | dednal/chromium.src,Jonekee/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,keishi/chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,dushu1203/chromium.src,dednal/chromium.src,chuan9/chromi... | ---
+++
@@ -1,4 +1,4 @@
-# Copyright (c) 2010 The Chromium Authors. All rights reserved.
+# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -7,9 +7,8 @@
class desktopui_SyncIntegrationTests(chro... |
5bcb267761e6c2694111757ee4fcf2a050f6c556 | byceps/blueprints/site/guest_server/forms.py | byceps/blueprints/site/guest_server/forms.py | """
byceps.blueprints.site.guest_server.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from flask_babel import lazy_gettext
from wtforms import StringField, TextAreaField
from wtforms.validators import Optional
fro... | """
byceps.blueprints.site.guest_server.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import re
from flask_babel import lazy_gettext
from wtforms import StringField, TextAreaField
from wtforms.validators import Le... | Make guest server form validation more strict | Make guest server form validation more strict
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -6,13 +6,23 @@
:License: Revised BSD (see `LICENSE` file for details)
"""
+import re
+
from flask_babel import lazy_gettext
from wtforms import StringField, TextAreaField
-from wtforms.validators import Optional
+from wtforms.validators import Length, Optional, Regexp
from ....util.l10n import Loc... |
5b45d4996de8c15dfc09905b0e63651fdbb2fcc6 | angr/engines/soot/expressions/phi.py | angr/engines/soot/expressions/phi.py |
from .base import SimSootExpr
class SimSootExpr_Phi(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Phi, self).__init__(expr, state)
def _execute(self):
if len(self.expr.values) != 2:
import ipdb; ipdb.set_trace();
v1, v2 = [self._translate_value(v) for... |
from .base import SimSootExpr
import logging
l = logging.getLogger('angr.engines.soot.expressions.phi')
class SimSootExpr_Phi(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Phi, self).__init__(expr, state)
def _execute(self):
locals_option = [self._translate_value(v) for v ... | Extend Phi expression to work with more than 2 values | Extend Phi expression to work with more than 2 values
| Python | bsd-2-clause | schieb/angr,iamahuman/angr,angr/angr,schieb/angr,angr/angr,angr/angr,iamahuman/angr,schieb/angr,iamahuman/angr | ---
+++
@@ -1,21 +1,26 @@
from .base import SimSootExpr
+import logging
+l = logging.getLogger('angr.engines.soot.expressions.phi')
class SimSootExpr_Phi(SimSootExpr):
def __init__(self, expr, state):
super(SimSootExpr_Phi, self).__init__(expr, state)
def _execute(self):
+ locals_o... |
e0cb864f19f05f4ddfed0fa90c8b9895bde9b8df | caminae/core/management/__init__.py | caminae/core/management/__init__.py | """
http://djangosnippets.org/snippets/2311/
Ensure South will update our custom SQL during a call to `migrate`.
"""
import logging
import traceback
from south.signals import post_migrate
logger = logging.getLogger(__name__)
def run_initial_sql(sender, **kwargs):
app_label = kwargs.get('app')
import... | """
http://djangosnippets.org/snippets/2311/
Ensure South will update our custom SQL during a call to `migrate`.
"""
import logging
import traceback
from south.signals import post_migrate
logger = logging.getLogger(__name__)
def run_initial_sql(sender, **kwargs):
import os
import re
from django.... | Enable loading of SQL scripts with arbitrary name | Enable loading of SQL scripts with arbitrary name
| Python | bsd-2-clause | Anaethelion/Geotrek,makinacorpus/Geotrek,johan--/Geotrek,makinacorpus/Geotrek,camillemonchicourt/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,Anaethelion/Geotrek,johan--/Geotrek,mabhub/Geotrek,camillemonchicourt/Geotrek,makinacorpus/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,makinaco... | ---
+++
@@ -11,23 +11,29 @@
def run_initial_sql(sender, **kwargs):
+ import os
+ import re
+ from django.db import connection, transaction, models
+
app_label = kwargs.get('app')
- import os
- from django.db import connection, transaction, models
app_dir = os.path.normpath(os.path.join(o... |
2834a22489ebe801743434dcf26e727448355756 | corehq/messaging/scheduling/scheduling_partitioned/migrations/0009_update_custom_recipient_ids.py | corehq/messaging/scheduling/scheduling_partitioned/migrations/0009_update_custom_recipient_ids.py | # Generated by Django 2.2.24 on 2021-11-19 14:36
from django.db import migrations
from corehq.messaging.scheduling.scheduling_partitioned.models import CaseTimedScheduleInstance
from corehq.sql_db.util import get_db_aliases_for_partitioned_query
def update_custom_recipient_ids(*args, **kwargs):
for db in get_db_... | from django.db import migrations
from corehq.messaging.scheduling.scheduling_partitioned.models import CaseTimedScheduleInstance
from corehq.sql_db.util import get_db_aliases_for_partitioned_query
def update_custom_recipient_ids(*args, **kwargs):
for db in get_db_aliases_for_partitioned_query():
CaseTimed... | Remove date from migration since this one is copied and edited | Remove date from migration since this one is copied and edited
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,5 +1,3 @@
-# Generated by Django 2.2.24 on 2021-11-19 14:36
-
from django.db import migrations
from corehq.messaging.scheduling.scheduling_partitioned.models import CaseTimedScheduleInstance
from corehq.sql_db.util import get_db_aliases_for_partitioned_query |
2cecc2e197e4a4089e29b350179103e323136268 | ddb_ngsflow/variation/sv/itdseek.py | ddb_ngsflow/variation/sv/itdseek.py | """
.. module:: freebayes
:platform: Unix, OSX
:synopsis: A wrapper module for calling ScanIndel.
.. moduleauthor:: Daniel Gaston <daniel.gaston@dal.ca>
"""
from ddb_ngsflow import pipeline
def run_flt3_itdseek(job, config, name, samples):
"""Run ITDseek without a matched normal sample
:param config: ... | """
.. module:: freebayes
:platform: Unix, OSX
:synopsis: A wrapper module for calling ScanIndel.
.. moduleauthor:: Daniel Gaston <daniel.gaston@dal.ca>
"""
from ddb_ngsflow import pipeline
def run_flt3_itdseek(job, config, name):
"""Run ITDseek without a matched normal sample
:param config: The confi... | Remove unneeded samples config passing | Remove unneeded samples config passing
| Python | mit | dgaston/ddb-ngsflow,dgaston/ddbio-ngsflow | ---
+++
@@ -9,14 +9,12 @@
from ddb_ngsflow import pipeline
-def run_flt3_itdseek(job, config, name, samples):
+def run_flt3_itdseek(job, config, name):
"""Run ITDseek without a matched normal sample
:param config: The configuration dictionary.
:type config: dict.
:param name: sample name.
... |
3ab5b791494111a3b0d962b8b5de588665498653 | airpy/main.py | airpy/main.py | import click
import requests
import os
import shutil
from appdirs import user_data_dir
from airpy.install import airinstall
from airpy.list import airlist
from airpy.start import airstart
from airpy.remove import airremove
from airpy.autopilot import airautopilot
def main():
@click.group()
def airpy():
"""AirPy : D... | import click
import requests
import os
import shutil
from appdirs import user_data_dir
from airpy.install import airinstall
from airpy.list import airlist
from airpy.start import airstart
from airpy.remove import airremove
from airpy.autopilot import airautopilot
def main():
@click.group()
def airpy():
"""AirPy : D... | Remove the Pythonic Soul Trademark for now.. causing unicode issues with python2 | Remove the Pythonic Soul Trademark for now.. causing unicode issues with python2
| Python | mit | kevinaloys/airpy | ---
+++
@@ -11,7 +11,7 @@
def main():
@click.group()
def airpy():
- """AirPy : Documentation Installer for the Pythonic Soul™"""
+ """AirPy : Documentation Installer for the Pythonic Soul"""
pass
@airpy.command(help = 'Install offline doc of a Python module.') |
e59f187f2e4557114e534be57dc078ddf112b87c | completions_dev.py | completions_dev.py | import sublime_plugin
from sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = "Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage" % PLUGIN_NAME
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger"... | import sublime_plugin
from sublime_lib.path import root_at_packages, get_package_name
PLUGIN_NAME = get_package_name()
COMPLETIONS_SYNTAX_DEF = "Packages/%s/Syntax Definitions/Sublime Completions.tmLanguage" % PLUGIN_NAME
TPL = """{
"scope": "source.${1:off}",
"completions": [
{ "trigger"... | Use tabs in new completions file snippet | Use tabs in new completions file snippet
Respects the user's indentation configuration.
| Python | mit | SublimeText/PackageDev,SublimeText/AAAPackageDev,SublimeText/AAAPackageDev | ---
+++
@@ -11,7 +11,7 @@
"completions": [
{ "trigger": "${2:some_trigger}", "contents": "${3:Hint: Use f, ff and fff plus Tab inside here.}" }$0
]
-}"""
+}""".replace(" ", "\t") # NOQA - line length
class NewCompletionsCommand(sublime_plugin.WindowCommand): |
62b74e6d6452012f8ad68810446a3648749a3fee | collections/show-test/print-divs.py | collections/show-test/print-divs.py | # print-divs.py
def printDivs(num):
for i in range(num):
print('<div class="item">Item ' + str(i+1) + '</div>')
printDivs(20) | # print-divs.py
def printDivs(num):
for i in range(num):
print('<div class="item">Item ' + str(i+1) + ': Lorem ipsum dolor sic amet</div>')
printDivs(20) | Add dummy text to divs. | Add dummy text to divs.
| Python | apache-2.0 | scholarslab/takeback,scholarslab/takeback,scholarslab/takeback,scholarslab/takeback,scholarslab/takeback | ---
+++
@@ -2,6 +2,6 @@
def printDivs(num):
for i in range(num):
- print('<div class="item">Item ' + str(i+1) + '</div>')
+ print('<div class="item">Item ' + str(i+1) + ': Lorem ipsum dolor sic amet</div>')
printDivs(20) |
02f18e2ec6788f4cf92e8a2f78898f6861f2f395 | gofast/gpio.py | gofast/gpio.py |
import cffi
ffi = cffi.FFI()
ffi.cdef("""
int setup(void);
void setup_gpio(int gpio, int direction, int pud);
int gpio_function(int gpio);
void output_gpio(int gpio, int value);
int input_gpio(int gpio);
void set_rising_event(int gpio, int enable);
void set_falling_event(int gpio, int enable);
void set_high_event(in... |
import cffi
ffi = cffi.FFI()
ffi.cdef("""
int setup(void);
void setup_gpio(int gpio, int direction, int pud);
int gpio_function(int gpio);
void output_gpio(int gpio, int value);
int input_gpio(int gpio);
void set_rising_event(int gpio, int enable);
void set_falling_event(int gpio, int enable);
void set_high_event(in... | Make GPIO importable, but not usable, as non-root | Make GPIO importable, but not usable, as non-root
| Python | bsd-2-clause | cg123/computernetworks,cg123/computernetworks,cg123/computernetworks | ---
+++
@@ -24,7 +24,9 @@
setup = C.setup_gpio
if C.setup():
- raise RuntimeError("Error initializing GPIO")
+ def error(*args):
+ raise RuntimeError("Error initializing GPIO")
+ write, read, cleanup, setup = error, error, error, error
INPUT = 1
OUTPUT = 0 |
5c4026fbe42625a3595d26c2ef71cb1298b36547 | version.py | version.py | major = 0
minor=0
patch=23
branch="master"
timestamp=1376526646.52 | major = 0
minor=0
patch=24
branch="master"
timestamp=1376526666.61 | Tag commit for v0.0.24-master generated by gitmake.py | Tag commit for v0.0.24-master generated by gitmake.py
| Python | mit | ryansturmer/gitmake | ---
+++
@@ -1,5 +1,5 @@
major = 0
minor=0
-patch=23
+patch=24
branch="master"
-timestamp=1376526646.52
+timestamp=1376526666.61 |
132f91c5f3f193ca3b1a246b9ef5b20b4e03609f | core/validators.py | core/validators.py | from datetime import datetime, timedelta
from django.core.exceptions import ValidationError
def validate_approximatedate(date):
if date.month == 0:
raise ValidationError(
'Event date can\'t be a year only. '
'Please, provide at least a month and a year.'
)
def validate_e... | from datetime import date, datetime, timedelta
from django.core.exceptions import ValidationError
def validate_approximatedate(date):
if date.month == 0:
raise ValidationError(
'Event date can\'t be a year only. '
'Please, provide at least a month and a year.'
)
def vali... | Apply suggested changes on date | Apply suggested changes on date
| Python | bsd-3-clause | DjangoGirls/djangogirls,DjangoGirls/djangogirls,DjangoGirls/djangogirls | ---
+++
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+from datetime import date, datetime, timedelta
from django.core.exceptions import ValidationError
@@ -11,9 +11,10 @@
)
-def validate_event_date(date):
- today = datetime.today()
- event_date = datetime.date(datetime.strptime('{... |
e0276f6c86e07fa82f19c5f895b6e513d38255c0 | server/management/commands/friendly_model_name.py | server/management/commands/friendly_model_name.py | '''
Retrieves the firendly model name for machines that don't have one yet.
'''
from django.core.management.base import BaseCommand, CommandError
from server.models import Machine
from django.db.models import Q
import server.utils as utils
class Command(BaseCommand):
help = 'Retrieves friendly model names for ma... | """Retrieves the friendly model name for machines that don't have one yet."""
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
import server.utils as utils
from server.models import Machine
class Command(BaseCommand):
help = 'Retrieves friendly model names for mac... | Fix missing paren, imports, spelling. | Fix missing paren, imports, spelling.
| Python | apache-2.0 | sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,salopensource/sal | ---
+++
@@ -1,11 +1,10 @@
-'''
-Retrieves the firendly model name for machines that don't have one yet.
-'''
+"""Retrieves the friendly model name for machines that don't have one yet."""
from django.core.management.base import BaseCommand, CommandError
+from django.db.models import Q
+
+import server.utils as uti... |
14cdf6b7a82e49f1860aee41e4b1a5b20cf179b2 | quickstats/signals.py | quickstats/signals.py | import logging
from . import tasks
from django.db.models.signals import post_save
from django.dispatch import receiver
logger = logging.getLogger(__name__)
@receiver(post_save, sender="quickstats.Sample", dispatch_uid="quickstats-refresh-chart")
def hook_update_data(sender, instance, *args, **kwargs):
... | import logging
from . import tasks
from django.db.models.signals import post_save
from django.dispatch import receiver
logger = logging.getLogger(__name__)
@receiver(post_save, sender="quickstats.Sample", dispatch_uid="quickstats-refresh-chart")
def hook_update_chart(sender, instance, *args, **kwargs):
... | Make unique names for signal functions | Make unique names for signal functions
| Python | mit | kfdm/django-simplestats,kfdm/django-simplestats | ---
+++
@@ -9,10 +9,10 @@
@receiver(post_save, sender="quickstats.Sample", dispatch_uid="quickstats-refresh-chart")
-def hook_update_data(sender, instance, *args, **kwargs):
+def hook_update_chart(sender, instance, *args, **kwargs):
tasks.update_chart.delay(instance.widget_id)
@receiver(post_save, send... |
171974ab9c069abe14c25ef220f683d4905d1454 | socorro/external/rabbitmq/rmq_new_crash_source.py | socorro/external/rabbitmq/rmq_new_crash_source.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import ... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import ... | Correct docs on RabbitMQ crash source. | Correct docs on RabbitMQ crash source.
| Python | mpl-2.0 | linearregression/socorro,linearregression/socorro,Serg09/socorro,Serg09/socorro,linearregression/socorro,m8ttyB/socorro,Serg09/socorro,luser/socorro,twobraids/socorro,lonnen/socorro,bsmedberg/socorro,AdrianGaudebert/socorro,cliqz/socorro,yglazko/socorro,pcabido/socorro,lonnen/socorro,twobraids/socorro,bsmedberg/socorro... | ---
+++
@@ -7,11 +7,11 @@
from functools import partial
+
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
- """this class is a refactoring of the iteratior portion of the legacy
- Socorro processor. It isolates just the part of fet... |
5a2673366224751e675b894c13a2152c50d28e87 | fileupload/urls.py | fileupload/urls.py | # encoding: utf-8
from django.conf.urls import patterns, url
from fileupload.views import (
BasicVersionCreateView, BasicPlusVersionCreateView,
jQueryVersionCreateView, AngularVersionCreateView,
PictureCreateView, PictureDeleteView, PictureListView,
)
urlpatterns = patterns('',
url(... | # encoding: utf-8
from django.conf.urls import patterns, url
from fileupload.views import (
BasicVersionCreateView, BasicPlusVersionCreateView,
jQueryVersionCreateView, AngularVersionCreateView,
PictureCreateView, PictureDeleteView, PictureListView,
)
from django.http import HttpResponse... | Update to redirect /upload/ to /upload/basic/plus/ | Update to redirect /upload/ to /upload/basic/plus/
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark | ---
+++
@@ -5,8 +5,10 @@
jQueryVersionCreateView, AngularVersionCreateView,
PictureCreateView, PictureDeleteView, PictureListView,
)
+from django.http import HttpResponseRedirect
urlpatterns = patterns('',
+ url(r'^$', lambda x: HttpResponseRedirect('/upload/basic/plus/')),
url(r... |
bbb3119c0087ec52185cd275b5dc132868129658 | oc/models.py | oc/models.py | class Person:
def __init__(self, name, birth_date):
self.name = name
self.birth_date = birth_date
class BirthDate:
def __init__(self, year, date):
self.year = year
self.date = date
class Date:
def __init__(self, day, month):
self.day = day
self.month = mon... | class Calendar:
def __init__(self, year=2015):
self.year = year # TODO get current year
self.dates = []
for month in range(1, 13):
self.insert_dates(month)
def insert_dates(self, month):
days = 28
if month in [1, 4, 6, 9, 11]:
days = 30
i... | Create Calender with list of all dates | Create Calender with list of all dates
| Python | mit | be-ndee/object-calisthenics | ---
+++
@@ -1,3 +1,25 @@
+class Calendar:
+ def __init__(self, year=2015):
+ self.year = year # TODO get current year
+ self.dates = []
+ for month in range(1, 13):
+ self.insert_dates(month)
+
+ def insert_dates(self, month):
+ days = 28
+ if month in [1, 4, 6, 9,... |
b627efe0675b2b1965eeac7104cf3a8f2d675539 | rhcephcompose/main.py | rhcephcompose/main.py | """ rhcephcompose CLI """
from argparse import ArgumentParser
import kobo.conf
from rhcephcompose.compose import Compose
class RHCephCompose(object):
""" Main class for rhcephcompose CLI. """
def __init__(self):
parser = ArgumentParser(description='Generate a compose for RHCS.')
parser.add_... | """ rhcephcompose CLI """
from argparse import ArgumentParser
import kobo.conf
from rhcephcompose.compose import Compose
class RHCephCompose(object):
""" Main class for rhcephcompose CLI. """
def __init__(self):
parser = ArgumentParser(description='Generate a compose for RHCS.')
parser.add_... | Add --insecure option to command line to disable SSL certificate verification when communicating with chacra | Add --insecure option to command line to disable SSL certificate verification when communicating with chacra
| Python | mit | red-hat-storage/rhcephcompose,red-hat-storage/rhcephcompose | ---
+++
@@ -13,10 +13,18 @@
parser = ArgumentParser(description='Generate a compose for RHCS.')
parser.add_argument('config_file', metavar='config',
help='main configuration file for this release.')
+ parser.add_argument('--insecure', action='store_const', const=T... |
ffce8ea9bda95945e335fef75ba93b1066c795ac | doc/quickstart/testlibs/LoginLibrary.py | doc/quickstart/testlibs/LoginLibrary.py | import os
import sys
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('create', username, pass... | import os
import sys
import subprocess
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('creat... | Use subprocess isntead of popen to get Jython working too | Use subprocess isntead of popen to get Jython working too
--HG--
extra : convert_revision : svn%3A79c32731-664e-0410-8185-e51b9e89f9fb/trunk%403645
| Python | apache-2.0 | Senseg/robotframework,userzimmermann/robotframework-python3,Senseg/robotframework,userzimmermann/robotframework-python3,Senseg/robotframework,userzimmermann/robotframework-python3,userzimmermann/robotframework-python3,userzimmermann/robotframework-python3,Senseg/robotframework,Senseg/robotframework | ---
+++
@@ -1,5 +1,6 @@
import os
import sys
+import subprocess
class LoginLibrary:
@@ -24,7 +25,9 @@
% (expected_status, self._status))
def _run_command(self, command, *args):
- command = '"%s" %s %s' % (self._sut_path, command, ' '.join(args))
- process... |
07d587cdf7883418a293fc3ff5a5f078c4da211f | astrobin_apps_donations/utils.py | astrobin_apps_donations/utils.py | from subscription.models import UserSubscription
def user_is_donor(user):
if user.is_authenticated:
return UserSubscription.objects.filter(user = user, subscription__name = 'AstroBin Donor').count() > 0
return False
| from subscription.models import UserSubscription
def user_is_donor(user):
if user.is_authenticated():
return UserSubscription.objects.filter(user = user, subscription__name = 'AstroBin Donor').count() > 0
return False
| Fix checking whether user is donor. | Fix checking whether user is donor.
| Python | agpl-3.0 | astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin | ---
+++
@@ -1,7 +1,7 @@
from subscription.models import UserSubscription
def user_is_donor(user):
- if user.is_authenticated:
+ if user.is_authenticated():
return UserSubscription.objects.filter(user = user, subscription__name = 'AstroBin Donor').count() > 0
return False
|
9d759bc8f7980ad4fa9707b2d6425ceac616460a | backend/post_handler/__init__.py | backend/post_handler/__init__.py | from flask import Flask
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def hello():
from flask import request
# print dir(request)
print request.values
print request.form.get('sdp')
return 'ok'
if __name__ == "__main__":
app.run('0.0.0.0')
| from flask import Flask
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def hello():
from flask import request
# print dir(request)
# print request.values
sdp_headers = request.form.get('sdp')
with open('./stream.sdp', 'w') as f:
f.write(sdp_headers)
cmd = "ffmpeg -i s... | Add handling of incoming requests to post_handler | Add handling of incoming requests to post_handler
| Python | mit | optimus-team/optimus-video,optimus-team/optimus-video,optimus-team/optimus-video,optimus-team/optimus-video | ---
+++
@@ -5,8 +5,16 @@
def hello():
from flask import request
# print dir(request)
- print request.values
- print request.form.get('sdp')
+ # print request.values
+ sdp_headers = request.form.get('sdp')
+
+ with open('./stream.sdp', 'w') as f:
+ f.write(sdp_headers)
+ cmd = "ff... |
e4c20eae4f847abe71ab661374abf14cdea3f99e | pyowm/constants.py | pyowm/constants.py | """
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.6.1'
LATEST_OWM_API_VERSION = '2.5'
DEFAULT_API_KEY = 'b1b15e88fa797225412429c1c50c122a'
| """
Constants for the PyOWM library
"""
PYOWM_VERSION = '2.7.0'
LATEST_OWM_API_VERSION = '2.5'
DEFAULT_API_KEY = 'b1b15e88fa797225412429c1c50c122a'
| Prepare bump to version 2.7.0 | Prepare bump to version 2.7.0
| Python | mit | csparpa/pyowm,csparpa/pyowm | ---
+++
@@ -2,6 +2,6 @@
Constants for the PyOWM library
"""
-PYOWM_VERSION = '2.6.1'
+PYOWM_VERSION = '2.7.0'
LATEST_OWM_API_VERSION = '2.5'
DEFAULT_API_KEY = 'b1b15e88fa797225412429c1c50c122a' |
2ccb6b1d1beddede7e98eabeeef0219bff293638 | calvin/calvinsys/sensors/distance.py | calvin/calvinsys/sensors/distance.py | # -*- coding: utf-8 -*-
# Copyright (c) 2016 Ericsson AB
#
# 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 ... | # -*- coding: utf-8 -*-
# Copyright (c) 2016 Ericsson AB
#
# 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 ... | Add default value to _has_data | Add default value to _has_data
| Python | apache-2.0 | EricssonResearch/calvin-base,les69/calvin-base,EricssonResearch/calvin-base,les69/calvin-base,les69/calvin-base,les69/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base | ---
+++
@@ -27,6 +27,7 @@
self._node = node
self._actor = actor
self._distance = distance.Distance(node, self._new_measurement)
+ self._has_data = False
def _new_measurement(self, measurement):
self._measurement = measurement |
552283714c329e3a304cd8a8bc14e5370fa6a879 | cosmo_tester/framework/constants.py | cosmo_tester/framework/constants.py | CLOUDIFY_TENANT_HEADER = 'Tenant'
SUPPORTED_RELEASES = [
'5.0.5',
'5.1.0',
'5.1.1',
'5.1.2',
'5.1.3',
'5.1.4',
'5.2.0',
'5.2.1',
'6.0.0',
'master',
]
SUPPORTED_FOR_RPM_UPGRADE = [
version + '-ga'
for version in SUPPORTED_RELEASES
if version not in ('master', '5.0.5'... | CLOUDIFY_TENANT_HEADER = 'Tenant'
SUPPORTED_RELEASES = [
'5.0.5',
'5.1.0',
'5.1.1',
'5.1.2',
'5.1.3',
'5.1.4',
'5.2.0',
'5.2.1',
'5.2.2',
'6.0.0',
'master',
]
SUPPORTED_FOR_RPM_UPGRADE = [
version + '-ga'
for version in SUPPORTED_RELEASES
if version not in ('mas... | Add 5.2.2 to supported versions | Add 5.2.2 to supported versions
| Python | apache-2.0 | cloudify-cosmo/cloudify-system-tests,cloudify-cosmo/cloudify-system-tests | ---
+++
@@ -9,6 +9,7 @@
'5.1.4',
'5.2.0',
'5.2.1',
+ '5.2.2',
'6.0.0',
'master',
] |
7848338fd8c1a73c8371617fc4b72a139380cc50 | blaze/expr/tests/test_strings.py | blaze/expr/tests/test_strings.py | import datashape
from blaze.expr import TableSymbol, like, Like
def test_like():
t = TableSymbol('t', '{name: string, amount: int, city: string}')
expr = like(t, name='Alice*')
assert eval(str(expr)).isidentical(expr)
assert expr.schema == t.schema
assert expr.dshape[0] == datashape.var
| import datashape
import pytest
from datashape import dshape
from blaze import symbol
@pytest.mark.parametrize(
'ds',
[
'var * {name: string}',
'var * {name: ?string}',
'var * string',
'var * ?string',
'string',
]
)
def test_like(ds):
t = symbol('t', ds)
exp... | Test for new like expression | Test for new like expression
| Python | bsd-3-clause | ContinuumIO/blaze,cpcloud/blaze,ContinuumIO/blaze,cpcloud/blaze,cowlicks/blaze,cowlicks/blaze | ---
+++
@@ -1,12 +1,24 @@
import datashape
-from blaze.expr import TableSymbol, like, Like
+import pytest
+from datashape import dshape
+
+from blaze import symbol
-def test_like():
- t = TableSymbol('t', '{name: string, amount: int, city: string}')
-
- expr = like(t, name='Alice*')
-
- assert eval(str(... |
e3e7fa542650cb909bb761771b08648252e9a279 | get-county-data.py | get-county-data.py | #!/usr/bin/env python3
from ftplib import FTP
import re
excluded = [x.strip() for x in open('bad-zip-names.txt').readlines()]
counties = [x.strip() for x in open('counties.txt').readlines()]
conn = FTP('ftp.lmic.state.mn.us')
conn.login()
filter_regex = re.compile('.*fi0.\.zip')
for county in counties:
print(co... | #!/usr/bin/env python3
from ftplib import FTP
import re
excluded = [x.strip() for x in open('bad-zip-names.txt').readlines()]
counties = [x.strip() for x in open('counties.txt').readlines()]
conn = FTP('ftp.lmic.state.mn.us')
conn.login()
filter_regex = re.compile('.*[fh][ic]0.\.zip')
for county in counties:
pr... | Allow half and combined plats to show up in list builder | Allow half and combined plats to show up in list builder
| Python | mit | simonsonc/mn-glo-mosaic,simonsonc/mn-glo-mosaic,simonsonc/mn-glo-mosaic | ---
+++
@@ -8,7 +8,7 @@
conn = FTP('ftp.lmic.state.mn.us')
conn.login()
-filter_regex = re.compile('.*fi0.\.zip')
+filter_regex = re.compile('.*[fh][ic]0.\.zip')
for county in counties:
print(county) |
de31fba90a541f272868d5868b402af3d2902ecc | labonneboite/common/maps/constants.py | labonneboite/common/maps/constants.py | ISOCHRONE_DURATIONS_MINUTES = (15, 30, 45)
CAR_MODE = 'car'
PUBLIC_MODE = 'public'
DEFAULT_TRAVEL_MODE = CAR_MODE
TRAVEL_MODES = (
PUBLIC_MODE,
CAR_MODE,
)
TRAVEL_MODES_FRENCH = {
CAR_MODE: 'Voiture',
PUBLIC_MODE: 'Transports en commun',
}
| ENABLE_CAR_MODE = True
ENABLE_PUBLIC_MODE = True
ISOCHRONE_DURATIONS_MINUTES = (15, 30, 45)
CAR_MODE = 'car'
PUBLIC_MODE = 'public'
TRAVEL_MODES = ()
if ENABLE_PUBLIC_MODE:
TRAVEL_MODES += (PUBLIC_MODE,)
if ENABLE_CAR_MODE:
TRAVEL_MODES += (CAR_MODE,)
if ENABLE_CAR_MODE:
DEFAULT_TRAVEL_MODE = CAR_MODE
e... | Add option to enable/disable each travel_mode | Add option to enable/disable each travel_mode
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite | ---
+++
@@ -1,14 +1,21 @@
+ENABLE_CAR_MODE = True
+ENABLE_PUBLIC_MODE = True
+
ISOCHRONE_DURATIONS_MINUTES = (15, 30, 45)
CAR_MODE = 'car'
PUBLIC_MODE = 'public'
-DEFAULT_TRAVEL_MODE = CAR_MODE
+TRAVEL_MODES = ()
+if ENABLE_PUBLIC_MODE:
+ TRAVEL_MODES += (PUBLIC_MODE,)
+if ENABLE_CAR_MODE:
+ TRAVEL_MODES... |
597451a5c33fb9f18f599627fb4a1e72daf08b90 | django/__init__.py | django/__init__.py | VERSION = (1, 0, 'post-release-SVN')
def get_version():
"Returns the version as a human-format string."
v = '.'.join([str(i) for i in VERSION[:-1]])
if VERSION[-1]:
from django.utils.version import get_svn_revision
v = '%s-%s-%s' % (v, VERSION[-1], get_svn_revision())
return v
| VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
version = '%s %s' % (version, VERSION[3])
if ... | Update django.VERSION in trunk per previous discussion | Update django.VERSION in trunk per previous discussion
git-svn-id: 554f83ef17aa7291f84efa897c1acfc5d0035373@9103 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| Python | bsd-3-clause | svn2github/django,svn2github/django,svn2github/django | ---
+++
@@ -1,9 +1,17 @@
-VERSION = (1, 0, 'post-release-SVN')
+VERSION = (1, 1, 0, 'alpha', 0)
def get_version():
- "Returns the version as a human-format string."
- v = '.'.join([str(i) for i in VERSION[:-1]])
- if VERSION[-1]:
- from django.utils.version import get_svn_revision
- v = '%s-... |
7ca12bb0d2b687c41f9e3b304cc2d7be37ca7a8d | tests/_test_mau_a_vs_an.py | tests/_test_mau_a_vs_an.py | """Unit tests for MAU101."""
from check import Check
from proselint.checks.garner import a_vs_an as chk
class TestCheck(Check):
"""Test garner.a_vs_n."""
__test__ = True
@property
def this_check(self):
"""Boilerplate."""
return chk
def test(self):
"""Ensure the test wo... | """Unit tests for MAU101."""
from check import Check
from proselint.checks.garner import a_vs_an as chk
class TestCheck(Check):
"""Test garner.a_vs_n."""
__test__ = True
@property
def this_check(self):
"""Boilerplate."""
return chk
def test(self):
"""Ensure the test wo... | Change 'check' to 'passes' in a vs. an check | Change 'check' to 'passes' in a vs. an check
| Python | bsd-3-clause | amperser/proselint,jstewmon/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint | ---
+++
@@ -17,8 +17,8 @@
def test(self):
"""Ensure the test works correctly."""
- assert self.check("""An apple a day keeps the doctor away.""")
- assert self.check("""The Epicurean garden.""")
- assert not self.check("""A apple a day keeps the doctor away.""")
- assert no... |
5ccfa503950156db79f3d63816168a4040f80b7b | testing/settings.py | testing/settings.py | # -*- encoding: utf-8 -*-
import os, sys
sys.path.insert(0, '..')
PROJECT_ROOT = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test'
}
}
MIDDLEWARE_CLASSES = ()
TIME_ZONE = 'America/Chic... | # -*- encoding: utf-8 -*-
import os, sys
sys.path.insert(0, '..')
PROJECT_ROOT = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test'
}
}
MIDDLEWARE_CLASSES = ()
TIME_ZONE = 'America/Chic... | Set task serializer to json | Set task serializer to json
| Python | bsd-3-clause | CloudNcodeInc/djmail,CloudNcodeInc/djmail,CloudNcodeInc/djmail | ---
+++
@@ -33,3 +33,4 @@
djcelery.setup_loader()
CELERY_ALWAYS_EAGER = True
+CELERY_TASK_SERIALIZER = 'json' |
482c215fc28785c53d252df95709fdd51c1c6679 | tests/frontend/conftest.py | tests/frontend/conftest.py | import pytest
import config
from skylines import model, create_frontend_app
from skylines.app import SkyLines
from tests import setup_app, setup_db, teardown_db, clean_db
from tests.data.bootstrap import bootstrap
@pytest.yield_fixture(scope="session")
def frontend_app():
"""Set up global front-end app for funct... | import pytest
import config
from skylines import model, create_frontend_app
from skylines.app import SkyLines
from tests import setup_app, setup_db, teardown_db, clean_db
from tests.data.bootstrap import bootstrap
@pytest.yield_fixture(scope="session")
def app():
"""Set up global front-end app for functional tes... | Rename frontend_app fixture to app | tests/frontend: Rename frontend_app fixture to app
| Python | agpl-3.0 | snip/skylines,Turbo87/skylines,shadowoneau/skylines,shadowoneau/skylines,Harry-R/skylines,Harry-R/skylines,RBE-Avionik/skylines,skylines-project/skylines,shadowoneau/skylines,RBE-Avionik/skylines,Turbo87/skylines,kerel-fs/skylines,snip/skylines,TobiasLohner/SkyLines,skylines-project/skylines,TobiasLohner/SkyLines,RBE-A... | ---
+++
@@ -8,7 +8,7 @@
@pytest.yield_fixture(scope="session")
-def frontend_app():
+def app():
"""Set up global front-end app for functional tests
Initialized once per test-run
@@ -22,15 +22,15 @@
@pytest.yield_fixture(scope="function")
-def frontend(frontend_app):
+def frontend(app):
"""C... |
18cd04d24965d173a98ebb4e7425344a1992bcce | tests/test_ecdsa.py | tests/test_ecdsa.py | import pytest
import unittest
from graphenebase.ecdsa import (
sign_message,
verify_message
)
wif = "5J4KCbg1G3my9b9hCaQXnHSm6vrwW9xQTJS6ZciW2Kek7cCkCEk"
class Testcases(unittest.TestCase):
# Ignore warning:
# https://www.reddit.com/r/joinmarket/comments/5crhfh/userwarning_implicit_cast_from_char_t... | import pytest
import unittest
from binascii import hexlify, unhexlify
import graphenebase.ecdsa as ecdsa
from graphenebase.account import PrivateKey, PublicKey, Address
wif = "5J4KCbg1G3my9b9hCaQXnHSm6vrwW9xQTJS6ZciW2Kek7cCkCEk"
class Testcases(unittest.TestCase):
# Ignore warning:
# https://www.reddit.com/... | Add unit test for cryptography and secp256k1 | Add unit test for cryptography and secp256k1
| Python | mit | xeroc/python-graphenelib | ---
+++
@@ -1,10 +1,8 @@
import pytest
import unittest
-from graphenebase.ecdsa import (
- sign_message,
- verify_message
-)
-
+from binascii import hexlify, unhexlify
+import graphenebase.ecdsa as ecdsa
+from graphenebase.account import PrivateKey, PublicKey, Address
wif = "5J4KCbg1G3my9b9hCaQXnHSm6vrwW9x... |
832fecfe5bfc8951c0d302c2f913a81acfbc657c | solarnmf_main_ts.py | solarnmf_main_ts.py | #solarnmf_main_ts.py
#Will Barnes
#31 March 2015
#Import needed modules
import solarnmf_functions as snf
import solarnmf_plot_routines as spr
#Read in and format the time series
results = snf.make_t_matrix("simulation",format="timeseries",filename='/home/wtb2/Desktop/gaussian_test.dat')
#Get the dimensions of the T... | #solarnmf_main_ts.py
#Will Barnes
#31 March 2015
#Import needed modules
import solarnmf_functions as snf
import solarnmf_plot_routines as spr
#Read in and format the time series
results = snf.make_t_matrix("simulation",format="timeseries",nx=100,ny=100,p=10,filename='/home/wtb2/Desktop/gaussian_test.dat')
#Get the ... | Fix for input options in make_t_matrix function | Fix for input options in make_t_matrix function
| Python | mit | wtbarnes/solarnmf | ---
+++
@@ -8,7 +8,7 @@
import solarnmf_plot_routines as spr
#Read in and format the time series
-results = snf.make_t_matrix("simulation",format="timeseries",filename='/home/wtb2/Desktop/gaussian_test.dat')
+results = snf.make_t_matrix("simulation",format="timeseries",nx=100,ny=100,p=10,filename='/home/wtb2/Desk... |
311dfdc28bda253e20d09c84a3ba739f5e9be7ef | tests/utils_test.py | tests/utils_test.py | import datetime
import json
import unittest
from clippings.utils import DatetimeJSONEncoder
DATE = datetime.datetime(2016, 1, 2, 3, 4, 5)
DATE_STRING = "2016-01-02T03:04:05"
class DatetimeJSONEncoderTest(unittest.TestCase):
def test_datetime_encoder_format(self):
dictionary = {"now": DATE}
exp... | import datetime
import json
import pytest
from clippings.utils import DatetimeJSONEncoder
DATE = datetime.datetime(2016, 1, 2, 3, 4, 5)
DATE_STRING = "2016-01-02T03:04:05"
def test_datetime_encoder_format():
dictionary = {"now": DATE}
expected_json_string = json.dumps({"now": DATE_STRING})
json_string... | Convert parser tests to pytest | Convert parser tests to pytest
| Python | mit | samueldg/clippings | ---
+++
@@ -1,6 +1,7 @@
import datetime
import json
-import unittest
+
+import pytest
from clippings.utils import DatetimeJSONEncoder
@@ -9,16 +10,15 @@
DATE_STRING = "2016-01-02T03:04:05"
-class DatetimeJSONEncoderTest(unittest.TestCase):
+def test_datetime_encoder_format():
+ dictionary = {"now": DAT... |
2f9c912c9071a498feb8d9cca69e447ffec397be | polygamy/pygit2_git.py | polygamy/pygit2_git.py | from __future__ import absolute_import
import pygit2
from .base_git import NoSuchRemote
from .plain_git import PlainGit
class Pygit2Git(PlainGit):
@staticmethod
def is_on_branch(path):
repo = pygit2.Repository(path)
return not (repo.head_is_detached or repo.head_is_unborn)
@staticmetho... | from __future__ import absolute_import
import pygit2
from .base_git import NoSuchRemote
from .plain_git import PlainGit
class Pygit2Git(PlainGit):
@staticmethod
def _find_remote(repo, remote_name):
for remote in repo.remotes:
if remote.name == remote_name:
return remote
... | Implement set_remote_url in pygit2 implementation | Implement set_remote_url in pygit2 implementation
| Python | bsd-3-clause | solarnz/polygamy,solarnz/polygamy | ---
+++
@@ -8,6 +8,14 @@
class Pygit2Git(PlainGit):
@staticmethod
+ def _find_remote(repo, remote_name):
+ for remote in repo.remotes:
+ if remote.name == remote_name:
+ return remote
+ else:
+ raise NoSuchRemote()
+
+ @staticmethod
def is_on_branc... |
cc51f18f0c123ed9ef68b35264f0e1f53ae22588 | index_addresses.py | index_addresses.py | import csv
import re
from elasticsearch import Elasticsearch
es = Elasticsearch({'host': ELASTICSEARCH_URL})
with open('data/ParcelCentroids.csv', 'r') as csvfile:
print "open file"
csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',')
current_row = 0
for row in c... | import csv
import re
import os
from elasticsearch import Elasticsearch
es = Elasticsearch({'host': os.environ['ELASTICSEARCH_URL']})
with open('data/ParcelCentroids.csv', 'r') as csvfile:
print "open file"
csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',')
curren... | Add correct syntax for environment variable | Add correct syntax for environment variable
| Python | mit | codeforamerica/streetscope,codeforamerica/streetscope | ---
+++
@@ -1,8 +1,9 @@
import csv
import re
+import os
from elasticsearch import Elasticsearch
-es = Elasticsearch({'host': ELASTICSEARCH_URL})
+es = Elasticsearch({'host': os.environ['ELASTICSEARCH_URL']})
with open('data/ParcelCentroids.csv', 'r') as csvfile:
print "open file" |
57318652ba9aacc0456334a1d6466734f35ab84d | e2etest/e2etest.py | e2etest/e2etest.py | #!/usr/bin/env python
# coding: utf-8
"""Run the end to end tests of the project."""
__author__ = "Martha Brennich"
__license__ = "MIT"
__copyright__ = "2020"
__date__ = "11/07/2020"
import sys
import unittest
import e2etest_freesas, e2etest_guinier_apps, e2etest_bift
def suite():
"""Creates suite for e2e test... | #!/usr/bin/env python
# coding: utf-8
"""Run the end to end tests of the project."""
__author__ = "Martha Brennich"
__license__ = "MIT"
__copyright__ = "2020"
__date__ = "11/07/2020"
import sys
import unittest
import e2etest_freesas, e2etest_guinier_apps, e2etest_bift, e2etest_cormap
def suite():
"""Creates su... | Add cormapy test suite to e2e test suite | Add cormapy test suite to e2e test suite
| Python | mit | kif/freesas,kif/freesas,kif/freesas | ---
+++
@@ -10,7 +10,7 @@
import sys
import unittest
-import e2etest_freesas, e2etest_guinier_apps, e2etest_bift
+import e2etest_freesas, e2etest_guinier_apps, e2etest_bift, e2etest_cormap
def suite():
@@ -19,6 +19,7 @@
test_suite.addTest(e2etest_freesas.suite())
test_suite.addTest(e2etest_guinier_... |
d0703be1d6adf6466f8c2120334a703210697176 | GCodeWriter.py | GCodeWriter.py | from UM.Mesh.MeshWriter import MeshWriter
from UM.Logger import Logger
import io
class GCodeWriter(MeshWriter):
def __init__(self):
super().__init__()
self._gcode = None
def write(self, file_name, storage_device, mesh_data):
if 'gcode' in file_name:
gcode = getattr(mesh_dat... | from UM.Mesh.MeshWriter import MeshWriter
from UM.Logger import Logger
from UM.Application import Application
import io
class GCodeWriter(MeshWriter):
def __init__(self):
super().__init__()
self._gcode = None
def write(self, file_name, storage_device, mesh_data):
if 'gcode' in file_na... | Use the new CuraEngine GCode protocol instead of temp files. | Use the new CuraEngine GCode protocol instead of temp files.
| Python | agpl-3.0 | ynotstartups/Wanhao,lo0ol/Ultimaker-Cura,senttech/Cura,ad1217/Cura,lo0ol/Ultimaker-Cura,Curahelper/Cura,quillford/Cura,derekhe/Cura,totalretribution/Cura,quillford/Cura,ynotstartups/Wanhao,fieldOfView/Cura,fieldOfView/Cura,ad1217/Cura,markwal/Cura,bq/Ultimaker-Cura,fxtentacle/Cura,fxtentacle/Cura,hmflash/Cura,derekhe/C... | ---
+++
@@ -1,6 +1,8 @@
from UM.Mesh.MeshWriter import MeshWriter
from UM.Logger import Logger
+from UM.Application import Application
import io
+
class GCodeWriter(MeshWriter):
def __init__(self):
@@ -9,11 +11,13 @@
def write(self, file_name, storage_device, mesh_data):
if 'gcode' in file_... |
6ee261309f4492994b52403d485bdfd08739a072 | kolibri/utils/tests/test_handler.py | kolibri/utils/tests/test_handler.py | import os
from time import sleep
from django.conf import settings
from django.test import TestCase
from kolibri.utils import cli
class KolibriTimedRotatingFileHandlerTestCase(TestCase):
def test_do_rollover(self):
archive_dir = os.path.join(os.environ["KOLIBRI_HOME"], "logs", "archive")
orig_val... | import os
from time import sleep
from django.conf import settings
from django.test import TestCase
from kolibri.utils import cli
class KolibriTimedRotatingFileHandlerTestCase(TestCase):
def test_do_rollover(self):
archive_dir = os.path.join(os.environ["KOLIBRI_HOME"], "logs", "archive")
orig_val... | Fix argument ordering in log handler test. | Fix argument ordering in log handler test.
| Python | mit | indirectlylit/kolibri,indirectlylit/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri,learningequality/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri | ---
+++
@@ -16,12 +16,12 @@
settings.LOGGING["handlers"]["file"]["when"] = "s"
# make sure that kolibri will be running for more than one second
try:
- cli.main(["--skipupdate", "manage", "help"])
+ cli.main(["manage", "--skipupdate", "help"])
except SystemExi... |
6a06ae04309b3d881b7001836b5c9cec86a59eae | api/main.py | api/main.py | from collections import OrderedDict
from server import prepare_data, query_server
from parser import parse_response
from bottle import route, request, run, view
import bottle
bottle.TEMPLATE_PATH = ["api/views/"]
bottle.debug(True)
bottle.TEMPLATES.clear()
@route('/api/')
@view('index')
def index():
site = "%s://... | from collections import OrderedDict
from server import prepare_data, query_server
from parser import parse_response
from bottle import route, request, run, view, JSONPlugin, json_dumps as dumps
from functools import partial
import bottle
bottle.TEMPLATE_PATH = ["api/views/"]
bottle.debug(True)
bottle.TEMPLATES.clear()... | Make output even more minimal. | Make output even more minimal.
| Python | mit | EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger,EmilStenstrom/json-tagger | ---
+++
@@ -1,12 +1,17 @@
from collections import OrderedDict
from server import prepare_data, query_server
from parser import parse_response
-from bottle import route, request, run, view
+from bottle import route, request, run, view, JSONPlugin, json_dumps as dumps
+from functools import partial
import bottle
... |
db47b7622595356ef75b18ef09ac8a5c2a55581e | foo.py | foo.py | """foo.py – a simple demo of importing a calss from C++"""
import ctypes
lib = ctypes.cdll.LoadLibrary('./libfoo.so')
class Foo(object):
"""The Foo class supports two methods, bar, and foobar..."""
def __init__(self, val):
lib.Foo_new.argtypes = [ctypes.c_int]
lib.Foo_new.restype = ctypes.c_vo... | """foo.py - a simple demo of importing a calss from C++"""
import ctypes
lib = ctypes.cdll.LoadLibrary('./libfoo.so')
class Foo(object):
"""The Foo class supports two methods, bar, and foobar..."""
def __init__(self, val):
lib.Foo_new.argtypes = [ctypes.c_int]
lib.Foo_new.restype = ctypes.c_vo... | Change extended ASCII character in docstring | Change extended ASCII character in docstring
Fix a – and replace it with a - | Python | mit | Auctoris/ctypes_demo,Auctoris/ctypes_demo | ---
+++
@@ -1,4 +1,4 @@
-"""foo.py – a simple demo of importing a calss from C++"""
+"""foo.py - a simple demo of importing a calss from C++"""
import ctypes
lib = ctypes.cdll.LoadLibrary('./libfoo.so') |
dc4511324bcd518dfceb828eacd72b64a5442468 | tests/test_wolfram_alpha.py | tests/test_wolfram_alpha.py | # -*- coding: utf-8 -*-
from nose.tools import eq_
import bot_mock
from pyfibot.modules import module_wolfram_alpha
config = {"module_wolfram_alpha":
{"appid": "3EYA3R-WVR6GJQWLH"}} # unit-test only APPID, do not abuse kthxbai
bot = bot_mock.BotMock(config)
def test_simple():
module_wolfram_alpha.in... | # -*- coding: utf-8 -*-
from nose.tools import eq_
import bot_mock
from pyfibot.modules import module_wolfram_alpha
config = {"module_wolfram_alpha":
{"appid": "3EYA3R-WVR6GJQWLH"}} # unit-test only APPID, do not abuse kthxbai
bot = bot_mock.BotMock(config)
def test_simple():
module_wolfram_alpha.in... | Change complex test to one that doesn't have a localizable response | Change complex test to one that doesn't have a localizable response
| Python | bsd-3-clause | lepinkainen/pyfibot,rnyberg/pyfibot,lepinkainen/pyfibot,EArmour/pyfibot,aapa/pyfibot,aapa/pyfibot,huqa/pyfibot,huqa/pyfibot,rnyberg/pyfibot,EArmour/pyfibot | ---
+++
@@ -19,7 +19,7 @@
def test_complex():
- query = "what is the airspeed of an unladen swallow?"
- target = ("#channel", u"estimated average cruising airspeed of an unladen European swallow = 11 m/s (meters per second) | (asked, but not answered, about a general swallow in the 1975 film Monty Python a... |
680a9345cc4087c521f5720472246bbf62e087c9 | wsgi/foodcheck_proj/foodcheck_app/management/commands/import_city_data.py | wsgi/foodcheck_proj/foodcheck_app/management/commands/import_city_data.py | from django.core.management.base import BaseCommand
from foodcheck_app.models import Restaurant, Score, Violation
class Command(BaseCommand):
args = '<city_name city_name ...>'
help = 'Imports the city data from a CSV into the database'
def handle(self, *args, **options):
self.stdout.write('Succes... | from django.core.management.base import BaseCommand
from foodcheck_app.models import Restaurant, Score, Violation
import os
class Command(BaseCommand):
# args = '<city_name city_name ...>' #Don't know what this does yet
help = 'Imports the city data from a CSV into the database'
def __load_csv_to_dict... | Test pulling from the business.csv | Test pulling from the business.csv
| Python | agpl-3.0 | esplinr/foodcheck,esplinr/foodcheck,esplinr/foodcheck,esplinr/foodcheck | ---
+++
@@ -1,11 +1,39 @@
from django.core.management.base import BaseCommand
from foodcheck_app.models import Restaurant, Score, Violation
+import os
class Command(BaseCommand):
- args = '<city_name city_name ...>'
+# args = '<city_name city_name ...>' #Don't know what this does yet
help = 'Imports t... |
292ee86bb7c21c3bc99ff04176592b74aa5b1e85 | docs/config/all.py | docs/config/all.py | # -*- coding: utf-8 -*-
#
# Phinx documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 14 17:39:42 2012.
#
# Import the base theme configuration
from cakephpsphinx.config.all import *
# The full version, including alpha/beta/rc tags.
release = '0.12.x'
# The search index version.
search_... | # -*- coding: utf-8 -*-
#
# Phinx documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 14 17:39:42 2012.
#
# Import the base theme configuration
from cakephpsphinx.config.all import *
# The full version, including alpha/beta/rc tags.
release = '0.12.x'
# The search index version.
search_... | Update docs config for 0.12 | Update docs config for 0.12 | Python | mit | robmorgan/phinx | ---
+++
@@ -21,7 +21,8 @@
# Other versions that display in the version picker menu.
version_list = [
- {'name': '0.11', 'number': '/phinx/11', 'title': '0.11', 'current': True},
+ {'name': '0.12', 'number': '/phinx/12', 'title': '0.12', 'current': True}
+ {'name': '0.11', 'number': '/phinx/11', 'title': ... |
d191a947e34e4d6eee1965f4896a44efc8c7ae91 | feedback/views.py | feedback/views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from feedback.forms import FeedbackForm
def leave_feedback(request):
form = FeedbackForm(request.POST or None)
if form.is_valid():
feedback = form.save(commit=False)
... | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from feedback.forms import FeedbackForm
def leave_feedback(request, template_name='feedback/feedback_form.html'):
form = FeedbackForm(request.POST or None)
if form.is_valid()... | Allow passing of template_name to view | Allow passing of template_name to view
| Python | bsd-3-clause | girasquid/django-feedback | ---
+++
@@ -4,7 +4,7 @@
from feedback.forms import FeedbackForm
-def leave_feedback(request):
+def leave_feedback(request, template_name='feedback/feedback_form.html'):
form = FeedbackForm(request.POST or None)
if form.is_valid():
feedback = form.save(commit=False)
@@ -12,4 +12,5 @@
f... |
8074fca48f6a7246f26471ecdc14633d78475d8c | opps/articles/utils.py | opps/articles/utils.py | # -*- coding: utf-8 -*-
from opps.articles.models import ArticleBox
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articlebo... | # -*- coding: utf-8 -*-
from opps.articles.models import ArticleBox
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
context['channel_long_slug'] = self.long_slug
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_... | Add context channel_long_slug on articles | Add context channel_long_slug on articles
| Python | mit | opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps | ---
+++
@@ -5,6 +5,7 @@
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
+ context['channel_long_slug'] = self.long_slug
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug: |
4ce3685ec4aab479a4d8c7a1d41d7028285c1656 | laalaa/apps/advisers/healthchecks.py | laalaa/apps/advisers/healthchecks.py | from django.conf import settings
from moj_irat.healthchecks import HealthcheckResponse, UrlHealthcheck, registry
def get_stats():
from celery import Celery
app = Celery("laalaa")
app.config_from_object("django.conf:settings")
return app.control.inspect().stats()
class CeleryWorkersHealthcheck(objec... | from django.conf import settings
from moj_irat.healthchecks import HealthcheckResponse, UrlHealthcheck, registry
def get_stats():
from celery import Celery
app = Celery("laalaa")
app.config_from_object("django.conf:settings", namespace="CELERY")
return app.control.inspect().stats()
class CeleryWork... | Load namespaced Celery configuration in healthcheck | Load namespaced Celery configuration in healthcheck
In bed52d9c60b00be751a6a9a6fc78b333fc5bccf6, I had to change the
configuration to be compatible with Django. I completely missed this
part.
Unfortunately, the test for this module starts with mocking the
`get_stats()` function, where this code exists, so I am at los... | Python | mit | ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api | ---
+++
@@ -6,7 +6,7 @@
from celery import Celery
app = Celery("laalaa")
- app.config_from_object("django.conf:settings")
+ app.config_from_object("django.conf:settings", namespace="CELERY")
return app.control.inspect().stats()
|
4a4da808289ad2edd6549cca921fbfd8fa4049c9 | corehq/apps/es/tests/test_sms.py | corehq/apps/es/tests/test_sms.py | from django.test.testcases import SimpleTestCase
from corehq.apps.es.sms import SMSES
from corehq.apps.es.tests.utils import ElasticTestMixin
from corehq.elastic import SIZE_LIMIT
class TestSMSES(ElasticTestMixin, SimpleTestCase):
def test_processed_or_incoming(self):
json_output = {
"query":... | from django.test.testcases import SimpleTestCase
from corehq.apps.es.sms import SMSES
from corehq.apps.es.tests.utils import ElasticTestMixin
from corehq.elastic import SIZE_LIMIT
class TestSMSES(ElasticTestMixin, SimpleTestCase):
def test_processed_or_incoming(self):
json_output = {
"query":... | Fix SMS ES test after not-and rewrite | Fix SMS ES test after not-and rewrite
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -14,12 +14,14 @@
"and": [
{"term": {"domain.exact": "demo"}},
{
- "not": {
- "and": (
- {"term": {"direction": "o"}},
-... |
c78aa5abc18dda674f607ead5af59ddb4a879ed4 | geozones/models.py | geozones/models.py | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Region(models.Model):
'''
Common regional zones. All messages can be grouped by this territorial
cluster.
TODO: use django-mptt
TODO: make nested regions
TODO: link message to nested re... | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Region(models.Model):
'''
Region
======
Common regional zones. All messages can be grouped by this territorial
cluster.
* TODO: use django-mptt
* TODO: make nested regions
* TOD... | Move location from core to geozones | Move location from core to geozones
| Python | mit | sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/flowofkindness | ---
+++
@@ -7,11 +7,13 @@
class Region(models.Model):
'''
+ Region
+ ======
Common regional zones. All messages can be grouped by this territorial
cluster.
- TODO: use django-mptt
- TODO: make nested regions
- TODO: link message to nested regions
+ * TODO: use django-mptt
+ * TO... |
257e8d2e6d1dc3c10eb7fc26c3deacaf4133bd9b | enactiveagents/view/agentevents.py | enactiveagents/view/agentevents.py | """
Prints a history of agent events to file.
"""
import events
class AgentEvents(events.EventListener):
"""
View class
"""
def __init__(self, file_path):
"""
:param file_path: The path of the file to output the history to.
"""
self.file_path = file_path
self.p... | """
Prints a history of agent events to file.
"""
import events
import json
class AgentEvents(events.EventListener):
"""
View class
"""
def __init__(self, file_path):
"""
:param file_path: The path of the file to output the history to.
"""
self.file_path = file_path
... | Write agent events to a traces history file for the website. | Write agent events to a traces history file for the website.
| Python | mit | Beskhue/enactive-agents,Beskhue/enactive-agents,Beskhue/enactive-agents | ---
+++
@@ -3,6 +3,7 @@
"""
import events
+import json
class AgentEvents(events.EventListener):
"""
@@ -19,14 +20,31 @@
def notify(self, event):
if isinstance(event, events.AgentPreparationEvent):
- if event.agent not in self.preparation_history:
- self.preparatio... |
709bdf06c38ccd9713fb1e92be3102e9b1b1ae59 | nodeconductor/server/test_runner.py | nodeconductor/server/test_runner.py | # This file mainly exists to allow python setup.py test to work.
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'nodeconductor.server.test_settings'
test_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), '..'))
sys.path.insert(0, test_dir)
from django.test.utils import get_ru... | # This file mainly exists to allow python setup.py test to work.
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'nodeconductor.server.test_settings'
test_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), '..'))
sys.path.insert(0, test_dir)
from django.test.utils import get_ru... | Make setup.py test honor migrations | Make setup.py test honor migrations
Kudos to django-setuptest project
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -12,6 +12,12 @@
def run_tests():
test_runner_class = get_runner(settings)
+
+ try:
+ from south.management.commands import patch_for_test_db_setup
+ patch_for_test_db_setup()
+ except ImportError:
+ pass
try:
import xmlrunner
@@ -40,4 +46,4 @@
if __na... |
3a9a6cb2c98403fc619c8979bdf48102028fd770 | rest/main.py | rest/main.py | import wol
import json
from flask import request
from app_factory import create_app
app = create_app(__name__)
@app.route('/help', methods=['GET'])
def help():
return json.dumps({'help message': wol.help_message().strip()})
@app.route('/ports', methods=['GET'])
def get_wol_ports():
return json.dumps({"port... | import wol
import json
from flask import request
from app_factory import create_app
app = create_app(__name__)
@app.route('/help', methods=['GET'])
def help():
return json.dumps({'help message': wol.help_message().strip()})
@app.route('/ports', methods=['GET'])
def get_wol_ports():
return json.dumps({"port... | Make the app externally visible | Make the app externally visible
| Python | mit | stevenaubertin/wol.py | ---
+++
@@ -41,4 +41,4 @@
if __name__ == "__main__":
- app.run()
+ app.run(host='0.0.0.0') |
d562756f6b48366508db6ef9ffb27e3d5c707845 | root/main.py | root/main.py | from .webdriver_util import init
def query_google(keywords):
print("Loading Firefox driver...")
driver, waiter, selector = init()
print("Fetching google front page...")
driver.get("http://google.com")
print("Taking a screenshot...")
waiter.shoot("frontpage")
print("Typing query string..... | from .webdriver_util import init
def query_google(keywords):
print("Loading Firefox driver...")
driver, waiter, selector, datapath = init()
print("Fetching google front page...")
driver.get("http://google.com")
print("Taking a screenshot...")
waiter.shoot("frontpage")
print("Typing quer... | Fix bug in example code | Fix bug in example code
Fixes:
line 6, in query_google
driver, waiter, selector = init()
ValueError: too many values to unpack (expected 3) | Python | apache-2.0 | weihanwang/webdriver-python,weihanwang/webdriver-python | ---
+++
@@ -3,7 +3,7 @@
def query_google(keywords):
print("Loading Firefox driver...")
- driver, waiter, selector = init()
+ driver, waiter, selector, datapath = init()
print("Fetching google front page...")
driver.get("http://google.com") |
92b9b557eef77f7ea4c05c74c1c229a2b508e640 | wsgi/openshift/urls.py | wsgi/openshift/urls.py | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'openshift.views.home', name='home'),
# url(r'^openshift/', include('openshift.foo.urls')... | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'openshift.views.home', name='home'),
# url(r'^openshift/', include('openshift.foo.urls')),
#... | Change to get Django 1.5 to work. | Change to get Django 1.5 to work.
| Python | agpl-3.0 | esplinr/foodcheck,esplinr/foodcheck,esplinr/foodcheck,esplinr/foodcheck | ---
+++
@@ -1,4 +1,4 @@
-from django.conf.urls.defaults import patterns, include, url
+from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin |
f0c590ef5d8ae98ee10e9c985cf14e626a9ca835 | zou/app/models/task_type.py | zou/app/models/task_type.py | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class TaskType(db.Model, BaseMixin, SerializerMixin):
"""
Categorize tasks in domain areas: modeling, animation, etc.
"""
name = db.Column(db.St... | from sqlalchemy_utils import UUIDType
from zou.app import db
from zou.app.models.serializer import SerializerMixin
from zou.app.models.base import BaseMixin
class TaskType(db.Model, BaseMixin, SerializerMixin):
"""
Categorize tasks in domain areas: modeling, animation, etc.
"""
name = db.Column(db.St... | Add allow_timelog to task type model | Add allow_timelog to task type model
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -15,6 +15,7 @@
priority = db.Column(db.Integer, default=1)
for_shots = db.Column(db.Boolean, default=False)
for_entity = db.Column(db.String(30), default="Asset")
+ allow_timelog = db.Column(db.Boolean, default=True)
shotgun_id = db.Column(db.Integer, index=True)
department_id... |
ae70502f910c85f6a4528b487eea3b535cec6c39 | frappe/desk/doctype/tag/test_tag.py | frappe/desk/doctype/tag/test_tag.py | # -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and Contributors
# See license.txt
# import frappe
import unittest
class TestTag(unittest.TestCase):
pass
| import unittest
import frappe
from frappe.desk.reportview import get_stats
from frappe.desk.doctype.tag.tag import add_tag
class TestTag(unittest.TestCase):
def setUp(self) -> None:
frappe.db.sql("DELETE from `tabTag`")
frappe.db.sql("UPDATE `tabDocType` set _user_tags=''")
def test_tag_count_query(self):
se... | Add test case to validate tag count query | test: Add test case to validate tag count query
| Python | mit | mhbu50/frappe,almeidapaulopt/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,frappe/frappe,frappe/frappe,StrellaGroup/frappe,yashodhank/frappe,frappe/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,mhbu50/frappe,mhbu50/frappe | ---
+++
@@ -1,8 +1,26 @@
-# -*- coding: utf-8 -*-
-# Copyright (c) 2019, Frappe Technologies and Contributors
-# See license.txt
-# import frappe
import unittest
+import frappe
+
+from frappe.desk.reportview import get_stats
+from frappe.desk.doctype.tag.tag import add_tag
class TestTag(unittest.TestCase):
- pass... |
a7c210a68a8671137681c55324341c60b256a92b | symantecssl/core.py | symantecssl/core.py | from __future__ import absolute_import, division, print_function
from .auth import SymantecAuth
from .session import SymantecSession
class Symantec(object):
def __init__(self, username, password,
url="https://api.geotrust.com/webtrust/partner"):
self.url = url
self.session = Sym... | from __future__ import absolute_import, division, print_function
from .auth import SymantecAuth
from .order import Order
from .session import SymantecSession
class Symantec(object):
def __init__(self, username, password,
url="https://api.geotrust.com/webtrust/partner"):
self.url = url
... | Add a slightly higher level API for submitting an order | Add a slightly higher level API for submitting an order
| Python | apache-2.0 | glyph/symantecssl,chelseawinfree/symantecssl,cloudkeep/symantecssl,grigouze/symantecssl,jmvrbanac/symantecssl | ---
+++
@@ -1,6 +1,7 @@
from __future__ import absolute_import, division, print_function
from .auth import SymantecAuth
+from .order import Order
from .session import SymantecSession
@@ -17,3 +18,7 @@
resp.raise_for_status()
return obj.response(resp.content)
+
+ def order(self, **kwarg... |
1062ef4daf124f0dcc056c1e95b7a234642fb36d | mopidy/backends/__init__.py | mopidy/backends/__init__.py | import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentP... | import logging
import time
from mopidy.exceptions import MpdNotImplemented
from mopidy.models import Playlist
logger = logging.getLogger('backends.base')
class BaseBackend(object):
current_playlist = None
library = None
playback = None
stored_playlists = None
uri_handlers = []
class BaseCurrentP... | Add playlist attribute to playlist controller | Add playlist attribute to playlist controller
| Python | apache-2.0 | vrs01/mopidy,dbrgn/mopidy,pacificIT/mopidy,kingosticks/mopidy,bacontext/mopidy,hkariti/mopidy,liamw9534/mopidy,rawdlite/mopidy,quartz55/mopidy,pacificIT/mopidy,tkem/mopidy,bacontext/mopidy,mopidy/mopidy,ZenithDK/mopidy,glogiotatidis/mopidy,rawdlite/mopidy,jmarsik/mopidy,jmarsik/mopidy,jcass77/mopidy,woutervanwijk/mopid... | ---
+++
@@ -16,6 +16,7 @@
class BaseCurrentPlaylistController(object):
def __init__(self, backend):
self.backend = backend
+ self.playlist = Playlist()
def add(self, track, at_position=None):
raise NotImplementedError |
3a8a7661c0aad111dbaace178062352b30f7fac5 | numcodecs/tests/__init__.py | numcodecs/tests/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
import pytest
pytest.register_assert_rewrite('numcodecs.tests.common')
| Enable pytest rewriting in test helper functions. | Enable pytest rewriting in test helper functions.
| Python | mit | alimanfoo/numcodecs,zarr-developers/numcodecs,alimanfoo/numcodecs | ---
+++
@@ -1,2 +1,6 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division
+
+import pytest
+
+pytest.register_assert_rewrite('numcodecs.tests.common') |
535d1f1ea3f229a0831830c4d19e7547e2b2ddab | cosmic/__init__.py | cosmic/__init__.py | from werkzeug.local import LocalProxy, LocalStack
from flask import request
from .models import _ctx_stack, Cosmos
_global_cosmos = Cosmos()
def _get_current_cosmos():
if _ctx_stack.top != None:
return _ctx_stack.top
else:
return _global_cosmos
cosmos = LocalProxy(_get_current_cosmos)
| from werkzeug.local import LocalProxy, LocalStack
from flask import request
from .models import _ctx_stack, Cosmos
import teleport
_global_cosmos = Cosmos()
# Temporary hack.
teleport._global_map = _global_cosmos
def _get_current_cosmos():
if _ctx_stack.top != None:
return _ctx_stack.top
else:
... | Add temporary hack to make teleport work with global Cosmos context | Add temporary hack to make teleport work with global Cosmos context
| Python | mit | cosmic-api/cosmic.py | ---
+++
@@ -2,9 +2,12 @@
from flask import request
from .models import _ctx_stack, Cosmos
+import teleport
_global_cosmos = Cosmos()
+# Temporary hack.
+teleport._global_map = _global_cosmos
def _get_current_cosmos():
if _ctx_stack.top != None: |
e1043bfb410740ab3429ff659e78197b44fefb74 | extract_options.py | extract_options.py | from pymongo import MongoClient
def main():
client = MongoClient()
db = client.cityhotspots
db.drop_collection('dineroptions')
diners_collection = db.diners
doc = {}
diner_options_collection = db.dineroptions
doc['categories'] = diners_collection.distinct('category')
doc['categories']... | from pymongo import MongoClient
def main():
client = MongoClient()
db = client.cityhotspots
db.drop_collection('dineroptions')
diners_collection = db.diners
doc = {}
diner_options_collection = db.dineroptions
doc['categories'] = diners_collection.distinct('category')
doc['categories']... | Change get min, max value method | Change get min, max value method
| Python | mit | earlwlkr/POICrawler | ---
+++
@@ -16,20 +16,8 @@
doc['districts'] = diners_collection.distinct('address.district')
doc['districts'].insert(0, 'Tất cả')
- doc['price_max'] = list(diners_collection.aggregate([{
- "$group":
- {
- "_id": None,
- "value": {"$max": "$price_max"}
- ... |
bf0990f1e5dda5e78c859dd625638357da5b1ef4 | sir/schema/modelext.py | sir/schema/modelext.py | # Copyright (c) 2014 Lukas Lalinsky, Wieland Hoffmann
# License: MIT, see LICENSE for details
from mbdata.models import Area, Artist, Label, Recording, ReleaseGroup, Work
from sqlalchemy import exc as sa_exc
from sqlalchemy.orm import relationship
from warnings import simplefilter
# Ignore SQLAlchemys warnings that we... | # Copyright (c) 2014 Lukas Lalinsky, Wieland Hoffmann
# License: MIT, see LICENSE for details
from mbdata.models import Area, Artist, Label, LinkAttribute, Recording, ReleaseGroup, Work
from sqlalchemy import exc as sa_exc
from sqlalchemy.orm import relationship
from warnings import simplefilter
# Ignore SQLAlchemys w... | Add a backref from Link to LinkAttribute | Add a backref from Link to LinkAttribute
| Python | mit | jeffweeksio/sir | ---
+++
@@ -1,6 +1,6 @@
# Copyright (c) 2014 Lukas Lalinsky, Wieland Hoffmann
# License: MIT, see LICENSE for details
-from mbdata.models import Area, Artist, Label, Recording, ReleaseGroup, Work
+from mbdata.models import Area, Artist, Label, LinkAttribute, Recording, ReleaseGroup, Work
from sqlalchemy import exc... |
d6bfac0ac2bc27c8d809467ed6071c5c9a7f5579 | client_test_run.py | client_test_run.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import unittest
import argparse
"""
Use this script either without arguments to run all tests:
python client_test_run.py
or with specific module/test to run on... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import unittest
import argparse
import sys
"""
Use this script either without arguments to run all tests:
python client_test_run.py
or with specific module/tes... | Exit with 1 if client tests fail | Exit with 1 if client tests fail
| Python | mit | lao605/product-definition-center,xychu/product-definition-center,product-definition-center/product-definition-center,release-engineering/product-definition-center,product-definition-center/product-definition-center,pombredanne/product-definition-center,lao605/product-definition-center,pombredanne/product-definition-cen... | ---
+++
@@ -7,6 +7,7 @@
#
import unittest
import argparse
+import sys
"""
Use this script either without arguments to run all tests:
@@ -24,4 +25,6 @@
suite = loader.loadTestsFromNames(options.tests)
else:
suite = loader.discover('pdc_client/tests', top_level_dir='.')
- unittest.TextT... |
10dc45d8e5fea60066b6719b2588fb65566a012f | dakis/api/views.py | dakis/api/views.py | from rest_framework import serializers, viewsets
from rest_framework import filters
from django.contrib.auth.models import User
from dakis.core.models import Experiment, Task
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(label='ID', read_only=True)
class ... | from rest_framework import serializers, viewsets
from rest_framework import filters
from django.contrib.auth.models import User
from dakis.core.models import Experiment, Task
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(label='ID', read_only=True)
class ... | Remove deprecated experiment details field from api | Remove deprecated experiment details field from api
| Python | agpl-3.0 | niekas/dakis,niekas/dakis,niekas/dakis | ---
+++
@@ -11,7 +11,7 @@
class Meta:
model = Experiment
- exclude = ('author', 'details')
+ exclude = ('author',)
def create(self, data):
user = self.context['request'].user |
19952d7f437270065a693dc886c867329ec7c4a0 | startzone.py | startzone.py | import xmlrpclib
from supervisor.xmlrpc import SupervisorTransport
def start_zone(port=1300, zoneid="defaultzone", processgroup='zones', autorestart=False):
s = xmlrpclib.ServerProxy('http://localhost:9001')
import socket
try:
version = s.twiddler.getAPIVersion()
except(socket.error), exc:
... | import xmlrpclib
from supervisor.xmlrpc import SupervisorTransport
def start_zone(port=1300, zoneid="defaultzone", processgroup='zones', autorestart=False):
s = xmlrpclib.ServerProxy('http://localhost:9001')
import socket
try:
version = s.twiddler.getAPIVersion()
except(socket.error), exc:
... | Fix up some settings for start_zone() | Fix up some settings for start_zone()
| Python | agpl-3.0 | cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO | ---
+++
@@ -11,8 +11,8 @@
raise UserWarning("Could not connect to supervisor: %s" % exc)
if float(version) >= 0.3:
- command = '/usr/bin/python zoneserver.py --port=%d --zoneid=%s' % (port, zoneid)
- settings = {'command': command, 'autostart': str(True), 'autorestart': str(autorestart)}... |
724a55ded262d4d0986e5a5a3c4c04e145558bea | test/test_device.py | test/test_device.py | from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-... | from pml.exceptions import PvException
import pml.device
import pytest
import mock
@pytest.fixture
def create_device(readback, setpoint):
_rb = readback
_sp = setpoint
device = pml.device.Device(rb_pv=_rb, sp_pv=_sp, cs=mock.MagicMock())
return device
def test_set_device_value():
rb_pv = 'SR01A-... | Add test to get device with non-existant key | Add test to get device with non-existant key
| Python | apache-2.0 | willrogers/pml,willrogers/pml | ---
+++
@@ -24,6 +24,7 @@
with pytest.raises(PvException):
device2.put_value(40)
+
def test_get_device_value():
sp_pv = 'SR01A-PC-SQUAD-01:SETI'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.